瀏覽代碼

[ADD] commit inicial

robert2206 7 年之前
當前提交
2d15e569b8

+ 1 - 0
__init__.py

@@ -0,0 +1 @@
+# -*- coding: utf-8 -*-

二進制
__init__.pyc


+ 14 - 0
__openerp__.py

@@ -0,0 +1,14 @@
+# -*- coding: utf-8 -*-
+{
+    'name': "Eiru Assets for Web Interface Extension",
+    'summary' : 'Eiru Assets for Develop Web Interface Extension Module',
+    'description' : 'Eiru Assets for Develop Web Interface Extension Module',
+    'author': "Robert Gauto",
+    'website': "http://www.yourcompany.com",
+    'category': 'Uncategorized',
+    'version': '0.1',
+    'depends': ['base'],
+    'data': [
+        'templates.xml',
+    ]
+}

二進制
static/description/icon.png


+ 414 - 0
static/lib/accounting/accounting.js

@@ -0,0 +1,414 @@
+/*!
+ * accounting.js v0.4.2
+ * Copyright 2014 Open Exchange Rates
+ *
+ * Freely distributable under the MIT license.
+ * Portions of accounting.js are inspired or borrowed from underscore.js
+ *
+ * Full details and documentation:
+ * http://openexchangerates.github.io/accounting.js/
+ */
+
+(function(root, undefined) {
+
+	/* --- Setup --- */
+
+	// Create the local library object, to be exported or referenced globally later
+	var lib = {};
+
+	// Current version
+	lib.version = '0.4.2';
+
+
+	/* --- Exposed settings --- */
+
+	// The library's settings configuration object. Contains default parameters for
+	// currency and number formatting
+	lib.settings = {
+		currency: {
+			symbol : "$",		// default currency symbol is '$'
+			format : "%s%v",	// controls output: %s = symbol, %v = value (can be object, see docs)
+			decimal : ".",		// decimal point separator
+			thousand : ",",		// thousands separator
+			precision : 2,		// decimal places
+			grouping : 3		// digit grouping (not implemented yet)
+		},
+		number: {
+			precision : 0,		// default precision on numbers is 0
+			grouping : 3,		// digit grouping (not implemented yet)
+			thousand : ",",
+			decimal : "."
+		}
+	};
+
+
+	/* --- Internal Helper Methods --- */
+
+	// Store reference to possibly-available ECMAScript 5 methods for later
+	var nativeMap = Array.prototype.map,
+		nativeIsArray = Array.isArray,
+		toString = Object.prototype.toString;
+
+	/**
+	 * Tests whether supplied parameter is a string
+	 * from underscore.js
+	 */
+	function isString(obj) {
+		return !!(obj === '' || (obj && obj.charCodeAt && obj.substr));
+	}
+
+	/**
+	 * Tests whether supplied parameter is an array
+	 * from underscore.js, delegates to ECMA5's native Array.isArray
+	 */
+	function isArray(obj) {
+		return nativeIsArray ? nativeIsArray(obj) : toString.call(obj) === '[object Array]';
+	}
+
+	/**
+	 * Tests whether supplied parameter is a true object
+	 */
+	function isObject(obj) {
+		return obj && toString.call(obj) === '[object Object]';
+	}
+
+	/**
+	 * Extends an object with a defaults object, similar to underscore's _.defaults
+	 *
+	 * Used for abstracting parameter handling from API methods
+	 */
+	function defaults(object, defs) {
+		var key;
+		object = object || {};
+		defs = defs || {};
+		// Iterate over object non-prototype properties:
+		for (key in defs) {
+			if (defs.hasOwnProperty(key)) {
+				// Replace values with defaults only if undefined (allow empty/zero values):
+				if (object[key] == null) object[key] = defs[key];
+			}
+		}
+		return object;
+	}
+
+	/**
+	 * Implementation of `Array.map()` for iteration loops
+	 *
+	 * Returns a new Array as a result of calling `iterator` on each array value.
+	 * Defers to native Array.map if available
+	 */
+	function map(obj, iterator, context) {
+		var results = [], i, j;
+
+		if (!obj) return results;
+
+		// Use native .map method if it exists:
+		if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context);
+
+		// Fallback for native .map:
+		for (i = 0, j = obj.length; i < j; i++ ) {
+			results[i] = iterator.call(context, obj[i], i, obj);
+		}
+		return results;
+	}
+
+	/**
+	 * Check and normalise the value of precision (must be positive integer)
+	 */
+	function checkPrecision(val, base) {
+		val = Math.round(Math.abs(val));
+		return isNaN(val)? base : val;
+	}
+
+
+	/**
+	 * Parses a format string or object and returns format obj for use in rendering
+	 *
+	 * `format` is either a string with the default (positive) format, or object
+	 * containing `pos` (required), `neg` and `zero` values (or a function returning
+	 * either a string or object)
+	 *
+	 * Either string or format.pos must contain "%v" (value) to be valid
+	 */
+	function checkCurrencyFormat(format) {
+		var defaults = lib.settings.currency.format;
+
+		// Allow function as format parameter (should return string or object):
+		if ( typeof format === "function" ) format = format();
+
+		// Format can be a string, in which case `value` ("%v") must be present:
+		if ( isString( format ) && format.match("%v") ) {
+
+			// Create and return positive, negative and zero formats:
+			return {
+				pos : format,
+				neg : format.replace("-", "").replace("%v", "-%v"),
+				zero : format
+			};
+
+		// If no format, or object is missing valid positive value, use defaults:
+		} else if ( !format || !format.pos || !format.pos.match("%v") ) {
+
+			// If defaults is a string, casts it to an object for faster checking next time:
+			return ( !isString( defaults ) ) ? defaults : lib.settings.currency.format = {
+				pos : defaults,
+				neg : defaults.replace("%v", "-%v"),
+				zero : defaults
+			};
+
+		}
+		// Otherwise, assume format was fine:
+		return format;
+	}
+
+
+	/* --- API Methods --- */
+
+	/**
+	 * Takes a string/array of strings, removes all formatting/cruft and returns the raw float value
+	 * Alias: `accounting.parse(string)`
+	 *
+	 * Decimal must be included in the regular expression to match floats (defaults to
+	 * accounting.settings.number.decimal), so if the number uses a non-standard decimal 
+	 * separator, provide it as the second argument.
+	 *
+	 * Also matches bracketed negatives (eg. "$ (1.99)" => -1.99)
+	 *
+	 * Doesn't throw any errors (`NaN`s become 0) but this may change in future
+	 */
+	var unformat = lib.unformat = lib.parse = function(value, decimal) {
+		// Recursively unformat arrays:
+		if (isArray(value)) {
+			return map(value, function(val) {
+				return unformat(val, decimal);
+			});
+		}
+
+		// Fails silently (need decent errors):
+		value = value || 0;
+
+		// Return the value as-is if it's already a number:
+		if (typeof value === "number") return value;
+
+		// Default decimal point comes from settings, but could be set to eg. "," in opts:
+		decimal = decimal || lib.settings.number.decimal;
+
+		 // Build regex to strip out everything except digits, decimal point and minus sign:
+		var regex = new RegExp("[^0-9-" + decimal + "]", ["g"]),
+			unformatted = parseFloat(
+				("" + value)
+				.replace(/\((?=\d+)(.*)\)/, "-$1") // replace bracketed values with negatives
+				.replace(regex, '')         // strip out any cruft
+				.replace(decimal, '.')      // make sure decimal point is standard
+			);
+
+		// This will fail silently which may cause trouble, let's wait and see:
+		return !isNaN(unformatted) ? unformatted : 0;
+	};
+
+
+	/**
+	 * Implementation of toFixed() that treats floats more like decimals
+	 *
+	 * Fixes binary rounding issues (eg. (0.615).toFixed(2) === "0.61") that present
+	 * problems for accounting- and finance-related software.
+	 */
+	var toFixed = lib.toFixed = function(value, precision) {
+		precision = checkPrecision(precision, lib.settings.number.precision);
+
+		var exponentialForm = Number(lib.unformat(value) + 'e' + precision);
+		var rounded = Math.round(exponentialForm);
+		var finalResult = Number(rounded + 'e-' + precision).toFixed(precision);
+		return finalResult;
+	};
+
+
+	/**
+	 * Format a number, with comma-separated thousands and custom precision/decimal places
+	 * Alias: `accounting.format()`
+	 *
+	 * Localise by overriding the precision and thousand / decimal separators
+	 * 2nd parameter `precision` can be an object matching `settings.number`
+	 */
+	var formatNumber = lib.formatNumber = lib.format = function(number, precision, thousand, decimal) {
+		// Resursively format arrays:
+		if (isArray(number)) {
+			return map(number, function(val) {
+				return formatNumber(val, precision, thousand, decimal);
+			});
+		}
+
+		// Clean up number:
+		number = unformat(number);
+
+		// Build options object from second param (if object) or all params, extending defaults:
+		var opts = defaults(
+				(isObject(precision) ? precision : {
+					precision : precision,
+					thousand : thousand,
+					decimal : decimal
+				}),
+				lib.settings.number
+			),
+
+			// Clean up precision
+			usePrecision = checkPrecision(opts.precision),
+
+			// Do some calc:
+			negative = number < 0 ? "-" : "",
+			base = parseInt(toFixed(Math.abs(number || 0), usePrecision), 10) + "",
+			mod = base.length > 3 ? base.length % 3 : 0;
+
+		// Format the number:
+		return negative + (mod ? base.substr(0, mod) + opts.thousand : "") + base.substr(mod).replace(/(\d{3})(?=\d)/g, "$1" + opts.thousand) + (usePrecision ? opts.decimal + toFixed(Math.abs(number), usePrecision).split('.')[1] : "");
+	};
+
+
+	/**
+	 * Format a number into currency
+	 *
+	 * Usage: accounting.formatMoney(number, symbol, precision, thousandsSep, decimalSep, format)
+	 * defaults: (0, "$", 2, ",", ".", "%s%v")
+	 *
+	 * Localise by overriding the symbol, precision, thousand / decimal separators and format
+	 * Second param can be an object matching `settings.currency` which is the easiest way.
+	 *
+	 * To do: tidy up the parameters
+	 */
+	var formatMoney = lib.formatMoney = function(number, symbol, precision, thousand, decimal, format) {
+		// Resursively format arrays:
+		if (isArray(number)) {
+			return map(number, function(val){
+				return formatMoney(val, symbol, precision, thousand, decimal, format);
+			});
+		}
+
+		// Clean up number:
+		number = unformat(number);
+
+		// Build options object from second param (if object) or all params, extending defaults:
+		var opts = defaults(
+				(isObject(symbol) ? symbol : {
+					symbol : symbol,
+					precision : precision,
+					thousand : thousand,
+					decimal : decimal,
+					format : format
+				}),
+				lib.settings.currency
+			),
+
+			// Check format (returns object with pos, neg and zero):
+			formats = checkCurrencyFormat(opts.format),
+
+			// Choose which format to use for this value:
+			useFormat = number > 0 ? formats.pos : number < 0 ? formats.neg : formats.zero;
+
+		// Return with currency symbol added:
+		return useFormat.replace('%s', opts.symbol).replace('%v', formatNumber(Math.abs(number), checkPrecision(opts.precision), opts.thousand, opts.decimal));
+	};
+
+
+	/**
+	 * Format a list of numbers into an accounting column, padding with whitespace
+	 * to line up currency symbols, thousand separators and decimals places
+	 *
+	 * List should be an array of numbers
+	 * Second parameter can be an object containing keys that match the params
+	 *
+	 * Returns array of accouting-formatted number strings of same length
+	 *
+	 * NB: `white-space:pre` CSS rule is required on the list container to prevent
+	 * browsers from collapsing the whitespace in the output strings.
+	 */
+	lib.formatColumn = function(list, symbol, precision, thousand, decimal, format) {
+		if (!list || !isArray(list)) return [];
+
+		// Build options object from second param (if object) or all params, extending defaults:
+		var opts = defaults(
+				(isObject(symbol) ? symbol : {
+					symbol : symbol,
+					precision : precision,
+					thousand : thousand,
+					decimal : decimal,
+					format : format
+				}),
+				lib.settings.currency
+			),
+
+			// Check format (returns object with pos, neg and zero), only need pos for now:
+			formats = checkCurrencyFormat(opts.format),
+
+			// Whether to pad at start of string or after currency symbol:
+			padAfterSymbol = formats.pos.indexOf("%s") < formats.pos.indexOf("%v") ? true : false,
+
+			// Store value for the length of the longest string in the column:
+			maxLength = 0,
+
+			// Format the list according to options, store the length of the longest string:
+			formatted = map(list, function(val, i) {
+				if (isArray(val)) {
+					// Recursively format columns if list is a multi-dimensional array:
+					return lib.formatColumn(val, opts);
+				} else {
+					// Clean up the value
+					val = unformat(val);
+
+					// Choose which format to use for this value (pos, neg or zero):
+					var useFormat = val > 0 ? formats.pos : val < 0 ? formats.neg : formats.zero,
+
+						// Format this value, push into formatted list and save the length:
+						fVal = useFormat.replace('%s', opts.symbol).replace('%v', formatNumber(Math.abs(val), checkPrecision(opts.precision), opts.thousand, opts.decimal));
+
+					if (fVal.length > maxLength) maxLength = fVal.length;
+					return fVal;
+				}
+			});
+
+		// Pad each number in the list and send back the column of numbers:
+		return map(formatted, function(val, i) {
+			// Only if this is a string (not a nested array, which would have already been padded):
+			if (isString(val) && val.length < maxLength) {
+				// Depending on symbol position, pad after symbol or at index 0:
+				return padAfterSymbol ? val.replace(opts.symbol, opts.symbol+(new Array(maxLength - val.length + 1).join(" "))) : (new Array(maxLength - val.length + 1).join(" ")) + val;
+			}
+			return val;
+		});
+	};
+
+
+	/* --- Module Definition --- */
+
+	// Export accounting for CommonJS. If being loaded as an AMD module, define it as such.
+	// Otherwise, just add `accounting` to the global object
+	if (typeof exports !== 'undefined') {
+		if (typeof module !== 'undefined' && module.exports) {
+			exports = module.exports = lib;
+		}
+		exports.accounting = lib;
+	} else if (typeof define === 'function' && define.amd) {
+		// Return the library as an AMD module:
+		define([], function() {
+			return lib;
+		});
+	} else {
+		// Use accounting.noConflict to restore `accounting` back to its original value.
+		// Returns a reference to the library's `accounting` object;
+		// e.g. `var numbers = accounting.noConflict();`
+		lib.noConflict = (function(oldAccounting) {
+			return function() {
+				// Reset the value of the root's `accounting` variable:
+				root.accounting = oldAccounting;
+				// Delete the noConflict method:
+				lib.noConflict = undefined;
+				// Return reference to the library to re-assign it:
+				return lib;
+			};
+		})(root.accounting);
+
+		// Declare `fx` on the root (global/window) object:
+		root['accounting'] = lib;
+	}
+
+	// Root will be `window` in browser or `global` on the server:
+}(this));

+ 43 - 0
static/lib/bootstrap-table/bootstrap-table-es-PY.js

@@ -0,0 +1,43 @@
+/**
+ * Bootstrap Table Spanish Spain translation
+ * Author: Marc Pina<iwalkalone69@gmail.com>
+ */
+(function ($) {
+    'use strict';
+
+    $.fn.bootstrapTable.locales['es-ES'] = {
+        formatLoadingMessage: function () {
+            return 'Por favor espere...';
+        },
+        formatRecordsPerPage: function (pageNumber) {
+            return pageNumber + ' resultados por página';
+        },
+        formatShowingRows: function (pageFrom, pageTo, totalRows) {
+            return 'Página ' + pageFrom + ' de ' + pageTo + ' - ' + totalRows + ' elementos';
+        },
+        formatSearch: function () {
+            return 'Buscar';
+        },
+        formatNoMatches: function () {
+            return 'No se encontraron resultados';
+        },
+        formatPaginationSwitch: function () {
+            return 'Ocultar/Mostrar paginación';
+        },
+        formatRefresh: function () {
+            return 'Refrescar';
+        },
+        formatToggle: function () {
+            return 'Ocultar/Mostrar';
+        },
+        formatColumns: function () {
+            return 'Columnas';
+        },
+        formatAllRows: function () {
+            return 'Todos';
+        }
+    };
+
+    $.extend($.fn.bootstrapTable.defaults, $.fn.bootstrapTable.locales['es-ES']);
+
+})(jQuery);

+ 131 - 0
static/lib/bootstrap-table/bootstrap-table-export.js

@@ -0,0 +1,131 @@
+/**
+ * @author zhixin wen <wenzhixin2010@gmail.com>
+ * extensions: https://github.com/kayalshri/tableExport.jquery.plugin
+ */
+
+(function ($) {
+    'use strict';
+    var sprintf = $.fn.bootstrapTable.utils.sprintf;
+
+    var TYPE_NAME = {
+        json: 'JSON',
+        xml: 'XML',
+        png: 'PNG',
+        csv: 'CSV',
+        txt: 'TXT',
+        sql: 'SQL',
+        doc: 'MS-Word',
+        excel: 'MS-Excel',
+        xlsx: 'MS-Excel (OpenXML)',
+        powerpoint: 'MS-Powerpoint',
+        pdf: 'PDF'
+    };
+
+    $.extend($.fn.bootstrapTable.defaults, {
+        showExport: false,
+        exportDataType: 'basic', // basic, all, selected
+        // 'json', 'xml', 'png', 'csv', 'txt', 'sql', 'doc', 'excel', 'powerpoint', 'pdf'
+        exportTypes: ['json', 'xml', 'csv', 'txt', 'sql', 'excel'],
+        exportOptions: {}
+    });
+
+    $.extend($.fn.bootstrapTable.defaults.icons, {
+        export: 'glyphicon-export icon-share'
+    });
+
+    $.extend($.fn.bootstrapTable.locales, {
+        formatExport: function () {
+            return 'Export data';
+        }
+    });
+    $.extend($.fn.bootstrapTable.defaults, $.fn.bootstrapTable.locales);
+
+    var BootstrapTable = $.fn.bootstrapTable.Constructor,
+        _initToolbar = BootstrapTable.prototype.initToolbar;
+
+    BootstrapTable.prototype.initToolbar = function () {
+        this.showToolbar = this.options.showExport;
+
+        _initToolbar.apply(this, Array.prototype.slice.apply(arguments));
+
+        if (this.options.showExport) {
+            var that = this,
+                $btnGroup = this.$toolbar.find('>.btn-group'),
+                $export = $btnGroup.find('div.export');
+
+            if (!$export.length) {
+                $export = $([
+                    '<div class="export btn-group">',
+                        '<button class="btn' +
+                            sprintf(' btn-%s', this.options.buttonsClass) +
+                            sprintf(' btn-%s', this.options.iconSize) +
+                            ' dropdown-toggle" aria-label="export type" ' +
+                            'title="' + this.options.formatExport() + '" ' +
+                            'data-toggle="dropdown" type="button">',
+                            sprintf('<i class="%s %s"></i> ', this.options.iconsPrefix, this.options.icons.export),
+                            '<span class="caret"></span>',
+                        '</button>',
+                        '<ul class="dropdown-menu" role="menu">',
+                        '</ul>',
+                    '</div>'].join('')).appendTo($btnGroup);
+
+                var $menu = $export.find('.dropdown-menu'),
+                    exportTypes = this.options.exportTypes;
+
+                if (typeof this.options.exportTypes === 'string') {
+                    var types = this.options.exportTypes.slice(1, -1).replace(/ /g, '').split(',');
+
+                    exportTypes = [];
+                    $.each(types, function (i, value) {
+                        exportTypes.push(value.slice(1, -1));
+                    });
+                }
+                $.each(exportTypes, function (i, type) {
+                    if (TYPE_NAME.hasOwnProperty(type)) {
+                        $menu.append(['<li role="menuitem" data-type="' + type + '">',
+                                '<a href="javascript:void(0)">',
+                                    TYPE_NAME[type],
+                                '</a>',
+                            '</li>'].join(''));
+                    }
+                });
+
+                $menu.find('li').click(function () {
+                    var type = $(this).data('type'),
+                        doExport = function () {
+                            that.$el.tableExport($.extend({}, that.options.exportOptions, {
+                                type: type,
+                                escape: false
+                            }));
+                        };
+
+                    if (that.options.exportDataType === 'all' && that.options.pagination) {
+                        that.$el.one(that.options.sidePagination === 'server' ? 'post-body.bs.table' : 'page-change.bs.table', function () {
+                            doExport();
+                            that.togglePagination();
+                        });
+                        that.togglePagination();
+                    } else if (that.options.exportDataType === 'selected') {
+                        var data = that.getData(),
+                            selectedData = that.getAllSelections();
+
+                        // Quick fix #2220
+                        if (that.options.sidePagination === 'server') {
+                            data = {total: that.options.totalRows};
+                            data[that.options.dataField] = that.getData();
+
+                            selectedData = {total: that.options.totalRows};
+                            selectedData[that.options.dataField] = that.getAllSelections();
+                        }
+
+                        that.load(selectedData);
+                        doExport();
+                        that.load(data);
+                    } else {
+                        doExport();
+                    }
+                });
+            }
+        }
+    };
+})(jQuery);

+ 181 - 0
static/lib/bootstrap-table/bootstrap-table-reorder-columns.js

@@ -0,0 +1,181 @@
+/**
+ * @author: Dennis Hernández
+ * @webSite: http://djhvscf.github.io/Blog
+ * @version: v1.1.0
+ */
+
+!function ($) {
+
+    'use strict';
+
+    //From MDN site, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
+    var filterFn = function () {
+        if (!Array.prototype.filter) {
+            Array.prototype.filter = function(fun/*, thisArg*/) {
+                'use strict';
+
+                if (this === void 0 || this === null) {
+                    throw new TypeError();
+                }
+
+                var t = Object(this);
+                var len = t.length >>> 0;
+                if (typeof fun !== 'function') {
+                    throw new TypeError();
+                }
+
+                var res = [];
+                var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
+                for (var i = 0; i < len; i++) {
+                    if (i in t) {
+                        var val = t[i];
+
+                        // NOTE: Technically this should Object.defineProperty at
+                        //       the next index, as push can be affected by
+                        //       properties on Object.prototype and Array.prototype.
+                        //       But that method's new, and collisions should be
+                        //       rare, so use the more-compatible alternative.
+                        if (fun.call(thisArg, val, i, t)) {
+                            res.push(val);
+                        }
+                    }
+                }
+
+                return res;
+            };
+        }
+    };
+
+    $.extend($.fn.bootstrapTable.defaults, {
+        reorderableColumns: false,
+        maxMovingRows: 10,
+        onReorderColumn: function (headerFields) {
+            return false;
+        },
+        dragaccept: null
+    });
+
+    $.extend($.fn.bootstrapTable.Constructor.EVENTS, {
+        'reorder-column.bs.table': 'onReorderColumn'
+    });
+
+    var BootstrapTable = $.fn.bootstrapTable.Constructor,
+        _initHeader = BootstrapTable.prototype.initHeader,
+        _toggleColumn = BootstrapTable.prototype.toggleColumn,
+        _toggleView = BootstrapTable.prototype.toggleView,
+        _resetView = BootstrapTable.prototype.resetView;
+
+    BootstrapTable.prototype.initHeader = function () {
+        _initHeader.apply(this, Array.prototype.slice.apply(arguments));
+
+        if (!this.options.reorderableColumns) {
+            return;
+        }
+
+        this.makeRowsReorderable();
+    };
+
+    BootstrapTable.prototype.toggleColumn = function () {
+        _toggleColumn.apply(this, Array.prototype.slice.apply(arguments));
+
+        if (!this.options.reorderableColumns) {
+            return;
+        }
+
+        this.makeRowsReorderable();
+    };
+
+    BootstrapTable.prototype.toggleView = function () {
+        _toggleView.apply(this, Array.prototype.slice.apply(arguments));
+
+        if (!this.options.reorderableColumns) {
+            return;
+        }
+
+        if (this.options.cardView) {
+            return;
+        }
+
+        this.makeRowsReorderable();
+    };
+
+    BootstrapTable.prototype.resetView = function () {
+        _resetView.apply(this, Array.prototype.slice.apply(arguments));
+
+        if (!this.options.reorderableColumns) {
+            return;
+        }
+
+        this.makeRowsReorderable();
+    };
+
+    BootstrapTable.prototype.makeRowsReorderable = function () {
+        var that = this;
+        try {
+            $(this.$el).dragtable('destroy');
+        } catch (e) {}
+        $(this.$el).dragtable({
+            maxMovingRows: that.options.maxMovingRows,
+            dragaccept: that.options.dragaccept,
+            clickDelay:200,
+            beforeStop: function() {
+                var ths = [],
+                    formatters = [],
+                    columns = [],
+                    columnsHidden = [],
+                    columnIndex = -1,
+                    optionsColumns = [];
+                that.$header.find('th').each(function (i) {
+                    ths.push($(this).data('field'));
+                    formatters.push($(this).data('formatter'));
+                });
+
+                //Exist columns not shown
+                if (ths.length < that.columns.length) {
+                    columnsHidden = $.grep(that.columns, function (column) {
+                       return !column.visible;
+                    });
+                    for (var i = 0; i < columnsHidden.length; i++) {
+                        ths.push(columnsHidden[i].field);
+                        formatters.push(columnsHidden[i].formatter);
+                    }
+                }
+
+                for (var i = 0; i < ths.length; i++ ) {
+                    columnIndex = $.fn.bootstrapTable.utils.getFieldIndex(that.columns, ths[i]);
+                    if (columnIndex !== -1) {
+                        that.columns[columnIndex].fieldIndex = i;
+                        columns.push(that.columns[columnIndex]);
+                        that.columns.splice(columnIndex, 1);
+                    }
+                }
+
+                that.columns = that.columns.concat(columns);
+
+                filterFn(); //Support <IE9
+                $.each(that.columns, function(i, column) {
+                    var found = false,
+                        field = column.field;
+                    that.options.columns[0].filter(function(item) {
+                        if(!found && item["field"] == field) {
+                            optionsColumns.push(item);
+                            found = true;
+                            return false;
+                        } else
+                            return true;
+                    })
+                });
+
+                that.options.columns[0] = optionsColumns;
+
+                that.header.fields = ths;
+                that.header.formatters = formatters;
+                that.initHeader();
+                that.initToolbar();
+                that.initBody();
+                that.resetView();
+                that.trigger('reorder-column', ths);
+            }
+        });
+    };
+}(jQuery);

+ 211 - 0
static/lib/bootstrap-table/bootstrap-table-toolbar.js

@@ -0,0 +1,211 @@
+/**
+ * @author: aperez <aperez@datadec.es>
+ * @version: v2.0.0
+ *
+ * @update Dennis Hernández <http://djhvscf.github.io/Blog>
+ */
+
+!function($) {
+    'use strict';
+
+    var firstLoad = false;
+
+    var sprintf = $.fn.bootstrapTable.utils.sprintf;
+
+    var showAvdSearch = function(pColumns, searchTitle, searchText, that) {
+        if (!$("#avdSearchModal" + "_" + that.options.idTable).hasClass("modal")) {
+            var vModal = sprintf("<div id=\"avdSearchModal%s\"  class=\"modal fade\" tabindex=\"-1\" role=\"dialog\" aria-labelledby=\"mySmallModalLabel\" aria-hidden=\"true\">", "_" + that.options.idTable);
+            vModal += "<div class=\"modal-dialog modal-xs\">";
+            vModal += " <div class=\"modal-content\">";
+            vModal += "  <div class=\"modal-header\">";
+            vModal += "   <button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-hidden=\"true\" >&times;</button>";
+            vModal += sprintf("   <h4 class=\"modal-title\">%s</h4>", searchTitle);
+            vModal += "  </div>";
+            vModal += "  <div class=\"modal-body modal-body-custom\">";
+            vModal += sprintf("   <div class=\"container-fluid\" id=\"avdSearchModalContent%s\" style=\"padding-right: 0px;padding-left: 0px;\" >", "_" + that.options.idTable);
+            vModal += "   </div>";
+            vModal += "  </div>";
+            vModal += "  </div>";
+            vModal += " </div>";
+            vModal += "</div>";
+
+            $("body").append($(vModal));
+
+            var vFormAvd = createFormAvd(pColumns, searchText, that),
+                timeoutId = 0;;
+
+            $('#avdSearchModalContent' + "_" + that.options.idTable).append(vFormAvd.join(''));
+
+            $('#' + that.options.idForm).off('keyup blur', 'input').on('keyup blur', 'input', function (event) {
+                clearTimeout(timeoutId);
+                timeoutId = setTimeout(function () {
+                    that.onColumnAdvancedSearch(event);
+                }, that.options.searchTimeOut);
+            });
+
+            $("#btnCloseAvd" + "_" + that.options.idTable).click(function() {
+                $("#avdSearchModal" + "_" + that.options.idTable).modal('hide');
+            });
+
+            $("#avdSearchModal" + "_" + that.options.idTable).modal();
+        } else {
+            $("#avdSearchModal" + "_" + that.options.idTable).modal();
+        }
+    };
+
+    var createFormAvd = function(pColumns, searchText, that) {
+        var htmlForm = [];
+        htmlForm.push(sprintf('<form class="form-horizontal" id="%s" action="%s" >', that.options.idForm, that.options.actionForm));
+        for (var i in pColumns) {
+            var vObjCol = pColumns[i];
+            if (!vObjCol.checkbox && vObjCol.visible && vObjCol.searchable) {
+                htmlForm.push('<div class="form-group">');
+                htmlForm.push(sprintf('<label class="col-sm-4 control-label">%s</label>', vObjCol.title));
+                htmlForm.push('<div class="col-sm-6">');
+                htmlForm.push(sprintf('<input type="text" class="form-control input-md" name="%s" placeholder="%s" id="%s">', vObjCol.field, vObjCol.title, vObjCol.field));
+                htmlForm.push('</div>');
+                htmlForm.push('</div>');
+            }
+        }
+
+        htmlForm.push('<div class="form-group">');
+        htmlForm.push('<div class="col-sm-offset-9 col-sm-3">');
+        htmlForm.push(sprintf('<button type="button" id="btnCloseAvd%s" class="btn btn-default" >%s</button>', "_" + that.options.idTable, searchText));
+        htmlForm.push('</div>');
+        htmlForm.push('</div>');
+        htmlForm.push('</form>');
+
+        return htmlForm;
+    };
+
+    $.extend($.fn.bootstrapTable.defaults, {
+        advancedSearch: false,
+        idForm: 'advancedSearch',
+        actionForm: '',
+        idTable: undefined,
+        onColumnAdvancedSearch: function (field, text) {
+            return false;
+        }
+    });
+
+    $.extend($.fn.bootstrapTable.defaults.icons, {
+        advancedSearchIcon: 'glyphicon-chevron-down'
+    });
+
+    $.extend($.fn.bootstrapTable.Constructor.EVENTS, {
+        'column-advanced-search.bs.table': 'onColumnAdvancedSearch'
+    });
+
+    $.extend($.fn.bootstrapTable.locales, {
+        formatAdvancedSearch: function() {
+            return 'Advanced search';
+        },
+        formatAdvancedCloseButton: function() {
+            return "Close";
+        }
+    });
+
+    $.extend($.fn.bootstrapTable.defaults, $.fn.bootstrapTable.locales);
+
+    var BootstrapTable = $.fn.bootstrapTable.Constructor,
+        _initToolbar = BootstrapTable.prototype.initToolbar,
+        _load = BootstrapTable.prototype.load,
+        _initSearch = BootstrapTable.prototype.initSearch;
+
+    BootstrapTable.prototype.initToolbar = function() {
+        _initToolbar.apply(this, Array.prototype.slice.apply(arguments));
+
+        if (!this.options.search) {
+            return;
+        }
+
+        if (!this.options.advancedSearch) {
+            return;
+        }
+
+        if (!this.options.idTable) {
+            return;
+        }
+
+        var that = this,
+            html = [];
+
+        html.push(sprintf('<div class="columns columns-%s btn-group pull-%s" role="group">', this.options.buttonsAlign, this.options.buttonsAlign));
+        html.push(sprintf('<button class="btn btn-default%s' + '" type="button" name="advancedSearch" aria-label="advanced search" title="%s">', that.options.iconSize === undefined ? '' : ' btn-' + that.options.iconSize, that.options.formatAdvancedSearch()));
+        html.push(sprintf('<i class="%s %s"></i>', that.options.iconsPrefix, that.options.icons.advancedSearchIcon))
+        html.push('</button></div>');
+
+        that.$toolbar.prepend(html.join(''));
+
+        that.$toolbar.find('button[name="advancedSearch"]')
+            .off('click').on('click', function() {
+                showAvdSearch(that.columns, that.options.formatAdvancedSearch(), that.options.formatAdvancedCloseButton(), that);
+            });
+    };
+
+    BootstrapTable.prototype.load = function(data) {
+        _load.apply(this, Array.prototype.slice.apply(arguments));
+
+        if (!this.options.advancedSearch) {
+            return;
+        }
+
+        if (typeof this.options.idTable === 'undefined') {
+            return;
+        } else {
+            if (!firstLoad) {
+                var height = parseInt($(".bootstrap-table").height());
+                height += 10;
+                $("#" + this.options.idTable).bootstrapTable("resetView", {height: height});
+                firstLoad = true;
+            }
+        }
+    };
+
+    BootstrapTable.prototype.initSearch = function () {
+        _initSearch.apply(this, Array.prototype.slice.apply(arguments));
+
+        if (!this.options.advancedSearch) {
+            return;
+        }
+
+        var that = this;
+        var fp = $.isEmptyObject(this.filterColumnsPartial) ? null : this.filterColumnsPartial;
+
+        this.data = fp ? $.grep(this.data, function (item, i) {
+            for (var key in fp) {
+                var fval = fp[key].toLowerCase();
+                var value = item[key];
+                value = $.fn.bootstrapTable.utils.calculateObjectValue(that.header,
+                    that.header.formatters[$.inArray(key, that.header.fields)],
+                    [value, item, i], value);
+
+                if (!($.inArray(key, that.header.fields) !== -1 &&
+                    (typeof value === 'string' || typeof value === 'number') &&
+                    (value + '').toLowerCase().indexOf(fval) !== -1)) {
+                    return false;
+                }
+            }
+            return true;
+        }) : this.data;
+    };
+
+    BootstrapTable.prototype.onColumnAdvancedSearch = function (event) {
+        var text = $.trim($(event.currentTarget).val());
+        var $field = $(event.currentTarget)[0].id;
+
+        if ($.isEmptyObject(this.filterColumnsPartial)) {
+            this.filterColumnsPartial = {};
+        }
+        if (text) {
+            this.filterColumnsPartial[$field] = text;
+        } else {
+            delete this.filterColumnsPartial[$field];
+        }
+
+        this.options.pageNumber = 1;
+        this.onSearch(event);
+        this.updatePagination();
+        this.trigger('column-advanced-search', $field, text);
+    };
+}(jQuery);

+ 313 - 0
static/lib/bootstrap-table/bootstrap-table.css

@@ -0,0 +1,313 @@
+/**
+ * @author zhixin wen <wenzhixin2010@gmail.com>
+ * version: 1.11.1
+ * https://github.com/wenzhixin/bootstrap-table/
+ */
+
+.bootstrap-table .table {
+    margin-bottom: 0 !important;
+    border-bottom: 1px solid #dddddd;
+    border-collapse: collapse !important;
+    border-radius: 1px;
+}
+
+.bootstrap-table .table:not(.table-condensed),
+.bootstrap-table .table:not(.table-condensed) > tbody > tr > th,
+.bootstrap-table .table:not(.table-condensed) > tfoot > tr > th,
+.bootstrap-table .table:not(.table-condensed) > thead > tr > td,
+.bootstrap-table .table:not(.table-condensed) > tbody > tr > td,
+.bootstrap-table .table:not(.table-condensed) > tfoot > tr > td {
+    padding: 8px;
+}
+
+.bootstrap-table .table.table-no-bordered > thead > tr > th,
+.bootstrap-table .table.table-no-bordered > tbody > tr > td {
+    border-right: 2px solid transparent;
+}
+
+.bootstrap-table .table.table-no-bordered > tbody > tr > td:last-child {
+    border-right: none;
+}
+
+.fixed-table-container {
+    position: relative;
+    clear: both;
+    border: 1px solid #dddddd;
+    border-radius: 4px;
+    -webkit-border-radius: 4px;
+    -moz-border-radius: 4px;
+}
+
+.fixed-table-container.table-no-bordered {
+    border: 1px solid transparent;
+}
+
+.fixed-table-footer,
+.fixed-table-header {
+    overflow: hidden;
+}
+
+.fixed-table-footer {
+    border-top: 1px solid #dddddd;
+}
+
+.fixed-table-body {
+    overflow-x: auto;
+    overflow-y: auto;
+    height: 100%;
+}
+
+.fixed-table-container table {
+    width: 100%;
+}
+
+.fixed-table-container thead th {
+    height: 0;
+    padding: 0;
+    margin: 0;
+    border-left: 1px solid #dddddd;
+}
+
+.fixed-table-container thead th:focus {
+    outline: 0 solid transparent;
+}
+
+.fixed-table-container thead th:first-child {
+    border-left: none;
+    border-top-left-radius: 4px;
+    -webkit-border-top-left-radius: 4px;
+    -moz-border-radius-topleft: 4px;
+}
+
+.fixed-table-container thead th .th-inner,
+.fixed-table-container tbody td .th-inner {
+    padding: 8px;
+    line-height: 24px;
+    vertical-align: top;
+    overflow: hidden;
+    text-overflow: ellipsis;
+    white-space: nowrap;
+}
+
+.fixed-table-container thead th .sortable {
+    cursor: pointer;
+    background-position: right;
+    background-repeat: no-repeat;
+    padding-right: 30px;
+}
+
+.fixed-table-container thead th .both {
+    background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABMAAAATCAQAAADYWf5HAAAAkElEQVQoz7X QMQ5AQBCF4dWQSJxC5wwax1Cq1e7BAdxD5SL+Tq/QCM1oNiJidwox0355mXnG/DrEtIQ6azioNZQxI0ykPhTQIwhCR+BmBYtlK7kLJYwWCcJA9M4qdrZrd8pPjZWPtOqdRQy320YSV17OatFC4euts6z39GYMKRPCTKY9UnPQ6P+GtMRfGtPnBCiqhAeJPmkqAAAAAElFTkSuQmCC');
+}
+
+.fixed-table-container thead th .asc {
+    background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABMAAAATCAYAAAByUDbMAAAAZ0lEQVQ4y2NgGLKgquEuFxBPAGI2ahhWCsS/gDibUoO0gPgxEP8H4ttArEyuQYxAPBdqEAxPBImTY5gjEL9DM+wTENuQahAvEO9DMwiGdwAxOymGJQLxTyD+jgWDxCMZRsEoGAVoAADeemwtPcZI2wAAAABJRU5ErkJggg==');
+}
+
+.fixed-table-container thead th .desc {
+    background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABMAAAATCAYAAAByUDbMAAAAZUlEQVQ4y2NgGAWjYBSggaqGu5FA/BOIv2PBIPFEUgxjB+IdQPwfC94HxLykus4GiD+hGfQOiB3J8SojEE9EM2wuSJzcsFMG4ttQgx4DsRalkZENxL+AuJQaMcsGxBOAmGvopk8AVz1sLZgg0bsAAAAASUVORK5CYII= ');
+}
+
+.fixed-table-container th.detail {
+    width: 30px;
+}
+
+.fixed-table-container tbody td {
+    border-left: 1px solid #dddddd;
+}
+
+.fixed-table-container tbody tr:first-child td {
+    border-top: none;
+}
+
+.fixed-table-container tbody td:first-child {
+    border-left: none;
+}
+
+/* the same color with .active */
+.fixed-table-container tbody .selected td {
+    background-color: #f5f5f5;
+}
+
+.fixed-table-container .bs-checkbox {
+    text-align: center;
+}
+
+.fixed-table-container .bs-checkbox .th-inner {
+    padding: 8px 0;
+}
+
+.fixed-table-container input[type="radio"],
+.fixed-table-container input[type="checkbox"] {
+    margin: 0 auto !important;
+}
+
+.fixed-table-container .no-records-found {
+    text-align: center;
+}
+
+.fixed-table-pagination div.pagination,
+.fixed-table-pagination .pagination-detail {
+    margin-top: 10px;
+    margin-bottom: 10px;
+}
+
+.fixed-table-pagination div.pagination .pagination {
+    margin: 0;
+}
+
+.fixed-table-pagination .pagination a {
+    padding: 6px 12px;
+    line-height: 1.428571429;
+}
+
+.fixed-table-pagination .pagination-info {
+    line-height: 34px;
+    margin-right: 5px;
+}
+
+.fixed-table-pagination .btn-group {
+    position: relative;
+    display: inline-block;
+    vertical-align: middle;
+}
+
+.fixed-table-pagination .dropup .dropdown-menu {
+    margin-bottom: 0;
+}
+
+.fixed-table-pagination .page-list {
+    display: inline-block;
+}
+
+.fixed-table-toolbar .columns-left {
+    margin-right: 5px;
+}
+
+.fixed-table-toolbar .columns-right {
+    margin-left: 5px;
+}
+
+.fixed-table-toolbar .columns label {
+    display: block;
+    padding: 3px 20px;
+    clear: both;
+    font-weight: normal;
+    line-height: 1.428571429;
+}
+
+.fixed-table-toolbar .bs-bars,
+.fixed-table-toolbar .search,
+.fixed-table-toolbar .columns {
+    position: relative;
+    margin-top: 10px;
+    margin-bottom: 10px;
+    line-height: 34px;
+}
+
+.fixed-table-pagination li.disabled a {
+    pointer-events: none;
+    cursor: default;
+}
+
+.fixed-table-loading {
+    display: none;
+    position: absolute;
+    top: 42px;
+    right: 0;
+    bottom: 0;
+    left: 0;
+    z-index: 99;
+    background-color: #fff;
+    text-align: center;
+}
+
+.fixed-table-body .card-view .title {
+    font-weight: bold;
+    display: inline-block;
+    min-width: 30%;
+    text-align: left !important;
+}
+
+/* support bootstrap 2 */
+.fixed-table-body thead th .th-inner {
+    box-sizing: border-box;
+}
+
+.table th, .table td {
+    vertical-align: middle;
+    box-sizing: border-box;
+}
+
+.fixed-table-toolbar .dropdown-menu {
+    text-align: left;
+    max-height: 300px;
+    overflow: auto;
+}
+
+.fixed-table-toolbar .btn-group > .btn-group {
+    display: inline-block;
+    margin-left: -1px !important;
+}
+
+.fixed-table-toolbar .btn-group > .btn-group > .btn {
+    border-radius: 0;
+}
+
+.fixed-table-toolbar .btn-group > .btn-group:first-child > .btn {
+    border-top-left-radius: 4px;
+    border-bottom-left-radius: 4px;
+}
+
+.fixed-table-toolbar .btn-group > .btn-group:last-child > .btn {
+    border-top-right-radius: 4px;
+    border-bottom-right-radius: 4px;
+}
+
+.bootstrap-table .table > thead > tr > th {
+    vertical-align: bottom;
+    border-bottom: 1px solid #ddd;
+}
+
+/* support bootstrap 3 */
+.bootstrap-table .table thead > tr > th {
+    padding: 0;
+    margin: 0;
+}
+
+.bootstrap-table .fixed-table-footer tbody > tr > td {
+    padding: 0 !important;
+}
+
+.bootstrap-table .fixed-table-footer .table {
+    border-bottom: none;
+    border-radius: 0;
+    padding: 0 !important;
+}
+
+.bootstrap-table .pull-right .dropdown-menu {
+    right: 0;
+    left: auto;
+}
+
+/* calculate scrollbar width */
+p.fixed-table-scroll-inner {
+    width: 100%;
+    height: 200px;
+}
+
+div.fixed-table-scroll-outer {
+    top: 0;
+    left: 0;
+    visibility: hidden;
+    width: 200px;
+    height: 150px;
+    overflow: hidden;
+}
+
+/* for get correct heights  */
+.fixed-table-toolbar:after, .fixed-table-pagination:after {
+    content: "";
+    display: block;
+    clear: both;
+}

+ 3094 - 0
static/lib/bootstrap-table/bootstrap-table.js

@@ -0,0 +1,3094 @@
+/**
+ * @author zhixin wen <wenzhixin2010@gmail.com>
+ * version: 1.11.1
+ * https://github.com/wenzhixin/bootstrap-table/
+ */
+
+(function ($) {
+    'use strict';
+
+    // TOOLS DEFINITION
+    // ======================
+
+    var cachedWidth = null;
+
+    // it only does '%s', and return '' when arguments are undefined
+    var sprintf = function (str) {
+        var args = arguments,
+            flag = true,
+            i = 1;
+
+        str = str.replace(/%s/g, function () {
+            var arg = args[i++];
+
+            if (typeof arg === 'undefined') {
+                flag = false;
+                return '';
+            }
+            return arg;
+        });
+        return flag ? str : '';
+    };
+
+    var getPropertyFromOther = function (list, from, to, value) {
+        var result = '';
+        $.each(list, function (i, item) {
+            if (item[from] === value) {
+                result = item[to];
+                return false;
+            }
+            return true;
+        });
+        return result;
+    };
+
+    var getFieldIndex = function (columns, field) {
+        var index = -1;
+
+        $.each(columns, function (i, column) {
+            if (column.field === field) {
+                index = i;
+                return false;
+            }
+            return true;
+        });
+        return index;
+    };
+
+    // http://jsfiddle.net/wenyi/47nz7ez9/3/
+    var setFieldIndex = function (columns) {
+        var i, j, k,
+            totalCol = 0,
+            flag = [];
+
+        for (i = 0; i < columns[0].length; i++) {
+            totalCol += columns[0][i].colspan || 1;
+        }
+
+        for (i = 0; i < columns.length; i++) {
+            flag[i] = [];
+            for (j = 0; j < totalCol; j++) {
+                flag[i][j] = false;
+            }
+        }
+
+        for (i = 0; i < columns.length; i++) {
+            for (j = 0; j < columns[i].length; j++) {
+                var r = columns[i][j],
+                    rowspan = r.rowspan || 1,
+                    colspan = r.colspan || 1,
+                    index = $.inArray(false, flag[i]);
+
+                if (colspan === 1) {
+                    r.fieldIndex = index;
+                    // when field is undefined, use index instead
+                    if (typeof r.field === 'undefined') {
+                        r.field = index;
+                    }
+                }
+
+                for (k = 0; k < rowspan; k++) {
+                    flag[i + k][index] = true;
+                }
+                for (k = 0; k < colspan; k++) {
+                    flag[i][index + k] = true;
+                }
+            }
+        }
+    };
+
+    var getScrollBarWidth = function () {
+        if (cachedWidth === null) {
+            var inner = $('<p/>').addClass('fixed-table-scroll-inner'),
+                outer = $('<div/>').addClass('fixed-table-scroll-outer'),
+                w1, w2;
+
+            outer.append(inner);
+            $('body').append(outer);
+
+            w1 = inner[0].offsetWidth;
+            outer.css('overflow', 'scroll');
+            w2 = inner[0].offsetWidth;
+
+            if (w1 === w2) {
+                w2 = outer[0].clientWidth;
+            }
+
+            outer.remove();
+            cachedWidth = w1 - w2;
+        }
+        return cachedWidth;
+    };
+
+    var calculateObjectValue = function (self, name, args, defaultValue) {
+        var func = name;
+
+        if (typeof name === 'string') {
+            // support obj.func1.func2
+            var names = name.split('.');
+
+            if (names.length > 1) {
+                func = window;
+                $.each(names, function (i, f) {
+                    func = func[f];
+                });
+            } else {
+                func = window[name];
+            }
+        }
+        if (typeof func === 'object') {
+            return func;
+        }
+        if (typeof func === 'function') {
+            return func.apply(self, args || []);
+        }
+        if (!func && typeof name === 'string' && sprintf.apply(this, [name].concat(args))) {
+            return sprintf.apply(this, [name].concat(args));
+        }
+        return defaultValue;
+    };
+
+    var compareObjects = function (objectA, objectB, compareLength) {
+        // Create arrays of property names
+        var objectAProperties = Object.getOwnPropertyNames(objectA),
+            objectBProperties = Object.getOwnPropertyNames(objectB),
+            propName = '';
+
+        if (compareLength) {
+            // If number of properties is different, objects are not equivalent
+            if (objectAProperties.length !== objectBProperties.length) {
+                return false;
+            }
+        }
+
+        for (var i = 0; i < objectAProperties.length; i++) {
+            propName = objectAProperties[i];
+
+            // If the property is not in the object B properties, continue with the next property
+            if ($.inArray(propName, objectBProperties) > -1) {
+                // If values of same property are not equal, objects are not equivalent
+                if (objectA[propName] !== objectB[propName]) {
+                    return false;
+                }
+            }
+        }
+
+        // If we made it this far, objects are considered equivalent
+        return true;
+    };
+
+    var escapeHTML = function (text) {
+        if (typeof text === 'string') {
+            return text
+                .replace(/&/g, '&amp;')
+                .replace(/</g, '&lt;')
+                .replace(/>/g, '&gt;')
+                .replace(/"/g, '&quot;')
+                .replace(/'/g, '&#039;')
+                .replace(/`/g, '&#x60;');
+        }
+        return text;
+    };
+
+    var getRealDataAttr = function (dataAttr) {
+        for (var attr in dataAttr) {
+            var auxAttr = attr.split(/(?=[A-Z])/).join('-').toLowerCase();
+            if (auxAttr !== attr) {
+                dataAttr[auxAttr] = dataAttr[attr];
+                delete dataAttr[attr];
+            }
+        }
+
+        return dataAttr;
+    };
+
+    var getItemField = function (item, field, escape) {
+        var value = item;
+
+        if (typeof field !== 'string' || item.hasOwnProperty(field)) {
+            return escape ? escapeHTML(item[field]) : item[field];
+        }
+        var props = field.split('.');
+        for (var p in props) {
+            if (props.hasOwnProperty(p)) {
+                value = value && value[props[p]];
+            }
+        }
+        return escape ? escapeHTML(value) : value;
+    };
+
+    var isIEBrowser = function () {
+        return !!(navigator.userAgent.indexOf("MSIE ") > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./));
+    };
+
+    var objectKeys = function () {
+        // From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
+        if (!Object.keys) {
+            Object.keys = (function() {
+                var hasOwnProperty = Object.prototype.hasOwnProperty,
+                    hasDontEnumBug = !({ toString: null }).propertyIsEnumerable('toString'),
+                    dontEnums = [
+                        'toString',
+                        'toLocaleString',
+                        'valueOf',
+                        'hasOwnProperty',
+                        'isPrototypeOf',
+                        'propertyIsEnumerable',
+                        'constructor'
+                    ],
+                    dontEnumsLength = dontEnums.length;
+
+                return function(obj) {
+                    if (typeof obj !== 'object' && (typeof obj !== 'function' || obj === null)) {
+                        throw new TypeError('Object.keys called on non-object');
+                    }
+
+                    var result = [], prop, i;
+
+                    for (prop in obj) {
+                        if (hasOwnProperty.call(obj, prop)) {
+                            result.push(prop);
+                        }
+                    }
+
+                    if (hasDontEnumBug) {
+                        for (i = 0; i < dontEnumsLength; i++) {
+                            if (hasOwnProperty.call(obj, dontEnums[i])) {
+                                result.push(dontEnums[i]);
+                            }
+                        }
+                    }
+                    return result;
+                };
+            }());
+        }
+    };
+
+    // BOOTSTRAP TABLE CLASS DEFINITION
+    // ======================
+
+    var BootstrapTable = function (el, options) {
+        this.options = options;
+        this.$el = $(el);
+        this.$el_ = this.$el.clone();
+        this.timeoutId_ = 0;
+        this.timeoutFooter_ = 0;
+
+        this.init();
+    };
+
+    BootstrapTable.DEFAULTS = {
+        classes: 'table table-hover',
+        sortClass: undefined,
+        locale: undefined,
+        height: undefined,
+        undefinedText: '-',
+        sortName: undefined,
+        sortOrder: 'asc',
+        sortStable: false,
+        striped: false,
+        columns: [[]],
+        data: [],
+        totalField: 'total',
+        dataField: 'rows',
+        method: 'get',
+        url: undefined,
+        ajax: undefined,
+        cache: true,
+        contentType: 'application/json',
+        dataType: 'json',
+        ajaxOptions: {},
+        queryParams: function (params) {
+            return params;
+        },
+        queryParamsType: 'limit', // undefined
+        responseHandler: function (res) {
+            return res;
+        },
+        pagination: false,
+        onlyInfoPagination: false,
+        paginationLoop: true,
+        sidePagination: 'client', // client or server
+        totalRows: 0, // server side need to set
+        pageNumber: 1,
+        pageSize: 10,
+        pageList: [10, 25, 50, 100],
+        paginationHAlign: 'right', //right, left
+        paginationVAlign: 'bottom', //bottom, top, both
+        paginationDetailHAlign: 'left', //right, left
+        paginationPreText: '&lsaquo;',
+        paginationNextText: '&rsaquo;',
+        search: false,
+        searchOnEnterKey: false,
+        strictSearch: false,
+        searchAlign: 'right',
+        selectItemName: 'btSelectItem',
+        showHeader: true,
+        showFooter: false,
+        showColumns: false,
+        showPaginationSwitch: false,
+        showRefresh: false,
+        showToggle: false,
+        buttonsAlign: 'right',
+        smartDisplay: true,
+        escape: false,
+        minimumCountColumns: 1,
+        idField: undefined,
+        uniqueId: undefined,
+        cardView: false,
+        detailView: false,
+        detailFormatter: function (index, row) {
+            return '';
+        },
+        trimOnSearch: true,
+        clickToSelect: false,
+        singleSelect: false,
+        toolbar: undefined,
+        toolbarAlign: 'left',
+        checkboxHeader: true,
+        sortable: true,
+        silentSort: true,
+        maintainSelected: false,
+        searchTimeOut: 500,
+        searchText: '',
+        iconSize: undefined,
+        buttonsClass: 'default',
+        iconsPrefix: 'glyphicon', // glyphicon of fa (font awesome)
+        icons: {
+            paginationSwitchDown: 'glyphicon-collapse-down icon-chevron-down',
+            paginationSwitchUp: 'glyphicon-collapse-up icon-chevron-up',
+            refresh: 'glyphicon-refresh icon-refresh',
+            toggle: 'glyphicon-list-alt icon-list-alt',
+            columns: 'glyphicon-th icon-th',
+            detailOpen: 'glyphicon-plus icon-plus',
+            detailClose: 'glyphicon-minus icon-minus'
+        },
+
+        customSearch: $.noop,
+
+        customSort: $.noop,
+
+        rowStyle: function (row, index) {
+            return {};
+        },
+
+        rowAttributes: function (row, index) {
+            return {};
+        },
+
+        footerStyle: function (row, index) {
+            return {};
+        },
+
+        onAll: function (name, args) {
+            return false;
+        },
+        onClickCell: function (field, value, row, $element) {
+            return false;
+        },
+        onDblClickCell: function (field, value, row, $element) {
+            return false;
+        },
+        onClickRow: function (item, $element) {
+            return false;
+        },
+        onDblClickRow: function (item, $element) {
+            return false;
+        },
+        onSort: function (name, order) {
+            return false;
+        },
+        onCheck: function (row) {
+            return false;
+        },
+        onUncheck: function (row) {
+            return false;
+        },
+        onCheckAll: function (rows) {
+            return false;
+        },
+        onUncheckAll: function (rows) {
+            return false;
+        },
+        onCheckSome: function (rows) {
+            return false;
+        },
+        onUncheckSome: function (rows) {
+            return false;
+        },
+        onLoadSuccess: function (data) {
+            return false;
+        },
+        onLoadError: function (status) {
+            return false;
+        },
+        onColumnSwitch: function (field, checked) {
+            return false;
+        },
+        onPageChange: function (number, size) {
+            return false;
+        },
+        onSearch: function (text) {
+            return false;
+        },
+        onToggle: function (cardView) {
+            return false;
+        },
+        onPreBody: function (data) {
+            return false;
+        },
+        onPostBody: function () {
+            return false;
+        },
+        onPostHeader: function () {
+            return false;
+        },
+        onExpandRow: function (index, row, $detail) {
+            return false;
+        },
+        onCollapseRow: function (index, row) {
+            return false;
+        },
+        onRefreshOptions: function (options) {
+            return false;
+        },
+        onRefresh: function (params) {
+          return false;
+        },
+        onResetView: function () {
+            return false;
+        }
+    };
+
+    BootstrapTable.LOCALES = {};
+
+    BootstrapTable.LOCALES['en-US'] = BootstrapTable.LOCALES.en = {
+        formatLoadingMessage: function () {
+            return 'Loading, please wait...';
+        },
+        formatRecordsPerPage: function (pageNumber) {
+            return sprintf('%s rows per page', pageNumber);
+        },
+        formatShowingRows: function (pageFrom, pageTo, totalRows) {
+            return sprintf('Showing %s to %s of %s rows', pageFrom, pageTo, totalRows);
+        },
+        formatDetailPagination: function (totalRows) {
+            return sprintf('Showing %s rows', totalRows);
+        },
+        formatSearch: function () {
+            return 'Search';
+        },
+        formatNoMatches: function () {
+            return 'No matching records found';
+        },
+        formatPaginationSwitch: function () {
+            return 'Hide/Show pagination';
+        },
+        formatRefresh: function () {
+            return 'Refresh';
+        },
+        formatToggle: function () {
+            return 'Toggle';
+        },
+        formatColumns: function () {
+            return 'Columns';
+        },
+        formatAllRows: function () {
+            return 'All';
+        }
+    };
+
+    $.extend(BootstrapTable.DEFAULTS, BootstrapTable.LOCALES['en-US']);
+
+    BootstrapTable.COLUMN_DEFAULTS = {
+        radio: false,
+        checkbox: false,
+        checkboxEnabled: true,
+        field: undefined,
+        title: undefined,
+        titleTooltip: undefined,
+        'class': undefined,
+        align: undefined, // left, right, center
+        halign: undefined, // left, right, center
+        falign: undefined, // left, right, center
+        valign: undefined, // top, middle, bottom
+        width: undefined,
+        sortable: false,
+        order: 'asc', // asc, desc
+        visible: true,
+        switchable: true,
+        clickToSelect: true,
+        formatter: undefined,
+        footerFormatter: undefined,
+        events: undefined,
+        sorter: undefined,
+        sortName: undefined,
+        cellStyle: undefined,
+        searchable: true,
+        searchFormatter: true,
+        cardVisible: true,
+        escape : false
+    };
+
+    BootstrapTable.EVENTS = {
+        'all.bs.table': 'onAll',
+        'click-cell.bs.table': 'onClickCell',
+        'dbl-click-cell.bs.table': 'onDblClickCell',
+        'click-row.bs.table': 'onClickRow',
+        'dbl-click-row.bs.table': 'onDblClickRow',
+        'sort.bs.table': 'onSort',
+        'check.bs.table': 'onCheck',
+        'uncheck.bs.table': 'onUncheck',
+        'check-all.bs.table': 'onCheckAll',
+        'uncheck-all.bs.table': 'onUncheckAll',
+        'check-some.bs.table': 'onCheckSome',
+        'uncheck-some.bs.table': 'onUncheckSome',
+        'load-success.bs.table': 'onLoadSuccess',
+        'load-error.bs.table': 'onLoadError',
+        'column-switch.bs.table': 'onColumnSwitch',
+        'page-change.bs.table': 'onPageChange',
+        'search.bs.table': 'onSearch',
+        'toggle.bs.table': 'onToggle',
+        'pre-body.bs.table': 'onPreBody',
+        'post-body.bs.table': 'onPostBody',
+        'post-header.bs.table': 'onPostHeader',
+        'expand-row.bs.table': 'onExpandRow',
+        'collapse-row.bs.table': 'onCollapseRow',
+        'refresh-options.bs.table': 'onRefreshOptions',
+        'reset-view.bs.table': 'onResetView',
+        'refresh.bs.table': 'onRefresh'
+    };
+
+    BootstrapTable.prototype.init = function () {
+        this.initLocale();
+        this.initContainer();
+        this.initTable();
+        this.initHeader();
+        this.initData();
+        this.initHiddenRows();
+        this.initFooter();
+        this.initToolbar();
+        this.initPagination();
+        this.initBody();
+        this.initSearchText();
+        this.initServer();
+    };
+
+    BootstrapTable.prototype.initLocale = function () {
+        if (this.options.locale) {
+            var parts = this.options.locale.split(/-|_/);
+            parts[0].toLowerCase();
+            if (parts[1]) parts[1].toUpperCase();
+            if ($.fn.bootstrapTable.locales[this.options.locale]) {
+                // locale as requested
+                $.extend(this.options, $.fn.bootstrapTable.locales[this.options.locale]);
+            } else if ($.fn.bootstrapTable.locales[parts.join('-')]) {
+                // locale with sep set to - (in case original was specified with _)
+                $.extend(this.options, $.fn.bootstrapTable.locales[parts.join('-')]);
+            } else if ($.fn.bootstrapTable.locales[parts[0]]) {
+                // short locale language code (i.e. 'en')
+                $.extend(this.options, $.fn.bootstrapTable.locales[parts[0]]);
+            }
+        }
+    };
+
+    BootstrapTable.prototype.initContainer = function () {
+        this.$container = $([
+            '<div class="bootstrap-table">',
+            '<div class="fixed-table-toolbar"></div>',
+            this.options.paginationVAlign === 'top' || this.options.paginationVAlign === 'both' ?
+                '<div class="fixed-table-pagination" style="clear: both;"></div>' :
+                '',
+            '<div class="fixed-table-container">',
+            '<div class="fixed-table-header"><table></table></div>',
+            '<div class="fixed-table-body">',
+            '<div class="fixed-table-loading">',
+            this.options.formatLoadingMessage(),
+            '</div>',
+            '</div>',
+            '<div class="fixed-table-footer"><table><tr></tr></table></div>',
+            this.options.paginationVAlign === 'bottom' || this.options.paginationVAlign === 'both' ?
+                '<div class="fixed-table-pagination"></div>' :
+                '',
+            '</div>',
+            '</div>'
+        ].join(''));
+
+        this.$container.insertAfter(this.$el);
+        this.$tableContainer = this.$container.find('.fixed-table-container');
+        this.$tableHeader = this.$container.find('.fixed-table-header');
+        this.$tableBody = this.$container.find('.fixed-table-body');
+        this.$tableLoading = this.$container.find('.fixed-table-loading');
+        this.$tableFooter = this.$container.find('.fixed-table-footer');
+        this.$toolbar = this.$container.find('.fixed-table-toolbar');
+        this.$pagination = this.$container.find('.fixed-table-pagination');
+
+        this.$tableBody.append(this.$el);
+        this.$container.after('<div class="clearfix"></div>');
+
+        this.$el.addClass(this.options.classes);
+        if (this.options.striped) {
+            this.$el.addClass('table-striped');
+        }
+        if ($.inArray('table-no-bordered', this.options.classes.split(' ')) !== -1) {
+            this.$tableContainer.addClass('table-no-bordered');
+        }
+    };
+
+    BootstrapTable.prototype.initTable = function () {
+        var that = this,
+            columns = [],
+            data = [];
+
+        this.$header = this.$el.find('>thead');
+        if (!this.$header.length) {
+            this.$header = $('<thead></thead>').appendTo(this.$el);
+        }
+        this.$header.find('tr').each(function () {
+            var column = [];
+
+            $(this).find('th').each(function () {
+                // Fix #2014 - getFieldIndex and elsewhere assume this is string, causes issues if not
+                if (typeof $(this).data('field') !== 'undefined') {
+                    $(this).data('field', $(this).data('field') + '');
+                }
+                column.push($.extend({}, {
+                    title: $(this).html(),
+                    'class': $(this).attr('class'),
+                    titleTooltip: $(this).attr('title'),
+                    rowspan: $(this).attr('rowspan') ? +$(this).attr('rowspan') : undefined,
+                    colspan: $(this).attr('colspan') ? +$(this).attr('colspan') : undefined
+                }, $(this).data()));
+            });
+            columns.push(column);
+        });
+        if (!$.isArray(this.options.columns[0])) {
+            this.options.columns = [this.options.columns];
+        }
+        this.options.columns = $.extend(true, [], columns, this.options.columns);
+        this.columns = [];
+
+        setFieldIndex(this.options.columns);
+        $.each(this.options.columns, function (i, columns) {
+            $.each(columns, function (j, column) {
+                column = $.extend({}, BootstrapTable.COLUMN_DEFAULTS, column);
+
+                if (typeof column.fieldIndex !== 'undefined') {
+                    that.columns[column.fieldIndex] = column;
+                }
+
+                that.options.columns[i][j] = column;
+            });
+        });
+
+        // if options.data is setting, do not process tbody data
+        if (this.options.data.length) {
+            return;
+        }
+
+        var m = [];
+        this.$el.find('>tbody>tr').each(function (y) {
+            var row = {};
+
+            // save tr's id, class and data-* attributes
+            row._id = $(this).attr('id');
+            row._class = $(this).attr('class');
+            row._data = getRealDataAttr($(this).data());
+
+            $(this).find('>td').each(function (x) {
+                var $this = $(this),
+                    cspan = +$this.attr('colspan') || 1,
+                    rspan = +$this.attr('rowspan') || 1,
+                    tx, ty;
+
+                for (; m[y] && m[y][x]; x++); //skip already occupied cells in current row
+
+                for (tx = x; tx < x + cspan; tx++) { //mark matrix elements occupied by current cell with true
+                    for (ty = y; ty < y + rspan; ty++) {
+                        if (!m[ty]) { //fill missing rows
+                            m[ty] = [];
+                        }
+                        m[ty][tx] = true;
+                    }
+                }
+
+                var field = that.columns[x].field;
+
+                row[field] = $(this).html();
+                // save td's id, class and data-* attributes
+                row['_' + field + '_id'] = $(this).attr('id');
+                row['_' + field + '_class'] = $(this).attr('class');
+                row['_' + field + '_rowspan'] = $(this).attr('rowspan');
+                row['_' + field + '_colspan'] = $(this).attr('colspan');
+                row['_' + field + '_title'] = $(this).attr('title');
+                row['_' + field + '_data'] = getRealDataAttr($(this).data());
+            });
+            data.push(row);
+        });
+        this.options.data = data;
+        if (data.length) this.fromHtml = true;
+    };
+
+    BootstrapTable.prototype.initHeader = function () {
+        var that = this,
+            visibleColumns = {},
+            html = [];
+
+        this.header = {
+            fields: [],
+            styles: [],
+            classes: [],
+            formatters: [],
+            events: [],
+            sorters: [],
+            sortNames: [],
+            cellStyles: [],
+            searchables: []
+        };
+
+        $.each(this.options.columns, function (i, columns) {
+            html.push('<tr>');
+
+            if (i === 0 && !that.options.cardView && that.options.detailView) {
+                html.push(sprintf('<th class="detail" rowspan="%s"><div class="fht-cell"></div></th>',
+                    that.options.columns.length));
+            }
+
+            $.each(columns, function (j, column) {
+                var text = '',
+                    halign = '', // header align style
+                    align = '', // body align style
+                    style = '',
+                    class_ = sprintf(' class="%s"', column['class']),
+                    order = that.options.sortOrder || column.order,
+                    unitWidth = 'px',
+                    width = column.width;
+
+                if (column.width !== undefined && (!that.options.cardView)) {
+                    if (typeof column.width === 'string') {
+                        if (column.width.indexOf('%') !== -1) {
+                            unitWidth = '%';
+                        }
+                    }
+                }
+                if (column.width && typeof column.width === 'string') {
+                    width = column.width.replace('%', '').replace('px', '');
+                }
+
+                halign = sprintf('text-align: %s; ', column.halign ? column.halign : column.align);
+                align = sprintf('text-align: %s; ', column.align);
+                style = sprintf('vertical-align: %s; ', column.valign);
+                style += sprintf('width: %s; ', (column.checkbox || column.radio) && !width ?
+                    '36px' : (width ? width + unitWidth : undefined));
+
+                if (typeof column.fieldIndex !== 'undefined') {
+                    that.header.fields[column.fieldIndex] = column.field;
+                    that.header.styles[column.fieldIndex] = align + style;
+                    that.header.classes[column.fieldIndex] = class_;
+                    that.header.formatters[column.fieldIndex] = column.formatter;
+                    that.header.events[column.fieldIndex] = column.events;
+                    that.header.sorters[column.fieldIndex] = column.sorter;
+                    that.header.sortNames[column.fieldIndex] = column.sortName;
+                    that.header.cellStyles[column.fieldIndex] = column.cellStyle;
+                    that.header.searchables[column.fieldIndex] = column.searchable;
+
+                    if (!column.visible) {
+                        return;
+                    }
+
+                    if (that.options.cardView && (!column.cardVisible)) {
+                        return;
+                    }
+
+                    visibleColumns[column.field] = column;
+                }
+
+                html.push('<th' + sprintf(' title="%s"', column.titleTooltip),
+                    column.checkbox || column.radio ?
+                        sprintf(' class="bs-checkbox %s"', column['class'] || '') :
+                        class_,
+                    sprintf(' style="%s"', halign + style),
+                    sprintf(' rowspan="%s"', column.rowspan),
+                    sprintf(' colspan="%s"', column.colspan),
+                    sprintf(' data-field="%s"', column.field),
+                    '>');
+
+                html.push(sprintf('<div class="th-inner %s">', that.options.sortable && column.sortable ?
+                    'sortable both' : ''));
+
+                text = that.options.escape ? escapeHTML(column.title) : column.title;
+
+                if (column.checkbox) {
+                    if (!that.options.singleSelect && that.options.checkboxHeader) {
+                        text = '<input name="btSelectAll" type="checkbox" />';
+                    }
+                    that.header.stateField = column.field;
+                }
+                if (column.radio) {
+                    text = '';
+                    that.header.stateField = column.field;
+                    that.options.singleSelect = true;
+                }
+
+                html.push(text);
+                html.push('</div>');
+                html.push('<div class="fht-cell"></div>');
+                html.push('</div>');
+                html.push('</th>');
+            });
+            html.push('</tr>');
+        });
+
+        this.$header.html(html.join(''));
+        this.$header.find('th[data-field]').each(function (i) {
+            $(this).data(visibleColumns[$(this).data('field')]);
+        });
+        this.$container.off('click', '.th-inner').on('click', '.th-inner', function (event) {
+            var target = $(this);
+
+            if (that.options.detailView) {
+                if (target.closest('.bootstrap-table')[0] !== that.$container[0])
+                    return false;
+            }
+
+            if (that.options.sortable && target.parent().data().sortable) {
+                that.onSort(event);
+            }
+        });
+
+        this.$header.children().children().off('keypress').on('keypress', function (event) {
+            if (that.options.sortable && $(this).data().sortable) {
+                var code = event.keyCode || event.which;
+                if (code == 13) { //Enter keycode
+                    that.onSort(event);
+                }
+            }
+        });
+
+        $(window).off('resize.bootstrap-table');
+        if (!this.options.showHeader || this.options.cardView) {
+            this.$header.hide();
+            this.$tableHeader.hide();
+            this.$tableLoading.css('top', 0);
+        } else {
+            this.$header.show();
+            this.$tableHeader.show();
+            this.$tableLoading.css('top', this.$header.outerHeight() + 1);
+            // Assign the correct sortable arrow
+            this.getCaret();
+            $(window).on('resize.bootstrap-table', $.proxy(this.resetWidth, this));
+        }
+
+        this.$selectAll = this.$header.find('[name="btSelectAll"]');
+        this.$selectAll.off('click').on('click', function () {
+                var checked = $(this).prop('checked');
+                that[checked ? 'checkAll' : 'uncheckAll']();
+                that.updateSelected();
+            });
+    };
+
+    BootstrapTable.prototype.initFooter = function () {
+        if (!this.options.showFooter || this.options.cardView) {
+            this.$tableFooter.hide();
+        } else {
+            this.$tableFooter.show();
+        }
+    };
+
+    /**
+     * @param data
+     * @param type: append / prepend
+     */
+    BootstrapTable.prototype.initData = function (data, type) {
+        if (type === 'append') {
+            this.data = this.data.concat(data);
+        } else if (type === 'prepend') {
+            this.data = [].concat(data).concat(this.data);
+        } else {
+            this.data = data || this.options.data;
+        }
+
+        // Fix #839 Records deleted when adding new row on filtered table
+        if (type === 'append') {
+            this.options.data = this.options.data.concat(data);
+        } else if (type === 'prepend') {
+            this.options.data = [].concat(data).concat(this.options.data);
+        } else {
+            this.options.data = this.data;
+        }
+
+        if (this.options.sidePagination === 'server') {
+            return;
+        }
+        this.initSort();
+    };
+
+    BootstrapTable.prototype.initSort = function () {
+        var that = this,
+            name = this.options.sortName,
+            order = this.options.sortOrder === 'desc' ? -1 : 1,
+            index = $.inArray(this.options.sortName, this.header.fields),
+            timeoutId = 0;
+
+        if (this.options.customSort !== $.noop) {
+            this.options.customSort.apply(this, [this.options.sortName, this.options.sortOrder]);
+            return;
+        }
+
+        if (index !== -1) {
+            if (this.options.sortStable) {
+                $.each(this.data, function (i, row) {
+                    if (!row.hasOwnProperty('_position')) row._position = i;
+                });
+            }
+
+            this.data.sort(function (a, b) {
+                if (that.header.sortNames[index]) {
+                    name = that.header.sortNames[index];
+                }
+                var aa = getItemField(a, name, that.options.escape),
+                    bb = getItemField(b, name, that.options.escape),
+                    value = calculateObjectValue(that.header, that.header.sorters[index], [aa, bb]);
+
+                if (value !== undefined) {
+                    return order * value;
+                }
+
+                // Fix #161: undefined or null string sort bug.
+                if (aa === undefined || aa === null) {
+                    aa = '';
+                }
+                if (bb === undefined || bb === null) {
+                    bb = '';
+                }
+
+                if (that.options.sortStable && aa === bb) {
+                    aa = a._position;
+                    bb = b._position;
+                }
+
+                // IF both values are numeric, do a numeric comparison
+                if ($.isNumeric(aa) && $.isNumeric(bb)) {
+                    // Convert numerical values form string to float.
+                    aa = parseFloat(aa);
+                    bb = parseFloat(bb);
+                    if (aa < bb) {
+                        return order * -1;
+                    }
+                    return order;
+                }
+
+                if (aa === bb) {
+                    return 0;
+                }
+
+                // If value is not a string, convert to string
+                if (typeof aa !== 'string') {
+                    aa = aa.toString();
+                }
+
+                if (aa.localeCompare(bb) === -1) {
+                    return order * -1;
+                }
+
+                return order;
+            });
+
+            if (this.options.sortClass !== undefined) {
+                clearTimeout(timeoutId);
+                timeoutId = setTimeout(function () {
+                    that.$el.removeClass(that.options.sortClass);
+                    var index = that.$header.find(sprintf('[data-field="%s"]',
+                        that.options.sortName).index() + 1);
+                    that.$el.find(sprintf('tr td:nth-child(%s)', index))
+                        .addClass(that.options.sortClass);
+                }, 250);
+            }
+        }
+    };
+
+    BootstrapTable.prototype.onSort = function (event) {
+        var $this = event.type === "keypress" ? $(event.currentTarget) : $(event.currentTarget).parent(),
+            $this_ = this.$header.find('th').eq($this.index());
+
+        this.$header.add(this.$header_).find('span.order').remove();
+
+        if (this.options.sortName === $this.data('field')) {
+            this.options.sortOrder = this.options.sortOrder === 'asc' ? 'desc' : 'asc';
+        } else {
+            this.options.sortName = $this.data('field');
+            this.options.sortOrder = $this.data('order') === 'asc' ? 'desc' : 'asc';
+        }
+        this.trigger('sort', this.options.sortName, this.options.sortOrder);
+
+        $this.add($this_).data('order', this.options.sortOrder);
+
+        // Assign the correct sortable arrow
+        this.getCaret();
+
+        if (this.options.sidePagination === 'server') {
+            this.initServer(this.options.silentSort);
+            return;
+        }
+
+        this.initSort();
+        this.initBody();
+    };
+
+    BootstrapTable.prototype.initToolbar = function () {
+        var that = this,
+            html = [],
+            timeoutId = 0,
+            $keepOpen,
+            $search,
+            switchableCount = 0;
+
+        if (this.$toolbar.find('.bs-bars').children().length) {
+            $('body').append($(this.options.toolbar));
+        }
+        this.$toolbar.html('');
+
+        if (typeof this.options.toolbar === 'string' || typeof this.options.toolbar === 'object') {
+            $(sprintf('<div class="bs-bars pull-%s"></div>', this.options.toolbarAlign))
+                .appendTo(this.$toolbar)
+                .append($(this.options.toolbar));
+        }
+
+        // showColumns, showToggle, showRefresh
+        html = [sprintf('<div class="columns columns-%s btn-group pull-%s">',
+            this.options.buttonsAlign, this.options.buttonsAlign)];
+
+        if (typeof this.options.icons === 'string') {
+            this.options.icons = calculateObjectValue(null, this.options.icons);
+        }
+
+        if (this.options.showPaginationSwitch) {
+            html.push(sprintf('<button class="btn' +
+                    sprintf(' btn-%s', this.options.buttonsClass) +
+                    sprintf(' btn-%s', this.options.iconSize) +
+                    '" type="button" name="paginationSwitch" aria-label="pagination Switch" title="%s">',
+                    this.options.formatPaginationSwitch()),
+                sprintf('<i class="%s %s"></i>', this.options.iconsPrefix, this.options.icons.paginationSwitchDown),
+                '</button>');
+        }
+
+        if (this.options.showRefresh) {
+            html.push(sprintf('<button class="btn' +
+                    sprintf(' btn-%s', this.options.buttonsClass) +
+                    sprintf(' btn-%s', this.options.iconSize) +
+                    '" type="button" name="refresh" aria-label="refresh" title="%s">',
+                    this.options.formatRefresh()),
+                sprintf('<i class="%s %s"></i>', this.options.iconsPrefix, this.options.icons.refresh),
+                '</button>');
+        }
+
+        if (this.options.showToggle) {
+            html.push(sprintf('<button class="btn' +
+                    sprintf(' btn-%s', this.options.buttonsClass) +
+                    sprintf(' btn-%s', this.options.iconSize) +
+                    '" type="button" name="toggle" aria-label="toggle" title="%s">',
+                    this.options.formatToggle()),
+                sprintf('<i class="%s %s"></i>', this.options.iconsPrefix, this.options.icons.toggle),
+                '</button>');
+        }
+
+        if (this.options.showColumns) {
+            html.push(sprintf('<div class="keep-open btn-group" title="%s">',
+                    this.options.formatColumns()),
+                '<button type="button" aria-label="columns" class="btn' +
+                sprintf(' btn-%s', this.options.buttonsClass) +
+                sprintf(' btn-%s', this.options.iconSize) +
+                ' dropdown-toggle" data-toggle="dropdown">',
+                sprintf('<i class="%s %s"></i>', this.options.iconsPrefix, this.options.icons.columns),
+                ' <span class="caret"></span>',
+                '</button>',
+                '<ul class="dropdown-menu" role="menu">');
+
+            $.each(this.columns, function (i, column) {
+                if (column.radio || column.checkbox) {
+                    return;
+                }
+
+                if (that.options.cardView && !column.cardVisible) {
+                    return;
+                }
+
+                var checked = column.visible ? ' checked="checked"' : '';
+
+                if (column.switchable) {
+                    html.push(sprintf('<li role="menuitem">' +
+                        '<label><input type="checkbox" data-field="%s" value="%s"%s> %s</label>' +
+                        '</li>', column.field, i, checked, column.title));
+                    switchableCount++;
+                }
+            });
+            html.push('</ul>',
+                '</div>');
+        }
+
+        html.push('</div>');
+
+        // Fix #188: this.showToolbar is for extensions
+        if (this.showToolbar || html.length > 2) {
+            this.$toolbar.append(html.join(''));
+        }
+
+        if (this.options.showPaginationSwitch) {
+            this.$toolbar.find('button[name="paginationSwitch"]')
+                .off('click').on('click', $.proxy(this.togglePagination, this));
+        }
+
+        if (this.options.showRefresh) {
+            this.$toolbar.find('button[name="refresh"]')
+                .off('click').on('click', $.proxy(this.refresh, this));
+        }
+
+        if (this.options.showToggle) {
+            this.$toolbar.find('button[name="toggle"]')
+                .off('click').on('click', function () {
+                    that.toggleView();
+                });
+        }
+
+        if (this.options.showColumns) {
+            $keepOpen = this.$toolbar.find('.keep-open');
+
+            if (switchableCount <= this.options.minimumCountColumns) {
+                $keepOpen.find('input').prop('disabled', true);
+            }
+
+            $keepOpen.find('li').off('click').on('click', function (event) {
+                event.stopImmediatePropagation();
+            });
+            $keepOpen.find('input').off('click').on('click', function () {
+                var $this = $(this);
+
+                that.toggleColumn($(this).val(), $this.prop('checked'), false);
+                that.trigger('column-switch', $(this).data('field'), $this.prop('checked'));
+            });
+        }
+
+        if (this.options.search) {
+            html = [];
+            html.push(
+                '<div class="pull-' + this.options.searchAlign + ' search">',
+                sprintf('<input class="form-control' +
+                    sprintf(' input-%s', this.options.iconSize) +
+                    '" type="text" placeholder="%s">',
+                    this.options.formatSearch()),
+                '</div>');
+
+            this.$toolbar.append(html.join(''));
+            $search = this.$toolbar.find('.search input');
+            $search.off('keyup drop blur').on('keyup drop blur', function (event) {
+                if (that.options.searchOnEnterKey && event.keyCode !== 13) {
+                    return;
+                }
+
+                if ($.inArray(event.keyCode, [37, 38, 39, 40]) > -1) {
+                    return;
+                }
+
+                clearTimeout(timeoutId); // doesn't matter if it's 0
+                timeoutId = setTimeout(function () {
+                    that.onSearch(event);
+                }, that.options.searchTimeOut);
+            });
+
+            if (isIEBrowser()) {
+                $search.off('mouseup').on('mouseup', function (event) {
+                    clearTimeout(timeoutId); // doesn't matter if it's 0
+                    timeoutId = setTimeout(function () {
+                        that.onSearch(event);
+                    }, that.options.searchTimeOut);
+                });
+            }
+        }
+    };
+
+    BootstrapTable.prototype.onSearch = function (event) {
+        var text = $.trim($(event.currentTarget).val());
+
+        // trim search input
+        if (this.options.trimOnSearch && $(event.currentTarget).val() !== text) {
+            $(event.currentTarget).val(text);
+        }
+
+        if (text === this.searchText) {
+            return;
+        }
+        this.searchText = text;
+        this.options.searchText = text;
+
+        this.options.pageNumber = 1;
+        this.initSearch();
+        this.updatePagination();
+        this.trigger('search', text);
+    };
+
+    BootstrapTable.prototype.initSearch = function () {
+        var that = this;
+
+        if (this.options.sidePagination !== 'server') {
+            if (this.options.customSearch !== $.noop) {
+                this.options.customSearch.apply(this, [this.searchText]);
+                return;
+            }
+
+            var s = this.searchText && (this.options.escape ?
+                escapeHTML(this.searchText) : this.searchText).toLowerCase();
+            var f = $.isEmptyObject(this.filterColumns) ? null : this.filterColumns;
+
+            // Check filter
+            this.data = f ? $.grep(this.options.data, function (item, i) {
+                for (var key in f) {
+                    if ($.isArray(f[key]) && $.inArray(item[key], f[key]) === -1 ||
+                            !$.isArray(f[key]) && item[key] !== f[key]) {
+                        return false;
+                    }
+                }
+                return true;
+            }) : this.options.data;
+
+            this.data = s ? $.grep(this.data, function (item, i) {
+                for (var j = 0; j < that.header.fields.length; j++) {
+
+                    if (!that.header.searchables[j]) {
+                        continue;
+                    }
+
+                    var key = $.isNumeric(that.header.fields[j]) ? parseInt(that.header.fields[j], 10) : that.header.fields[j];
+                    var column = that.columns[getFieldIndex(that.columns, key)];
+                    var value;
+
+                    if (typeof key === 'string') {
+                        value = item;
+                        var props = key.split('.');
+                        for (var prop_index = 0; prop_index < props.length; prop_index++) {
+                            value = value[props[prop_index]];
+                        }
+
+                        // Fix #142: respect searchForamtter boolean
+                        if (column && column.searchFormatter) {
+                            value = calculateObjectValue(column,
+                                that.header.formatters[j], [value, item, i], value);
+                        }
+                    } else {
+                        value = item[key];
+                    }
+
+                    if (typeof value === 'string' || typeof value === 'number') {
+                        if (that.options.strictSearch) {
+                            if ((value + '').toLowerCase() === s) {
+                                return true;
+                            }
+                        } else {
+                            if ((value + '').toLowerCase().indexOf(s) !== -1) {
+                                return true;
+                            }
+                        }
+                    }
+                }
+                return false;
+            }) : this.data;
+        }
+    };
+
+    BootstrapTable.prototype.initPagination = function () {
+        if (!this.options.pagination) {
+            this.$pagination.hide();
+            return;
+        } else {
+            this.$pagination.show();
+        }
+
+        var that = this,
+            html = [],
+            $allSelected = false,
+            i, from, to,
+            $pageList,
+            $first, $pre,
+            $next, $last,
+            $number,
+            data = this.getData(),
+            pageList = this.options.pageList;
+
+        if (this.options.sidePagination !== 'server') {
+            this.options.totalRows = data.length;
+        }
+
+        this.totalPages = 0;
+        if (this.options.totalRows) {
+            if (this.options.pageSize === this.options.formatAllRows()) {
+                this.options.pageSize = this.options.totalRows;
+                $allSelected = true;
+            } else if (this.options.pageSize === this.options.totalRows) {
+                // Fix #667 Table with pagination,
+                // multiple pages and a search that matches to one page throws exception
+                var pageLst = typeof this.options.pageList === 'string' ?
+                    this.options.pageList.replace('[', '').replace(']', '')
+                        .replace(/ /g, '').toLowerCase().split(',') : this.options.pageList;
+                if ($.inArray(this.options.formatAllRows().toLowerCase(), pageLst)  > -1) {
+                    $allSelected = true;
+                }
+            }
+
+            this.totalPages = ~~((this.options.totalRows - 1) / this.options.pageSize) + 1;
+
+            this.options.totalPages = this.totalPages;
+        }
+        if (this.totalPages > 0 && this.options.pageNumber > this.totalPages) {
+            this.options.pageNumber = this.totalPages;
+        }
+
+        this.pageFrom = (this.options.pageNumber - 1) * this.options.pageSize + 1;
+        this.pageTo = this.options.pageNumber * this.options.pageSize;
+        if (this.pageTo > this.options.totalRows) {
+            this.pageTo = this.options.totalRows;
+        }
+
+        html.push(
+            '<div class="pull-' + this.options.paginationDetailHAlign + ' pagination-detail">',
+            '<span class="pagination-info">',
+            this.options.onlyInfoPagination ? this.options.formatDetailPagination(this.options.totalRows) :
+            this.options.formatShowingRows(this.pageFrom, this.pageTo, this.options.totalRows),
+            '</span>');
+
+        if (!this.options.onlyInfoPagination) {
+            html.push('<span class="page-list">');
+
+            var pageNumber = [
+                    sprintf('<span class="btn-group %s">',
+                        this.options.paginationVAlign === 'top' || this.options.paginationVAlign === 'both' ?
+                            'dropdown' : 'dropup'),
+                    '<button type="button" class="btn' +
+                    sprintf(' btn-%s', this.options.buttonsClass) +
+                    sprintf(' btn-%s', this.options.iconSize) +
+                    ' dropdown-toggle" data-toggle="dropdown">',
+                    '<span class="page-size">',
+                    $allSelected ? this.options.formatAllRows() : this.options.pageSize,
+                    '</span>',
+                    ' <span class="caret"></span>',
+                    '</button>',
+                    '<ul class="dropdown-menu" role="menu">'
+                ];
+
+            if (typeof this.options.pageList === 'string') {
+                var list = this.options.pageList.replace('[', '').replace(']', '')
+                    .replace(/ /g, '').split(',');
+
+                pageList = [];
+                $.each(list, function (i, value) {
+                    pageList.push(value.toUpperCase() === that.options.formatAllRows().toUpperCase() ?
+                        that.options.formatAllRows() : +value);
+                });
+            }
+
+            $.each(pageList, function (i, page) {
+                if (!that.options.smartDisplay || i === 0 || pageList[i - 1] < that.options.totalRows) {
+                    var active;
+                    if ($allSelected) {
+                        active = page === that.options.formatAllRows() ? ' class="active"' : '';
+                    } else {
+                        active = page === that.options.pageSize ? ' class="active"' : '';
+                    }
+                    pageNumber.push(sprintf('<li role="menuitem"%s><a href="#">%s</a></li>', active, page));
+                }
+            });
+            pageNumber.push('</ul></span>');
+
+            html.push(this.options.formatRecordsPerPage(pageNumber.join('')));
+            html.push('</span>');
+
+            html.push('</div>',
+                '<div class="pull-' + this.options.paginationHAlign + ' pagination">',
+                '<ul class="pagination' + sprintf(' pagination-%s', this.options.iconSize) + '">',
+                '<li class="page-pre"><a href="#">' + this.options.paginationPreText + '</a></li>');
+
+            if (this.totalPages < 5) {
+                from = 1;
+                to = this.totalPages;
+            } else {
+                from = this.options.pageNumber - 2;
+                to = from + 4;
+                if (from < 1) {
+                    from = 1;
+                    to = 5;
+                }
+                if (to > this.totalPages) {
+                    to = this.totalPages;
+                    from = to - 4;
+                }
+            }
+
+            if (this.totalPages >= 6) {
+                if (this.options.pageNumber >= 3) {
+                    html.push('<li class="page-first' + (1 === this.options.pageNumber ? ' active' : '') + '">',
+                        '<a href="#">', 1, '</a>',
+                        '</li>');
+
+                    from++;
+                }
+
+                if (this.options.pageNumber >= 4) {
+                    if (this.options.pageNumber == 4 || this.totalPages == 6 || this.totalPages == 7) {
+                        from--;
+                    } else {
+                        html.push('<li class="page-first-separator disabled">',
+                            '<a href="#">...</a>',
+                            '</li>');
+                    }
+
+                    to--;
+                }
+            }
+
+            if (this.totalPages >= 7) {
+                if (this.options.pageNumber >= (this.totalPages - 2)) {
+                    from--;
+                }
+            }
+
+            if (this.totalPages == 6) {
+                if (this.options.pageNumber >= (this.totalPages - 2)) {
+                    to++;
+                }
+            } else if (this.totalPages >= 7) {
+                if (this.totalPages == 7 || this.options.pageNumber >= (this.totalPages - 3)) {
+                    to++;
+                }
+            }
+
+            for (i = from; i <= to; i++) {
+                html.push('<li class="page-number' + (i === this.options.pageNumber ? ' active' : '') + '">',
+                    '<a href="#">', i, '</a>',
+                    '</li>');
+            }
+
+            if (this.totalPages >= 8) {
+                if (this.options.pageNumber <= (this.totalPages - 4)) {
+                    html.push('<li class="page-last-separator disabled">',
+                        '<a href="#">...</a>',
+                        '</li>');
+                }
+            }
+
+            if (this.totalPages >= 6) {
+                if (this.options.pageNumber <= (this.totalPages - 3)) {
+                    html.push('<li class="page-last' + (this.totalPages === this.options.pageNumber ? ' active' : '') + '">',
+                        '<a href="#">', this.totalPages, '</a>',
+                        '</li>');
+                }
+            }
+
+            html.push(
+                '<li class="page-next"><a href="#">' + this.options.paginationNextText + '</a></li>',
+                '</ul>',
+                '</div>');
+        }
+        this.$pagination.html(html.join(''));
+
+        if (!this.options.onlyInfoPagination) {
+            $pageList = this.$pagination.find('.page-list a');
+            $first = this.$pagination.find('.page-first');
+            $pre = this.$pagination.find('.page-pre');
+            $next = this.$pagination.find('.page-next');
+            $last = this.$pagination.find('.page-last');
+            $number = this.$pagination.find('.page-number');
+
+            if (this.options.smartDisplay) {
+                if (this.totalPages <= 1) {
+                    this.$pagination.find('div.pagination').hide();
+                }
+                if (pageList.length < 2 || this.options.totalRows <= pageList[0]) {
+                    this.$pagination.find('span.page-list').hide();
+                }
+
+                // when data is empty, hide the pagination
+                this.$pagination[this.getData().length ? 'show' : 'hide']();
+            }
+
+            if (!this.options.paginationLoop) {
+                if (this.options.pageNumber === 1) {
+                    $pre.addClass('disabled');
+                }
+                if (this.options.pageNumber === this.totalPages) {
+                    $next.addClass('disabled');
+                }
+            }
+
+            if ($allSelected) {
+                this.options.pageSize = this.options.formatAllRows();
+            }
+            $pageList.off('click').on('click', $.proxy(this.onPageListChange, this));
+            $first.off('click').on('click', $.proxy(this.onPageFirst, this));
+            $pre.off('click').on('click', $.proxy(this.onPagePre, this));
+            $next.off('click').on('click', $.proxy(this.onPageNext, this));
+            $last.off('click').on('click', $.proxy(this.onPageLast, this));
+            $number.off('click').on('click', $.proxy(this.onPageNumber, this));
+        }
+    };
+
+    BootstrapTable.prototype.updatePagination = function (event) {
+        // Fix #171: IE disabled button can be clicked bug.
+        if (event && $(event.currentTarget).hasClass('disabled')) {
+            return;
+        }
+
+        if (!this.options.maintainSelected) {
+            this.resetRows();
+        }
+
+        this.initPagination();
+        if (this.options.sidePagination === 'server') {
+            this.initServer();
+        } else {
+            this.initBody();
+        }
+
+        this.trigger('page-change', this.options.pageNumber, this.options.pageSize);
+    };
+
+    BootstrapTable.prototype.onPageListChange = function (event) {
+        var $this = $(event.currentTarget);
+
+        $this.parent().addClass('active').siblings().removeClass('active');
+        this.options.pageSize = $this.text().toUpperCase() === this.options.formatAllRows().toUpperCase() ?
+            this.options.formatAllRows() : +$this.text();
+        this.$toolbar.find('.page-size').text(this.options.pageSize);
+
+        this.updatePagination(event);
+        return false;
+    };
+
+    BootstrapTable.prototype.onPageFirst = function (event) {
+        this.options.pageNumber = 1;
+        this.updatePagination(event);
+        return false;
+    };
+
+    BootstrapTable.prototype.onPagePre = function (event) {
+        if ((this.options.pageNumber - 1) === 0) {
+            this.options.pageNumber = this.options.totalPages;
+        } else {
+            this.options.pageNumber--;
+        }
+        this.updatePagination(event);
+        return false;
+    };
+
+    BootstrapTable.prototype.onPageNext = function (event) {
+        if ((this.options.pageNumber + 1) > this.options.totalPages) {
+            this.options.pageNumber = 1;
+        } else {
+            this.options.pageNumber++;
+        }
+        this.updatePagination(event);
+        return false;
+    };
+
+    BootstrapTable.prototype.onPageLast = function (event) {
+        this.options.pageNumber = this.totalPages;
+        this.updatePagination(event);
+        return false;
+    };
+
+    BootstrapTable.prototype.onPageNumber = function (event) {
+        if (this.options.pageNumber === +$(event.currentTarget).text()) {
+            return;
+        }
+        this.options.pageNumber = +$(event.currentTarget).text();
+        this.updatePagination(event);
+        return false;
+    };
+
+    BootstrapTable.prototype.initRow = function(item, i, data, parentDom) {
+        var that=this,
+            key,
+            html = [],
+            style = {},
+            csses = [],
+            data_ = '',
+            attributes = {},
+            htmlAttributes = [];
+
+        if ($.inArray(item, this.hiddenRows) > -1) {
+            return;
+        }
+
+        style = calculateObjectValue(this.options, this.options.rowStyle, [item, i], style);
+
+        if (style && style.css) {
+            for (key in style.css) {
+                csses.push(key + ': ' + style.css[key]);
+            }
+        }
+
+        attributes = calculateObjectValue(this.options,
+            this.options.rowAttributes, [item, i], attributes);
+
+        if (attributes) {
+            for (key in attributes) {
+                htmlAttributes.push(sprintf('%s="%s"', key, escapeHTML(attributes[key])));
+            }
+        }
+
+        if (item._data && !$.isEmptyObject(item._data)) {
+            $.each(item._data, function(k, v) {
+                // ignore data-index
+                if (k === 'index') {
+                    return;
+                }
+                data_ += sprintf(' data-%s="%s"', k, v);
+            });
+        }
+
+        html.push('<tr',
+            sprintf(' %s', htmlAttributes.join(' ')),
+            sprintf(' id="%s"', $.isArray(item) ? undefined : item._id),
+            sprintf(' class="%s"', style.classes || ($.isArray(item) ? undefined : item._class)),
+            sprintf(' data-index="%s"', i),
+            sprintf(' data-uniqueid="%s"', item[this.options.uniqueId]),
+            sprintf('%s', data_),
+            '>'
+        );
+
+        if (this.options.cardView) {
+            html.push(sprintf('<td colspan="%s"><div class="card-views">', this.header.fields.length));
+        }
+
+        if (!this.options.cardView && this.options.detailView) {
+            html.push('<td>',
+                '<a class="detail-icon" href="#">',
+                sprintf('<i class="%s %s"></i>', this.options.iconsPrefix, this.options.icons.detailOpen),
+                '</a>',
+                '</td>');
+        }
+
+        $.each(this.header.fields, function(j, field) {
+            var text = '',
+                value_ = getItemField(item, field, that.options.escape),
+                value = '',
+                type = '',
+                cellStyle = {},
+                id_ = '',
+                class_ = that.header.classes[j],
+                data_ = '',
+                rowspan_ = '',
+                colspan_ = '',
+                title_ = '',
+                column = that.columns[j];
+
+            if (that.fromHtml && typeof value_ === 'undefined') {
+                return;
+            }
+
+            if (!column.visible) {
+                return;
+            }
+
+            if (that.options.cardView && (!column.cardVisible)) {
+                return;
+            }
+
+            if (column.escape) {
+                value_ = escapeHTML(value_);
+            }
+
+            style = sprintf('style="%s"', csses.concat(that.header.styles[j]).join('; '));
+
+            // handle td's id and class
+            if (item['_' + field + '_id']) {
+                id_ = sprintf(' id="%s"', item['_' + field + '_id']);
+            }
+            if (item['_' + field + '_class']) {
+                class_ = sprintf(' class="%s"', item['_' + field + '_class']);
+            }
+            if (item['_' + field + '_rowspan']) {
+                rowspan_ = sprintf(' rowspan="%s"', item['_' + field + '_rowspan']);
+            }
+            if (item['_' + field + '_colspan']) {
+                colspan_ = sprintf(' colspan="%s"', item['_' + field + '_colspan']);
+            }
+            if (item['_' + field + '_title']) {
+                title_ = sprintf(' title="%s"', item['_' + field + '_title']);
+            }
+            cellStyle = calculateObjectValue(that.header,
+                that.header.cellStyles[j], [value_, item, i, field], cellStyle);
+            if (cellStyle.classes) {
+                class_ = sprintf(' class="%s"', cellStyle.classes);
+            }
+            if (cellStyle.css) {
+                var csses_ = [];
+                for (var key in cellStyle.css) {
+                    csses_.push(key + ': ' + cellStyle.css[key]);
+                }
+                style = sprintf('style="%s"', csses_.concat(that.header.styles[j]).join('; '));
+            }
+
+            value = calculateObjectValue(column,
+                that.header.formatters[j], [value_, item, i], value_);
+
+            if (item['_' + field + '_data'] && !$.isEmptyObject(item['_' + field + '_data'])) {
+                $.each(item['_' + field + '_data'], function(k, v) {
+                    // ignore data-index
+                    if (k === 'index') {
+                        return;
+                    }
+                    data_ += sprintf(' data-%s="%s"', k, v);
+                });
+            }
+
+            if (column.checkbox || column.radio) {
+                type = column.checkbox ? 'checkbox' : type;
+                type = column.radio ? 'radio' : type;
+
+                text = [sprintf(that.options.cardView ?
+                        '<div class="card-view %s">' : '<td class="bs-checkbox %s">', column['class'] || ''),
+                    '<input' +
+                    sprintf(' data-index="%s"', i) +
+                    sprintf(' name="%s"', that.options.selectItemName) +
+                    sprintf(' type="%s"', type) +
+                    sprintf(' value="%s"', item[that.options.idField]) +
+                    sprintf(' checked="%s"', value === true ||
+                        (value_ || value && value.checked) ? 'checked' : undefined) +
+                    sprintf(' disabled="%s"', !column.checkboxEnabled ||
+                        (value && value.disabled) ? 'disabled' : undefined) +
+                    ' />',
+                    that.header.formatters[j] && typeof value === 'string' ? value : '',
+                    that.options.cardView ? '</div>' : '</td>'
+                ].join('');
+
+                item[that.header.stateField] = value === true || (value && value.checked);
+            } else {
+                value = typeof value === 'undefined' || value === null ?
+                    that.options.undefinedText : value;
+
+                text = that.options.cardView ? ['<div class="card-view">',
+                    that.options.showHeader ? sprintf('<span class="title" %s>%s</span>', style,
+                        getPropertyFromOther(that.columns, 'field', 'title', field)) : '',
+                    sprintf('<span class="value">%s</span>', value),
+                    '</div>'
+                ].join('') : [sprintf('<td%s %s %s %s %s %s %s>',
+                        id_, class_, style, data_, rowspan_, colspan_, title_),
+                    value,
+                    '</td>'
+                ].join('');
+
+                // Hide empty data on Card view when smartDisplay is set to true.
+                if (that.options.cardView && that.options.smartDisplay && value === '') {
+                    // Should set a placeholder for event binding correct fieldIndex
+                    text = '<div class="card-view"></div>';
+                }
+            }
+
+            html.push(text);
+        });
+
+        if (this.options.cardView) {
+            html.push('</div></td>');
+        }
+        html.push('</tr>');
+
+        return html.join(' ');
+    };
+
+    BootstrapTable.prototype.initBody = function (fixedScroll) {
+        var that = this,
+            html = [],
+            data = this.getData();
+
+        this.trigger('pre-body', data);
+
+        this.$body = this.$el.find('>tbody');
+        if (!this.$body.length) {
+            this.$body = $('<tbody></tbody>').appendTo(this.$el);
+        }
+
+        //Fix #389 Bootstrap-table-flatJSON is not working
+
+        if (!this.options.pagination || this.options.sidePagination === 'server') {
+            this.pageFrom = 1;
+            this.pageTo = data.length;
+        }
+
+        var trFragments = $(document.createDocumentFragment());
+        var hasTr;
+
+        for (var i = this.pageFrom - 1; i < this.pageTo; i++) {
+            var item = data[i];
+            var tr = this.initRow(item, i, data, trFragments);
+            hasTr = hasTr || !!tr;
+            if (tr&&tr!==true) {
+                trFragments.append(tr);
+            }
+        }
+
+        // show no records
+        if (!hasTr) {
+            trFragments.append('<tr class="no-records-found">' +
+                sprintf('<td colspan="%s">%s</td>',
+                this.$header.find('th').length,
+                this.options.formatNoMatches()) +
+                '</tr>');
+        }
+
+        this.$body.html(trFragments);
+
+        if (!fixedScroll) {
+            this.scrollTo(0);
+        }
+
+        // click to select by column
+        this.$body.find('> tr[data-index] > td').off('click dblclick').on('click dblclick', function (e) {
+            var $td = $(this),
+                $tr = $td.parent(),
+                item = that.data[$tr.data('index')],
+                index = $td[0].cellIndex,
+                fields = that.getVisibleFields(),
+                field = fields[that.options.detailView && !that.options.cardView ? index - 1 : index],
+                column = that.columns[getFieldIndex(that.columns, field)],
+                value = getItemField(item, field, that.options.escape);
+
+            if ($td.find('.detail-icon').length) {
+                return;
+            }
+
+            that.trigger(e.type === 'click' ? 'click-cell' : 'dbl-click-cell', field, value, item, $td);
+            that.trigger(e.type === 'click' ? 'click-row' : 'dbl-click-row', item, $tr, field);
+
+            // if click to select - then trigger the checkbox/radio click
+            if (e.type === 'click' && that.options.clickToSelect && column.clickToSelect) {
+                var $selectItem = $tr.find(sprintf('[name="%s"]', that.options.selectItemName));
+                if ($selectItem.length) {
+                    $selectItem[0].click(); // #144: .trigger('click') bug
+                }
+            }
+        });
+
+        this.$body.find('> tr[data-index] > td > .detail-icon').off('click').on('click', function () {
+            var $this = $(this),
+                $tr = $this.parent().parent(),
+                index = $tr.data('index'),
+                row = data[index]; // Fix #980 Detail view, when searching, returns wrong row
+
+            // remove and update
+            if ($tr.next().is('tr.detail-view')) {
+                $this.find('i').attr('class', sprintf('%s %s', that.options.iconsPrefix, that.options.icons.detailOpen));
+                that.trigger('collapse-row', index, row);
+                $tr.next().remove();
+            } else {
+                $this.find('i').attr('class', sprintf('%s %s', that.options.iconsPrefix, that.options.icons.detailClose));
+                $tr.after(sprintf('<tr class="detail-view"><td colspan="%s"></td></tr>', $tr.find('td').length));
+                var $element = $tr.next().find('td');
+                var content = calculateObjectValue(that.options, that.options.detailFormatter, [index, row, $element], '');
+                if($element.length === 1) {
+                    $element.append(content);
+                }
+                that.trigger('expand-row', index, row, $element);
+            }
+            that.resetView();
+            return false;
+        });
+
+        this.$selectItem = this.$body.find(sprintf('[name="%s"]', this.options.selectItemName));
+        this.$selectItem.off('click').on('click', function (event) {
+            event.stopImmediatePropagation();
+
+            var $this = $(this),
+                checked = $this.prop('checked'),
+                row = that.data[$this.data('index')];
+
+            if (that.options.maintainSelected && $(this).is(':radio')) {
+                $.each(that.options.data, function (i, row) {
+                    row[that.header.stateField] = false;
+                });
+            }
+
+            row[that.header.stateField] = checked;
+
+            if (that.options.singleSelect) {
+                that.$selectItem.not(this).each(function () {
+                    that.data[$(this).data('index')][that.header.stateField] = false;
+                });
+                that.$selectItem.filter(':checked').not(this).prop('checked', false);
+            }
+
+            that.updateSelected();
+            that.trigger(checked ? 'check' : 'uncheck', row, $this);
+        });
+
+        $.each(this.header.events, function (i, events) {
+            if (!events) {
+                return;
+            }
+            // fix bug, if events is defined with namespace
+            if (typeof events === 'string') {
+                events = calculateObjectValue(null, events);
+            }
+
+            var field = that.header.fields[i],
+                fieldIndex = $.inArray(field, that.getVisibleFields());
+
+            if (that.options.detailView && !that.options.cardView) {
+                fieldIndex += 1;
+            }
+
+            for (var key in events) {
+                that.$body.find('>tr:not(.no-records-found)').each(function () {
+                    var $tr = $(this),
+                        $td = $tr.find(that.options.cardView ? '.card-view' : 'td').eq(fieldIndex),
+                        index = key.indexOf(' '),
+                        name = key.substring(0, index),
+                        el = key.substring(index + 1),
+                        func = events[key];
+
+                    $td.find(el).off(name).on(name, function (e) {
+                        var index = $tr.data('index'),
+                            row = that.data[index],
+                            value = row[field];
+
+                        func.apply(this, [e, value, row, index]);
+                    });
+                });
+            }
+        });
+
+        this.updateSelected();
+        this.resetView();
+
+        this.trigger('post-body', data);
+    };
+
+    BootstrapTable.prototype.initServer = function (silent, query, url) {
+        var that = this,
+            data = {},
+            params = {
+                searchText: this.searchText,
+                sortName: this.options.sortName,
+                sortOrder: this.options.sortOrder
+            },
+            request;
+
+        if (this.options.pagination) {
+            params.pageSize = this.options.pageSize === this.options.formatAllRows() ?
+                this.options.totalRows : this.options.pageSize;
+            params.pageNumber = this.options.pageNumber;
+        }
+
+        if (!(url || this.options.url) && !this.options.ajax) {
+            return;
+        }
+
+        if (this.options.queryParamsType === 'limit') {
+            params = {
+                search: params.searchText,
+                sort: params.sortName,
+                order: params.sortOrder
+            };
+
+            if (this.options.pagination) {
+                params.offset = this.options.pageSize === this.options.formatAllRows() ?
+                    0 : this.options.pageSize * (this.options.pageNumber - 1);
+                params.limit = this.options.pageSize === this.options.formatAllRows() ?
+                    this.options.totalRows : this.options.pageSize;
+            }
+        }
+
+        if (!($.isEmptyObject(this.filterColumnsPartial))) {
+            params.filter = JSON.stringify(this.filterColumnsPartial, null);
+        }
+
+        data = calculateObjectValue(this.options, this.options.queryParams, [params], data);
+
+        $.extend(data, query || {});
+
+        // false to stop request
+        if (data === false) {
+            return;
+        }
+
+        if (!silent) {
+            this.$tableLoading.show();
+        }
+        request = $.extend({}, calculateObjectValue(null, this.options.ajaxOptions), {
+            type: this.options.method,
+            url:  url || this.options.url,
+            data: this.options.contentType === 'application/json' && this.options.method === 'post' ?
+                JSON.stringify(data) : data,
+            cache: this.options.cache,
+            contentType: this.options.contentType,
+            dataType: this.options.dataType,
+            success: function (res) {
+                res = calculateObjectValue(that.options, that.options.responseHandler, [res], res);
+
+                that.load(res);
+                that.trigger('load-success', res);
+                if (!silent) that.$tableLoading.hide();
+            },
+            error: function (res) {
+                that.trigger('load-error', res.status, res);
+                if (!silent) that.$tableLoading.hide();
+            }
+        });
+
+        if (this.options.ajax) {
+            calculateObjectValue(this, this.options.ajax, [request], null);
+        } else {
+            if (this._xhr && this._xhr.readyState !== 4) {
+                this._xhr.abort();
+            }
+            this._xhr = $.ajax(request);
+        }
+    };
+
+    BootstrapTable.prototype.initSearchText = function () {
+        if (this.options.search) {
+            if (this.options.searchText !== '') {
+                var $search = this.$toolbar.find('.search input');
+                $search.val(this.options.searchText);
+                this.onSearch({currentTarget: $search});
+            }
+        }
+    };
+
+    BootstrapTable.prototype.getCaret = function () {
+        var that = this;
+
+        $.each(this.$header.find('th'), function (i, th) {
+            $(th).find('.sortable').removeClass('desc asc').addClass($(th).data('field') === that.options.sortName ? that.options.sortOrder : 'both');
+        });
+    };
+
+    BootstrapTable.prototype.updateSelected = function () {
+        var checkAll = this.$selectItem.filter(':enabled').length &&
+            this.$selectItem.filter(':enabled').length ===
+            this.$selectItem.filter(':enabled').filter(':checked').length;
+
+        this.$selectAll.add(this.$selectAll_).prop('checked', checkAll);
+
+        this.$selectItem.each(function () {
+            $(this).closest('tr')[$(this).prop('checked') ? 'addClass' : 'removeClass']('selected');
+        });
+    };
+
+    BootstrapTable.prototype.updateRows = function () {
+        var that = this;
+
+        this.$selectItem.each(function () {
+            that.data[$(this).data('index')][that.header.stateField] = $(this).prop('checked');
+        });
+    };
+
+    BootstrapTable.prototype.resetRows = function () {
+        var that = this;
+
+        $.each(this.data, function (i, row) {
+            that.$selectAll.prop('checked', false);
+            that.$selectItem.prop('checked', false);
+            if (that.header.stateField) {
+                row[that.header.stateField] = false;
+            }
+        });
+        this.initHiddenRows();
+    };
+
+    BootstrapTable.prototype.trigger = function (name) {
+        var args = Array.prototype.slice.call(arguments, 1);
+
+        name += '.bs.table';
+        this.options[BootstrapTable.EVENTS[name]].apply(this.options, args);
+        this.$el.trigger($.Event(name), args);
+
+        this.options.onAll(name, args);
+        this.$el.trigger($.Event('all.bs.table'), [name, args]);
+    };
+
+    BootstrapTable.prototype.resetHeader = function () {
+        // fix #61: the hidden table reset header bug.
+        // fix bug: get $el.css('width') error sometime (height = 500)
+        clearTimeout(this.timeoutId_);
+        this.timeoutId_ = setTimeout($.proxy(this.fitHeader, this), this.$el.is(':hidden') ? 100 : 0);
+    };
+
+    BootstrapTable.prototype.fitHeader = function () {
+        var that = this,
+            fixedBody,
+            scrollWidth,
+            focused,
+            focusedTemp;
+
+        if (that.$el.is(':hidden')) {
+            that.timeoutId_ = setTimeout($.proxy(that.fitHeader, that), 100);
+            return;
+        }
+        fixedBody = this.$tableBody.get(0);
+
+        scrollWidth = fixedBody.scrollWidth > fixedBody.clientWidth &&
+        fixedBody.scrollHeight > fixedBody.clientHeight + this.$header.outerHeight() ?
+            getScrollBarWidth() : 0;
+
+        this.$el.css('margin-top', -this.$header.outerHeight());
+
+        focused = $(':focus');
+        if (focused.length > 0) {
+            var $th = focused.parents('th');
+            if ($th.length > 0) {
+                var dataField = $th.attr('data-field');
+                if (dataField !== undefined) {
+                    var $headerTh = this.$header.find("[data-field='" + dataField + "']");
+                    if ($headerTh.length > 0) {
+                        $headerTh.find(":input").addClass("focus-temp");
+                    }
+                }
+            }
+        }
+
+        this.$header_ = this.$header.clone(true, true);
+        this.$selectAll_ = this.$header_.find('[name="btSelectAll"]');
+        this.$tableHeader.css({
+            'margin-right': scrollWidth
+        }).find('table').css('width', this.$el.outerWidth())
+            .html('').attr('class', this.$el.attr('class'))
+            .append(this.$header_);
+
+
+        focusedTemp = $('.focus-temp:visible:eq(0)');
+        if (focusedTemp.length > 0) {
+            focusedTemp.focus();
+            this.$header.find('.focus-temp').removeClass('focus-temp');
+        }
+
+        // fix bug: $.data() is not working as expected after $.append()
+        this.$header.find('th[data-field]').each(function (i) {
+            that.$header_.find(sprintf('th[data-field="%s"]', $(this).data('field'))).data($(this).data());
+        });
+
+        var visibleFields = this.getVisibleFields(),
+            $ths = this.$header_.find('th');
+
+        this.$body.find('>tr:first-child:not(.no-records-found) > *').each(function (i) {
+            var $this = $(this),
+                index = i;
+
+            if (that.options.detailView && !that.options.cardView) {
+                if (i === 0) {
+                    that.$header_.find('th.detail').find('.fht-cell').width($this.innerWidth());
+                }
+                index = i - 1;
+            }
+
+            var $th = that.$header_.find(sprintf('th[data-field="%s"]', visibleFields[index]));
+            if ($th.length > 1) {
+                $th = $($ths[$this[0].cellIndex]);
+            }
+
+            $th.find('.fht-cell').width($this.innerWidth());
+        });
+        // horizontal scroll event
+        // TODO: it's probably better improving the layout than binding to scroll event
+        this.$tableBody.off('scroll').on('scroll', function () {
+            that.$tableHeader.scrollLeft($(this).scrollLeft());
+
+            if (that.options.showFooter && !that.options.cardView) {
+                that.$tableFooter.scrollLeft($(this).scrollLeft());
+            }
+        });
+        that.trigger('post-header');
+    };
+
+    BootstrapTable.prototype.resetFooter = function () {
+        var that = this,
+            data = that.getData(),
+            html = [];
+
+        if (!this.options.showFooter || this.options.cardView) { //do nothing
+            return;
+        }
+
+        if (!this.options.cardView && this.options.detailView) {
+            html.push('<td><div class="th-inner">&nbsp;</div><div class="fht-cell"></div></td>');
+        }
+
+        $.each(this.columns, function (i, column) {
+            var key,
+                falign = '', // footer align style
+                valign = '',
+                csses = [],
+                style = {},
+                class_ = sprintf(' class="%s"', column['class']);
+
+            if (!column.visible) {
+                return;
+            }
+
+            if (that.options.cardView && (!column.cardVisible)) {
+                return;
+            }
+
+            falign = sprintf('text-align: %s; ', column.falign ? column.falign : column.align);
+            valign = sprintf('vertical-align: %s; ', column.valign);
+
+            style = calculateObjectValue(null, that.options.footerStyle);
+
+            if (style && style.css) {
+                for (key in style.css) {
+                    csses.push(key + ': ' + style.css[key]);
+                }
+            }
+
+            html.push('<td', class_, sprintf(' style="%s"', falign + valign + csses.concat().join('; ')), '>');
+            html.push('<div class="th-inner">');
+
+            html.push(calculateObjectValue(column, column.footerFormatter, [data], '&nbsp;') || '&nbsp;');
+
+            html.push('</div>');
+            html.push('<div class="fht-cell"></div>');
+            html.push('</div>');
+            html.push('</td>');
+        });
+
+        this.$tableFooter.find('tr').html(html.join(''));
+        this.$tableFooter.show();
+        clearTimeout(this.timeoutFooter_);
+        this.timeoutFooter_ = setTimeout($.proxy(this.fitFooter, this),
+            this.$el.is(':hidden') ? 100 : 0);
+    };
+
+    BootstrapTable.prototype.fitFooter = function () {
+        var that = this,
+            $footerTd,
+            elWidth,
+            scrollWidth;
+
+        clearTimeout(this.timeoutFooter_);
+        if (this.$el.is(':hidden')) {
+            this.timeoutFooter_ = setTimeout($.proxy(this.fitFooter, this), 100);
+            return;
+        }
+
+        elWidth = this.$el.css('width');
+        scrollWidth = elWidth > this.$tableBody.width() ? getScrollBarWidth() : 0;
+
+        this.$tableFooter.css({
+            'margin-right': scrollWidth
+        }).find('table').css('width', elWidth)
+            .attr('class', this.$el.attr('class'));
+
+        $footerTd = this.$tableFooter.find('td');
+
+        this.$body.find('>tr:first-child:not(.no-records-found) > *').each(function (i) {
+            var $this = $(this);
+
+            $footerTd.eq(i).find('.fht-cell').width($this.innerWidth());
+        });
+    };
+
+    BootstrapTable.prototype.toggleColumn = function (index, checked, needUpdate) {
+        if (index === -1) {
+            return;
+        }
+        this.columns[index].visible = checked;
+        this.initHeader();
+        this.initSearch();
+        this.initPagination();
+        this.initBody();
+
+        if (this.options.showColumns) {
+            var $items = this.$toolbar.find('.keep-open input').prop('disabled', false);
+
+            if (needUpdate) {
+                $items.filter(sprintf('[value="%s"]', index)).prop('checked', checked);
+            }
+
+            if ($items.filter(':checked').length <= this.options.minimumCountColumns) {
+                $items.filter(':checked').prop('disabled', true);
+            }
+        }
+    };
+
+    BootstrapTable.prototype.getVisibleFields = function () {
+        var that = this,
+            visibleFields = [];
+
+        $.each(this.header.fields, function (j, field) {
+            var column = that.columns[getFieldIndex(that.columns, field)];
+
+            if (!column.visible) {
+                return;
+            }
+            visibleFields.push(field);
+        });
+        return visibleFields;
+    };
+
+    // PUBLIC FUNCTION DEFINITION
+    // =======================
+
+    BootstrapTable.prototype.resetView = function (params) {
+        var padding = 0;
+
+        if (params && params.height) {
+            this.options.height = params.height;
+        }
+
+        this.$selectAll.prop('checked', this.$selectItem.length > 0 &&
+            this.$selectItem.length === this.$selectItem.filter(':checked').length);
+
+        if (this.options.height) {
+            var toolbarHeight = this.$toolbar.outerHeight(true),
+                paginationHeight = this.$pagination.outerHeight(true),
+                height = this.options.height - toolbarHeight - paginationHeight;
+
+            this.$tableContainer.css('height', height + 'px');
+        }
+
+        if (this.options.cardView) {
+            // remove the element css
+            this.$el.css('margin-top', '0');
+            this.$tableContainer.css('padding-bottom', '0');
+            this.$tableFooter.hide();
+            return;
+        }
+
+        if (this.options.showHeader && this.options.height) {
+            this.$tableHeader.show();
+            this.resetHeader();
+            padding += this.$header.outerHeight();
+        } else {
+            this.$tableHeader.hide();
+            this.trigger('post-header');
+        }
+
+        if (this.options.showFooter) {
+            this.resetFooter();
+            if (this.options.height) {
+                padding += this.$tableFooter.outerHeight() + 1;
+            }
+        }
+
+        // Assign the correct sortable arrow
+        this.getCaret();
+        this.$tableContainer.css('padding-bottom', padding + 'px');
+        this.trigger('reset-view');
+    };
+
+    BootstrapTable.prototype.getData = function (useCurrentPage) {
+        return (this.searchText || !$.isEmptyObject(this.filterColumns) || !$.isEmptyObject(this.filterColumnsPartial)) ?
+            (useCurrentPage ? this.data.slice(this.pageFrom - 1, this.pageTo) : this.data) :
+            (useCurrentPage ? this.options.data.slice(this.pageFrom - 1, this.pageTo) : this.options.data);
+    };
+
+    BootstrapTable.prototype.load = function (data) {
+        var fixedScroll = false;
+
+        // #431: support pagination
+        if (this.options.sidePagination === 'server') {
+            this.options.totalRows = data[this.options.totalField];
+            fixedScroll = data.fixedScroll;
+            data = data[this.options.dataField];
+        } else if (!$.isArray(data)) { // support fixedScroll
+            fixedScroll = data.fixedScroll;
+            data = data.data;
+        }
+
+        this.initData(data);
+        this.initSearch();
+        this.initPagination();
+        this.initBody(fixedScroll);
+    };
+
+    BootstrapTable.prototype.append = function (data) {
+        this.initData(data, 'append');
+        this.initSearch();
+        this.initPagination();
+        this.initSort();
+        this.initBody(true);
+    };
+
+    BootstrapTable.prototype.prepend = function (data) {
+        this.initData(data, 'prepend');
+        this.initSearch();
+        this.initPagination();
+        this.initSort();
+        this.initBody(true);
+    };
+
+    BootstrapTable.prototype.remove = function (params) {
+        var len = this.options.data.length,
+            i, row;
+
+        if (!params.hasOwnProperty('field') || !params.hasOwnProperty('values')) {
+            return;
+        }
+
+        for (i = len - 1; i >= 0; i--) {
+            row = this.options.data[i];
+
+            if (!row.hasOwnProperty(params.field)) {
+                continue;
+            }
+            if ($.inArray(row[params.field], params.values) !== -1) {
+                this.options.data.splice(i, 1);
+                if (this.options.sidePagination === 'server') {
+                    this.options.totalRows -= 1;
+                }
+            }
+        }
+
+        if (len === this.options.data.length) {
+            return;
+        }
+
+        this.initSearch();
+        this.initPagination();
+        this.initSort();
+        this.initBody(true);
+    };
+
+    BootstrapTable.prototype.removeAll = function () {
+        if (this.options.data.length > 0) {
+            this.options.data.splice(0, this.options.data.length);
+            this.initSearch();
+            this.initPagination();
+            this.initBody(true);
+        }
+    };
+
+    BootstrapTable.prototype.getRowByUniqueId = function (id) {
+        var uniqueId = this.options.uniqueId,
+            len = this.options.data.length,
+            dataRow = null,
+            i, row, rowUniqueId;
+
+        for (i = len - 1; i >= 0; i--) {
+            row = this.options.data[i];
+
+            if (row.hasOwnProperty(uniqueId)) { // uniqueId is a column
+                rowUniqueId = row[uniqueId];
+            } else if(row._data.hasOwnProperty(uniqueId)) { // uniqueId is a row data property
+                rowUniqueId = row._data[uniqueId];
+            } else {
+                continue;
+            }
+
+            if (typeof rowUniqueId === 'string') {
+                id = id.toString();
+            } else if (typeof rowUniqueId === 'number') {
+                if ((Number(rowUniqueId) === rowUniqueId) && (rowUniqueId % 1 === 0)) {
+                    id = parseInt(id);
+                } else if ((rowUniqueId === Number(rowUniqueId)) && (rowUniqueId !== 0)) {
+                    id = parseFloat(id);
+                }
+            }
+
+            if (rowUniqueId === id) {
+                dataRow = row;
+                break;
+            }
+        }
+
+        return dataRow;
+    };
+
+    BootstrapTable.prototype.removeByUniqueId = function (id) {
+        var len = this.options.data.length,
+            row = this.getRowByUniqueId(id);
+
+        if (row) {
+            this.options.data.splice(this.options.data.indexOf(row), 1);
+        }
+
+        if (len === this.options.data.length) {
+            return;
+        }
+
+        this.initSearch();
+        this.initPagination();
+        this.initBody(true);
+    };
+
+    BootstrapTable.prototype.updateByUniqueId = function (params) {
+        var that = this;
+        var allParams = $.isArray(params) ? params : [ params ];
+
+        $.each(allParams, function(i, params) {
+            var rowId;
+
+            if (!params.hasOwnProperty('id') || !params.hasOwnProperty('row')) {
+                return;
+            }
+
+            rowId = $.inArray(that.getRowByUniqueId(params.id), that.options.data);
+
+            if (rowId === -1) {
+                return;
+            }
+            $.extend(that.options.data[rowId], params.row);
+        });
+
+        this.initSearch();
+        this.initPagination();
+        this.initSort();
+        this.initBody(true);
+    };
+
+    BootstrapTable.prototype.insertRow = function (params) {
+        if (!params.hasOwnProperty('index') || !params.hasOwnProperty('row')) {
+            return;
+        }
+        this.data.splice(params.index, 0, params.row);
+        this.initSearch();
+        this.initPagination();
+        this.initSort();
+        this.initBody(true);
+    };
+
+    BootstrapTable.prototype.updateRow = function (params) {
+        var that = this;
+        var allParams = $.isArray(params) ? params : [ params ];
+
+        $.each(allParams, function(i, params) {
+            if (!params.hasOwnProperty('index') || !params.hasOwnProperty('row')) {
+                return;
+            }
+            $.extend(that.options.data[params.index], params.row);
+        });
+
+        this.initSearch();
+        this.initPagination();
+        this.initSort();
+        this.initBody(true);
+    };
+
+    BootstrapTable.prototype.initHiddenRows = function () {
+        this.hiddenRows = [];
+    };
+
+    BootstrapTable.prototype.showRow = function (params) {
+        this.toggleRow(params, true);
+    };
+
+    BootstrapTable.prototype.hideRow = function (params) {
+        this.toggleRow(params, false);
+    };
+
+    BootstrapTable.prototype.toggleRow = function (params, visible) {
+        var row, index;
+
+        if (params.hasOwnProperty('index')) {
+            row = this.getData()[params.index];
+        } else if (params.hasOwnProperty('uniqueId')) {
+            row = this.getRowByUniqueId(params.uniqueId);
+        }
+
+        if (!row) {
+            return;
+        }
+
+        index = $.inArray(row, this.hiddenRows);
+
+        if (!visible && index === -1) {
+            this.hiddenRows.push(row);
+        } else if (visible && index > -1) {
+            this.hiddenRows.splice(index, 1);
+        }
+        this.initBody(true);
+    };
+
+    BootstrapTable.prototype.getHiddenRows = function (show) {
+        var that = this,
+            data = this.getData(),
+            rows = [];
+
+        $.each(data, function (i, row) {
+            if ($.inArray(row, that.hiddenRows) > -1) {
+                rows.push(row);
+            }
+        });
+        this.hiddenRows = rows;
+        return rows;
+    };
+
+    BootstrapTable.prototype.mergeCells = function (options) {
+        var row = options.index,
+            col = $.inArray(options.field, this.getVisibleFields()),
+            rowspan = options.rowspan || 1,
+            colspan = options.colspan || 1,
+            i, j,
+            $tr = this.$body.find('>tr'),
+            $td;
+
+        if (this.options.detailView && !this.options.cardView) {
+            col += 1;
+        }
+
+        $td = $tr.eq(row).find('>td').eq(col);
+
+        if (row < 0 || col < 0 || row >= this.data.length) {
+            return;
+        }
+
+        for (i = row; i < row + rowspan; i++) {
+            for (j = col; j < col + colspan; j++) {
+                $tr.eq(i).find('>td').eq(j).hide();
+            }
+        }
+
+        $td.attr('rowspan', rowspan).attr('colspan', colspan).show();
+    };
+
+    BootstrapTable.prototype.updateCell = function (params) {
+        if (!params.hasOwnProperty('index') ||
+            !params.hasOwnProperty('field') ||
+            !params.hasOwnProperty('value')) {
+            return;
+        }
+        this.data[params.index][params.field] = params.value;
+
+        if (params.reinit === false) {
+            return;
+        }
+        this.initSort();
+        this.initBody(true);
+    };
+
+    BootstrapTable.prototype.getOptions = function () {
+        return this.options;
+    };
+
+    BootstrapTable.prototype.getSelections = function () {
+        var that = this;
+
+        return $.grep(this.options.data, function (row) {
+            // fix #2424: from html with checkbox
+            return row[that.header.stateField] === true;
+        });
+    };
+
+    BootstrapTable.prototype.getAllSelections = function () {
+        var that = this;
+
+        return $.grep(this.options.data, function (row) {
+            return row[that.header.stateField];
+        });
+    };
+
+    BootstrapTable.prototype.checkAll = function () {
+        this.checkAll_(true);
+    };
+
+    BootstrapTable.prototype.uncheckAll = function () {
+        this.checkAll_(false);
+    };
+
+    BootstrapTable.prototype.checkInvert = function () {
+        var that = this;
+        var rows = that.$selectItem.filter(':enabled');
+        var checked = rows.filter(':checked');
+        rows.each(function() {
+            $(this).prop('checked', !$(this).prop('checked'));
+        });
+        that.updateRows();
+        that.updateSelected();
+        that.trigger('uncheck-some', checked);
+        checked = that.getSelections();
+        that.trigger('check-some', checked);
+    };
+
+    BootstrapTable.prototype.checkAll_ = function (checked) {
+        var rows;
+        if (!checked) {
+            rows = this.getSelections();
+        }
+        this.$selectAll.add(this.$selectAll_).prop('checked', checked);
+        this.$selectItem.filter(':enabled').prop('checked', checked);
+        this.updateRows();
+        if (checked) {
+            rows = this.getSelections();
+        }
+        this.trigger(checked ? 'check-all' : 'uncheck-all', rows);
+    };
+
+    BootstrapTable.prototype.check = function (index) {
+        this.check_(true, index);
+    };
+
+    BootstrapTable.prototype.uncheck = function (index) {
+        this.check_(false, index);
+    };
+
+    BootstrapTable.prototype.check_ = function (checked, index) {
+        var $el = this.$selectItem.filter(sprintf('[data-index="%s"]', index)).prop('checked', checked);
+        this.data[index][this.header.stateField] = checked;
+        this.updateSelected();
+        this.trigger(checked ? 'check' : 'uncheck', this.data[index], $el);
+    };
+
+    BootstrapTable.prototype.checkBy = function (obj) {
+        this.checkBy_(true, obj);
+    };
+
+    BootstrapTable.prototype.uncheckBy = function (obj) {
+        this.checkBy_(false, obj);
+    };
+
+    BootstrapTable.prototype.checkBy_ = function (checked, obj) {
+        if (!obj.hasOwnProperty('field') || !obj.hasOwnProperty('values')) {
+            return;
+        }
+
+        var that = this,
+            rows = [];
+        $.each(this.options.data, function (index, row) {
+            if (!row.hasOwnProperty(obj.field)) {
+                return false;
+            }
+            if ($.inArray(row[obj.field], obj.values) !== -1) {
+                var $el = that.$selectItem.filter(':enabled')
+                    .filter(sprintf('[data-index="%s"]', index)).prop('checked', checked);
+                row[that.header.stateField] = checked;
+                rows.push(row);
+                that.trigger(checked ? 'check' : 'uncheck', row, $el);
+            }
+        });
+        this.updateSelected();
+        this.trigger(checked ? 'check-some' : 'uncheck-some', rows);
+    };
+
+    BootstrapTable.prototype.destroy = function () {
+        this.$el.insertBefore(this.$container);
+        $(this.options.toolbar).insertBefore(this.$el);
+        this.$container.next().remove();
+        this.$container.remove();
+        this.$el.html(this.$el_.html())
+            .css('margin-top', '0')
+            .attr('class', this.$el_.attr('class') || ''); // reset the class
+    };
+
+    BootstrapTable.prototype.showLoading = function () {
+        this.$tableLoading.show();
+    };
+
+    BootstrapTable.prototype.hideLoading = function () {
+        this.$tableLoading.hide();
+    };
+
+    BootstrapTable.prototype.togglePagination = function () {
+        this.options.pagination = !this.options.pagination;
+        var button = this.$toolbar.find('button[name="paginationSwitch"] i');
+        if (this.options.pagination) {
+            button.attr("class", this.options.iconsPrefix + " " + this.options.icons.paginationSwitchDown);
+        } else {
+            button.attr("class", this.options.iconsPrefix + " " + this.options.icons.paginationSwitchUp);
+        }
+        this.updatePagination();
+    };
+
+    BootstrapTable.prototype.refresh = function (params) {
+        if (params && params.url) {
+            this.options.url = params.url;
+        }
+        if (params && params.pageNumber) {
+            this.options.pageNumber = params.pageNumber;
+        }
+        if (params && params.pageSize) {
+            this.options.pageSize = params.pageSize;
+        }
+        this.initServer(params && params.silent,
+            params && params.query, params && params.url);
+        this.trigger('refresh', params);
+    };
+
+    BootstrapTable.prototype.resetWidth = function () {
+        if (this.options.showHeader && this.options.height) {
+            this.fitHeader();
+        }
+        if (this.options.showFooter) {
+            this.fitFooter();
+        }
+    };
+
+    BootstrapTable.prototype.showColumn = function (field) {
+        this.toggleColumn(getFieldIndex(this.columns, field), true, true);
+    };
+
+    BootstrapTable.prototype.hideColumn = function (field) {
+        this.toggleColumn(getFieldIndex(this.columns, field), false, true);
+    };
+
+    BootstrapTable.prototype.getHiddenColumns = function () {
+        return $.grep(this.columns, function (column) {
+            return !column.visible;
+        });
+    };
+
+    BootstrapTable.prototype.getVisibleColumns = function () {
+        return $.grep(this.columns, function (column) {
+            return column.visible;
+        });
+    };
+
+    BootstrapTable.prototype.toggleAllColumns = function (visible) {
+        $.each(this.columns, function (i, column) {
+            this.columns[i].visible = visible;
+        });
+
+        this.initHeader();
+        this.initSearch();
+        this.initPagination();
+        this.initBody();
+        if (this.options.showColumns) {
+            var $items = this.$toolbar.find('.keep-open input').prop('disabled', false);
+
+            if ($items.filter(':checked').length <= this.options.minimumCountColumns) {
+                $items.filter(':checked').prop('disabled', true);
+            }
+        }
+    };
+
+    BootstrapTable.prototype.showAllColumns = function () {
+        this.toggleAllColumns(true);
+    };
+
+    BootstrapTable.prototype.hideAllColumns = function () {
+        this.toggleAllColumns(false);
+    };
+
+    BootstrapTable.prototype.filterBy = function (columns) {
+        this.filterColumns = $.isEmptyObject(columns) ? {} : columns;
+        this.options.pageNumber = 1;
+        this.initSearch();
+        this.updatePagination();
+    };
+
+    BootstrapTable.prototype.scrollTo = function (value) {
+        if (typeof value === 'string') {
+            value = value === 'bottom' ? this.$tableBody[0].scrollHeight : 0;
+        }
+        if (typeof value === 'number') {
+            this.$tableBody.scrollTop(value);
+        }
+        if (typeof value === 'undefined') {
+            return this.$tableBody.scrollTop();
+        }
+    };
+
+    BootstrapTable.prototype.getScrollPosition = function () {
+        return this.scrollTo();
+    };
+
+    BootstrapTable.prototype.selectPage = function (page) {
+        if (page > 0 && page <= this.options.totalPages) {
+            this.options.pageNumber = page;
+            this.updatePagination();
+        }
+    };
+
+    BootstrapTable.prototype.prevPage = function () {
+        if (this.options.pageNumber > 1) {
+            this.options.pageNumber--;
+            this.updatePagination();
+        }
+    };
+
+    BootstrapTable.prototype.nextPage = function () {
+        if (this.options.pageNumber < this.options.totalPages) {
+            this.options.pageNumber++;
+            this.updatePagination();
+        }
+    };
+
+    BootstrapTable.prototype.toggleView = function () {
+        this.options.cardView = !this.options.cardView;
+        this.initHeader();
+        // Fixed remove toolbar when click cardView button.
+        //that.initToolbar();
+        this.initBody();
+        this.trigger('toggle', this.options.cardView);
+    };
+
+    BootstrapTable.prototype.refreshOptions = function (options) {
+        //If the objects are equivalent then avoid the call of destroy / init methods
+        if (compareObjects(this.options, options, true)) {
+            return;
+        }
+        this.options = $.extend(this.options, options);
+        this.trigger('refresh-options', this.options);
+        this.destroy();
+        this.init();
+    };
+
+    BootstrapTable.prototype.resetSearch = function (text) {
+        var $search = this.$toolbar.find('.search input');
+        $search.val(text || '');
+        this.onSearch({currentTarget: $search});
+    };
+
+    BootstrapTable.prototype.expandRow_ = function (expand, index) {
+        var $tr = this.$body.find(sprintf('> tr[data-index="%s"]', index));
+        if ($tr.next().is('tr.detail-view') === (expand ? false : true)) {
+            $tr.find('> td > .detail-icon').click();
+        }
+    };
+
+    BootstrapTable.prototype.expandRow = function (index) {
+        this.expandRow_(true, index);
+    };
+
+    BootstrapTable.prototype.collapseRow = function (index) {
+        this.expandRow_(false, index);
+    };
+
+    BootstrapTable.prototype.expandAllRows = function (isSubTable) {
+        if (isSubTable) {
+            var $tr = this.$body.find(sprintf('> tr[data-index="%s"]', 0)),
+                that = this,
+                detailIcon = null,
+                executeInterval = false,
+                idInterval = -1;
+
+            if (!$tr.next().is('tr.detail-view')) {
+                $tr.find('> td > .detail-icon').click();
+                executeInterval = true;
+            } else if (!$tr.next().next().is('tr.detail-view')) {
+                $tr.next().find(".detail-icon").click();
+                executeInterval = true;
+            }
+
+            if (executeInterval) {
+                try {
+                    idInterval = setInterval(function () {
+                        detailIcon = that.$body.find("tr.detail-view").last().find(".detail-icon");
+                        if (detailIcon.length > 0) {
+                            detailIcon.click();
+                        } else {
+                            clearInterval(idInterval);
+                        }
+                    }, 1);
+                } catch (ex) {
+                    clearInterval(idInterval);
+                }
+            }
+        } else {
+            var trs = this.$body.children();
+            for (var i = 0; i < trs.length; i++) {
+                this.expandRow_(true, $(trs[i]).data("index"));
+            }
+        }
+    };
+
+    BootstrapTable.prototype.collapseAllRows = function (isSubTable) {
+        if (isSubTable) {
+            this.expandRow_(false, 0);
+        } else {
+            var trs = this.$body.children();
+            for (var i = 0; i < trs.length; i++) {
+                this.expandRow_(false, $(trs[i]).data("index"));
+            }
+        }
+    };
+
+    BootstrapTable.prototype.updateFormatText = function (name, text) {
+        if (this.options[sprintf('format%s', name)]) {
+            if (typeof text === 'string') {
+                this.options[sprintf('format%s', name)] = function () {
+                    return text;
+                };
+            } else if (typeof text === 'function') {
+                this.options[sprintf('format%s', name)] = text;
+            }
+        }
+        this.initToolbar();
+        this.initPagination();
+        this.initBody();
+    };
+
+    // BOOTSTRAP TABLE PLUGIN DEFINITION
+    // =======================
+
+    var allowedMethods = [
+        'getOptions',
+        'getSelections', 'getAllSelections', 'getData',
+        'load', 'append', 'prepend', 'remove', 'removeAll',
+        'insertRow', 'updateRow', 'updateCell', 'updateByUniqueId', 'removeByUniqueId',
+        'getRowByUniqueId', 'showRow', 'hideRow', 'getHiddenRows',
+        'mergeCells',
+        'checkAll', 'uncheckAll', 'checkInvert',
+        'check', 'uncheck',
+        'checkBy', 'uncheckBy',
+        'refresh',
+        'resetView',
+        'resetWidth',
+        'destroy',
+        'showLoading', 'hideLoading',
+        'showColumn', 'hideColumn', 'getHiddenColumns', 'getVisibleColumns',
+        'showAllColumns', 'hideAllColumns',
+        'filterBy',
+        'scrollTo',
+        'getScrollPosition',
+        'selectPage', 'prevPage', 'nextPage',
+        'togglePagination',
+        'toggleView',
+        'refreshOptions',
+        'resetSearch',
+        'expandRow', 'collapseRow', 'expandAllRows', 'collapseAllRows',
+        'updateFormatText'
+    ];
+
+    $.fn.bootstrapTable = function (option) {
+        var value,
+            args = Array.prototype.slice.call(arguments, 1);
+
+        this.each(function () {
+            var $this = $(this),
+                data = $this.data('bootstrap.table'),
+                options = $.extend({}, BootstrapTable.DEFAULTS, $this.data(),
+                    typeof option === 'object' && option);
+
+            if (typeof option === 'string') {
+                if ($.inArray(option, allowedMethods) < 0) {
+                    throw new Error("Unknown method: " + option);
+                }
+
+                if (!data) {
+                    return;
+                }
+
+                value = data[option].apply(data, args);
+
+                if (option === 'destroy') {
+                    $this.removeData('bootstrap.table');
+                }
+            }
+
+            if (!data) {
+                $this.data('bootstrap.table', (data = new BootstrapTable(this, options)));
+            }
+        });
+
+        return typeof value === 'undefined' ? this : value;
+    };
+
+    $.fn.bootstrapTable.Constructor = BootstrapTable;
+    $.fn.bootstrapTable.defaults = BootstrapTable.DEFAULTS;
+    $.fn.bootstrapTable.columnDefaults = BootstrapTable.COLUMN_DEFAULTS;
+    $.fn.bootstrapTable.locales = BootstrapTable.LOCALES;
+    $.fn.bootstrapTable.methods = allowedMethods;
+    $.fn.bootstrapTable.utils = {
+        sprintf: sprintf,
+        getFieldIndex: getFieldIndex,
+        compareObjects: compareObjects,
+        calculateObjectValue: calculateObjectValue,
+        getItemField: getItemField,
+        objectKeys: objectKeys,
+        isIEBrowser: isIEBrowser
+    };
+
+    // BOOTSTRAP TABLE INIT
+    // =======================
+
+    $(function () {
+        $('[data-toggle="table"]').bootstrapTable();
+    });
+})(jQuery);

+ 359 - 0
static/lib/bootstrap-table/tableExport.js

@@ -0,0 +1,359 @@
+/*The MIT License (MIT)
+
+Copyright (c) 2014 https://github.com/kayalshri/
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.*/
+
+(function($){
+        $.fn.extend({
+            tableExport: function(options) {
+                var defaults = {
+						separator: ',',
+						ignoreColumn: [],
+						tableName:'yourTableName',
+						type:'csv',
+						pdfFontSize:14,
+						pdfLeftMargin:20,
+						escape:'true',
+						htmlContent:'false',
+						consoleLog:'false'
+				};
+                
+				var options = $.extend(defaults, options);
+				var el = this;
+				
+				if(defaults.type == 'csv' || defaults.type == 'txt'){
+				
+					// Header
+					var tdData ="";
+					$(el).find('thead').find('tr').each(function() {
+					tdData += "\n";					
+						$(this).filter(':visible').find('th').each(function(index,data) {
+							if ($(this).css('display') != 'none'){
+								if(defaults.ignoreColumn.indexOf(index) == -1){
+									tdData += '"' + parseString($(this)) + '"' + defaults.separator;									
+								}
+							}
+							
+						});
+						tdData = $.trim(tdData);
+						tdData = $.trim(tdData).substring(0, tdData.length -1);
+					});
+					
+					// Row vs Column
+					$(el).find('tbody').find('tr').each(function() {
+					tdData += "\n";
+						$(this).filter(':visible').find('td').each(function(index,data) {
+							if ($(this).css('display') != 'none'){
+								if(defaults.ignoreColumn.indexOf(index) == -1){
+									tdData += '"'+ parseString($(this)) + '"'+ defaults.separator;
+								}
+							}
+						});
+						//tdData = $.trim(tdData);
+						tdData = $.trim(tdData).substring(0, tdData.length -1);
+					});
+					
+					//output
+					if(defaults.consoleLog == 'true'){
+						console.log(tdData);
+					}
+					var base64data = "base64," + $.base64.encode(tdData);
+					window.open('data:application/'+defaults.type+';filename=exportData;' + base64data);
+				}else if(defaults.type == 'sql'){
+				
+					// Header
+					var tdData ="INSERT INTO `"+defaults.tableName+"` (";
+					$(el).find('thead').find('tr').each(function() {
+					
+						$(this).filter(':visible').find('th').each(function(index,data) {
+							if ($(this).css('display') != 'none'){
+								if(defaults.ignoreColumn.indexOf(index) == -1){
+									tdData += '`' + parseString($(this)) + '`,' ;									
+								}
+							}
+							
+						});
+						tdData = $.trim(tdData);
+						tdData = $.trim(tdData).substring(0, tdData.length -1);
+					});
+					tdData += ") VALUES ";
+					// Row vs Column
+					$(el).find('tbody').find('tr').each(function() {
+					tdData += "(";
+						$(this).filter(':visible').find('td').each(function(index,data) {
+							if ($(this).css('display') != 'none'){
+								if(defaults.ignoreColumn.indexOf(index) == -1){
+									tdData += '"'+ parseString($(this)) + '",';
+								}
+							}
+						});
+						
+						tdData = $.trim(tdData).substring(0, tdData.length -1);
+						tdData += "),";
+					});
+					tdData = $.trim(tdData).substring(0, tdData.length -1);
+					tdData += ";";
+					
+					//output
+					//console.log(tdData);
+					
+					if(defaults.consoleLog == 'true'){
+						console.log(tdData);
+					}
+					
+					var base64data = "base64," + $.base64.encode(tdData);
+					window.open('data:application/sql;filename=exportData;' + base64data);
+					
+				
+				}else if(defaults.type == 'json'){
+				
+					var jsonHeaderArray = [];
+					$(el).find('thead').find('tr').each(function() {
+						var tdData ="";	
+						var jsonArrayTd = [];
+					
+						$(this).filter(':visible').find('th').each(function(index,data) {
+							if ($(this).css('display') != 'none'){
+								if(defaults.ignoreColumn.indexOf(index) == -1){
+									jsonArrayTd.push(parseString($(this)));									
+								}
+							}
+						});									
+						jsonHeaderArray.push(jsonArrayTd);						
+						
+					});
+					
+					var jsonArray = [];
+					$(el).find('tbody').find('tr').each(function() {
+						var tdData ="";	
+						var jsonArrayTd = [];
+					
+						$(this).filter(':visible').find('td').each(function(index,data) {
+							if ($(this).css('display') != 'none'){
+								if(defaults.ignoreColumn.indexOf(index) == -1){
+									jsonArrayTd.push(parseString($(this)));									
+								}
+							}
+						});									
+						jsonArray.push(jsonArrayTd);									
+						
+					});
+					
+					var jsonExportArray =[];
+					jsonExportArray.push({header:jsonHeaderArray,data:jsonArray});
+					
+					//Return as JSON
+					//console.log(JSON.stringify(jsonExportArray));
+					
+					//Return as Array
+					//console.log(jsonExportArray);
+					if(defaults.consoleLog == 'true'){
+						console.log(JSON.stringify(jsonExportArray));
+					}
+					var base64data = "base64," + $.base64.encode(JSON.stringify(jsonExportArray));
+					window.open('data:application/json;filename=exportData;' + base64data);
+				}else if(defaults.type == 'xml'){
+				
+					var xml = '<?xml version="1.0" encoding="utf-8"?>';
+					xml += '<tabledata><fields>';
+
+					// Header
+					$(el).find('thead').find('tr').each(function() {
+						$(this).filter(':visible').find('th').each(function(index,data) {
+							if ($(this).css('display') != 'none'){					
+								if(defaults.ignoreColumn.indexOf(index) == -1){
+									xml += "<field>" + parseString($(this)) + "</field>";
+								}
+							}
+						});									
+					});					
+					xml += '</fields><data>';
+					
+					// Row Vs Column
+					var rowCount=1;
+					$(el).find('tbody').find('tr').each(function() {
+						xml += '<row id="'+rowCount+'">';
+						var colCount=0;
+						$(this).filter(':visible').find('td').each(function(index,data) {
+							if ($(this).css('display') != 'none'){	
+								if(defaults.ignoreColumn.indexOf(index) == -1){
+									xml += "<column-"+colCount+">"+parseString($(this))+"</column-"+colCount+">";
+								}
+							}
+							colCount++;
+						});															
+						rowCount++;
+						xml += '</row>';
+					});					
+					xml += '</data></tabledata>'
+					
+					if(defaults.consoleLog == 'true'){
+						console.log(xml);
+					}
+					
+					var base64data = "base64," + $.base64.encode(xml);
+					window.open('data:application/xml;filename=exportData;' + base64data);
+
+				}else if(defaults.type == 'excel' || defaults.type == 'doc'|| defaults.type == 'powerpoint'  ){
+					//console.log($(this).html());
+					var excel="<table>";
+					// Header
+					$(el).find('thead').find('tr').each(function() {
+						excel += "<tr>";
+						$(this).filter(':visible').find('th').each(function(index,data) {
+							if ($(this).css('display') != 'none'){					
+								if(defaults.ignoreColumn.indexOf(index) == -1){
+									excel += "<td>" + parseString($(this))+ "</td>";
+								}
+							}
+						});	
+						excel += '</tr>';						
+						
+					});					
+					
+					
+					// Row Vs Column
+					var rowCount=1;
+					$(el).find('tbody').find('tr').each(function() {
+						excel += "<tr>";
+						var colCount=0;
+						$(this).filter(':visible').find('td').each(function(index,data) {
+							if ($(this).css('display') != 'none'){	
+								if(defaults.ignoreColumn.indexOf(index) == -1){
+									excel += "<td>"+parseString($(this))+"</td>";
+								}
+							}
+							colCount++;
+						});															
+						rowCount++;
+						excel += '</tr>';
+					});					
+					excel += '</table>'
+					
+					if(defaults.consoleLog == 'true'){
+						console.log(excel);
+					}
+					
+					var excelFile = "<html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:x='urn:schemas-microsoft-com:office:"+defaults.type+"' xmlns='http://www.w3.org/TR/REC-html40'>";
+					excelFile += "<head>";
+					excelFile += "<!--[if gte mso 9]>";
+					excelFile += "<xml>";
+					excelFile += "<x:ExcelWorkbook>";
+					excelFile += "<x:ExcelWorksheets>";
+					excelFile += "<x:ExcelWorksheet>";
+					excelFile += "<x:Name>";
+					excelFile += "{worksheet}";
+					excelFile += "</x:Name>";
+					excelFile += "<x:WorksheetOptions>";
+					excelFile += "<x:DisplayGridlines/>";
+					excelFile += "</x:WorksheetOptions>";
+					excelFile += "</x:ExcelWorksheet>";
+					excelFile += "</x:ExcelWorksheets>";
+					excelFile += "</x:ExcelWorkbook>";
+					excelFile += "</xml>";
+					excelFile += "<![endif]-->";
+					excelFile += "</head>";
+					excelFile += "<body>";
+					excelFile += excel;
+					excelFile += "</body>";
+					excelFile += "</html>";
+
+					var base64data = "base64," + $.base64.encode(excelFile);
+					window.open('data:application/vnd.ms-'+defaults.type+';filename=exportData.doc;' + base64data);
+					
+				}else if(defaults.type == 'png'){
+					html2canvas($(el), {
+						onrendered: function(canvas) {										
+							var img = canvas.toDataURL("image/png");
+							window.open(img);
+							
+							
+						}
+					});		
+				}else if(defaults.type == 'pdf'){
+	
+					var doc = new jsPDF('p','pt', 'a4', true);
+					doc.setFontSize(defaults.pdfFontSize);
+					
+					// Header
+					var startColPosition=defaults.pdfLeftMargin;
+					$(el).find('thead').find('tr').each(function() {
+						$(this).filter(':visible').find('th').each(function(index,data) {
+							if ($(this).css('display') != 'none'){					
+								if(defaults.ignoreColumn.indexOf(index) == -1){
+									var colPosition = startColPosition+ (index * 50);									
+									doc.text(colPosition,20, parseString($(this)));
+								}
+							}
+						});									
+					});					
+				
+				
+					// Row Vs Column
+					var startRowPosition = 20; var page =1;var rowPosition=0;
+					$(el).find('tbody').find('tr').each(function(index,data) {
+						rowCalc = index+1;
+						
+					if (rowCalc % 26 == 0){
+						doc.addPage();
+						page++;
+						startRowPosition=startRowPosition+10;
+					}
+					rowPosition=(startRowPosition + (rowCalc * 10)) - ((page -1) * 280);
+						
+						$(this).filter(':visible').find('td').each(function(index,data) {
+							if ($(this).css('display') != 'none'){	
+								if(defaults.ignoreColumn.indexOf(index) == -1){
+									var colPosition = startColPosition+ (index * 50);									
+									doc.text(colPosition,rowPosition, parseString($(this)));
+								}
+							}
+							
+						});															
+						
+					});					
+										
+					// Output as Data URI
+					doc.output('datauri');
+	
+				}
+				
+				
+				function parseString(data){
+				
+					if(defaults.htmlContent == 'true'){
+						content_data = data.html().trim();
+					}else{
+						content_data = data.text().trim();
+					}
+					
+					if(defaults.escape == 'true'){
+						content_data = escape(content_data);
+					}
+					
+					
+					
+					return content_data;
+				}
+			
+			}
+        });
+    })(jQuery);
+        

+ 12269 - 0
static/lib/chartjs/Chart.js

@@ -0,0 +1,12269 @@
+/*!
+ * Chart.js
+ * http://chartjs.org/
+ * Version: 2.5.0
+ *
+ * Copyright 2017 Nick Downie
+ * Released under the MIT license
+ * https://github.com/chartjs/Chart.js/blob/master/LICENSE.md
+ */
+(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.Chart = 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){
+
+},{}],2:[function(require,module,exports){
+/* MIT license */
+var colorNames = require(6);
+
+module.exports = {
+   getRgba: getRgba,
+   getHsla: getHsla,
+   getRgb: getRgb,
+   getHsl: getHsl,
+   getHwb: getHwb,
+   getAlpha: getAlpha,
+
+   hexString: hexString,
+   rgbString: rgbString,
+   rgbaString: rgbaString,
+   percentString: percentString,
+   percentaString: percentaString,
+   hslString: hslString,
+   hslaString: hslaString,
+   hwbString: hwbString,
+   keyword: keyword
+}
+
+function getRgba(string) {
+   if (!string) {
+      return;
+   }
+   var abbr =  /^#([a-fA-F0-9]{3})$/,
+       hex =  /^#([a-fA-F0-9]{6})$/,
+       rgba = /^rgba?\(\s*([+-]?\d+)\s*,\s*([+-]?\d+)\s*,\s*([+-]?\d+)\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)$/,
+       per = /^rgba?\(\s*([+-]?[\d\.]+)\%\s*,\s*([+-]?[\d\.]+)\%\s*,\s*([+-]?[\d\.]+)\%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)$/,
+       keyword = /(\w+)/;
+
+   var rgb = [0, 0, 0],
+       a = 1,
+       match = string.match(abbr);
+   if (match) {
+      match = match[1];
+      for (var i = 0; i < rgb.length; i++) {
+         rgb[i] = parseInt(match[i] + match[i], 16);
+      }
+   }
+   else if (match = string.match(hex)) {
+      match = match[1];
+      for (var i = 0; i < rgb.length; i++) {
+         rgb[i] = parseInt(match.slice(i * 2, i * 2 + 2), 16);
+      }
+   }
+   else if (match = string.match(rgba)) {
+      for (var i = 0; i < rgb.length; i++) {
+         rgb[i] = parseInt(match[i + 1]);
+      }
+      a = parseFloat(match[4]);
+   }
+   else if (match = string.match(per)) {
+      for (var i = 0; i < rgb.length; i++) {
+         rgb[i] = Math.round(parseFloat(match[i + 1]) * 2.55);
+      }
+      a = parseFloat(match[4]);
+   }
+   else if (match = string.match(keyword)) {
+      if (match[1] == "transparent") {
+         return [0, 0, 0, 0];
+      }
+      rgb = colorNames[match[1]];
+      if (!rgb) {
+         return;
+      }
+   }
+
+   for (var i = 0; i < rgb.length; i++) {
+      rgb[i] = scale(rgb[i], 0, 255);
+   }
+   if (!a && a != 0) {
+      a = 1;
+   }
+   else {
+      a = scale(a, 0, 1);
+   }
+   rgb[3] = a;
+   return rgb;
+}
+
+function getHsla(string) {
+   if (!string) {
+      return;
+   }
+   var hsl = /^hsla?\(\s*([+-]?\d+)(?:deg)?\s*,\s*([+-]?[\d\.]+)%\s*,\s*([+-]?[\d\.]+)%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)/;
+   var match = string.match(hsl);
+   if (match) {
+      var alpha = parseFloat(match[4]);
+      var h = scale(parseInt(match[1]), 0, 360),
+          s = scale(parseFloat(match[2]), 0, 100),
+          l = scale(parseFloat(match[3]), 0, 100),
+          a = scale(isNaN(alpha) ? 1 : alpha, 0, 1);
+      return [h, s, l, a];
+   }
+}
+
+function getHwb(string) {
+   if (!string) {
+      return;
+   }
+   var hwb = /^hwb\(\s*([+-]?\d+)(?:deg)?\s*,\s*([+-]?[\d\.]+)%\s*,\s*([+-]?[\d\.]+)%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)/;
+   var match = string.match(hwb);
+   if (match) {
+    var alpha = parseFloat(match[4]);
+      var h = scale(parseInt(match[1]), 0, 360),
+          w = scale(parseFloat(match[2]), 0, 100),
+          b = scale(parseFloat(match[3]), 0, 100),
+          a = scale(isNaN(alpha) ? 1 : alpha, 0, 1);
+      return [h, w, b, a];
+   }
+}
+
+function getRgb(string) {
+   var rgba = getRgba(string);
+   return rgba && rgba.slice(0, 3);
+}
+
+function getHsl(string) {
+  var hsla = getHsla(string);
+  return hsla && hsla.slice(0, 3);
+}
+
+function getAlpha(string) {
+   var vals = getRgba(string);
+   if (vals) {
+      return vals[3];
+   }
+   else if (vals = getHsla(string)) {
+      return vals[3];
+   }
+   else if (vals = getHwb(string)) {
+      return vals[3];
+   }
+}
+
+// generators
+function hexString(rgb) {
+   return "#" + hexDouble(rgb[0]) + hexDouble(rgb[1])
+              + hexDouble(rgb[2]);
+}
+
+function rgbString(rgba, alpha) {
+   if (alpha < 1 || (rgba[3] && rgba[3] < 1)) {
+      return rgbaString(rgba, alpha);
+   }
+   return "rgb(" + rgba[0] + ", " + rgba[1] + ", " + rgba[2] + ")";
+}
+
+function rgbaString(rgba, alpha) {
+   if (alpha === undefined) {
+      alpha = (rgba[3] !== undefined ? rgba[3] : 1);
+   }
+   return "rgba(" + rgba[0] + ", " + rgba[1] + ", " + rgba[2]
+           + ", " + alpha + ")";
+}
+
+function percentString(rgba, alpha) {
+   if (alpha < 1 || (rgba[3] && rgba[3] < 1)) {
+      return percentaString(rgba, alpha);
+   }
+   var r = Math.round(rgba[0]/255 * 100),
+       g = Math.round(rgba[1]/255 * 100),
+       b = Math.round(rgba[2]/255 * 100);
+
+   return "rgb(" + r + "%, " + g + "%, " + b + "%)";
+}
+
+function percentaString(rgba, alpha) {
+   var r = Math.round(rgba[0]/255 * 100),
+       g = Math.round(rgba[1]/255 * 100),
+       b = Math.round(rgba[2]/255 * 100);
+   return "rgba(" + r + "%, " + g + "%, " + b + "%, " + (alpha || rgba[3] || 1) + ")";
+}
+
+function hslString(hsla, alpha) {
+   if (alpha < 1 || (hsla[3] && hsla[3] < 1)) {
+      return hslaString(hsla, alpha);
+   }
+   return "hsl(" + hsla[0] + ", " + hsla[1] + "%, " + hsla[2] + "%)";
+}
+
+function hslaString(hsla, alpha) {
+   if (alpha === undefined) {
+      alpha = (hsla[3] !== undefined ? hsla[3] : 1);
+   }
+   return "hsla(" + hsla[0] + ", " + hsla[1] + "%, " + hsla[2] + "%, "
+           + alpha + ")";
+}
+
+// hwb is a bit different than rgb(a) & hsl(a) since there is no alpha specific syntax
+// (hwb have alpha optional & 1 is default value)
+function hwbString(hwb, alpha) {
+   if (alpha === undefined) {
+      alpha = (hwb[3] !== undefined ? hwb[3] : 1);
+   }
+   return "hwb(" + hwb[0] + ", " + hwb[1] + "%, " + hwb[2] + "%"
+           + (alpha !== undefined && alpha !== 1 ? ", " + alpha : "") + ")";
+}
+
+function keyword(rgb) {
+  return reverseNames[rgb.slice(0, 3)];
+}
+
+// helpers
+function scale(num, min, max) {
+   return Math.min(Math.max(min, num), max);
+}
+
+function hexDouble(num) {
+  var str = num.toString(16).toUpperCase();
+  return (str.length < 2) ? "0" + str : str;
+}
+
+
+//create a list of reverse color names
+var reverseNames = {};
+for (var name in colorNames) {
+   reverseNames[colorNames[name]] = name;
+}
+
+},{"6":6}],3:[function(require,module,exports){
+/* MIT license */
+var convert = require(5);
+var string = require(2);
+
+var Color = function (obj) {
+	if (obj instanceof Color) {
+		return obj;
+	}
+	if (!(this instanceof Color)) {
+		return new Color(obj);
+	}
+
+	this.values = {
+		rgb: [0, 0, 0],
+		hsl: [0, 0, 0],
+		hsv: [0, 0, 0],
+		hwb: [0, 0, 0],
+		cmyk: [0, 0, 0, 0],
+		alpha: 1
+	};
+
+	// parse Color() argument
+	var vals;
+	if (typeof obj === 'string') {
+		vals = string.getRgba(obj);
+		if (vals) {
+			this.setValues('rgb', vals);
+		} else if (vals = string.getHsla(obj)) {
+			this.setValues('hsl', vals);
+		} else if (vals = string.getHwb(obj)) {
+			this.setValues('hwb', vals);
+		} else {
+			throw new Error('Unable to parse color from string "' + obj + '"');
+		}
+	} else if (typeof obj === 'object') {
+		vals = obj;
+		if (vals.r !== undefined || vals.red !== undefined) {
+			this.setValues('rgb', vals);
+		} else if (vals.l !== undefined || vals.lightness !== undefined) {
+			this.setValues('hsl', vals);
+		} else if (vals.v !== undefined || vals.value !== undefined) {
+			this.setValues('hsv', vals);
+		} else if (vals.w !== undefined || vals.whiteness !== undefined) {
+			this.setValues('hwb', vals);
+		} else if (vals.c !== undefined || vals.cyan !== undefined) {
+			this.setValues('cmyk', vals);
+		} else {
+			throw new Error('Unable to parse color from object ' + JSON.stringify(obj));
+		}
+	}
+};
+
+Color.prototype = {
+	rgb: function () {
+		return this.setSpace('rgb', arguments);
+	},
+	hsl: function () {
+		return this.setSpace('hsl', arguments);
+	},
+	hsv: function () {
+		return this.setSpace('hsv', arguments);
+	},
+	hwb: function () {
+		return this.setSpace('hwb', arguments);
+	},
+	cmyk: function () {
+		return this.setSpace('cmyk', arguments);
+	},
+
+	rgbArray: function () {
+		return this.values.rgb;
+	},
+	hslArray: function () {
+		return this.values.hsl;
+	},
+	hsvArray: function () {
+		return this.values.hsv;
+	},
+	hwbArray: function () {
+		var values = this.values;
+		if (values.alpha !== 1) {
+			return values.hwb.concat([values.alpha]);
+		}
+		return values.hwb;
+	},
+	cmykArray: function () {
+		return this.values.cmyk;
+	},
+	rgbaArray: function () {
+		var values = this.values;
+		return values.rgb.concat([values.alpha]);
+	},
+	hslaArray: function () {
+		var values = this.values;
+		return values.hsl.concat([values.alpha]);
+	},
+	alpha: function (val) {
+		if (val === undefined) {
+			return this.values.alpha;
+		}
+		this.setValues('alpha', val);
+		return this;
+	},
+
+	red: function (val) {
+		return this.setChannel('rgb', 0, val);
+	},
+	green: function (val) {
+		return this.setChannel('rgb', 1, val);
+	},
+	blue: function (val) {
+		return this.setChannel('rgb', 2, val);
+	},
+	hue: function (val) {
+		if (val) {
+			val %= 360;
+			val = val < 0 ? 360 + val : val;
+		}
+		return this.setChannel('hsl', 0, val);
+	},
+	saturation: function (val) {
+		return this.setChannel('hsl', 1, val);
+	},
+	lightness: function (val) {
+		return this.setChannel('hsl', 2, val);
+	},
+	saturationv: function (val) {
+		return this.setChannel('hsv', 1, val);
+	},
+	whiteness: function (val) {
+		return this.setChannel('hwb', 1, val);
+	},
+	blackness: function (val) {
+		return this.setChannel('hwb', 2, val);
+	},
+	value: function (val) {
+		return this.setChannel('hsv', 2, val);
+	},
+	cyan: function (val) {
+		return this.setChannel('cmyk', 0, val);
+	},
+	magenta: function (val) {
+		return this.setChannel('cmyk', 1, val);
+	},
+	yellow: function (val) {
+		return this.setChannel('cmyk', 2, val);
+	},
+	black: function (val) {
+		return this.setChannel('cmyk', 3, val);
+	},
+
+	hexString: function () {
+		return string.hexString(this.values.rgb);
+	},
+	rgbString: function () {
+		return string.rgbString(this.values.rgb, this.values.alpha);
+	},
+	rgbaString: function () {
+		return string.rgbaString(this.values.rgb, this.values.alpha);
+	},
+	percentString: function () {
+		return string.percentString(this.values.rgb, this.values.alpha);
+	},
+	hslString: function () {
+		return string.hslString(this.values.hsl, this.values.alpha);
+	},
+	hslaString: function () {
+		return string.hslaString(this.values.hsl, this.values.alpha);
+	},
+	hwbString: function () {
+		return string.hwbString(this.values.hwb, this.values.alpha);
+	},
+	keyword: function () {
+		return string.keyword(this.values.rgb, this.values.alpha);
+	},
+
+	rgbNumber: function () {
+		var rgb = this.values.rgb;
+		return (rgb[0] << 16) | (rgb[1] << 8) | rgb[2];
+	},
+
+	luminosity: function () {
+		// http://www.w3.org/TR/WCAG20/#relativeluminancedef
+		var rgb = this.values.rgb;
+		var lum = [];
+		for (var i = 0; i < rgb.length; i++) {
+			var chan = rgb[i] / 255;
+			lum[i] = (chan <= 0.03928) ? chan / 12.92 : Math.pow(((chan + 0.055) / 1.055), 2.4);
+		}
+		return 0.2126 * lum[0] + 0.7152 * lum[1] + 0.0722 * lum[2];
+	},
+
+	contrast: function (color2) {
+		// http://www.w3.org/TR/WCAG20/#contrast-ratiodef
+		var lum1 = this.luminosity();
+		var lum2 = color2.luminosity();
+		if (lum1 > lum2) {
+			return (lum1 + 0.05) / (lum2 + 0.05);
+		}
+		return (lum2 + 0.05) / (lum1 + 0.05);
+	},
+
+	level: function (color2) {
+		var contrastRatio = this.contrast(color2);
+		if (contrastRatio >= 7.1) {
+			return 'AAA';
+		}
+
+		return (contrastRatio >= 4.5) ? 'AA' : '';
+	},
+
+	dark: function () {
+		// YIQ equation from http://24ways.org/2010/calculating-color-contrast
+		var rgb = this.values.rgb;
+		var yiq = (rgb[0] * 299 + rgb[1] * 587 + rgb[2] * 114) / 1000;
+		return yiq < 128;
+	},
+
+	light: function () {
+		return !this.dark();
+	},
+
+	negate: function () {
+		var rgb = [];
+		for (var i = 0; i < 3; i++) {
+			rgb[i] = 255 - this.values.rgb[i];
+		}
+		this.setValues('rgb', rgb);
+		return this;
+	},
+
+	lighten: function (ratio) {
+		var hsl = this.values.hsl;
+		hsl[2] += hsl[2] * ratio;
+		this.setValues('hsl', hsl);
+		return this;
+	},
+
+	darken: function (ratio) {
+		var hsl = this.values.hsl;
+		hsl[2] -= hsl[2] * ratio;
+		this.setValues('hsl', hsl);
+		return this;
+	},
+
+	saturate: function (ratio) {
+		var hsl = this.values.hsl;
+		hsl[1] += hsl[1] * ratio;
+		this.setValues('hsl', hsl);
+		return this;
+	},
+
+	desaturate: function (ratio) {
+		var hsl = this.values.hsl;
+		hsl[1] -= hsl[1] * ratio;
+		this.setValues('hsl', hsl);
+		return this;
+	},
+
+	whiten: function (ratio) {
+		var hwb = this.values.hwb;
+		hwb[1] += hwb[1] * ratio;
+		this.setValues('hwb', hwb);
+		return this;
+	},
+
+	blacken: function (ratio) {
+		var hwb = this.values.hwb;
+		hwb[2] += hwb[2] * ratio;
+		this.setValues('hwb', hwb);
+		return this;
+	},
+
+	greyscale: function () {
+		var rgb = this.values.rgb;
+		// http://en.wikipedia.org/wiki/Grayscale#Converting_color_to_grayscale
+		var val = rgb[0] * 0.3 + rgb[1] * 0.59 + rgb[2] * 0.11;
+		this.setValues('rgb', [val, val, val]);
+		return this;
+	},
+
+	clearer: function (ratio) {
+		var alpha = this.values.alpha;
+		this.setValues('alpha', alpha - (alpha * ratio));
+		return this;
+	},
+
+	opaquer: function (ratio) {
+		var alpha = this.values.alpha;
+		this.setValues('alpha', alpha + (alpha * ratio));
+		return this;
+	},
+
+	rotate: function (degrees) {
+		var hsl = this.values.hsl;
+		var hue = (hsl[0] + degrees) % 360;
+		hsl[0] = hue < 0 ? 360 + hue : hue;
+		this.setValues('hsl', hsl);
+		return this;
+	},
+
+	/**
+	 * Ported from sass implementation in C
+	 * https://github.com/sass/libsass/blob/0e6b4a2850092356aa3ece07c6b249f0221caced/functions.cpp#L209
+	 */
+	mix: function (mixinColor, weight) {
+		var color1 = this;
+		var color2 = mixinColor;
+		var p = weight === undefined ? 0.5 : weight;
+
+		var w = 2 * p - 1;
+		var a = color1.alpha() - color2.alpha();
+
+		var w1 = (((w * a === -1) ? w : (w + a) / (1 + w * a)) + 1) / 2.0;
+		var w2 = 1 - w1;
+
+		return this
+			.rgb(
+				w1 * color1.red() + w2 * color2.red(),
+				w1 * color1.green() + w2 * color2.green(),
+				w1 * color1.blue() + w2 * color2.blue()
+			)
+			.alpha(color1.alpha() * p + color2.alpha() * (1 - p));
+	},
+
+	toJSON: function () {
+		return this.rgb();
+	},
+
+	clone: function () {
+		// NOTE(SB): using node-clone creates a dependency to Buffer when using browserify,
+		// making the final build way to big to embed in Chart.js. So let's do it manually,
+		// assuming that values to clone are 1 dimension arrays containing only numbers,
+		// except 'alpha' which is a number.
+		var result = new Color();
+		var source = this.values;
+		var target = result.values;
+		var value, type;
+
+		for (var prop in source) {
+			if (source.hasOwnProperty(prop)) {
+				value = source[prop];
+				type = ({}).toString.call(value);
+				if (type === '[object Array]') {
+					target[prop] = value.slice(0);
+				} else if (type === '[object Number]') {
+					target[prop] = value;
+				} else {
+					console.error('unexpected color value:', value);
+				}
+			}
+		}
+
+		return result;
+	}
+};
+
+Color.prototype.spaces = {
+	rgb: ['red', 'green', 'blue'],
+	hsl: ['hue', 'saturation', 'lightness'],
+	hsv: ['hue', 'saturation', 'value'],
+	hwb: ['hue', 'whiteness', 'blackness'],
+	cmyk: ['cyan', 'magenta', 'yellow', 'black']
+};
+
+Color.prototype.maxes = {
+	rgb: [255, 255, 255],
+	hsl: [360, 100, 100],
+	hsv: [360, 100, 100],
+	hwb: [360, 100, 100],
+	cmyk: [100, 100, 100, 100]
+};
+
+Color.prototype.getValues = function (space) {
+	var values = this.values;
+	var vals = {};
+
+	for (var i = 0; i < space.length; i++) {
+		vals[space.charAt(i)] = values[space][i];
+	}
+
+	if (values.alpha !== 1) {
+		vals.a = values.alpha;
+	}
+
+	// {r: 255, g: 255, b: 255, a: 0.4}
+	return vals;
+};
+
+Color.prototype.setValues = function (space, vals) {
+	var values = this.values;
+	var spaces = this.spaces;
+	var maxes = this.maxes;
+	var alpha = 1;
+	var i;
+
+	if (space === 'alpha') {
+		alpha = vals;
+	} else if (vals.length) {
+		// [10, 10, 10]
+		values[space] = vals.slice(0, space.length);
+		alpha = vals[space.length];
+	} else if (vals[space.charAt(0)] !== undefined) {
+		// {r: 10, g: 10, b: 10}
+		for (i = 0; i < space.length; i++) {
+			values[space][i] = vals[space.charAt(i)];
+		}
+
+		alpha = vals.a;
+	} else if (vals[spaces[space][0]] !== undefined) {
+		// {red: 10, green: 10, blue: 10}
+		var chans = spaces[space];
+
+		for (i = 0; i < space.length; i++) {
+			values[space][i] = vals[chans[i]];
+		}
+
+		alpha = vals.alpha;
+	}
+
+	values.alpha = Math.max(0, Math.min(1, (alpha === undefined ? values.alpha : alpha)));
+
+	if (space === 'alpha') {
+		return false;
+	}
+
+	var capped;
+
+	// cap values of the space prior converting all values
+	for (i = 0; i < space.length; i++) {
+		capped = Math.max(0, Math.min(maxes[space][i], values[space][i]));
+		values[space][i] = Math.round(capped);
+	}
+
+	// convert to all the other color spaces
+	for (var sname in spaces) {
+		if (sname !== space) {
+			values[sname] = convert[space][sname](values[space]);
+		}
+	}
+
+	return true;
+};
+
+Color.prototype.setSpace = function (space, args) {
+	var vals = args[0];
+
+	if (vals === undefined) {
+		// color.rgb()
+		return this.getValues(space);
+	}
+
+	// color.rgb(10, 10, 10)
+	if (typeof vals === 'number') {
+		vals = Array.prototype.slice.call(args);
+	}
+
+	this.setValues(space, vals);
+	return this;
+};
+
+Color.prototype.setChannel = function (space, index, val) {
+	var svalues = this.values[space];
+	if (val === undefined) {
+		// color.red()
+		return svalues[index];
+	} else if (val === svalues[index]) {
+		// color.red(color.red())
+		return this;
+	}
+
+	// color.red(100)
+	svalues[index] = val;
+	this.setValues(space, svalues);
+
+	return this;
+};
+
+if (typeof window !== 'undefined') {
+	window.Color = Color;
+}
+
+module.exports = Color;
+
+},{"2":2,"5":5}],4:[function(require,module,exports){
+/* MIT license */
+
+module.exports = {
+  rgb2hsl: rgb2hsl,
+  rgb2hsv: rgb2hsv,
+  rgb2hwb: rgb2hwb,
+  rgb2cmyk: rgb2cmyk,
+  rgb2keyword: rgb2keyword,
+  rgb2xyz: rgb2xyz,
+  rgb2lab: rgb2lab,
+  rgb2lch: rgb2lch,
+
+  hsl2rgb: hsl2rgb,
+  hsl2hsv: hsl2hsv,
+  hsl2hwb: hsl2hwb,
+  hsl2cmyk: hsl2cmyk,
+  hsl2keyword: hsl2keyword,
+
+  hsv2rgb: hsv2rgb,
+  hsv2hsl: hsv2hsl,
+  hsv2hwb: hsv2hwb,
+  hsv2cmyk: hsv2cmyk,
+  hsv2keyword: hsv2keyword,
+
+  hwb2rgb: hwb2rgb,
+  hwb2hsl: hwb2hsl,
+  hwb2hsv: hwb2hsv,
+  hwb2cmyk: hwb2cmyk,
+  hwb2keyword: hwb2keyword,
+
+  cmyk2rgb: cmyk2rgb,
+  cmyk2hsl: cmyk2hsl,
+  cmyk2hsv: cmyk2hsv,
+  cmyk2hwb: cmyk2hwb,
+  cmyk2keyword: cmyk2keyword,
+
+  keyword2rgb: keyword2rgb,
+  keyword2hsl: keyword2hsl,
+  keyword2hsv: keyword2hsv,
+  keyword2hwb: keyword2hwb,
+  keyword2cmyk: keyword2cmyk,
+  keyword2lab: keyword2lab,
+  keyword2xyz: keyword2xyz,
+
+  xyz2rgb: xyz2rgb,
+  xyz2lab: xyz2lab,
+  xyz2lch: xyz2lch,
+
+  lab2xyz: lab2xyz,
+  lab2rgb: lab2rgb,
+  lab2lch: lab2lch,
+
+  lch2lab: lch2lab,
+  lch2xyz: lch2xyz,
+  lch2rgb: lch2rgb
+}
+
+
+function rgb2hsl(rgb) {
+  var r = rgb[0]/255,
+      g = rgb[1]/255,
+      b = rgb[2]/255,
+      min = Math.min(r, g, b),
+      max = Math.max(r, g, b),
+      delta = max - min,
+      h, s, l;
+
+  if (max == min)
+    h = 0;
+  else if (r == max)
+    h = (g - b) / delta;
+  else if (g == max)
+    h = 2 + (b - r) / delta;
+  else if (b == max)
+    h = 4 + (r - g)/ delta;
+
+  h = Math.min(h * 60, 360);
+
+  if (h < 0)
+    h += 360;
+
+  l = (min + max) / 2;
+
+  if (max == min)
+    s = 0;
+  else if (l <= 0.5)
+    s = delta / (max + min);
+  else
+    s = delta / (2 - max - min);
+
+  return [h, s * 100, l * 100];
+}
+
+function rgb2hsv(rgb) {
+  var r = rgb[0],
+      g = rgb[1],
+      b = rgb[2],
+      min = Math.min(r, g, b),
+      max = Math.max(r, g, b),
+      delta = max - min,
+      h, s, v;
+
+  if (max == 0)
+    s = 0;
+  else
+    s = (delta/max * 1000)/10;
+
+  if (max == min)
+    h = 0;
+  else if (r == max)
+    h = (g - b) / delta;
+  else if (g == max)
+    h = 2 + (b - r) / delta;
+  else if (b == max)
+    h = 4 + (r - g) / delta;
+
+  h = Math.min(h * 60, 360);
+
+  if (h < 0)
+    h += 360;
+
+  v = ((max / 255) * 1000) / 10;
+
+  return [h, s, v];
+}
+
+function rgb2hwb(rgb) {
+  var r = rgb[0],
+      g = rgb[1],
+      b = rgb[2],
+      h = rgb2hsl(rgb)[0],
+      w = 1/255 * Math.min(r, Math.min(g, b)),
+      b = 1 - 1/255 * Math.max(r, Math.max(g, b));
+
+  return [h, w * 100, b * 100];
+}
+
+function rgb2cmyk(rgb) {
+  var r = rgb[0] / 255,
+      g = rgb[1] / 255,
+      b = rgb[2] / 255,
+      c, m, y, k;
+
+  k = Math.min(1 - r, 1 - g, 1 - b);
+  c = (1 - r - k) / (1 - k) || 0;
+  m = (1 - g - k) / (1 - k) || 0;
+  y = (1 - b - k) / (1 - k) || 0;
+  return [c * 100, m * 100, y * 100, k * 100];
+}
+
+function rgb2keyword(rgb) {
+  return reverseKeywords[JSON.stringify(rgb)];
+}
+
+function rgb2xyz(rgb) {
+  var r = rgb[0] / 255,
+      g = rgb[1] / 255,
+      b = rgb[2] / 255;
+
+  // assume sRGB
+  r = r > 0.04045 ? Math.pow(((r + 0.055) / 1.055), 2.4) : (r / 12.92);
+  g = g > 0.04045 ? Math.pow(((g + 0.055) / 1.055), 2.4) : (g / 12.92);
+  b = b > 0.04045 ? Math.pow(((b + 0.055) / 1.055), 2.4) : (b / 12.92);
+
+  var x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805);
+  var y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722);
+  var z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505);
+
+  return [x * 100, y *100, z * 100];
+}
+
+function rgb2lab(rgb) {
+  var xyz = rgb2xyz(rgb),
+        x = xyz[0],
+        y = xyz[1],
+        z = xyz[2],
+        l, a, b;
+
+  x /= 95.047;
+  y /= 100;
+  z /= 108.883;
+
+  x = x > 0.008856 ? Math.pow(x, 1/3) : (7.787 * x) + (16 / 116);
+  y = y > 0.008856 ? Math.pow(y, 1/3) : (7.787 * y) + (16 / 116);
+  z = z > 0.008856 ? Math.pow(z, 1/3) : (7.787 * z) + (16 / 116);
+
+  l = (116 * y) - 16;
+  a = 500 * (x - y);
+  b = 200 * (y - z);
+
+  return [l, a, b];
+}
+
+function rgb2lch(args) {
+  return lab2lch(rgb2lab(args));
+}
+
+function hsl2rgb(hsl) {
+  var h = hsl[0] / 360,
+      s = hsl[1] / 100,
+      l = hsl[2] / 100,
+      t1, t2, t3, rgb, val;
+
+  if (s == 0) {
+    val = l * 255;
+    return [val, val, val];
+  }
+
+  if (l < 0.5)
+    t2 = l * (1 + s);
+  else
+    t2 = l + s - l * s;
+  t1 = 2 * l - t2;
+
+  rgb = [0, 0, 0];
+  for (var i = 0; i < 3; i++) {
+    t3 = h + 1 / 3 * - (i - 1);
+    t3 < 0 && t3++;
+    t3 > 1 && t3--;
+
+    if (6 * t3 < 1)
+      val = t1 + (t2 - t1) * 6 * t3;
+    else if (2 * t3 < 1)
+      val = t2;
+    else if (3 * t3 < 2)
+      val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
+    else
+      val = t1;
+
+    rgb[i] = val * 255;
+  }
+
+  return rgb;
+}
+
+function hsl2hsv(hsl) {
+  var h = hsl[0],
+      s = hsl[1] / 100,
+      l = hsl[2] / 100,
+      sv, v;
+
+  if(l === 0) {
+      // no need to do calc on black
+      // also avoids divide by 0 error
+      return [0, 0, 0];
+  }
+
+  l *= 2;
+  s *= (l <= 1) ? l : 2 - l;
+  v = (l + s) / 2;
+  sv = (2 * s) / (l + s);
+  return [h, sv * 100, v * 100];
+}
+
+function hsl2hwb(args) {
+  return rgb2hwb(hsl2rgb(args));
+}
+
+function hsl2cmyk(args) {
+  return rgb2cmyk(hsl2rgb(args));
+}
+
+function hsl2keyword(args) {
+  return rgb2keyword(hsl2rgb(args));
+}
+
+
+function hsv2rgb(hsv) {
+  var h = hsv[0] / 60,
+      s = hsv[1] / 100,
+      v = hsv[2] / 100,
+      hi = Math.floor(h) % 6;
+
+  var f = h - Math.floor(h),
+      p = 255 * v * (1 - s),
+      q = 255 * v * (1 - (s * f)),
+      t = 255 * v * (1 - (s * (1 - f))),
+      v = 255 * v;
+
+  switch(hi) {
+    case 0:
+      return [v, t, p];
+    case 1:
+      return [q, v, p];
+    case 2:
+      return [p, v, t];
+    case 3:
+      return [p, q, v];
+    case 4:
+      return [t, p, v];
+    case 5:
+      return [v, p, q];
+  }
+}
+
+function hsv2hsl(hsv) {
+  var h = hsv[0],
+      s = hsv[1] / 100,
+      v = hsv[2] / 100,
+      sl, l;
+
+  l = (2 - s) * v;
+  sl = s * v;
+  sl /= (l <= 1) ? l : 2 - l;
+  sl = sl || 0;
+  l /= 2;
+  return [h, sl * 100, l * 100];
+}
+
+function hsv2hwb(args) {
+  return rgb2hwb(hsv2rgb(args))
+}
+
+function hsv2cmyk(args) {
+  return rgb2cmyk(hsv2rgb(args));
+}
+
+function hsv2keyword(args) {
+  return rgb2keyword(hsv2rgb(args));
+}
+
+// http://dev.w3.org/csswg/css-color/#hwb-to-rgb
+function hwb2rgb(hwb) {
+  var h = hwb[0] / 360,
+      wh = hwb[1] / 100,
+      bl = hwb[2] / 100,
+      ratio = wh + bl,
+      i, v, f, n;
+
+  // wh + bl cant be > 1
+  if (ratio > 1) {
+    wh /= ratio;
+    bl /= ratio;
+  }
+
+  i = Math.floor(6 * h);
+  v = 1 - bl;
+  f = 6 * h - i;
+  if ((i & 0x01) != 0) {
+    f = 1 - f;
+  }
+  n = wh + f * (v - wh);  // linear interpolation
+
+  switch (i) {
+    default:
+    case 6:
+    case 0: r = v; g = n; b = wh; break;
+    case 1: r = n; g = v; b = wh; break;
+    case 2: r = wh; g = v; b = n; break;
+    case 3: r = wh; g = n; b = v; break;
+    case 4: r = n; g = wh; b = v; break;
+    case 5: r = v; g = wh; b = n; break;
+  }
+
+  return [r * 255, g * 255, b * 255];
+}
+
+function hwb2hsl(args) {
+  return rgb2hsl(hwb2rgb(args));
+}
+
+function hwb2hsv(args) {
+  return rgb2hsv(hwb2rgb(args));
+}
+
+function hwb2cmyk(args) {
+  return rgb2cmyk(hwb2rgb(args));
+}
+
+function hwb2keyword(args) {
+  return rgb2keyword(hwb2rgb(args));
+}
+
+function cmyk2rgb(cmyk) {
+  var c = cmyk[0] / 100,
+      m = cmyk[1] / 100,
+      y = cmyk[2] / 100,
+      k = cmyk[3] / 100,
+      r, g, b;
+
+  r = 1 - Math.min(1, c * (1 - k) + k);
+  g = 1 - Math.min(1, m * (1 - k) + k);
+  b = 1 - Math.min(1, y * (1 - k) + k);
+  return [r * 255, g * 255, b * 255];
+}
+
+function cmyk2hsl(args) {
+  return rgb2hsl(cmyk2rgb(args));
+}
+
+function cmyk2hsv(args) {
+  return rgb2hsv(cmyk2rgb(args));
+}
+
+function cmyk2hwb(args) {
+  return rgb2hwb(cmyk2rgb(args));
+}
+
+function cmyk2keyword(args) {
+  return rgb2keyword(cmyk2rgb(args));
+}
+
+
+function xyz2rgb(xyz) {
+  var x = xyz[0] / 100,
+      y = xyz[1] / 100,
+      z = xyz[2] / 100,
+      r, g, b;
+
+  r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986);
+  g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415);
+  b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570);
+
+  // assume sRGB
+  r = r > 0.0031308 ? ((1.055 * Math.pow(r, 1.0 / 2.4)) - 0.055)
+    : r = (r * 12.92);
+
+  g = g > 0.0031308 ? ((1.055 * Math.pow(g, 1.0 / 2.4)) - 0.055)
+    : g = (g * 12.92);
+
+  b = b > 0.0031308 ? ((1.055 * Math.pow(b, 1.0 / 2.4)) - 0.055)
+    : b = (b * 12.92);
+
+  r = Math.min(Math.max(0, r), 1);
+  g = Math.min(Math.max(0, g), 1);
+  b = Math.min(Math.max(0, b), 1);
+
+  return [r * 255, g * 255, b * 255];
+}
+
+function xyz2lab(xyz) {
+  var x = xyz[0],
+      y = xyz[1],
+      z = xyz[2],
+      l, a, b;
+
+  x /= 95.047;
+  y /= 100;
+  z /= 108.883;
+
+  x = x > 0.008856 ? Math.pow(x, 1/3) : (7.787 * x) + (16 / 116);
+  y = y > 0.008856 ? Math.pow(y, 1/3) : (7.787 * y) + (16 / 116);
+  z = z > 0.008856 ? Math.pow(z, 1/3) : (7.787 * z) + (16 / 116);
+
+  l = (116 * y) - 16;
+  a = 500 * (x - y);
+  b = 200 * (y - z);
+
+  return [l, a, b];
+}
+
+function xyz2lch(args) {
+  return lab2lch(xyz2lab(args));
+}
+
+function lab2xyz(lab) {
+  var l = lab[0],
+      a = lab[1],
+      b = lab[2],
+      x, y, z, y2;
+
+  if (l <= 8) {
+    y = (l * 100) / 903.3;
+    y2 = (7.787 * (y / 100)) + (16 / 116);
+  } else {
+    y = 100 * Math.pow((l + 16) / 116, 3);
+    y2 = Math.pow(y / 100, 1/3);
+  }
+
+  x = x / 95.047 <= 0.008856 ? x = (95.047 * ((a / 500) + y2 - (16 / 116))) / 7.787 : 95.047 * Math.pow((a / 500) + y2, 3);
+
+  z = z / 108.883 <= 0.008859 ? z = (108.883 * (y2 - (b / 200) - (16 / 116))) / 7.787 : 108.883 * Math.pow(y2 - (b / 200), 3);
+
+  return [x, y, z];
+}
+
+function lab2lch(lab) {
+  var l = lab[0],
+      a = lab[1],
+      b = lab[2],
+      hr, h, c;
+
+  hr = Math.atan2(b, a);
+  h = hr * 360 / 2 / Math.PI;
+  if (h < 0) {
+    h += 360;
+  }
+  c = Math.sqrt(a * a + b * b);
+  return [l, c, h];
+}
+
+function lab2rgb(args) {
+  return xyz2rgb(lab2xyz(args));
+}
+
+function lch2lab(lch) {
+  var l = lch[0],
+      c = lch[1],
+      h = lch[2],
+      a, b, hr;
+
+  hr = h / 360 * 2 * Math.PI;
+  a = c * Math.cos(hr);
+  b = c * Math.sin(hr);
+  return [l, a, b];
+}
+
+function lch2xyz(args) {
+  return lab2xyz(lch2lab(args));
+}
+
+function lch2rgb(args) {
+  return lab2rgb(lch2lab(args));
+}
+
+function keyword2rgb(keyword) {
+  return cssKeywords[keyword];
+}
+
+function keyword2hsl(args) {
+  return rgb2hsl(keyword2rgb(args));
+}
+
+function keyword2hsv(args) {
+  return rgb2hsv(keyword2rgb(args));
+}
+
+function keyword2hwb(args) {
+  return rgb2hwb(keyword2rgb(args));
+}
+
+function keyword2cmyk(args) {
+  return rgb2cmyk(keyword2rgb(args));
+}
+
+function keyword2lab(args) {
+  return rgb2lab(keyword2rgb(args));
+}
+
+function keyword2xyz(args) {
+  return rgb2xyz(keyword2rgb(args));
+}
+
+var cssKeywords = {
+  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]
+};
+
+var reverseKeywords = {};
+for (var key in cssKeywords) {
+  reverseKeywords[JSON.stringify(cssKeywords[key])] = key;
+}
+
+},{}],5:[function(require,module,exports){
+var conversions = require(4);
+
+var convert = function() {
+   return new Converter();
+}
+
+for (var func in conversions) {
+  // export Raw versions
+  convert[func + "Raw"] =  (function(func) {
+    // accept array or plain args
+    return function(arg) {
+      if (typeof arg == "number")
+        arg = Array.prototype.slice.call(arguments);
+      return conversions[func](arg);
+    }
+  })(func);
+
+  var pair = /(\w+)2(\w+)/.exec(func),
+      from = pair[1],
+      to = pair[2];
+
+  // export rgb2hsl and ["rgb"]["hsl"]
+  convert[from] = convert[from] || {};
+
+  convert[from][to] = convert[func] = (function(func) { 
+    return function(arg) {
+      if (typeof arg == "number")
+        arg = Array.prototype.slice.call(arguments);
+      
+      var val = conversions[func](arg);
+      if (typeof val == "string" || val === undefined)
+        return val; // keyword
+
+      for (var i = 0; i < val.length; i++)
+        val[i] = Math.round(val[i]);
+      return val;
+    }
+  })(func);
+}
+
+
+/* Converter does lazy conversion and caching */
+var Converter = function() {
+   this.convs = {};
+};
+
+/* Either get the values for a space or
+  set the values for a space, depending on args */
+Converter.prototype.routeSpace = function(space, args) {
+   var values = args[0];
+   if (values === undefined) {
+      // color.rgb()
+      return this.getValues(space);
+   }
+   // color.rgb(10, 10, 10)
+   if (typeof values == "number") {
+      values = Array.prototype.slice.call(args);        
+   }
+
+   return this.setValues(space, values);
+};
+  
+/* Set the values for a space, invalidating cache */
+Converter.prototype.setValues = function(space, values) {
+   this.space = space;
+   this.convs = {};
+   this.convs[space] = values;
+   return this;
+};
+
+/* Get the values for a space. If there's already
+  a conversion for the space, fetch it, otherwise
+  compute it */
+Converter.prototype.getValues = function(space) {
+   var vals = this.convs[space];
+   if (!vals) {
+      var fspace = this.space,
+          from = this.convs[fspace];
+      vals = convert[fspace][space](from);
+
+      this.convs[space] = vals;
+   }
+  return vals;
+};
+
+["rgb", "hsl", "hsv", "cmyk", "keyword"].forEach(function(space) {
+   Converter.prototype[space] = function(vals) {
+      return this.routeSpace(space, arguments);
+   }
+});
+
+module.exports = convert;
+},{"4":4}],6:[function(require,module,exports){
+module.exports = {
+	"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]
+};
+},{}],7:[function(require,module,exports){
+/**
+ * @namespace Chart
+ */
+var Chart = require(28)();
+
+require(26)(Chart);
+require(42)(Chart);
+require(22)(Chart);
+require(31)(Chart);
+require(25)(Chart);
+require(21)(Chart);
+require(23)(Chart);
+require(24)(Chart);
+require(29)(Chart);
+require(33)(Chart);
+require(34)(Chart);
+require(32)(Chart);
+require(35)(Chart);
+require(30)(Chart);
+require(27)(Chart);
+require(36)(Chart);
+
+require(37)(Chart);
+require(38)(Chart);
+require(39)(Chart);
+require(40)(Chart);
+
+require(45)(Chart);
+require(43)(Chart);
+require(44)(Chart);
+require(46)(Chart);
+require(47)(Chart);
+require(48)(Chart);
+
+// Controllers must be loaded after elements
+// See Chart.core.datasetController.dataElementType
+require(15)(Chart);
+require(16)(Chart);
+require(17)(Chart);
+require(18)(Chart);
+require(19)(Chart);
+require(20)(Chart);
+
+require(8)(Chart);
+require(9)(Chart);
+require(10)(Chart);
+require(11)(Chart);
+require(12)(Chart);
+require(13)(Chart);
+require(14)(Chart);
+
+window.Chart = module.exports = Chart;
+
+},{"10":10,"11":11,"12":12,"13":13,"14":14,"15":15,"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,"30":30,"31":31,"32":32,"33":33,"34":34,"35":35,"36":36,"37":37,"38":38,"39":39,"40":40,"42":42,"43":43,"44":44,"45":45,"46":46,"47":47,"48":48,"8":8,"9":9}],8:[function(require,module,exports){
+'use strict';
+
+module.exports = function(Chart) {
+
+	Chart.Bar = function(context, config) {
+		config.type = 'bar';
+
+		return new Chart(context, config);
+	};
+
+};
+
+},{}],9:[function(require,module,exports){
+'use strict';
+
+module.exports = function(Chart) {
+
+	Chart.Bubble = function(context, config) {
+		config.type = 'bubble';
+		return new Chart(context, config);
+	};
+
+};
+
+},{}],10:[function(require,module,exports){
+'use strict';
+
+module.exports = function(Chart) {
+
+	Chart.Doughnut = function(context, config) {
+		config.type = 'doughnut';
+
+		return new Chart(context, config);
+	};
+
+};
+
+},{}],11:[function(require,module,exports){
+'use strict';
+
+module.exports = function(Chart) {
+
+	Chart.Line = function(context, config) {
+		config.type = 'line';
+
+		return new Chart(context, config);
+	};
+
+};
+
+},{}],12:[function(require,module,exports){
+'use strict';
+
+module.exports = function(Chart) {
+
+	Chart.PolarArea = function(context, config) {
+		config.type = 'polarArea';
+
+		return new Chart(context, config);
+	};
+
+};
+
+},{}],13:[function(require,module,exports){
+'use strict';
+
+module.exports = function(Chart) {
+
+	Chart.Radar = function(context, config) {
+		config.type = 'radar';
+
+		return new Chart(context, config);
+	};
+
+};
+
+},{}],14:[function(require,module,exports){
+'use strict';
+
+module.exports = function(Chart) {
+
+	var defaultConfig = {
+		hover: {
+			mode: 'single'
+		},
+
+		scales: {
+			xAxes: [{
+				type: 'linear', // scatter should not use a category axis
+				position: 'bottom',
+				id: 'x-axis-1' // need an ID so datasets can reference the scale
+			}],
+			yAxes: [{
+				type: 'linear',
+				position: 'left',
+				id: 'y-axis-1'
+			}]
+		},
+
+		tooltips: {
+			callbacks: {
+				title: function() {
+					// Title doesn't make sense for scatter since we format the data as a point
+					return '';
+				},
+				label: function(tooltipItem) {
+					return '(' + tooltipItem.xLabel + ', ' + tooltipItem.yLabel + ')';
+				}
+			}
+		}
+	};
+
+	// Register the default config for this type
+	Chart.defaults.scatter = defaultConfig;
+
+	// Scatter charts use line controllers
+	Chart.controllers.scatter = Chart.controllers.line;
+
+	Chart.Scatter = function(context, config) {
+		config.type = 'scatter';
+		return new Chart(context, config);
+	};
+
+};
+
+},{}],15:[function(require,module,exports){
+'use strict';
+
+module.exports = function(Chart) {
+
+	var helpers = Chart.helpers;
+
+	Chart.defaults.bar = {
+		hover: {
+			mode: 'label'
+		},
+
+		scales: {
+			xAxes: [{
+				type: 'category',
+
+				// Specific to Bar Controller
+				categoryPercentage: 0.8,
+				barPercentage: 0.9,
+
+				// grid line settings
+				gridLines: {
+					offsetGridLines: true
+				}
+			}],
+			yAxes: [{
+				type: 'linear'
+			}]
+		}
+	};
+
+	Chart.controllers.bar = Chart.DatasetController.extend({
+
+		dataElementType: Chart.elements.Rectangle,
+
+		initialize: function(chart, datasetIndex) {
+			Chart.DatasetController.prototype.initialize.call(this, chart, datasetIndex);
+
+			var me = this;
+			var meta = me.getMeta();
+			var dataset = me.getDataset();
+
+			meta.stack = dataset.stack;
+			// Use this to indicate that this is a bar dataset.
+			meta.bar = true;
+		},
+
+		// Correctly calculate the bar width accounting for stacks and the fact that not all bars are visible
+		getStackCount: function() {
+			var me = this;
+			var meta = me.getMeta();
+			var yScale = me.getScaleForId(meta.yAxisID);
+
+			var stacks = [];
+			helpers.each(me.chart.data.datasets, function(dataset, datasetIndex) {
+				var dsMeta = me.chart.getDatasetMeta(datasetIndex);
+				if (dsMeta.bar && me.chart.isDatasetVisible(datasetIndex) &&
+					(yScale.options.stacked === false ||
+					(yScale.options.stacked === true && stacks.indexOf(dsMeta.stack) === -1) ||
+					(yScale.options.stacked === undefined && (dsMeta.stack === undefined || stacks.indexOf(dsMeta.stack) === -1)))) {
+					stacks.push(dsMeta.stack);
+				}
+			}, me);
+
+			return stacks.length;
+		},
+
+		update: function(reset) {
+			var me = this;
+			helpers.each(me.getMeta().data, function(rectangle, index) {
+				me.updateElement(rectangle, index, reset);
+			}, me);
+		},
+
+		updateElement: function(rectangle, index, reset) {
+			var me = this;
+			var meta = me.getMeta();
+			var xScale = me.getScaleForId(meta.xAxisID);
+			var yScale = me.getScaleForId(meta.yAxisID);
+			var scaleBase = yScale.getBasePixel();
+			var rectangleElementOptions = me.chart.options.elements.rectangle;
+			var custom = rectangle.custom || {};
+			var dataset = me.getDataset();
+
+			rectangle._xScale = xScale;
+			rectangle._yScale = yScale;
+			rectangle._datasetIndex = me.index;
+			rectangle._index = index;
+
+			var ruler = me.getRuler(index); // The index argument for compatible
+			rectangle._model = {
+				x: me.calculateBarX(index, me.index, ruler),
+				y: reset ? scaleBase : me.calculateBarY(index, me.index),
+
+				// Tooltip
+				label: me.chart.data.labels[index],
+				datasetLabel: dataset.label,
+
+				// Appearance
+				horizontal: false,
+				base: reset ? scaleBase : me.calculateBarBase(me.index, index),
+				width: me.calculateBarWidth(ruler),
+				backgroundColor: custom.backgroundColor ? custom.backgroundColor : helpers.getValueAtIndexOrDefault(dataset.backgroundColor, index, rectangleElementOptions.backgroundColor),
+				borderSkipped: custom.borderSkipped ? custom.borderSkipped : rectangleElementOptions.borderSkipped,
+				borderColor: custom.borderColor ? custom.borderColor : helpers.getValueAtIndexOrDefault(dataset.borderColor, index, rectangleElementOptions.borderColor),
+				borderWidth: custom.borderWidth ? custom.borderWidth : helpers.getValueAtIndexOrDefault(dataset.borderWidth, index, rectangleElementOptions.borderWidth)
+			};
+
+			rectangle.pivot();
+		},
+
+		calculateBarBase: function(datasetIndex, index) {
+			var me = this;
+			var meta = me.getMeta();
+			var yScale = me.getScaleForId(meta.yAxisID);
+			var base = yScale.getBaseValue();
+			var original = base;
+
+			if ((yScale.options.stacked === true) ||
+				(yScale.options.stacked === undefined && meta.stack !== undefined)) {
+				var chart = me.chart;
+				var datasets = chart.data.datasets;
+				var value = Number(datasets[datasetIndex].data[index]);
+
+				for (var i = 0; i < datasetIndex; i++) {
+					var currentDs = datasets[i];
+					var currentDsMeta = chart.getDatasetMeta(i);
+					if (currentDsMeta.bar && currentDsMeta.yAxisID === yScale.id && chart.isDatasetVisible(i) &&
+						meta.stack === currentDsMeta.stack) {
+						var currentVal = Number(currentDs.data[index]);
+						base += value < 0 ? Math.min(currentVal, original) : Math.max(currentVal, original);
+					}
+				}
+
+				return yScale.getPixelForValue(base);
+			}
+
+			return yScale.getBasePixel();
+		},
+
+		getRuler: function() {
+			var me = this;
+			var meta = me.getMeta();
+			var xScale = me.getScaleForId(meta.xAxisID);
+			var stackCount = me.getStackCount();
+
+			var tickWidth = xScale.width / xScale.ticks.length;
+			var categoryWidth = tickWidth * xScale.options.categoryPercentage;
+			var categorySpacing = (tickWidth - (tickWidth * xScale.options.categoryPercentage)) / 2;
+			var fullBarWidth = categoryWidth / stackCount;
+
+			var barWidth = fullBarWidth * xScale.options.barPercentage;
+			var barSpacing = fullBarWidth - (fullBarWidth * xScale.options.barPercentage);
+
+			return {
+				stackCount: stackCount,
+				tickWidth: tickWidth,
+				categoryWidth: categoryWidth,
+				categorySpacing: categorySpacing,
+				fullBarWidth: fullBarWidth,
+				barWidth: barWidth,
+				barSpacing: barSpacing
+			};
+		},
+
+		calculateBarWidth: function(ruler) {
+			var me = this;
+			var meta = me.getMeta();
+			var xScale = me.getScaleForId(meta.xAxisID);
+			if (xScale.options.barThickness) {
+				return xScale.options.barThickness;
+			}
+			return ruler.barWidth;
+		},
+
+		// Get stack index from the given dataset index accounting for stacks and the fact that not all bars are visible
+		getStackIndex: function(datasetIndex) {
+			var me = this;
+			var meta = me.chart.getDatasetMeta(datasetIndex);
+			var yScale = me.getScaleForId(meta.yAxisID);
+			var dsMeta, j;
+			var stacks = [meta.stack];
+
+			for (j = 0; j < datasetIndex; ++j) {
+				dsMeta = this.chart.getDatasetMeta(j);
+				if (dsMeta.bar && this.chart.isDatasetVisible(j) &&
+					(yScale.options.stacked === false ||
+					(yScale.options.stacked === true && stacks.indexOf(dsMeta.stack) === -1) ||
+					(yScale.options.stacked === undefined && (dsMeta.stack === undefined || stacks.indexOf(dsMeta.stack) === -1)))) {
+					stacks.push(dsMeta.stack);
+				}
+			}
+
+			return stacks.length - 1;
+		},
+
+		calculateBarX: function(index, datasetIndex, ruler) {
+			var me = this;
+			var meta = me.getMeta();
+			var xScale = me.getScaleForId(meta.xAxisID);
+			var stackIndex = me.getStackIndex(datasetIndex);
+			var leftTick = xScale.getPixelForValue(null, index, datasetIndex, me.chart.isCombo);
+			leftTick -= me.chart.isCombo ? (ruler.tickWidth / 2) : 0;
+
+			return leftTick +
+				(ruler.barWidth / 2) +
+				ruler.categorySpacing +
+				(ruler.barWidth * stackIndex) +
+				(ruler.barSpacing / 2) +
+				(ruler.barSpacing * stackIndex);
+		},
+
+		calculateBarY: function(index, datasetIndex) {
+			var me = this;
+			var meta = me.getMeta();
+			var yScale = me.getScaleForId(meta.yAxisID);
+			var value = Number(me.getDataset().data[index]);
+
+			if (yScale.options.stacked ||
+				(yScale.options.stacked === undefined && meta.stack !== undefined)) {
+				var base = yScale.getBaseValue();
+				var sumPos = base,
+					sumNeg = base;
+
+				for (var i = 0; i < datasetIndex; i++) {
+					var ds = me.chart.data.datasets[i];
+					var dsMeta = me.chart.getDatasetMeta(i);
+					if (dsMeta.bar && dsMeta.yAxisID === yScale.id && me.chart.isDatasetVisible(i) &&
+						meta.stack === dsMeta.stack) {
+						var stackedVal = Number(ds.data[index]);
+						if (stackedVal < 0) {
+							sumNeg += stackedVal || 0;
+						} else {
+							sumPos += stackedVal || 0;
+						}
+					}
+				}
+
+				if (value < 0) {
+					return yScale.getPixelForValue(sumNeg + value);
+				}
+				return yScale.getPixelForValue(sumPos + value);
+			}
+
+			return yScale.getPixelForValue(value);
+		},
+
+		draw: function(ease) {
+			var me = this;
+			var easingDecimal = ease || 1;
+			var metaData = me.getMeta().data;
+			var dataset = me.getDataset();
+			var i, len;
+
+			Chart.canvasHelpers.clipArea(me.chart.chart.ctx, me.chart.chartArea);
+			for (i = 0, len = metaData.length; i < len; ++i) {
+				var d = dataset.data[i];
+				if (d !== null && d !== undefined && !isNaN(d)) {
+					metaData[i].transition(easingDecimal).draw();
+				}
+			}
+			Chart.canvasHelpers.unclipArea(me.chart.chart.ctx);
+		},
+
+		setHoverStyle: function(rectangle) {
+			var dataset = this.chart.data.datasets[rectangle._datasetIndex];
+			var index = rectangle._index;
+
+			var custom = rectangle.custom || {};
+			var model = rectangle._model;
+			model.backgroundColor = custom.hoverBackgroundColor ? custom.hoverBackgroundColor : helpers.getValueAtIndexOrDefault(dataset.hoverBackgroundColor, index, helpers.getHoverColor(model.backgroundColor));
+			model.borderColor = custom.hoverBorderColor ? custom.hoverBorderColor : helpers.getValueAtIndexOrDefault(dataset.hoverBorderColor, index, helpers.getHoverColor(model.borderColor));
+			model.borderWidth = custom.hoverBorderWidth ? custom.hoverBorderWidth : helpers.getValueAtIndexOrDefault(dataset.hoverBorderWidth, index, model.borderWidth);
+		},
+
+		removeHoverStyle: function(rectangle) {
+			var dataset = this.chart.data.datasets[rectangle._datasetIndex];
+			var index = rectangle._index;
+			var custom = rectangle.custom || {};
+			var model = rectangle._model;
+			var rectangleElementOptions = this.chart.options.elements.rectangle;
+
+			model.backgroundColor = custom.backgroundColor ? custom.backgroundColor : helpers.getValueAtIndexOrDefault(dataset.backgroundColor, index, rectangleElementOptions.backgroundColor);
+			model.borderColor = custom.borderColor ? custom.borderColor : helpers.getValueAtIndexOrDefault(dataset.borderColor, index, rectangleElementOptions.borderColor);
+			model.borderWidth = custom.borderWidth ? custom.borderWidth : helpers.getValueAtIndexOrDefault(dataset.borderWidth, index, rectangleElementOptions.borderWidth);
+		}
+
+	});
+
+
+	// including horizontalBar in the bar file, instead of a file of its own
+	// it extends bar (like pie extends doughnut)
+	Chart.defaults.horizontalBar = {
+		hover: {
+			mode: 'label'
+		},
+
+		scales: {
+			xAxes: [{
+				type: 'linear',
+				position: 'bottom'
+			}],
+			yAxes: [{
+				position: 'left',
+				type: 'category',
+
+				// Specific to Horizontal Bar Controller
+				categoryPercentage: 0.8,
+				barPercentage: 0.9,
+
+				// grid line settings
+				gridLines: {
+					offsetGridLines: true
+				}
+			}]
+		},
+		elements: {
+			rectangle: {
+				borderSkipped: 'left'
+			}
+		},
+		tooltips: {
+			callbacks: {
+				title: function(tooltipItems, data) {
+					// Pick first xLabel for now
+					var title = '';
+
+					if (tooltipItems.length > 0) {
+						if (tooltipItems[0].yLabel) {
+							title = tooltipItems[0].yLabel;
+						} else if (data.labels.length > 0 && tooltipItems[0].index < data.labels.length) {
+							title = data.labels[tooltipItems[0].index];
+						}
+					}
+
+					return title;
+				},
+				label: function(tooltipItem, data) {
+					var datasetLabel = data.datasets[tooltipItem.datasetIndex].label || '';
+					return datasetLabel + ': ' + tooltipItem.xLabel;
+				}
+			}
+		}
+	};
+
+	Chart.controllers.horizontalBar = Chart.controllers.bar.extend({
+
+		// Correctly calculate the bar width accounting for stacks and the fact that not all bars are visible
+		getStackCount: function() {
+			var me = this;
+			var meta = me.getMeta();
+			var xScale = me.getScaleForId(meta.xAxisID);
+
+			var stacks = [];
+			helpers.each(me.chart.data.datasets, function(dataset, datasetIndex) {
+				var dsMeta = me.chart.getDatasetMeta(datasetIndex);
+				if (dsMeta.bar && me.chart.isDatasetVisible(datasetIndex) &&
+					(xScale.options.stacked === false ||
+					(xScale.options.stacked === true && stacks.indexOf(dsMeta.stack) === -1) ||
+					(xScale.options.stacked === undefined && (dsMeta.stack === undefined || stacks.indexOf(dsMeta.stack) === -1)))) {
+					stacks.push(dsMeta.stack);
+				}
+			}, me);
+
+			return stacks.length;
+		},
+
+		updateElement: function(rectangle, index, reset) {
+			var me = this;
+			var meta = me.getMeta();
+			var xScale = me.getScaleForId(meta.xAxisID);
+			var yScale = me.getScaleForId(meta.yAxisID);
+			var scaleBase = xScale.getBasePixel();
+			var custom = rectangle.custom || {};
+			var dataset = me.getDataset();
+			var rectangleElementOptions = me.chart.options.elements.rectangle;
+
+			rectangle._xScale = xScale;
+			rectangle._yScale = yScale;
+			rectangle._datasetIndex = me.index;
+			rectangle._index = index;
+
+			var ruler = me.getRuler(index); // The index argument for compatible
+			rectangle._model = {
+				x: reset ? scaleBase : me.calculateBarX(index, me.index),
+				y: me.calculateBarY(index, me.index, ruler),
+
+				// Tooltip
+				label: me.chart.data.labels[index],
+				datasetLabel: dataset.label,
+
+				// Appearance
+				horizontal: true,
+				base: reset ? scaleBase : me.calculateBarBase(me.index, index),
+				height: me.calculateBarHeight(ruler),
+				backgroundColor: custom.backgroundColor ? custom.backgroundColor : helpers.getValueAtIndexOrDefault(dataset.backgroundColor, index, rectangleElementOptions.backgroundColor),
+				borderSkipped: custom.borderSkipped ? custom.borderSkipped : rectangleElementOptions.borderSkipped,
+				borderColor: custom.borderColor ? custom.borderColor : helpers.getValueAtIndexOrDefault(dataset.borderColor, index, rectangleElementOptions.borderColor),
+				borderWidth: custom.borderWidth ? custom.borderWidth : helpers.getValueAtIndexOrDefault(dataset.borderWidth, index, rectangleElementOptions.borderWidth)
+			};
+
+			rectangle.pivot();
+		},
+
+		calculateBarBase: function(datasetIndex, index) {
+			var me = this;
+			var meta = me.getMeta();
+			var xScale = me.getScaleForId(meta.xAxisID);
+			var base = xScale.getBaseValue();
+			var originalBase = base;
+
+			if (xScale.options.stacked ||
+				(xScale.options.stacked === undefined && meta.stack !== undefined)) {
+				var chart = me.chart;
+				var datasets = chart.data.datasets;
+				var value = Number(datasets[datasetIndex].data[index]);
+
+				for (var i = 0; i < datasetIndex; i++) {
+					var currentDs = datasets[i];
+					var currentDsMeta = chart.getDatasetMeta(i);
+					if (currentDsMeta.bar && currentDsMeta.xAxisID === xScale.id && chart.isDatasetVisible(i) &&
+						meta.stack === currentDsMeta.stack) {
+						var currentVal = Number(currentDs.data[index]);
+						base += value < 0 ? Math.min(currentVal, originalBase) : Math.max(currentVal, originalBase);
+					}
+				}
+
+				return xScale.getPixelForValue(base);
+			}
+
+			return xScale.getBasePixel();
+		},
+
+		getRuler: function() {
+			var me = this;
+			var meta = me.getMeta();
+			var yScale = me.getScaleForId(meta.yAxisID);
+			var stackCount = me.getStackCount();
+
+			var tickHeight = yScale.height / yScale.ticks.length;
+			var categoryHeight = tickHeight * yScale.options.categoryPercentage;
+			var categorySpacing = (tickHeight - (tickHeight * yScale.options.categoryPercentage)) / 2;
+			var fullBarHeight = categoryHeight / stackCount;
+
+			var barHeight = fullBarHeight * yScale.options.barPercentage;
+			var barSpacing = fullBarHeight - (fullBarHeight * yScale.options.barPercentage);
+
+			return {
+				stackCount: stackCount,
+				tickHeight: tickHeight,
+				categoryHeight: categoryHeight,
+				categorySpacing: categorySpacing,
+				fullBarHeight: fullBarHeight,
+				barHeight: barHeight,
+				barSpacing: barSpacing
+			};
+		},
+
+		calculateBarHeight: function(ruler) {
+			var me = this;
+			var meta = me.getMeta();
+			var yScale = me.getScaleForId(meta.yAxisID);
+			if (yScale.options.barThickness) {
+				return yScale.options.barThickness;
+			}
+			return ruler.barHeight;
+		},
+
+		// Get stack index from the given dataset index accounting for stacks and the fact that not all bars are visible
+		getStackIndex: function(datasetIndex) {
+			var me = this;
+			var meta = me.chart.getDatasetMeta(datasetIndex);
+			var xScale = me.getScaleForId(meta.xAxisID);
+			var dsMeta, j;
+			var stacks = [meta.stack];
+
+			for (j = 0; j < datasetIndex; ++j) {
+				dsMeta = this.chart.getDatasetMeta(j);
+				if (dsMeta.bar && this.chart.isDatasetVisible(j) &&
+					(xScale.options.stacked === false ||
+					(xScale.options.stacked === true && stacks.indexOf(dsMeta.stack) === -1) ||
+					(xScale.options.stacked === undefined && (dsMeta.stack === undefined || stacks.indexOf(dsMeta.stack) === -1)))) {
+					stacks.push(dsMeta.stack);
+				}
+			}
+
+			return stacks.length - 1;
+		},
+
+		calculateBarX: function(index, datasetIndex) {
+			var me = this;
+			var meta = me.getMeta();
+			var xScale = me.getScaleForId(meta.xAxisID);
+			var value = Number(me.getDataset().data[index]);
+
+			if (xScale.options.stacked ||
+				(xScale.options.stacked === undefined && meta.stack !== undefined)) {
+				var base = xScale.getBaseValue();
+				var sumPos = base,
+					sumNeg = base;
+
+				for (var i = 0; i < datasetIndex; i++) {
+					var ds = me.chart.data.datasets[i];
+					var dsMeta = me.chart.getDatasetMeta(i);
+					if (dsMeta.bar && dsMeta.xAxisID === xScale.id && me.chart.isDatasetVisible(i) &&
+						meta.stack === dsMeta.stack) {
+						var stackedVal = Number(ds.data[index]);
+						if (stackedVal < 0) {
+							sumNeg += stackedVal || 0;
+						} else {
+							sumPos += stackedVal || 0;
+						}
+					}
+				}
+
+				if (value < 0) {
+					return xScale.getPixelForValue(sumNeg + value);
+				}
+				return xScale.getPixelForValue(sumPos + value);
+			}
+
+			return xScale.getPixelForValue(value);
+		},
+
+		calculateBarY: function(index, datasetIndex, ruler) {
+			var me = this;
+			var meta = me.getMeta();
+			var yScale = me.getScaleForId(meta.yAxisID);
+			var stackIndex = me.getStackIndex(datasetIndex);
+			var topTick = yScale.getPixelForValue(null, index, datasetIndex, me.chart.isCombo);
+			topTick -= me.chart.isCombo ? (ruler.tickHeight / 2) : 0;
+
+			return topTick +
+				(ruler.barHeight / 2) +
+				ruler.categorySpacing +
+				(ruler.barHeight * stackIndex) +
+				(ruler.barSpacing / 2) +
+				(ruler.barSpacing * stackIndex);
+		}
+	});
+};
+
+},{}],16:[function(require,module,exports){
+'use strict';
+
+module.exports = function(Chart) {
+
+	var helpers = Chart.helpers;
+
+	Chart.defaults.bubble = {
+		hover: {
+			mode: 'single'
+		},
+
+		scales: {
+			xAxes: [{
+				type: 'linear', // bubble should probably use a linear scale by default
+				position: 'bottom',
+				id: 'x-axis-0' // need an ID so datasets can reference the scale
+			}],
+			yAxes: [{
+				type: 'linear',
+				position: 'left',
+				id: 'y-axis-0'
+			}]
+		},
+
+		tooltips: {
+			callbacks: {
+				title: function() {
+					// Title doesn't make sense for scatter since we format the data as a point
+					return '';
+				},
+				label: function(tooltipItem, data) {
+					var datasetLabel = data.datasets[tooltipItem.datasetIndex].label || '';
+					var dataPoint = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
+					return datasetLabel + ': (' + tooltipItem.xLabel + ', ' + tooltipItem.yLabel + ', ' + dataPoint.r + ')';
+				}
+			}
+		}
+	};
+
+	Chart.controllers.bubble = Chart.DatasetController.extend({
+
+		dataElementType: Chart.elements.Point,
+
+		update: function(reset) {
+			var me = this;
+			var meta = me.getMeta();
+			var points = meta.data;
+
+			// Update Points
+			helpers.each(points, function(point, index) {
+				me.updateElement(point, index, reset);
+			});
+		},
+
+		updateElement: function(point, index, reset) {
+			var me = this;
+			var meta = me.getMeta();
+			var xScale = me.getScaleForId(meta.xAxisID);
+			var yScale = me.getScaleForId(meta.yAxisID);
+
+			var custom = point.custom || {};
+			var dataset = me.getDataset();
+			var data = dataset.data[index];
+			var pointElementOptions = me.chart.options.elements.point;
+			var dsIndex = me.index;
+
+			helpers.extend(point, {
+				// Utility
+				_xScale: xScale,
+				_yScale: yScale,
+				_datasetIndex: dsIndex,
+				_index: index,
+
+				// Desired view properties
+				_model: {
+					x: reset ? xScale.getPixelForDecimal(0.5) : xScale.getPixelForValue(typeof data === 'object' ? data : NaN, index, dsIndex, me.chart.isCombo),
+					y: reset ? yScale.getBasePixel() : yScale.getPixelForValue(data, index, dsIndex),
+					// Appearance
+					radius: reset ? 0 : custom.radius ? custom.radius : me.getRadius(data),
+
+					// Tooltip
+					hitRadius: custom.hitRadius ? custom.hitRadius : helpers.getValueAtIndexOrDefault(dataset.hitRadius, index, pointElementOptions.hitRadius)
+				}
+			});
+
+			// Trick to reset the styles of the point
+			Chart.DatasetController.prototype.removeHoverStyle.call(me, point, pointElementOptions);
+
+			var model = point._model;
+			model.skip = custom.skip ? custom.skip : (isNaN(model.x) || isNaN(model.y));
+
+			point.pivot();
+		},
+
+		getRadius: function(value) {
+			return value.r || this.chart.options.elements.point.radius;
+		},
+
+		setHoverStyle: function(point) {
+			var me = this;
+			Chart.DatasetController.prototype.setHoverStyle.call(me, point);
+
+			// Radius
+			var dataset = me.chart.data.datasets[point._datasetIndex];
+			var index = point._index;
+			var custom = point.custom || {};
+			var model = point._model;
+			model.radius = custom.hoverRadius ? custom.hoverRadius : (helpers.getValueAtIndexOrDefault(dataset.hoverRadius, index, me.chart.options.elements.point.hoverRadius)) + me.getRadius(dataset.data[index]);
+		},
+
+		removeHoverStyle: function(point) {
+			var me = this;
+			Chart.DatasetController.prototype.removeHoverStyle.call(me, point, me.chart.options.elements.point);
+
+			var dataVal = me.chart.data.datasets[point._datasetIndex].data[point._index];
+			var custom = point.custom || {};
+			var model = point._model;
+
+			model.radius = custom.radius ? custom.radius : me.getRadius(dataVal);
+		}
+	});
+};
+
+},{}],17:[function(require,module,exports){
+'use strict';
+
+module.exports = function(Chart) {
+
+	var helpers = Chart.helpers,
+		defaults = Chart.defaults;
+
+	defaults.doughnut = {
+		animation: {
+			// Boolean - Whether we animate the rotation of the Doughnut
+			animateRotate: true,
+			// Boolean - Whether we animate scaling the Doughnut from the centre
+			animateScale: false
+		},
+		aspectRatio: 1,
+		hover: {
+			mode: 'single'
+		},
+		legendCallback: function(chart) {
+			var text = [];
+			text.push('<ul class="' + chart.id + '-legend">');
+
+			var data = chart.data;
+			var datasets = data.datasets;
+			var labels = data.labels;
+
+			if (datasets.length) {
+				for (var i = 0; i < datasets[0].data.length; ++i) {
+					text.push('<li><span style="background-color:' + datasets[0].backgroundColor[i] + '"></span>');
+					if (labels[i]) {
+						text.push(labels[i]);
+					}
+					text.push('</li>');
+				}
+			}
+
+			text.push('</ul>');
+			return text.join('');
+		},
+		legend: {
+			labels: {
+				generateLabels: function(chart) {
+					var data = chart.data;
+					if (data.labels.length && data.datasets.length) {
+						return data.labels.map(function(label, i) {
+							var meta = chart.getDatasetMeta(0);
+							var ds = data.datasets[0];
+							var arc = meta.data[i];
+							var custom = arc && arc.custom || {};
+							var getValueAtIndexOrDefault = helpers.getValueAtIndexOrDefault;
+							var arcOpts = chart.options.elements.arc;
+							var fill = custom.backgroundColor ? custom.backgroundColor : getValueAtIndexOrDefault(ds.backgroundColor, i, arcOpts.backgroundColor);
+							var stroke = custom.borderColor ? custom.borderColor : getValueAtIndexOrDefault(ds.borderColor, i, arcOpts.borderColor);
+							var bw = custom.borderWidth ? custom.borderWidth : getValueAtIndexOrDefault(ds.borderWidth, i, arcOpts.borderWidth);
+
+							return {
+								text: label,
+								fillStyle: fill,
+								strokeStyle: stroke,
+								lineWidth: bw,
+								hidden: isNaN(ds.data[i]) || meta.data[i].hidden,
+
+								// Extra data used for toggling the correct item
+								index: i
+							};
+						});
+					}
+					return [];
+				}
+			},
+
+			onClick: function(e, legendItem) {
+				var index = legendItem.index;
+				var chart = this.chart;
+				var i, ilen, meta;
+
+				for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) {
+					meta = chart.getDatasetMeta(i);
+					// toggle visibility of index if exists
+					if (meta.data[index]) {
+						meta.data[index].hidden = !meta.data[index].hidden;
+					}
+				}
+
+				chart.update();
+			}
+		},
+
+		// The percentage of the chart that we cut out of the middle.
+		cutoutPercentage: 50,
+
+		// The rotation of the chart, where the first data arc begins.
+		rotation: Math.PI * -0.5,
+
+		// The total circumference of the chart.
+		circumference: Math.PI * 2.0,
+
+		// Need to override these to give a nice default
+		tooltips: {
+			callbacks: {
+				title: function() {
+					return '';
+				},
+				label: function(tooltipItem, data) {
+					var dataLabel = data.labels[tooltipItem.index];
+					var value = ': ' + data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
+
+					if (helpers.isArray(dataLabel)) {
+						// show value on first line of multiline label
+						// need to clone because we are changing the value
+						dataLabel = dataLabel.slice();
+						dataLabel[0] += value;
+					} else {
+						dataLabel += value;
+					}
+
+					return dataLabel;
+				}
+			}
+		}
+	};
+
+	defaults.pie = helpers.clone(defaults.doughnut);
+	helpers.extend(defaults.pie, {
+		cutoutPercentage: 0
+	});
+
+
+	Chart.controllers.doughnut = Chart.controllers.pie = Chart.DatasetController.extend({
+
+		dataElementType: Chart.elements.Arc,
+
+		linkScales: helpers.noop,
+
+		// Get index of the dataset in relation to the visible datasets. This allows determining the inner and outer radius correctly
+		getRingIndex: function(datasetIndex) {
+			var ringIndex = 0;
+
+			for (var j = 0; j < datasetIndex; ++j) {
+				if (this.chart.isDatasetVisible(j)) {
+					++ringIndex;
+				}
+			}
+
+			return ringIndex;
+		},
+
+		update: function(reset) {
+			var me = this;
+			var chart = me.chart,
+				chartArea = chart.chartArea,
+				opts = chart.options,
+				arcOpts = opts.elements.arc,
+				availableWidth = chartArea.right - chartArea.left - arcOpts.borderWidth,
+				availableHeight = chartArea.bottom - chartArea.top - arcOpts.borderWidth,
+				minSize = Math.min(availableWidth, availableHeight),
+				offset = {
+					x: 0,
+					y: 0
+				},
+				meta = me.getMeta(),
+				cutoutPercentage = opts.cutoutPercentage,
+				circumference = opts.circumference;
+
+			// If the chart's circumference isn't a full circle, calculate minSize as a ratio of the width/height of the arc
+			if (circumference < Math.PI * 2.0) {
+				var startAngle = opts.rotation % (Math.PI * 2.0);
+				startAngle += Math.PI * 2.0 * (startAngle >= Math.PI ? -1 : startAngle < -Math.PI ? 1 : 0);
+				var endAngle = startAngle + circumference;
+				var start = {x: Math.cos(startAngle), y: Math.sin(startAngle)};
+				var end = {x: Math.cos(endAngle), y: Math.sin(endAngle)};
+				var contains0 = (startAngle <= 0 && 0 <= endAngle) || (startAngle <= Math.PI * 2.0 && Math.PI * 2.0 <= endAngle);
+				var contains90 = (startAngle <= Math.PI * 0.5 && Math.PI * 0.5 <= endAngle) || (startAngle <= Math.PI * 2.5 && Math.PI * 2.5 <= endAngle);
+				var contains180 = (startAngle <= -Math.PI && -Math.PI <= endAngle) || (startAngle <= Math.PI && Math.PI <= endAngle);
+				var contains270 = (startAngle <= -Math.PI * 0.5 && -Math.PI * 0.5 <= endAngle) || (startAngle <= Math.PI * 1.5 && Math.PI * 1.5 <= endAngle);
+				var cutout = cutoutPercentage / 100.0;
+				var min = {x: contains180 ? -1 : Math.min(start.x * (start.x < 0 ? 1 : cutout), end.x * (end.x < 0 ? 1 : cutout)), y: contains270 ? -1 : Math.min(start.y * (start.y < 0 ? 1 : cutout), end.y * (end.y < 0 ? 1 : cutout))};
+				var max = {x: contains0 ? 1 : Math.max(start.x * (start.x > 0 ? 1 : cutout), end.x * (end.x > 0 ? 1 : cutout)), y: contains90 ? 1 : Math.max(start.y * (start.y > 0 ? 1 : cutout), end.y * (end.y > 0 ? 1 : cutout))};
+				var size = {width: (max.x - min.x) * 0.5, height: (max.y - min.y) * 0.5};
+				minSize = Math.min(availableWidth / size.width, availableHeight / size.height);
+				offset = {x: (max.x + min.x) * -0.5, y: (max.y + min.y) * -0.5};
+			}
+
+			chart.borderWidth = me.getMaxBorderWidth(meta.data);
+			chart.outerRadius = Math.max((minSize - chart.borderWidth) / 2, 0);
+			chart.innerRadius = Math.max(cutoutPercentage ? (chart.outerRadius / 100) * (cutoutPercentage) : 0, 0);
+			chart.radiusLength = (chart.outerRadius - chart.innerRadius) / chart.getVisibleDatasetCount();
+			chart.offsetX = offset.x * chart.outerRadius;
+			chart.offsetY = offset.y * chart.outerRadius;
+
+			meta.total = me.calculateTotal();
+
+			me.outerRadius = chart.outerRadius - (chart.radiusLength * me.getRingIndex(me.index));
+			me.innerRadius = Math.max(me.outerRadius - chart.radiusLength, 0);
+
+			helpers.each(meta.data, function(arc, index) {
+				me.updateElement(arc, index, reset);
+			});
+		},
+
+		updateElement: function(arc, index, reset) {
+			var me = this;
+			var chart = me.chart,
+				chartArea = chart.chartArea,
+				opts = chart.options,
+				animationOpts = opts.animation,
+				centerX = (chartArea.left + chartArea.right) / 2,
+				centerY = (chartArea.top + chartArea.bottom) / 2,
+				startAngle = opts.rotation, // non reset case handled later
+				endAngle = opts.rotation, // non reset case handled later
+				dataset = me.getDataset(),
+				circumference = reset && animationOpts.animateRotate ? 0 : arc.hidden ? 0 : me.calculateCircumference(dataset.data[index]) * (opts.circumference / (2.0 * Math.PI)),
+				innerRadius = reset && animationOpts.animateScale ? 0 : me.innerRadius,
+				outerRadius = reset && animationOpts.animateScale ? 0 : me.outerRadius,
+				valueAtIndexOrDefault = helpers.getValueAtIndexOrDefault;
+
+			helpers.extend(arc, {
+				// Utility
+				_datasetIndex: me.index,
+				_index: index,
+
+				// Desired view properties
+				_model: {
+					x: centerX + chart.offsetX,
+					y: centerY + chart.offsetY,
+					startAngle: startAngle,
+					endAngle: endAngle,
+					circumference: circumference,
+					outerRadius: outerRadius,
+					innerRadius: innerRadius,
+					label: valueAtIndexOrDefault(dataset.label, index, chart.data.labels[index])
+				}
+			});
+
+			var model = arc._model;
+			// Resets the visual styles
+			this.removeHoverStyle(arc);
+
+			// Set correct angles if not resetting
+			if (!reset || !animationOpts.animateRotate) {
+				if (index === 0) {
+					model.startAngle = opts.rotation;
+				} else {
+					model.startAngle = me.getMeta().data[index - 1]._model.endAngle;
+				}
+
+				model.endAngle = model.startAngle + model.circumference;
+			}
+
+			arc.pivot();
+		},
+
+		removeHoverStyle: function(arc) {
+			Chart.DatasetController.prototype.removeHoverStyle.call(this, arc, this.chart.options.elements.arc);
+		},
+
+		calculateTotal: function() {
+			var dataset = this.getDataset();
+			var meta = this.getMeta();
+			var total = 0;
+			var value;
+
+			helpers.each(meta.data, function(element, index) {
+				value = dataset.data[index];
+				if (!isNaN(value) && !element.hidden) {
+					total += Math.abs(value);
+				}
+			});
+
+			/* if (total === 0) {
+				total = NaN;
+			}*/
+
+			return total;
+		},
+
+		calculateCircumference: function(value) {
+			var total = this.getMeta().total;
+			if (total > 0 && !isNaN(value)) {
+				return (Math.PI * 2.0) * (value / total);
+			}
+			return 0;
+		},
+
+		// gets the max border or hover width to properly scale pie charts
+		getMaxBorderWidth: function(elements) {
+			var max = 0,
+				index = this.index,
+				length = elements.length,
+				borderWidth,
+				hoverWidth;
+
+			for (var i = 0; i < length; i++) {
+				borderWidth = elements[i]._model ? elements[i]._model.borderWidth : 0;
+				hoverWidth = elements[i]._chart ? elements[i]._chart.config.data.datasets[index].hoverBorderWidth : 0;
+
+				max = borderWidth > max ? borderWidth : max;
+				max = hoverWidth > max ? hoverWidth : max;
+			}
+			return max;
+		}
+	});
+};
+
+},{}],18:[function(require,module,exports){
+'use strict';
+
+module.exports = function(Chart) {
+
+	var helpers = Chart.helpers;
+
+	Chart.defaults.line = {
+		showLines: true,
+		spanGaps: false,
+
+		hover: {
+			mode: 'label'
+		},
+
+		scales: {
+			xAxes: [{
+				type: 'category',
+				id: 'x-axis-0'
+			}],
+			yAxes: [{
+				type: 'linear',
+				id: 'y-axis-0'
+			}]
+		}
+	};
+
+	function lineEnabled(dataset, options) {
+		return helpers.getValueOrDefault(dataset.showLine, options.showLines);
+	}
+
+	Chart.controllers.line = Chart.DatasetController.extend({
+
+		datasetElementType: Chart.elements.Line,
+
+		dataElementType: Chart.elements.Point,
+
+		update: function(reset) {
+			var me = this;
+			var meta = me.getMeta();
+			var line = meta.dataset;
+			var points = meta.data || [];
+			var options = me.chart.options;
+			var lineElementOptions = options.elements.line;
+			var scale = me.getScaleForId(meta.yAxisID);
+			var i, ilen, custom;
+			var dataset = me.getDataset();
+			var showLine = lineEnabled(dataset, options);
+
+			// Update Line
+			if (showLine) {
+				custom = line.custom || {};
+
+				// Compatibility: If the properties are defined with only the old name, use those values
+				if ((dataset.tension !== undefined) && (dataset.lineTension === undefined)) {
+					dataset.lineTension = dataset.tension;
+				}
+
+				// Utility
+				line._scale = scale;
+				line._datasetIndex = me.index;
+				// Data
+				line._children = points;
+				// Model
+				line._model = {
+					// Appearance
+					// The default behavior of lines is to break at null values, according
+					// to https://github.com/chartjs/Chart.js/issues/2435#issuecomment-216718158
+					// This option gives lines the ability to span gaps
+					spanGaps: dataset.spanGaps ? dataset.spanGaps : options.spanGaps,
+					tension: custom.tension ? custom.tension : helpers.getValueOrDefault(dataset.lineTension, lineElementOptions.tension),
+					backgroundColor: custom.backgroundColor ? custom.backgroundColor : (dataset.backgroundColor || lineElementOptions.backgroundColor),
+					borderWidth: custom.borderWidth ? custom.borderWidth : (dataset.borderWidth || lineElementOptions.borderWidth),
+					borderColor: custom.borderColor ? custom.borderColor : (dataset.borderColor || lineElementOptions.borderColor),
+					borderCapStyle: custom.borderCapStyle ? custom.borderCapStyle : (dataset.borderCapStyle || lineElementOptions.borderCapStyle),
+					borderDash: custom.borderDash ? custom.borderDash : (dataset.borderDash || lineElementOptions.borderDash),
+					borderDashOffset: custom.borderDashOffset ? custom.borderDashOffset : (dataset.borderDashOffset || lineElementOptions.borderDashOffset),
+					borderJoinStyle: custom.borderJoinStyle ? custom.borderJoinStyle : (dataset.borderJoinStyle || lineElementOptions.borderJoinStyle),
+					fill: custom.fill ? custom.fill : (dataset.fill !== undefined ? dataset.fill : lineElementOptions.fill),
+					steppedLine: custom.steppedLine ? custom.steppedLine : helpers.getValueOrDefault(dataset.steppedLine, lineElementOptions.stepped),
+					cubicInterpolationMode: custom.cubicInterpolationMode ? custom.cubicInterpolationMode : helpers.getValueOrDefault(dataset.cubicInterpolationMode, lineElementOptions.cubicInterpolationMode),
+					// Scale
+					scaleTop: scale.top,
+					scaleBottom: scale.bottom,
+					scaleZero: scale.getBasePixel()
+				};
+
+				line.pivot();
+			}
+
+			// Update Points
+			for (i=0, ilen=points.length; i<ilen; ++i) {
+				me.updateElement(points[i], i, reset);
+			}
+
+			if (showLine && line._model.tension !== 0) {
+				me.updateBezierControlPoints();
+			}
+
+			// Now pivot the point for animation
+			for (i=0, ilen=points.length; i<ilen; ++i) {
+				points[i].pivot();
+			}
+		},
+
+		getPointBackgroundColor: function(point, index) {
+			var backgroundColor = this.chart.options.elements.point.backgroundColor;
+			var dataset = this.getDataset();
+			var custom = point.custom || {};
+
+			if (custom.backgroundColor) {
+				backgroundColor = custom.backgroundColor;
+			} else if (dataset.pointBackgroundColor) {
+				backgroundColor = helpers.getValueAtIndexOrDefault(dataset.pointBackgroundColor, index, backgroundColor);
+			} else if (dataset.backgroundColor) {
+				backgroundColor = dataset.backgroundColor;
+			}
+
+			return backgroundColor;
+		},
+
+		getPointBorderColor: function(point, index) {
+			var borderColor = this.chart.options.elements.point.borderColor;
+			var dataset = this.getDataset();
+			var custom = point.custom || {};
+
+			if (custom.borderColor) {
+				borderColor = custom.borderColor;
+			} else if (dataset.pointBorderColor) {
+				borderColor = helpers.getValueAtIndexOrDefault(dataset.pointBorderColor, index, borderColor);
+			} else if (dataset.borderColor) {
+				borderColor = dataset.borderColor;
+			}
+
+			return borderColor;
+		},
+
+		getPointBorderWidth: function(point, index) {
+			var borderWidth = this.chart.options.elements.point.borderWidth;
+			var dataset = this.getDataset();
+			var custom = point.custom || {};
+
+			if (!isNaN(custom.borderWidth)) {
+				borderWidth = custom.borderWidth;
+			} else if (!isNaN(dataset.pointBorderWidth)) {
+				borderWidth = helpers.getValueAtIndexOrDefault(dataset.pointBorderWidth, index, borderWidth);
+			} else if (!isNaN(dataset.borderWidth)) {
+				borderWidth = dataset.borderWidth;
+			}
+
+			return borderWidth;
+		},
+
+		updateElement: function(point, index, reset) {
+			var me = this;
+			var meta = me.getMeta();
+			var custom = point.custom || {};
+			var dataset = me.getDataset();
+			var datasetIndex = me.index;
+			var value = dataset.data[index];
+			var yScale = me.getScaleForId(meta.yAxisID);
+			var xScale = me.getScaleForId(meta.xAxisID);
+			var pointOptions = me.chart.options.elements.point;
+			var x, y;
+			var labels = me.chart.data.labels || [];
+			var includeOffset = (labels.length === 1 || dataset.data.length === 1) || me.chart.isCombo;
+
+			// Compatibility: If the properties are defined with only the old name, use those values
+			if ((dataset.radius !== undefined) && (dataset.pointRadius === undefined)) {
+				dataset.pointRadius = dataset.radius;
+			}
+			if ((dataset.hitRadius !== undefined) && (dataset.pointHitRadius === undefined)) {
+				dataset.pointHitRadius = dataset.hitRadius;
+			}
+
+			x = xScale.getPixelForValue(typeof value === 'object' ? value : NaN, index, datasetIndex, includeOffset);
+			y = reset ? yScale.getBasePixel() : me.calculatePointY(value, index, datasetIndex);
+
+			// Utility
+			point._xScale = xScale;
+			point._yScale = yScale;
+			point._datasetIndex = datasetIndex;
+			point._index = index;
+
+			// Desired view properties
+			point._model = {
+				x: x,
+				y: y,
+				skip: custom.skip || isNaN(x) || isNaN(y),
+				// Appearance
+				radius: custom.radius || helpers.getValueAtIndexOrDefault(dataset.pointRadius, index, pointOptions.radius),
+				pointStyle: custom.pointStyle || helpers.getValueAtIndexOrDefault(dataset.pointStyle, index, pointOptions.pointStyle),
+				backgroundColor: me.getPointBackgroundColor(point, index),
+				borderColor: me.getPointBorderColor(point, index),
+				borderWidth: me.getPointBorderWidth(point, index),
+				tension: meta.dataset._model ? meta.dataset._model.tension : 0,
+				steppedLine: meta.dataset._model ? meta.dataset._model.steppedLine : false,
+				// Tooltip
+				hitRadius: custom.hitRadius || helpers.getValueAtIndexOrDefault(dataset.pointHitRadius, index, pointOptions.hitRadius)
+			};
+		},
+
+		calculatePointY: function(value, index, datasetIndex) {
+			var me = this;
+			var chart = me.chart;
+			var meta = me.getMeta();
+			var yScale = me.getScaleForId(meta.yAxisID);
+			var sumPos = 0;
+			var sumNeg = 0;
+			var i, ds, dsMeta;
+
+			if (yScale.options.stacked) {
+				for (i = 0; i < datasetIndex; i++) {
+					ds = chart.data.datasets[i];
+					dsMeta = chart.getDatasetMeta(i);
+					if (dsMeta.type === 'line' && dsMeta.yAxisID === yScale.id && chart.isDatasetVisible(i)) {
+						var stackedRightValue = Number(yScale.getRightValue(ds.data[index]));
+						if (stackedRightValue < 0) {
+							sumNeg += stackedRightValue || 0;
+						} else {
+							sumPos += stackedRightValue || 0;
+						}
+					}
+				}
+
+				var rightValue = Number(yScale.getRightValue(value));
+				if (rightValue < 0) {
+					return yScale.getPixelForValue(sumNeg + rightValue);
+				}
+				return yScale.getPixelForValue(sumPos + rightValue);
+			}
+
+			return yScale.getPixelForValue(value);
+		},
+
+		updateBezierControlPoints: function() {
+			var me = this;
+			var meta = me.getMeta();
+			var area = me.chart.chartArea;
+			var points = (meta.data || []);
+			var i, ilen, point, model, controlPoints;
+
+			// Only consider points that are drawn in case the spanGaps option is used
+			if (meta.dataset._model.spanGaps) {
+				points = points.filter(function(pt) {
+					return !pt._model.skip;
+				});
+			}
+
+			function capControlPoint(pt, min, max) {
+				return Math.max(Math.min(pt, max), min);
+			}
+
+			if (meta.dataset._model.cubicInterpolationMode === 'monotone') {
+				helpers.splineCurveMonotone(points);
+			} else {
+				for (i = 0, ilen = points.length; i < ilen; ++i) {
+					point = points[i];
+					model = point._model;
+					controlPoints = helpers.splineCurve(
+						helpers.previousItem(points, i)._model,
+						model,
+						helpers.nextItem(points, i)._model,
+						meta.dataset._model.tension
+					);
+					model.controlPointPreviousX = controlPoints.previous.x;
+					model.controlPointPreviousY = controlPoints.previous.y;
+					model.controlPointNextX = controlPoints.next.x;
+					model.controlPointNextY = controlPoints.next.y;
+				}
+			}
+
+			if (me.chart.options.elements.line.capBezierPoints) {
+				for (i = 0, ilen = points.length; i < ilen; ++i) {
+					model = points[i]._model;
+					model.controlPointPreviousX = capControlPoint(model.controlPointPreviousX, area.left, area.right);
+					model.controlPointPreviousY = capControlPoint(model.controlPointPreviousY, area.top, area.bottom);
+					model.controlPointNextX = capControlPoint(model.controlPointNextX, area.left, area.right);
+					model.controlPointNextY = capControlPoint(model.controlPointNextY, area.top, area.bottom);
+				}
+			}
+		},
+
+		draw: function(ease) {
+			var me = this;
+			var meta = me.getMeta();
+			var points = meta.data || [];
+			var easingDecimal = ease || 1;
+			var i, ilen;
+
+			// Transition Point Locations
+			for (i=0, ilen=points.length; i<ilen; ++i) {
+				points[i].transition(easingDecimal);
+			}
+
+			Chart.canvasHelpers.clipArea(me.chart.chart.ctx, me.chart.chartArea);
+			// Transition and Draw the line
+			if (lineEnabled(me.getDataset(), me.chart.options)) {
+				meta.dataset.transition(easingDecimal).draw();
+			}
+			Chart.canvasHelpers.unclipArea(me.chart.chart.ctx);
+
+			// Draw the points
+			for (i=0, ilen=points.length; i<ilen; ++i) {
+				points[i].draw(me.chart.chartArea);
+			}
+		},
+
+		setHoverStyle: function(point) {
+			// Point
+			var dataset = this.chart.data.datasets[point._datasetIndex];
+			var index = point._index;
+			var custom = point.custom || {};
+			var model = point._model;
+
+			model.radius = custom.hoverRadius || helpers.getValueAtIndexOrDefault(dataset.pointHoverRadius, index, this.chart.options.elements.point.hoverRadius);
+			model.backgroundColor = custom.hoverBackgroundColor || helpers.getValueAtIndexOrDefault(dataset.pointHoverBackgroundColor, index, helpers.getHoverColor(model.backgroundColor));
+			model.borderColor = custom.hoverBorderColor || helpers.getValueAtIndexOrDefault(dataset.pointHoverBorderColor, index, helpers.getHoverColor(model.borderColor));
+			model.borderWidth = custom.hoverBorderWidth || helpers.getValueAtIndexOrDefault(dataset.pointHoverBorderWidth, index, model.borderWidth);
+		},
+
+		removeHoverStyle: function(point) {
+			var me = this;
+			var dataset = me.chart.data.datasets[point._datasetIndex];
+			var index = point._index;
+			var custom = point.custom || {};
+			var model = point._model;
+
+			// Compatibility: If the properties are defined with only the old name, use those values
+			if ((dataset.radius !== undefined) && (dataset.pointRadius === undefined)) {
+				dataset.pointRadius = dataset.radius;
+			}
+
+			model.radius = custom.radius || helpers.getValueAtIndexOrDefault(dataset.pointRadius, index, me.chart.options.elements.point.radius);
+			model.backgroundColor = me.getPointBackgroundColor(point, index);
+			model.borderColor = me.getPointBorderColor(point, index);
+			model.borderWidth = me.getPointBorderWidth(point, index);
+		}
+	});
+};
+
+},{}],19:[function(require,module,exports){
+'use strict';
+
+module.exports = function(Chart) {
+
+	var helpers = Chart.helpers;
+
+	Chart.defaults.polarArea = {
+
+		scale: {
+			type: 'radialLinear',
+			lineArc: true, // so that lines are circular
+			ticks: {
+				beginAtZero: true
+			}
+		},
+
+		// Boolean - Whether to animate the rotation of the chart
+		animation: {
+			animateRotate: true,
+			animateScale: true
+		},
+
+		startAngle: -0.5 * Math.PI,
+		aspectRatio: 1,
+		legendCallback: function(chart) {
+			var text = [];
+			text.push('<ul class="' + chart.id + '-legend">');
+
+			var data = chart.data;
+			var datasets = data.datasets;
+			var labels = data.labels;
+
+			if (datasets.length) {
+				for (var i = 0; i < datasets[0].data.length; ++i) {
+					text.push('<li><span style="background-color:' + datasets[0].backgroundColor[i] + '"></span>');
+					if (labels[i]) {
+						text.push(labels[i]);
+					}
+					text.push('</li>');
+				}
+			}
+
+			text.push('</ul>');
+			return text.join('');
+		},
+		legend: {
+			labels: {
+				generateLabels: function(chart) {
+					var data = chart.data;
+					if (data.labels.length && data.datasets.length) {
+						return data.labels.map(function(label, i) {
+							var meta = chart.getDatasetMeta(0);
+							var ds = data.datasets[0];
+							var arc = meta.data[i];
+							var custom = arc.custom || {};
+							var getValueAtIndexOrDefault = helpers.getValueAtIndexOrDefault;
+							var arcOpts = chart.options.elements.arc;
+							var fill = custom.backgroundColor ? custom.backgroundColor : getValueAtIndexOrDefault(ds.backgroundColor, i, arcOpts.backgroundColor);
+							var stroke = custom.borderColor ? custom.borderColor : getValueAtIndexOrDefault(ds.borderColor, i, arcOpts.borderColor);
+							var bw = custom.borderWidth ? custom.borderWidth : getValueAtIndexOrDefault(ds.borderWidth, i, arcOpts.borderWidth);
+
+							return {
+								text: label,
+								fillStyle: fill,
+								strokeStyle: stroke,
+								lineWidth: bw,
+								hidden: isNaN(ds.data[i]) || meta.data[i].hidden,
+
+								// Extra data used for toggling the correct item
+								index: i
+							};
+						});
+					}
+					return [];
+				}
+			},
+
+			onClick: function(e, legendItem) {
+				var index = legendItem.index;
+				var chart = this.chart;
+				var i, ilen, meta;
+
+				for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) {
+					meta = chart.getDatasetMeta(i);
+					meta.data[index].hidden = !meta.data[index].hidden;
+				}
+
+				chart.update();
+			}
+		},
+
+		// Need to override these to give a nice default
+		tooltips: {
+			callbacks: {
+				title: function() {
+					return '';
+				},
+				label: function(tooltipItem, data) {
+					return data.labels[tooltipItem.index] + ': ' + tooltipItem.yLabel;
+				}
+			}
+		}
+	};
+
+	Chart.controllers.polarArea = Chart.DatasetController.extend({
+
+		dataElementType: Chart.elements.Arc,
+
+		linkScales: helpers.noop,
+
+		update: function(reset) {
+			var me = this;
+			var chart = me.chart;
+			var chartArea = chart.chartArea;
+			var meta = me.getMeta();
+			var opts = chart.options;
+			var arcOpts = opts.elements.arc;
+			var minSize = Math.min(chartArea.right - chartArea.left, chartArea.bottom - chartArea.top);
+			chart.outerRadius = Math.max((minSize - arcOpts.borderWidth / 2) / 2, 0);
+			chart.innerRadius = Math.max(opts.cutoutPercentage ? (chart.outerRadius / 100) * (opts.cutoutPercentage) : 1, 0);
+			chart.radiusLength = (chart.outerRadius - chart.innerRadius) / chart.getVisibleDatasetCount();
+
+			me.outerRadius = chart.outerRadius - (chart.radiusLength * me.index);
+			me.innerRadius = me.outerRadius - chart.radiusLength;
+
+			meta.count = me.countVisibleElements();
+
+			helpers.each(meta.data, function(arc, index) {
+				me.updateElement(arc, index, reset);
+			});
+		},
+
+		updateElement: function(arc, index, reset) {
+			var me = this;
+			var chart = me.chart;
+			var dataset = me.getDataset();
+			var opts = chart.options;
+			var animationOpts = opts.animation;
+			var scale = chart.scale;
+			var getValueAtIndexOrDefault = helpers.getValueAtIndexOrDefault;
+			var labels = chart.data.labels;
+
+			var circumference = me.calculateCircumference(dataset.data[index]);
+			var centerX = scale.xCenter;
+			var centerY = scale.yCenter;
+
+			// If there is NaN data before us, we need to calculate the starting angle correctly.
+			// We could be way more efficient here, but its unlikely that the polar area chart will have a lot of data
+			var visibleCount = 0;
+			var meta = me.getMeta();
+			for (var i = 0; i < index; ++i) {
+				if (!isNaN(dataset.data[i]) && !meta.data[i].hidden) {
+					++visibleCount;
+				}
+			}
+
+			// var negHalfPI = -0.5 * Math.PI;
+			var datasetStartAngle = opts.startAngle;
+			var distance = arc.hidden ? 0 : scale.getDistanceFromCenterForValue(dataset.data[index]);
+			var startAngle = datasetStartAngle + (circumference * visibleCount);
+			var endAngle = startAngle + (arc.hidden ? 0 : circumference);
+
+			var resetRadius = animationOpts.animateScale ? 0 : scale.getDistanceFromCenterForValue(dataset.data[index]);
+
+			helpers.extend(arc, {
+				// Utility
+				_datasetIndex: me.index,
+				_index: index,
+				_scale: scale,
+
+				// Desired view properties
+				_model: {
+					x: centerX,
+					y: centerY,
+					innerRadius: 0,
+					outerRadius: reset ? resetRadius : distance,
+					startAngle: reset && animationOpts.animateRotate ? datasetStartAngle : startAngle,
+					endAngle: reset && animationOpts.animateRotate ? datasetStartAngle : endAngle,
+					label: getValueAtIndexOrDefault(labels, index, labels[index])
+				}
+			});
+
+			// Apply border and fill style
+			me.removeHoverStyle(arc);
+
+			arc.pivot();
+		},
+
+		removeHoverStyle: function(arc) {
+			Chart.DatasetController.prototype.removeHoverStyle.call(this, arc, this.chart.options.elements.arc);
+		},
+
+		countVisibleElements: function() {
+			var dataset = this.getDataset();
+			var meta = this.getMeta();
+			var count = 0;
+
+			helpers.each(meta.data, function(element, index) {
+				if (!isNaN(dataset.data[index]) && !element.hidden) {
+					count++;
+				}
+			});
+
+			return count;
+		},
+
+		calculateCircumference: function(value) {
+			var count = this.getMeta().count;
+			if (count > 0 && !isNaN(value)) {
+				return (2 * Math.PI) / count;
+			}
+			return 0;
+		}
+	});
+};
+
+},{}],20:[function(require,module,exports){
+'use strict';
+
+module.exports = function(Chart) {
+
+	var helpers = Chart.helpers;
+
+	Chart.defaults.radar = {
+		aspectRatio: 1,
+		scale: {
+			type: 'radialLinear'
+		},
+		elements: {
+			line: {
+				tension: 0 // no bezier in radar
+			}
+		}
+	};
+
+	Chart.controllers.radar = Chart.DatasetController.extend({
+
+		datasetElementType: Chart.elements.Line,
+
+		dataElementType: Chart.elements.Point,
+
+		linkScales: helpers.noop,
+
+		update: function(reset) {
+			var me = this;
+			var meta = me.getMeta();
+			var line = meta.dataset;
+			var points = meta.data;
+			var custom = line.custom || {};
+			var dataset = me.getDataset();
+			var lineElementOptions = me.chart.options.elements.line;
+			var scale = me.chart.scale;
+
+			// Compatibility: If the properties are defined with only the old name, use those values
+			if ((dataset.tension !== undefined) && (dataset.lineTension === undefined)) {
+				dataset.lineTension = dataset.tension;
+			}
+
+			helpers.extend(meta.dataset, {
+				// Utility
+				_datasetIndex: me.index,
+				// Data
+				_children: points,
+				_loop: true,
+				// Model
+				_model: {
+					// Appearance
+					tension: custom.tension ? custom.tension : helpers.getValueOrDefault(dataset.lineTension, lineElementOptions.tension),
+					backgroundColor: custom.backgroundColor ? custom.backgroundColor : (dataset.backgroundColor || lineElementOptions.backgroundColor),
+					borderWidth: custom.borderWidth ? custom.borderWidth : (dataset.borderWidth || lineElementOptions.borderWidth),
+					borderColor: custom.borderColor ? custom.borderColor : (dataset.borderColor || lineElementOptions.borderColor),
+					fill: custom.fill ? custom.fill : (dataset.fill !== undefined ? dataset.fill : lineElementOptions.fill),
+					borderCapStyle: custom.borderCapStyle ? custom.borderCapStyle : (dataset.borderCapStyle || lineElementOptions.borderCapStyle),
+					borderDash: custom.borderDash ? custom.borderDash : (dataset.borderDash || lineElementOptions.borderDash),
+					borderDashOffset: custom.borderDashOffset ? custom.borderDashOffset : (dataset.borderDashOffset || lineElementOptions.borderDashOffset),
+					borderJoinStyle: custom.borderJoinStyle ? custom.borderJoinStyle : (dataset.borderJoinStyle || lineElementOptions.borderJoinStyle),
+
+					// Scale
+					scaleTop: scale.top,
+					scaleBottom: scale.bottom,
+					scaleZero: scale.getBasePosition()
+				}
+			});
+
+			meta.dataset.pivot();
+
+			// Update Points
+			helpers.each(points, function(point, index) {
+				me.updateElement(point, index, reset);
+			}, me);
+
+			// Update bezier control points
+			me.updateBezierControlPoints();
+		},
+		updateElement: function(point, index, reset) {
+			var me = this;
+			var custom = point.custom || {};
+			var dataset = me.getDataset();
+			var scale = me.chart.scale;
+			var pointElementOptions = me.chart.options.elements.point;
+			var pointPosition = scale.getPointPositionForValue(index, dataset.data[index]);
+
+			helpers.extend(point, {
+				// Utility
+				_datasetIndex: me.index,
+				_index: index,
+				_scale: scale,
+
+				// Desired view properties
+				_model: {
+					x: reset ? scale.xCenter : pointPosition.x, // value not used in dataset scale, but we want a consistent API between scales
+					y: reset ? scale.yCenter : pointPosition.y,
+
+					// Appearance
+					tension: custom.tension ? custom.tension : helpers.getValueOrDefault(dataset.lineTension, me.chart.options.elements.line.tension),
+					radius: custom.radius ? custom.radius : helpers.getValueAtIndexOrDefault(dataset.pointRadius, index, pointElementOptions.radius),
+					backgroundColor: custom.backgroundColor ? custom.backgroundColor : helpers.getValueAtIndexOrDefault(dataset.pointBackgroundColor, index, pointElementOptions.backgroundColor),
+					borderColor: custom.borderColor ? custom.borderColor : helpers.getValueAtIndexOrDefault(dataset.pointBorderColor, index, pointElementOptions.borderColor),
+					borderWidth: custom.borderWidth ? custom.borderWidth : helpers.getValueAtIndexOrDefault(dataset.pointBorderWidth, index, pointElementOptions.borderWidth),
+					pointStyle: custom.pointStyle ? custom.pointStyle : helpers.getValueAtIndexOrDefault(dataset.pointStyle, index, pointElementOptions.pointStyle),
+
+					// Tooltip
+					hitRadius: custom.hitRadius ? custom.hitRadius : helpers.getValueAtIndexOrDefault(dataset.hitRadius, index, pointElementOptions.hitRadius)
+				}
+			});
+
+			point._model.skip = custom.skip ? custom.skip : (isNaN(point._model.x) || isNaN(point._model.y));
+		},
+		updateBezierControlPoints: function() {
+			var chartArea = this.chart.chartArea;
+			var meta = this.getMeta();
+
+			helpers.each(meta.data, function(point, index) {
+				var model = point._model;
+				var controlPoints = helpers.splineCurve(
+					helpers.previousItem(meta.data, index, true)._model,
+					model,
+					helpers.nextItem(meta.data, index, true)._model,
+					model.tension
+				);
+
+				// Prevent the bezier going outside of the bounds of the graph
+				model.controlPointPreviousX = Math.max(Math.min(controlPoints.previous.x, chartArea.right), chartArea.left);
+				model.controlPointPreviousY = Math.max(Math.min(controlPoints.previous.y, chartArea.bottom), chartArea.top);
+
+				model.controlPointNextX = Math.max(Math.min(controlPoints.next.x, chartArea.right), chartArea.left);
+				model.controlPointNextY = Math.max(Math.min(controlPoints.next.y, chartArea.bottom), chartArea.top);
+
+				// Now pivot the point for animation
+				point.pivot();
+			});
+		},
+
+		draw: function(ease) {
+			var meta = this.getMeta();
+			var easingDecimal = ease || 1;
+
+			// Transition Point Locations
+			helpers.each(meta.data, function(point) {
+				point.transition(easingDecimal);
+			});
+
+			// Transition and Draw the line
+			meta.dataset.transition(easingDecimal).draw();
+
+			// Draw the points
+			helpers.each(meta.data, function(point) {
+				point.draw();
+			});
+		},
+
+		setHoverStyle: function(point) {
+			// Point
+			var dataset = this.chart.data.datasets[point._datasetIndex];
+			var custom = point.custom || {};
+			var index = point._index;
+			var model = point._model;
+
+			model.radius = custom.hoverRadius ? custom.hoverRadius : helpers.getValueAtIndexOrDefault(dataset.pointHoverRadius, index, this.chart.options.elements.point.hoverRadius);
+			model.backgroundColor = custom.hoverBackgroundColor ? custom.hoverBackgroundColor : helpers.getValueAtIndexOrDefault(dataset.pointHoverBackgroundColor, index, helpers.getHoverColor(model.backgroundColor));
+			model.borderColor = custom.hoverBorderColor ? custom.hoverBorderColor : helpers.getValueAtIndexOrDefault(dataset.pointHoverBorderColor, index, helpers.getHoverColor(model.borderColor));
+			model.borderWidth = custom.hoverBorderWidth ? custom.hoverBorderWidth : helpers.getValueAtIndexOrDefault(dataset.pointHoverBorderWidth, index, model.borderWidth);
+		},
+
+		removeHoverStyle: function(point) {
+			var dataset = this.chart.data.datasets[point._datasetIndex];
+			var custom = point.custom || {};
+			var index = point._index;
+			var model = point._model;
+			var pointElementOptions = this.chart.options.elements.point;
+
+			model.radius = custom.radius ? custom.radius : helpers.getValueAtIndexOrDefault(dataset.radius, index, pointElementOptions.radius);
+			model.backgroundColor = custom.backgroundColor ? custom.backgroundColor : helpers.getValueAtIndexOrDefault(dataset.pointBackgroundColor, index, pointElementOptions.backgroundColor);
+			model.borderColor = custom.borderColor ? custom.borderColor : helpers.getValueAtIndexOrDefault(dataset.pointBorderColor, index, pointElementOptions.borderColor);
+			model.borderWidth = custom.borderWidth ? custom.borderWidth : helpers.getValueAtIndexOrDefault(dataset.pointBorderWidth, index, pointElementOptions.borderWidth);
+		}
+	});
+};
+
+},{}],21:[function(require,module,exports){
+/* global window: false */
+'use strict';
+
+module.exports = function(Chart) {
+
+	var helpers = Chart.helpers;
+
+	Chart.defaults.global.animation = {
+		duration: 1000,
+		easing: 'easeOutQuart',
+		onProgress: helpers.noop,
+		onComplete: helpers.noop
+	};
+
+	Chart.Animation = Chart.Element.extend({
+		currentStep: null, // the current animation step
+		numSteps: 60, // default number of steps
+		easing: '', // the easing to use for this animation
+		render: null, // render function used by the animation service
+
+		onAnimationProgress: null, // user specified callback to fire on each step of the animation
+		onAnimationComplete: null // user specified callback to fire when the animation finishes
+	});
+
+	Chart.animationService = {
+		frameDuration: 17,
+		animations: [],
+		dropFrames: 0,
+		request: null,
+
+		/**
+		 * @function Chart.animationService.addAnimation
+		 * @param chartInstance {ChartController} the chart to animate
+		 * @param animationObject {IAnimation} the animation that we will animate
+		 * @param duration {Number} length of animation in ms
+		 * @param lazy {Boolean} if true, the chart is not marked as animating to enable more responsive interactions
+		 */
+		addAnimation: function(chartInstance, animationObject, duration, lazy) {
+			var me = this;
+
+			if (!lazy) {
+				chartInstance.animating = true;
+			}
+
+			for (var index = 0; index < me.animations.length; ++index) {
+				if (me.animations[index].chartInstance === chartInstance) {
+					// replacing an in progress animation
+					me.animations[index].animationObject = animationObject;
+					return;
+				}
+			}
+
+			me.animations.push({
+				chartInstance: chartInstance,
+				animationObject: animationObject
+			});
+
+			// If there are no animations queued, manually kickstart a digest, for lack of a better word
+			if (me.animations.length === 1) {
+				me.requestAnimationFrame();
+			}
+		},
+		// Cancel the animation for a given chart instance
+		cancelAnimation: function(chartInstance) {
+			var index = helpers.findIndex(this.animations, function(animationWrapper) {
+				return animationWrapper.chartInstance === chartInstance;
+			});
+
+			if (index !== -1) {
+				this.animations.splice(index, 1);
+				chartInstance.animating = false;
+			}
+		},
+		requestAnimationFrame: function() {
+			var me = this;
+			if (me.request === null) {
+				// Skip animation frame requests until the active one is executed.
+				// This can happen when processing mouse events, e.g. 'mousemove'
+				// and 'mouseout' events will trigger multiple renders.
+				me.request = helpers.requestAnimFrame.call(window, function() {
+					me.request = null;
+					me.startDigest();
+				});
+			}
+		},
+		startDigest: function() {
+			var me = this;
+
+			var startTime = Date.now();
+			var framesToDrop = 0;
+
+			if (me.dropFrames > 1) {
+				framesToDrop = Math.floor(me.dropFrames);
+				me.dropFrames = me.dropFrames % 1;
+			}
+
+			var i = 0;
+			while (i < me.animations.length) {
+				if (me.animations[i].animationObject.currentStep === null) {
+					me.animations[i].animationObject.currentStep = 0;
+				}
+
+				me.animations[i].animationObject.currentStep += 1 + framesToDrop;
+
+				if (me.animations[i].animationObject.currentStep > me.animations[i].animationObject.numSteps) {
+					me.animations[i].animationObject.currentStep = me.animations[i].animationObject.numSteps;
+				}
+
+				me.animations[i].animationObject.render(me.animations[i].chartInstance, me.animations[i].animationObject);
+				if (me.animations[i].animationObject.onAnimationProgress && me.animations[i].animationObject.onAnimationProgress.call) {
+					me.animations[i].animationObject.onAnimationProgress.call(me.animations[i].chartInstance, me.animations[i]);
+				}
+
+				if (me.animations[i].animationObject.currentStep === me.animations[i].animationObject.numSteps) {
+					if (me.animations[i].animationObject.onAnimationComplete && me.animations[i].animationObject.onAnimationComplete.call) {
+						me.animations[i].animationObject.onAnimationComplete.call(me.animations[i].chartInstance, me.animations[i]);
+					}
+
+					// executed the last frame. Remove the animation.
+					me.animations[i].chartInstance.animating = false;
+
+					me.animations.splice(i, 1);
+				} else {
+					++i;
+				}
+			}
+
+			var endTime = Date.now();
+			var dropFrames = (endTime - startTime) / me.frameDuration;
+
+			me.dropFrames += dropFrames;
+
+			// Do we have more stuff to animate?
+			if (me.animations.length > 0) {
+				me.requestAnimationFrame();
+			}
+		}
+	};
+};
+
+},{}],22:[function(require,module,exports){
+'use strict';
+
+module.exports = function(Chart) {
+	// Global Chart canvas helpers object for drawing items to canvas
+	var helpers = Chart.canvasHelpers = {};
+
+	helpers.drawPoint = function(ctx, pointStyle, radius, x, y) {
+		var type, edgeLength, xOffset, yOffset, height, size;
+
+		if (typeof pointStyle === 'object') {
+			type = pointStyle.toString();
+			if (type === '[object HTMLImageElement]' || type === '[object HTMLCanvasElement]') {
+				ctx.drawImage(pointStyle, x - pointStyle.width / 2, y - pointStyle.height / 2);
+				return;
+			}
+		}
+
+		if (isNaN(radius) || radius <= 0) {
+			return;
+		}
+
+		switch (pointStyle) {
+		// Default includes circle
+		default:
+			ctx.beginPath();
+			ctx.arc(x, y, radius, 0, Math.PI * 2);
+			ctx.closePath();
+			ctx.fill();
+			break;
+		case 'triangle':
+			ctx.beginPath();
+			edgeLength = 3 * radius / Math.sqrt(3);
+			height = edgeLength * Math.sqrt(3) / 2;
+			ctx.moveTo(x - edgeLength / 2, y + height / 3);
+			ctx.lineTo(x + edgeLength / 2, y + height / 3);
+			ctx.lineTo(x, y - 2 * height / 3);
+			ctx.closePath();
+			ctx.fill();
+			break;
+		case 'rect':
+			size = 1 / Math.SQRT2 * radius;
+			ctx.beginPath();
+			ctx.fillRect(x - size, y - size, 2 * size, 2 * size);
+			ctx.strokeRect(x - size, y - size, 2 * size, 2 * size);
+			break;
+		case 'rectRounded':
+			var offset = radius / Math.SQRT2;
+			var leftX = x - offset;
+			var topY = y - offset;
+			var sideSize = Math.SQRT2 * radius;
+			Chart.helpers.drawRoundedRectangle(ctx, leftX, topY, sideSize, sideSize, radius / 2);
+			ctx.fill();
+			break;
+		case 'rectRot':
+			size = 1 / Math.SQRT2 * radius;
+			ctx.beginPath();
+			ctx.moveTo(x - size, y);
+			ctx.lineTo(x, y + size);
+			ctx.lineTo(x + size, y);
+			ctx.lineTo(x, y - size);
+			ctx.closePath();
+			ctx.fill();
+			break;
+		case 'cross':
+			ctx.beginPath();
+			ctx.moveTo(x, y + radius);
+			ctx.lineTo(x, y - radius);
+			ctx.moveTo(x - radius, y);
+			ctx.lineTo(x + radius, y);
+			ctx.closePath();
+			break;
+		case 'crossRot':
+			ctx.beginPath();
+			xOffset = Math.cos(Math.PI / 4) * radius;
+			yOffset = Math.sin(Math.PI / 4) * radius;
+			ctx.moveTo(x - xOffset, y - yOffset);
+			ctx.lineTo(x + xOffset, y + yOffset);
+			ctx.moveTo(x - xOffset, y + yOffset);
+			ctx.lineTo(x + xOffset, y - yOffset);
+			ctx.closePath();
+			break;
+		case 'star':
+			ctx.beginPath();
+			ctx.moveTo(x, y + radius);
+			ctx.lineTo(x, y - radius);
+			ctx.moveTo(x - radius, y);
+			ctx.lineTo(x + radius, y);
+			xOffset = Math.cos(Math.PI / 4) * radius;
+			yOffset = Math.sin(Math.PI / 4) * radius;
+			ctx.moveTo(x - xOffset, y - yOffset);
+			ctx.lineTo(x + xOffset, y + yOffset);
+			ctx.moveTo(x - xOffset, y + yOffset);
+			ctx.lineTo(x + xOffset, y - yOffset);
+			ctx.closePath();
+			break;
+		case 'line':
+			ctx.beginPath();
+			ctx.moveTo(x - radius, y);
+			ctx.lineTo(x + radius, y);
+			ctx.closePath();
+			break;
+		case 'dash':
+			ctx.beginPath();
+			ctx.moveTo(x, y);
+			ctx.lineTo(x + radius, y);
+			ctx.closePath();
+			break;
+		}
+
+		ctx.stroke();
+	};
+
+	helpers.clipArea = function(ctx, clipArea) {
+		ctx.save();
+		ctx.beginPath();
+		ctx.rect(clipArea.left, clipArea.top, clipArea.right - clipArea.left, clipArea.bottom - clipArea.top);
+		ctx.clip();
+	};
+
+	helpers.unclipArea = function(ctx) {
+		ctx.restore();
+	};
+
+};
+
+},{}],23:[function(require,module,exports){
+'use strict';
+
+module.exports = function(Chart) {
+
+	var helpers = Chart.helpers;
+	var plugins = Chart.plugins;
+	var platform = Chart.platform;
+
+	// Create a dictionary of chart types, to allow for extension of existing types
+	Chart.types = {};
+
+	// Store a reference to each instance - allowing us to globally resize chart instances on window resize.
+	// Destroy method on the chart will remove the instance of the chart from this reference.
+	Chart.instances = {};
+
+	// Controllers available for dataset visualization eg. bar, line, slice, etc.
+	Chart.controllers = {};
+
+	/**
+	 * Initializes the given config with global and chart default values.
+	 */
+	function initConfig(config) {
+		config = config || {};
+
+		// Do NOT use configMerge() for the data object because this method merges arrays
+		// and so would change references to labels and datasets, preventing data updates.
+		var data = config.data = config.data || {};
+		data.datasets = data.datasets || [];
+		data.labels = data.labels || [];
+
+		config.options = helpers.configMerge(
+			Chart.defaults.global,
+			Chart.defaults[config.type],
+			config.options || {});
+
+		return config;
+	}
+
+	/**
+	 * Updates the config of the chart
+	 * @param chart {Chart.Controller} chart to update the options for
+	 */
+	function updateConfig(chart) {
+		var newOptions = chart.options;
+
+		// Update Scale(s) with options
+		if (newOptions.scale) {
+			chart.scale.options = newOptions.scale;
+		} else if (newOptions.scales) {
+			newOptions.scales.xAxes.concat(newOptions.scales.yAxes).forEach(function(scaleOptions) {
+				chart.scales[scaleOptions.id].options = scaleOptions;
+			});
+		}
+
+		// Tooltip
+		chart.tooltip._options = newOptions.tooltips;
+	}
+
+	/**
+	 * @class Chart.Controller
+	 * The main controller of a chart.
+	 */
+	Chart.Controller = function(item, config, instance) {
+		var me = this;
+
+		config = initConfig(config);
+
+		var context = platform.acquireContext(item, config);
+		var canvas = context && context.canvas;
+		var height = canvas && canvas.height;
+		var width = canvas && canvas.width;
+
+		instance.ctx = context;
+		instance.canvas = canvas;
+		instance.config = config;
+		instance.width = width;
+		instance.height = height;
+		instance.aspectRatio = height? width / height : null;
+
+		me.id = helpers.uid();
+		me.chart = instance;
+		me.config = config;
+		me.options = config.options;
+		me._bufferedRender = false;
+
+		// Add the chart instance to the global namespace
+		Chart.instances[me.id] = me;
+
+		Object.defineProperty(me, 'data', {
+			get: function() {
+				return me.config.data;
+			}
+		});
+
+		if (!context || !canvas) {
+			// The given item is not a compatible context2d element, let's return before finalizing
+			// the chart initialization but after setting basic chart / controller properties that
+			// can help to figure out that the chart is not valid (e.g chart.canvas !== null);
+			// https://github.com/chartjs/Chart.js/issues/2807
+			console.error("Failed to create chart: can't acquire context from the given item");
+			return me;
+		}
+
+		me.initialize();
+		me.update();
+
+		return me;
+	};
+
+	helpers.extend(Chart.Controller.prototype, /** @lends Chart.Controller.prototype */ {
+		initialize: function() {
+			var me = this;
+
+			// Before init plugin notification
+			plugins.notify(me, 'beforeInit');
+
+			helpers.retinaScale(me.chart);
+
+			me.bindEvents();
+
+			if (me.options.responsive) {
+				// Initial resize before chart draws (must be silent to preserve initial animations).
+				me.resize(true);
+			}
+
+			// Make sure scales have IDs and are built before we build any controllers.
+			me.ensureScalesHaveIDs();
+			me.buildScales();
+			me.initToolTip();
+
+			// After init plugin notification
+			plugins.notify(me, 'afterInit');
+
+			return me;
+		},
+
+		clear: function() {
+			helpers.clear(this.chart);
+			return this;
+		},
+
+		stop: function() {
+			// Stops any current animation loop occurring
+			Chart.animationService.cancelAnimation(this);
+			return this;
+		},
+
+		resize: function(silent) {
+			var me = this;
+			var chart = me.chart;
+			var options = me.options;
+			var canvas = chart.canvas;
+			var aspectRatio = (options.maintainAspectRatio && chart.aspectRatio) || null;
+
+			// the canvas render width and height will be casted to integers so make sure that
+			// the canvas display style uses the same integer values to avoid blurring effect.
+			var newWidth = Math.floor(helpers.getMaximumWidth(canvas));
+			var newHeight = Math.floor(aspectRatio? newWidth / aspectRatio : helpers.getMaximumHeight(canvas));
+
+			if (chart.width === newWidth && chart.height === newHeight) {
+				return;
+			}
+
+			canvas.width = chart.width = newWidth;
+			canvas.height = chart.height = newHeight;
+			canvas.style.width = newWidth + 'px';
+			canvas.style.height = newHeight + 'px';
+
+			helpers.retinaScale(chart);
+
+			if (!silent) {
+				// Notify any plugins about the resize
+				var newSize = {width: newWidth, height: newHeight};
+				plugins.notify(me, 'resize', [newSize]);
+
+				// Notify of resize
+				if (me.options.onResize) {
+					me.options.onResize(me, newSize);
+				}
+
+				me.stop();
+				me.update(me.options.responsiveAnimationDuration);
+			}
+		},
+
+		ensureScalesHaveIDs: function() {
+			var options = this.options;
+			var scalesOptions = options.scales || {};
+			var scaleOptions = options.scale;
+
+			helpers.each(scalesOptions.xAxes, function(xAxisOptions, index) {
+				xAxisOptions.id = xAxisOptions.id || ('x-axis-' + index);
+			});
+
+			helpers.each(scalesOptions.yAxes, function(yAxisOptions, index) {
+				yAxisOptions.id = yAxisOptions.id || ('y-axis-' + index);
+			});
+
+			if (scaleOptions) {
+				scaleOptions.id = scaleOptions.id || 'scale';
+			}
+		},
+
+		/**
+		 * Builds a map of scale ID to scale object for future lookup.
+		 */
+		buildScales: function() {
+			var me = this;
+			var options = me.options;
+			var scales = me.scales = {};
+			var items = [];
+
+			if (options.scales) {
+				items = items.concat(
+					(options.scales.xAxes || []).map(function(xAxisOptions) {
+						return {options: xAxisOptions, dtype: 'category'};
+					}),
+					(options.scales.yAxes || []).map(function(yAxisOptions) {
+						return {options: yAxisOptions, dtype: 'linear'};
+					})
+				);
+			}
+
+			if (options.scale) {
+				items.push({options: options.scale, dtype: 'radialLinear', isDefault: true});
+			}
+
+			helpers.each(items, function(item) {
+				var scaleOptions = item.options;
+				var scaleType = helpers.getValueOrDefault(scaleOptions.type, item.dtype);
+				var scaleClass = Chart.scaleService.getScaleConstructor(scaleType);
+				if (!scaleClass) {
+					return;
+				}
+
+				var scale = new scaleClass({
+					id: scaleOptions.id,
+					options: scaleOptions,
+					ctx: me.chart.ctx,
+					chart: me
+				});
+
+				scales[scale.id] = scale;
+
+				// TODO(SB): I think we should be able to remove this custom case (options.scale)
+				// and consider it as a regular scale part of the "scales"" map only! This would
+				// make the logic easier and remove some useless? custom code.
+				if (item.isDefault) {
+					me.scale = scale;
+				}
+			});
+
+			Chart.scaleService.addScalesToLayout(this);
+		},
+
+		buildOrUpdateControllers: function() {
+			var me = this;
+			var types = [];
+			var newControllers = [];
+
+			helpers.each(me.data.datasets, function(dataset, datasetIndex) {
+				var meta = me.getDatasetMeta(datasetIndex);
+				if (!meta.type) {
+					meta.type = dataset.type || me.config.type;
+				}
+
+				types.push(meta.type);
+
+				if (meta.controller) {
+					meta.controller.updateIndex(datasetIndex);
+				} else {
+					meta.controller = new Chart.controllers[meta.type](me, datasetIndex);
+					newControllers.push(meta.controller);
+				}
+			}, me);
+
+			if (types.length > 1) {
+				for (var i = 1; i < types.length; i++) {
+					if (types[i] !== types[i - 1]) {
+						me.isCombo = true;
+						break;
+					}
+				}
+			}
+
+			return newControllers;
+		},
+
+		/**
+		 * Reset the elements of all datasets
+		 * @private
+		 */
+		resetElements: function() {
+			var me = this;
+			helpers.each(me.data.datasets, function(dataset, datasetIndex) {
+				me.getDatasetMeta(datasetIndex).controller.reset();
+			}, me);
+		},
+
+		/**
+		* Resets the chart back to it's state before the initial animation
+		*/
+		reset: function() {
+			this.resetElements();
+			this.tooltip.initialize();
+		},
+
+		update: function(animationDuration, lazy) {
+			var me = this;
+
+			updateConfig(me);
+
+			if (plugins.notify(me, 'beforeUpdate') === false) {
+				return;
+			}
+
+			// In case the entire data object changed
+			me.tooltip._data = me.data;
+
+			// Make sure dataset controllers are updated and new controllers are reset
+			var newControllers = me.buildOrUpdateControllers();
+
+			// Make sure all dataset controllers have correct meta data counts
+			helpers.each(me.data.datasets, function(dataset, datasetIndex) {
+				me.getDatasetMeta(datasetIndex).controller.buildOrUpdateElements();
+			}, me);
+
+			me.updateLayout();
+
+			// Can only reset the new controllers after the scales have been updated
+			helpers.each(newControllers, function(controller) {
+				controller.reset();
+			});
+
+			me.updateDatasets();
+
+			// Do this before render so that any plugins that need final scale updates can use it
+			plugins.notify(me, 'afterUpdate');
+
+			if (me._bufferedRender) {
+				me._bufferedRequest = {
+					lazy: lazy,
+					duration: animationDuration
+				};
+			} else {
+				me.render(animationDuration, lazy);
+			}
+		},
+
+		/**
+		 * Updates the chart layout unless a plugin returns `false` to the `beforeLayout`
+		 * hook, in which case, plugins will not be called on `afterLayout`.
+		 * @private
+		 */
+		updateLayout: function() {
+			var me = this;
+
+			if (plugins.notify(me, 'beforeLayout') === false) {
+				return;
+			}
+
+			Chart.layoutService.update(this, this.chart.width, this.chart.height);
+
+			/**
+			 * Provided for backward compatibility, use `afterLayout` instead.
+			 * @method IPlugin#afterScaleUpdate
+			 * @deprecated since version 2.5.0
+			 * @todo remove at version 3
+			 */
+			plugins.notify(me, 'afterScaleUpdate');
+			plugins.notify(me, 'afterLayout');
+		},
+
+		/**
+		 * Updates all datasets unless a plugin returns `false` to the `beforeDatasetsUpdate`
+		 * hook, in which case, plugins will not be called on `afterDatasetsUpdate`.
+		 * @private
+		 */
+		updateDatasets: function() {
+			var me = this;
+
+			if (plugins.notify(me, 'beforeDatasetsUpdate') === false) {
+				return;
+			}
+
+			for (var i = 0, ilen = me.data.datasets.length; i < ilen; ++i) {
+				me.getDatasetMeta(i).controller.update();
+			}
+
+			plugins.notify(me, 'afterDatasetsUpdate');
+		},
+
+		render: function(duration, lazy) {
+			var me = this;
+
+			if (plugins.notify(me, 'beforeRender') === false) {
+				return;
+			}
+
+			var animationOptions = me.options.animation;
+			var onComplete = function() {
+				plugins.notify(me, 'afterRender');
+				var callback = animationOptions && animationOptions.onComplete;
+				if (callback && callback.call) {
+					callback.call(me);
+				}
+			};
+
+			if (animationOptions && ((typeof duration !== 'undefined' && duration !== 0) || (typeof duration === 'undefined' && animationOptions.duration !== 0))) {
+				var animation = new Chart.Animation();
+				animation.numSteps = (duration || animationOptions.duration) / 16.66; // 60 fps
+				animation.easing = animationOptions.easing;
+
+				// render function
+				animation.render = function(chartInstance, animationObject) {
+					var easingFunction = helpers.easingEffects[animationObject.easing];
+					var stepDecimal = animationObject.currentStep / animationObject.numSteps;
+					var easeDecimal = easingFunction(stepDecimal);
+
+					chartInstance.draw(easeDecimal, stepDecimal, animationObject.currentStep);
+				};
+
+				// user events
+				animation.onAnimationProgress = animationOptions.onProgress;
+				animation.onAnimationComplete = onComplete;
+
+				Chart.animationService.addAnimation(me, animation, duration, lazy);
+			} else {
+				me.draw();
+				onComplete();
+			}
+
+			return me;
+		},
+
+		draw: function(easingValue) {
+			var me = this;
+
+			me.clear();
+
+			if (easingValue === undefined || easingValue === null) {
+				easingValue = 1;
+			}
+
+			if (plugins.notify(me, 'beforeDraw', [easingValue]) === false) {
+				return;
+			}
+
+			// Draw all the scales
+			helpers.each(me.boxes, function(box) {
+				box.draw(me.chartArea);
+			}, me);
+
+			if (me.scale) {
+				me.scale.draw();
+			}
+
+			me.drawDatasets(easingValue);
+
+			// Finally draw the tooltip
+			me.tooltip.transition(easingValue).draw();
+
+			plugins.notify(me, 'afterDraw', [easingValue]);
+		},
+
+		/**
+		 * Draws all datasets unless a plugin returns `false` to the `beforeDatasetsDraw`
+		 * hook, in which case, plugins will not be called on `afterDatasetsDraw`.
+		 * @private
+		 */
+		drawDatasets: function(easingValue) {
+			var me = this;
+
+			if (plugins.notify(me, 'beforeDatasetsDraw', [easingValue]) === false) {
+				return;
+			}
+
+			// Draw each dataset via its respective controller (reversed to support proper line stacking)
+			helpers.each(me.data.datasets, function(dataset, datasetIndex) {
+				if (me.isDatasetVisible(datasetIndex)) {
+					me.getDatasetMeta(datasetIndex).controller.draw(easingValue);
+				}
+			}, me, true);
+
+			plugins.notify(me, 'afterDatasetsDraw', [easingValue]);
+		},
+
+		// Get the single element that was clicked on
+		// @return : An object containing the dataset index and element index of the matching element. Also contains the rectangle that was draw
+		getElementAtEvent: function(e) {
+			return Chart.Interaction.modes.single(this, e);
+		},
+
+		getElementsAtEvent: function(e) {
+			return Chart.Interaction.modes.label(this, e, {intersect: true});
+		},
+
+		getElementsAtXAxis: function(e) {
+			return Chart.Interaction.modes['x-axis'](this, e, {intersect: true});
+		},
+
+		getElementsAtEventForMode: function(e, mode, options) {
+			var method = Chart.Interaction.modes[mode];
+			if (typeof method === 'function') {
+				return method(this, e, options);
+			}
+
+			return [];
+		},
+
+		getDatasetAtEvent: function(e) {
+			return Chart.Interaction.modes.dataset(this, e, {intersect: true});
+		},
+
+		getDatasetMeta: function(datasetIndex) {
+			var me = this;
+			var dataset = me.data.datasets[datasetIndex];
+			if (!dataset._meta) {
+				dataset._meta = {};
+			}
+
+			var meta = dataset._meta[me.id];
+			if (!meta) {
+				meta = dataset._meta[me.id] = {
+					type: null,
+					data: [],
+					dataset: null,
+					controller: null,
+					hidden: null,			// See isDatasetVisible() comment
+					xAxisID: null,
+					yAxisID: null
+				};
+			}
+
+			return meta;
+		},
+
+		getVisibleDatasetCount: function() {
+			var count = 0;
+			for (var i = 0, ilen = this.data.datasets.length; i<ilen; ++i) {
+				if (this.isDatasetVisible(i)) {
+					count++;
+				}
+			}
+			return count;
+		},
+
+		isDatasetVisible: function(datasetIndex) {
+			var meta = this.getDatasetMeta(datasetIndex);
+
+			// meta.hidden is a per chart dataset hidden flag override with 3 states: if true or false,
+			// the dataset.hidden value is ignored, else if null, the dataset hidden state is returned.
+			return typeof meta.hidden === 'boolean'? !meta.hidden : !this.data.datasets[datasetIndex].hidden;
+		},
+
+		generateLegend: function() {
+			return this.options.legendCallback(this);
+		},
+
+		destroy: function() {
+			var me = this;
+			var canvas = me.chart.canvas;
+			var meta, i, ilen;
+
+			me.stop();
+
+			// dataset controllers need to cleanup associated data
+			for (i = 0, ilen = me.data.datasets.length; i < ilen; ++i) {
+				meta = me.getDatasetMeta(i);
+				if (meta.controller) {
+					meta.controller.destroy();
+					meta.controller = null;
+				}
+			}
+
+			if (canvas) {
+				me.unbindEvents();
+				helpers.clear(me.chart);
+				platform.releaseContext(me.chart.ctx);
+				me.chart.canvas = null;
+				me.chart.ctx = null;
+			}
+
+			plugins.notify(me, 'destroy');
+
+			delete Chart.instances[me.id];
+		},
+
+		toBase64Image: function() {
+			return this.chart.canvas.toDataURL.apply(this.chart.canvas, arguments);
+		},
+
+		initToolTip: function() {
+			var me = this;
+			me.tooltip = new Chart.Tooltip({
+				_chart: me.chart,
+				_chartInstance: me,
+				_data: me.data,
+				_options: me.options.tooltips
+			}, me);
+			me.tooltip.initialize();
+		},
+
+		/**
+		 * @private
+		 */
+		bindEvents: function() {
+			var me = this;
+			var listeners = me._listeners = {};
+			var listener = function() {
+				me.eventHandler.apply(me, arguments);
+			};
+
+			helpers.each(me.options.events, function(type) {
+				platform.addEventListener(me, type, listener);
+				listeners[type] = listener;
+			});
+
+			// Responsiveness is currently based on the use of an iframe, however this method causes
+			// performance issues and could be troublesome when used with ad blockers. So make sure
+			// that the user is still able to create a chart without iframe when responsive is false.
+			// See https://github.com/chartjs/Chart.js/issues/2210
+			if (me.options.responsive) {
+				listener = function() {
+					me.resize();
+				};
+
+				platform.addEventListener(me, 'resize', listener);
+				listeners.resize = listener;
+			}
+		},
+
+		/**
+		 * @private
+		 */
+		unbindEvents: function() {
+			var me = this;
+			var listeners = me._listeners;
+			if (!listeners) {
+				return;
+			}
+
+			delete me._listeners;
+			helpers.each(listeners, function(listener, type) {
+				platform.removeEventListener(me, type, listener);
+			});
+		},
+
+		updateHoverStyle: function(elements, mode, enabled) {
+			var method = enabled? 'setHoverStyle' : 'removeHoverStyle';
+			var element, i, ilen;
+
+			for (i=0, ilen=elements.length; i<ilen; ++i) {
+				element = elements[i];
+				if (element) {
+					this.getDatasetMeta(element._datasetIndex).controller[method](element);
+				}
+			}
+		},
+
+		/**
+		 * @private
+		 */
+		eventHandler: function(e) {
+			var me = this;
+			var tooltip = me.tooltip;
+
+			if (plugins.notify(me, 'beforeEvent', [e]) === false) {
+				return;
+			}
+
+			// Buffer any update calls so that renders do not occur
+			me._bufferedRender = true;
+			me._bufferedRequest = null;
+
+			var changed = me.handleEvent(e);
+			changed |= tooltip && tooltip.handleEvent(e);
+
+			plugins.notify(me, 'afterEvent', [e]);
+
+			var bufferedRequest = me._bufferedRequest;
+			if (bufferedRequest) {
+				// If we have an update that was triggered, we need to do a normal render
+				me.render(bufferedRequest.duration, bufferedRequest.lazy);
+			} else if (changed && !me.animating) {
+				// If entering, leaving, or changing elements, animate the change via pivot
+				me.stop();
+
+				// We only need to render at this point. Updating will cause scales to be
+				// recomputed generating flicker & using more memory than necessary.
+				me.render(me.options.hover.animationDuration, true);
+			}
+
+			me._bufferedRender = false;
+			me._bufferedRequest = null;
+
+			return me;
+		},
+
+		/**
+		 * Handle an event
+		 * @private
+		 * @param {IEvent} event the event to handle
+		 * @return {Boolean} true if the chart needs to re-render
+		 */
+		handleEvent: function(e) {
+			var me = this;
+			var options = me.options || {};
+			var hoverOptions = options.hover;
+			var changed = false;
+
+			me.lastActive = me.lastActive || [];
+
+			// Find Active Elements for hover and tooltips
+			if (e.type === 'mouseout') {
+				me.active = [];
+			} else {
+				me.active = me.getElementsAtEventForMode(e, hoverOptions.mode, hoverOptions);
+			}
+
+			// On Hover hook
+			if (hoverOptions.onHover) {
+				// Need to call with native event here to not break backwards compatibility
+				hoverOptions.onHover.call(me, e.native, me.active);
+			}
+
+			if (e.type === 'mouseup' || e.type === 'click') {
+				if (options.onClick) {
+					// Use e.native here for backwards compatibility
+					options.onClick.call(me, e.native, me.active);
+				}
+			}
+
+			// Remove styling for last active (even if it may still be active)
+			if (me.lastActive.length) {
+				me.updateHoverStyle(me.lastActive, hoverOptions.mode, false);
+			}
+
+			// Built in hover styling
+			if (me.active.length && hoverOptions.mode) {
+				me.updateHoverStyle(me.active, hoverOptions.mode, true);
+			}
+
+			changed = !helpers.arrayEquals(me.active, me.lastActive);
+
+			// Remember Last Actives
+			me.lastActive = me.active;
+
+			return changed;
+		}
+	});
+};
+
+},{}],24:[function(require,module,exports){
+'use strict';
+
+module.exports = function(Chart) {
+
+	var helpers = Chart.helpers;
+
+	var arrayEvents = ['push', 'pop', 'shift', 'splice', 'unshift'];
+
+	/**
+	 * Hooks the array methods that add or remove values ('push', pop', 'shift', 'splice',
+	 * 'unshift') and notify the listener AFTER the array has been altered. Listeners are
+	 * called on the 'onData*' callbacks (e.g. onDataPush, etc.) with same arguments.
+	 */
+	function listenArrayEvents(array, listener) {
+		if (array._chartjs) {
+			array._chartjs.listeners.push(listener);
+			return;
+		}
+
+		Object.defineProperty(array, '_chartjs', {
+			configurable: true,
+			enumerable: false,
+			value: {
+				listeners: [listener]
+			}
+		});
+
+		arrayEvents.forEach(function(key) {
+			var method = 'onData' + key.charAt(0).toUpperCase() + key.slice(1);
+			var base = array[key];
+
+			Object.defineProperty(array, key, {
+				configurable: true,
+				enumerable: false,
+				value: function() {
+					var args = Array.prototype.slice.call(arguments);
+					var res = base.apply(this, args);
+
+					helpers.each(array._chartjs.listeners, function(object) {
+						if (typeof object[method] === 'function') {
+							object[method].apply(object, args);
+						}
+					});
+
+					return res;
+				}
+			});
+		});
+	}
+
+	/**
+	 * Removes the given array event listener and cleanup extra attached properties (such as
+	 * the _chartjs stub and overridden methods) if array doesn't have any more listeners.
+	 */
+	function unlistenArrayEvents(array, listener) {
+		var stub = array._chartjs;
+		if (!stub) {
+			return;
+		}
+
+		var listeners = stub.listeners;
+		var index = listeners.indexOf(listener);
+		if (index !== -1) {
+			listeners.splice(index, 1);
+		}
+
+		if (listeners.length > 0) {
+			return;
+		}
+
+		arrayEvents.forEach(function(key) {
+			delete array[key];
+		});
+
+		delete array._chartjs;
+	}
+
+	// Base class for all dataset controllers (line, bar, etc)
+	Chart.DatasetController = function(chart, datasetIndex) {
+		this.initialize(chart, datasetIndex);
+	};
+
+	helpers.extend(Chart.DatasetController.prototype, {
+
+		/**
+		 * Element type used to generate a meta dataset (e.g. Chart.element.Line).
+		 * @type {Chart.core.element}
+		 */
+		datasetElementType: null,
+
+		/**
+		 * Element type used to generate a meta data (e.g. Chart.element.Point).
+		 * @type {Chart.core.element}
+		 */
+		dataElementType: null,
+
+		initialize: function(chart, datasetIndex) {
+			var me = this;
+			me.chart = chart;
+			me.index = datasetIndex;
+			me.linkScales();
+			me.addElements();
+		},
+
+		updateIndex: function(datasetIndex) {
+			this.index = datasetIndex;
+		},
+
+		linkScales: function() {
+			var me = this;
+			var meta = me.getMeta();
+			var dataset = me.getDataset();
+
+			if (meta.xAxisID === null) {
+				meta.xAxisID = dataset.xAxisID || me.chart.options.scales.xAxes[0].id;
+			}
+			if (meta.yAxisID === null) {
+				meta.yAxisID = dataset.yAxisID || me.chart.options.scales.yAxes[0].id;
+			}
+		},
+
+		getDataset: function() {
+			return this.chart.data.datasets[this.index];
+		},
+
+		getMeta: function() {
+			return this.chart.getDatasetMeta(this.index);
+		},
+
+		getScaleForId: function(scaleID) {
+			return this.chart.scales[scaleID];
+		},
+
+		reset: function() {
+			this.update(true);
+		},
+
+		/**
+		 * @private
+		 */
+		destroy: function() {
+			if (this._data) {
+				unlistenArrayEvents(this._data, this);
+			}
+		},
+
+		createMetaDataset: function() {
+			var me = this;
+			var type = me.datasetElementType;
+			return type && new type({
+				_chart: me.chart.chart,
+				_datasetIndex: me.index
+			});
+		},
+
+		createMetaData: function(index) {
+			var me = this;
+			var type = me.dataElementType;
+			return type && new type({
+				_chart: me.chart.chart,
+				_datasetIndex: me.index,
+				_index: index
+			});
+		},
+
+		addElements: function() {
+			var me = this;
+			var meta = me.getMeta();
+			var data = me.getDataset().data || [];
+			var metaData = meta.data;
+			var i, ilen;
+
+			for (i=0, ilen=data.length; i<ilen; ++i) {
+				metaData[i] = metaData[i] || me.createMetaData(i);
+			}
+
+			meta.dataset = meta.dataset || me.createMetaDataset();
+		},
+
+		addElementAndReset: function(index) {
+			var element = this.createMetaData(index);
+			this.getMeta().data.splice(index, 0, element);
+			this.updateElement(element, index, true);
+		},
+
+		buildOrUpdateElements: function() {
+			var me = this;
+			var dataset = me.getDataset();
+			var data = dataset.data || (dataset.data = []);
+
+			// In order to correctly handle data addition/deletion animation (an thus simulate
+			// real-time charts), we need to monitor these data modifications and synchronize
+			// the internal meta data accordingly.
+			if (me._data !== data) {
+				if (me._data) {
+					// This case happens when the user replaced the data array instance.
+					unlistenArrayEvents(me._data, me);
+				}
+
+				listenArrayEvents(data, me);
+				me._data = data;
+			}
+
+			// Re-sync meta data in case the user replaced the data array or if we missed
+			// any updates and so make sure that we handle number of datapoints changing.
+			me.resyncElements();
+		},
+
+		update: helpers.noop,
+
+		draw: function(ease) {
+			var easingDecimal = ease || 1;
+			var i, len;
+			var metaData = this.getMeta().data;
+			for (i = 0, len = metaData.length; i < len; ++i) {
+				metaData[i].transition(easingDecimal).draw();
+			}
+		},
+
+		removeHoverStyle: function(element, elementOpts) {
+			var dataset = this.chart.data.datasets[element._datasetIndex],
+				index = element._index,
+				custom = element.custom || {},
+				valueOrDefault = helpers.getValueAtIndexOrDefault,
+				model = element._model;
+
+			model.backgroundColor = custom.backgroundColor ? custom.backgroundColor : valueOrDefault(dataset.backgroundColor, index, elementOpts.backgroundColor);
+			model.borderColor = custom.borderColor ? custom.borderColor : valueOrDefault(dataset.borderColor, index, elementOpts.borderColor);
+			model.borderWidth = custom.borderWidth ? custom.borderWidth : valueOrDefault(dataset.borderWidth, index, elementOpts.borderWidth);
+		},
+
+		setHoverStyle: function(element) {
+			var dataset = this.chart.data.datasets[element._datasetIndex],
+				index = element._index,
+				custom = element.custom || {},
+				valueOrDefault = helpers.getValueAtIndexOrDefault,
+				getHoverColor = helpers.getHoverColor,
+				model = element._model;
+
+			model.backgroundColor = custom.hoverBackgroundColor ? custom.hoverBackgroundColor : valueOrDefault(dataset.hoverBackgroundColor, index, getHoverColor(model.backgroundColor));
+			model.borderColor = custom.hoverBorderColor ? custom.hoverBorderColor : valueOrDefault(dataset.hoverBorderColor, index, getHoverColor(model.borderColor));
+			model.borderWidth = custom.hoverBorderWidth ? custom.hoverBorderWidth : valueOrDefault(dataset.hoverBorderWidth, index, model.borderWidth);
+		},
+
+		/**
+		 * @private
+		 */
+		resyncElements: function() {
+			var me = this;
+			var meta = me.getMeta();
+			var data = me.getDataset().data;
+			var numMeta = meta.data.length;
+			var numData = data.length;
+
+			if (numData < numMeta) {
+				meta.data.splice(numData, numMeta - numData);
+			} else if (numData > numMeta) {
+				me.insertElements(numMeta, numData - numMeta);
+			}
+		},
+
+		/**
+		 * @private
+		 */
+		insertElements: function(start, count) {
+			for (var i=0; i<count; ++i) {
+				this.addElementAndReset(start + i);
+			}
+		},
+
+		/**
+		 * @private
+		 */
+		onDataPush: function() {
+			this.insertElements(this.getDataset().data.length-1, arguments.length);
+		},
+
+		/**
+		 * @private
+		 */
+		onDataPop: function() {
+			this.getMeta().data.pop();
+		},
+
+		/**
+		 * @private
+		 */
+		onDataShift: function() {
+			this.getMeta().data.shift();
+		},
+
+		/**
+		 * @private
+		 */
+		onDataSplice: function(start, count) {
+			this.getMeta().data.splice(start, count);
+			this.insertElements(start, arguments.length - 2);
+		},
+
+		/**
+		 * @private
+		 */
+		onDataUnshift: function() {
+			this.insertElements(0, arguments.length);
+		}
+	});
+
+	Chart.DatasetController.extend = helpers.inherits;
+};
+
+},{}],25:[function(require,module,exports){
+'use strict';
+
+module.exports = function(Chart) {
+
+	var helpers = Chart.helpers;
+
+	Chart.elements = {};
+
+	Chart.Element = function(configuration) {
+		helpers.extend(this, configuration);
+		this.initialize.apply(this, arguments);
+	};
+
+	helpers.extend(Chart.Element.prototype, {
+
+		initialize: function() {
+			this.hidden = false;
+		},
+
+		pivot: function() {
+			var me = this;
+			if (!me._view) {
+				me._view = helpers.clone(me._model);
+			}
+			me._start = helpers.clone(me._view);
+			return me;
+		},
+
+		transition: function(ease) {
+			var me = this;
+
+			if (!me._view) {
+				me._view = helpers.clone(me._model);
+			}
+
+			// No animation -> No Transition
+			if (ease === 1) {
+				me._view = me._model;
+				me._start = null;
+				return me;
+			}
+
+			if (!me._start) {
+				me.pivot();
+			}
+
+			helpers.each(me._model, function(value, key) {
+
+				if (key[0] === '_') {
+					// Only non-underscored properties
+				// Init if doesn't exist
+				} else if (!me._view.hasOwnProperty(key)) {
+					if (typeof value === 'number' && !isNaN(me._view[key])) {
+						me._view[key] = value * ease;
+					} else {
+						me._view[key] = value;
+					}
+				// No unnecessary computations
+				} else if (value === me._view[key]) {
+					// It's the same! Woohoo!
+				// Color transitions if possible
+				} else if (typeof value === 'string') {
+					try {
+						var color = helpers.color(me._model[key]).mix(helpers.color(me._start[key]), ease);
+						me._view[key] = color.rgbString();
+					} catch (err) {
+						me._view[key] = value;
+					}
+				// Number transitions
+				} else if (typeof value === 'number') {
+					var startVal = me._start[key] !== undefined && isNaN(me._start[key]) === false ? me._start[key] : 0;
+					me._view[key] = ((me._model[key] - startVal) * ease) + startVal;
+				// Everything else
+				} else {
+					me._view[key] = value;
+				}
+			}, me);
+
+			return me;
+		},
+
+		tooltipPosition: function() {
+			return {
+				x: this._model.x,
+				y: this._model.y
+			};
+		},
+
+		hasValue: function() {
+			return helpers.isNumber(this._model.x) && helpers.isNumber(this._model.y);
+		}
+	});
+
+	Chart.Element.extend = helpers.inherits;
+
+};
+
+},{}],26:[function(require,module,exports){
+/* global window: false */
+/* global document: false */
+'use strict';
+
+var color = require(3);
+
+module.exports = function(Chart) {
+	// Global Chart helpers object for utility methods and classes
+	var helpers = Chart.helpers = {};
+
+	// -- Basic js utility methods
+	helpers.each = function(loopable, callback, self, reverse) {
+		// Check to see if null or undefined firstly.
+		var i, len;
+		if (helpers.isArray(loopable)) {
+			len = loopable.length;
+			if (reverse) {
+				for (i = len - 1; i >= 0; i--) {
+					callback.call(self, loopable[i], i);
+				}
+			} else {
+				for (i = 0; i < len; i++) {
+					callback.call(self, loopable[i], i);
+				}
+			}
+		} else if (typeof loopable === 'object') {
+			var keys = Object.keys(loopable);
+			len = keys.length;
+			for (i = 0; i < len; i++) {
+				callback.call(self, loopable[keys[i]], keys[i]);
+			}
+		}
+	};
+	helpers.clone = function(obj) {
+		var objClone = {};
+		helpers.each(obj, function(value, key) {
+			if (helpers.isArray(value)) {
+				objClone[key] = value.slice(0);
+			} else if (typeof value === 'object' && value !== null) {
+				objClone[key] = helpers.clone(value);
+			} else {
+				objClone[key] = value;
+			}
+		});
+		return objClone;
+	};
+	helpers.extend = function(base) {
+		var setFn = function(value, key) {
+			base[key] = value;
+		};
+		for (var i = 1, ilen = arguments.length; i < ilen; i++) {
+			helpers.each(arguments[i], setFn);
+		}
+		return base;
+	};
+	// Need a special merge function to chart configs since they are now grouped
+	helpers.configMerge = function(_base) {
+		var base = helpers.clone(_base);
+		helpers.each(Array.prototype.slice.call(arguments, 1), function(extension) {
+			helpers.each(extension, function(value, key) {
+				var baseHasProperty = base.hasOwnProperty(key);
+				var baseVal = baseHasProperty ? base[key] : {};
+
+				if (key === 'scales') {
+					// Scale config merging is complex. Add our own function here for that
+					base[key] = helpers.scaleMerge(baseVal, value);
+				} else if (key === 'scale') {
+					// Used in polar area & radar charts since there is only one scale
+					base[key] = helpers.configMerge(baseVal, Chart.scaleService.getScaleDefaults(value.type), value);
+				} else if (baseHasProperty
+						&& typeof baseVal === 'object'
+						&& !helpers.isArray(baseVal)
+						&& baseVal !== null
+						&& typeof value === 'object'
+						&& !helpers.isArray(value)) {
+					// If we are overwriting an object with an object, do a merge of the properties.
+					base[key] = helpers.configMerge(baseVal, value);
+				} else {
+					// can just overwrite the value in this case
+					base[key] = value;
+				}
+			});
+		});
+
+		return base;
+	};
+	helpers.scaleMerge = function(_base, extension) {
+		var base = helpers.clone(_base);
+
+		helpers.each(extension, function(value, key) {
+			if (key === 'xAxes' || key === 'yAxes') {
+				// These properties are arrays of items
+				if (base.hasOwnProperty(key)) {
+					helpers.each(value, function(valueObj, index) {
+						var axisType = helpers.getValueOrDefault(valueObj.type, key === 'xAxes' ? 'category' : 'linear');
+						var axisDefaults = Chart.scaleService.getScaleDefaults(axisType);
+						if (index >= base[key].length || !base[key][index].type) {
+							base[key].push(helpers.configMerge(axisDefaults, valueObj));
+						} else if (valueObj.type && valueObj.type !== base[key][index].type) {
+							// Type changed. Bring in the new defaults before we bring in valueObj so that valueObj can override the correct scale defaults
+							base[key][index] = helpers.configMerge(base[key][index], axisDefaults, valueObj);
+						} else {
+							// Type is the same
+							base[key][index] = helpers.configMerge(base[key][index], valueObj);
+						}
+					});
+				} else {
+					base[key] = [];
+					helpers.each(value, function(valueObj) {
+						var axisType = helpers.getValueOrDefault(valueObj.type, key === 'xAxes' ? 'category' : 'linear');
+						base[key].push(helpers.configMerge(Chart.scaleService.getScaleDefaults(axisType), valueObj));
+					});
+				}
+			} else if (base.hasOwnProperty(key) && typeof base[key] === 'object' && base[key] !== null && typeof value === 'object') {
+				// If we are overwriting an object with an object, do a merge of the properties.
+				base[key] = helpers.configMerge(base[key], value);
+
+			} else {
+				// can just overwrite the value in this case
+				base[key] = value;
+			}
+		});
+
+		return base;
+	};
+	helpers.getValueAtIndexOrDefault = function(value, index, defaultValue) {
+		if (value === undefined || value === null) {
+			return defaultValue;
+		}
+
+		if (helpers.isArray(value)) {
+			return index < value.length ? value[index] : defaultValue;
+		}
+
+		return value;
+	};
+	helpers.getValueOrDefault = function(value, defaultValue) {
+		return value === undefined ? defaultValue : value;
+	};
+	helpers.indexOf = Array.prototype.indexOf?
+		function(array, item) {
+			return array.indexOf(item);
+		}:
+		function(array, item) {
+			for (var i = 0, ilen = array.length; i < ilen; ++i) {
+				if (array[i] === item) {
+					return i;
+				}
+			}
+			return -1;
+		};
+	helpers.where = function(collection, filterCallback) {
+		if (helpers.isArray(collection) && Array.prototype.filter) {
+			return collection.filter(filterCallback);
+		}
+		var filtered = [];
+
+		helpers.each(collection, function(item) {
+			if (filterCallback(item)) {
+				filtered.push(item);
+			}
+		});
+
+		return filtered;
+	};
+	helpers.findIndex = Array.prototype.findIndex?
+		function(array, callback, scope) {
+			return array.findIndex(callback, scope);
+		} :
+		function(array, callback, scope) {
+			scope = scope === undefined? array : scope;
+			for (var i = 0, ilen = array.length; i < ilen; ++i) {
+				if (callback.call(scope, array[i], i, array)) {
+					return i;
+				}
+			}
+			return -1;
+		};
+	helpers.findNextWhere = function(arrayToSearch, filterCallback, startIndex) {
+		// Default to start of the array
+		if (startIndex === undefined || startIndex === null) {
+			startIndex = -1;
+		}
+		for (var i = startIndex + 1; i < arrayToSearch.length; i++) {
+			var currentItem = arrayToSearch[i];
+			if (filterCallback(currentItem)) {
+				return currentItem;
+			}
+		}
+	};
+	helpers.findPreviousWhere = function(arrayToSearch, filterCallback, startIndex) {
+		// Default to end of the array
+		if (startIndex === undefined || startIndex === null) {
+			startIndex = arrayToSearch.length;
+		}
+		for (var i = startIndex - 1; i >= 0; i--) {
+			var currentItem = arrayToSearch[i];
+			if (filterCallback(currentItem)) {
+				return currentItem;
+			}
+		}
+	};
+	helpers.inherits = function(extensions) {
+		// Basic javascript inheritance based on the model created in Backbone.js
+		var me = this;
+		var ChartElement = (extensions && extensions.hasOwnProperty('constructor')) ? extensions.constructor : function() {
+			return me.apply(this, arguments);
+		};
+
+		var Surrogate = function() {
+			this.constructor = ChartElement;
+		};
+		Surrogate.prototype = me.prototype;
+		ChartElement.prototype = new Surrogate();
+
+		ChartElement.extend = helpers.inherits;
+
+		if (extensions) {
+			helpers.extend(ChartElement.prototype, extensions);
+		}
+
+		ChartElement.__super__ = me.prototype;
+
+		return ChartElement;
+	};
+	helpers.noop = function() {};
+	helpers.uid = (function() {
+		var id = 0;
+		return function() {
+			return id++;
+		};
+	}());
+	// -- Math methods
+	helpers.isNumber = function(n) {
+		return !isNaN(parseFloat(n)) && isFinite(n);
+	};
+	helpers.almostEquals = function(x, y, epsilon) {
+		return Math.abs(x - y) < epsilon;
+	};
+	helpers.almostWhole = function(x, epsilon) {
+		var rounded = Math.round(x);
+		return (((rounded - epsilon) < x) && ((rounded + epsilon) > x));
+	};
+	helpers.max = function(array) {
+		return array.reduce(function(max, value) {
+			if (!isNaN(value)) {
+				return Math.max(max, value);
+			}
+			return max;
+		}, Number.NEGATIVE_INFINITY);
+	};
+	helpers.min = function(array) {
+		return array.reduce(function(min, value) {
+			if (!isNaN(value)) {
+				return Math.min(min, value);
+			}
+			return min;
+		}, Number.POSITIVE_INFINITY);
+	};
+	helpers.sign = Math.sign?
+		function(x) {
+			return Math.sign(x);
+		} :
+		function(x) {
+			x = +x; // convert to a number
+			if (x === 0 || isNaN(x)) {
+				return x;
+			}
+			return x > 0 ? 1 : -1;
+		};
+	helpers.log10 = Math.log10?
+		function(x) {
+			return Math.log10(x);
+		} :
+		function(x) {
+			return Math.log(x) / Math.LN10;
+		};
+	helpers.toRadians = function(degrees) {
+		return degrees * (Math.PI / 180);
+	};
+	helpers.toDegrees = function(radians) {
+		return radians * (180 / Math.PI);
+	};
+	// Gets the angle from vertical upright to the point about a centre.
+	helpers.getAngleFromPoint = function(centrePoint, anglePoint) {
+		var distanceFromXCenter = anglePoint.x - centrePoint.x,
+			distanceFromYCenter = anglePoint.y - centrePoint.y,
+			radialDistanceFromCenter = Math.sqrt(distanceFromXCenter * distanceFromXCenter + distanceFromYCenter * distanceFromYCenter);
+
+		var angle = Math.atan2(distanceFromYCenter, distanceFromXCenter);
+
+		if (angle < (-0.5 * Math.PI)) {
+			angle += 2.0 * Math.PI; // make sure the returned angle is in the range of (-PI/2, 3PI/2]
+		}
+
+		return {
+			angle: angle,
+			distance: radialDistanceFromCenter
+		};
+	};
+	helpers.distanceBetweenPoints = function(pt1, pt2) {
+		return Math.sqrt(Math.pow(pt2.x - pt1.x, 2) + Math.pow(pt2.y - pt1.y, 2));
+	};
+	helpers.aliasPixel = function(pixelWidth) {
+		return (pixelWidth % 2 === 0) ? 0 : 0.5;
+	};
+	helpers.splineCurve = function(firstPoint, middlePoint, afterPoint, t) {
+		// Props to Rob Spencer at scaled innovation for his post on splining between points
+		// http://scaledinnovation.com/analytics/splines/aboutSplines.html
+
+		// This function must also respect "skipped" points
+
+		var previous = firstPoint.skip ? middlePoint : firstPoint,
+			current = middlePoint,
+			next = afterPoint.skip ? middlePoint : afterPoint;
+
+		var d01 = Math.sqrt(Math.pow(current.x - previous.x, 2) + Math.pow(current.y - previous.y, 2));
+		var d12 = Math.sqrt(Math.pow(next.x - current.x, 2) + Math.pow(next.y - current.y, 2));
+
+		var s01 = d01 / (d01 + d12);
+		var s12 = d12 / (d01 + d12);
+
+		// If all points are the same, s01 & s02 will be inf
+		s01 = isNaN(s01) ? 0 : s01;
+		s12 = isNaN(s12) ? 0 : s12;
+
+		var fa = t * s01; // scaling factor for triangle Ta
+		var fb = t * s12;
+
+		return {
+			previous: {
+				x: current.x - fa * (next.x - previous.x),
+				y: current.y - fa * (next.y - previous.y)
+			},
+			next: {
+				x: current.x + fb * (next.x - previous.x),
+				y: current.y + fb * (next.y - previous.y)
+			}
+		};
+	};
+	helpers.EPSILON = Number.EPSILON || 1e-14;
+	helpers.splineCurveMonotone = function(points) {
+		// This function calculates Bézier control points in a similar way than |splineCurve|,
+		// but preserves monotonicity of the provided data and ensures no local extremums are added
+		// between the dataset discrete points due to the interpolation.
+		// See : https://en.wikipedia.org/wiki/Monotone_cubic_interpolation
+
+		var pointsWithTangents = (points || []).map(function(point) {
+			return {
+				model: point._model,
+				deltaK: 0,
+				mK: 0
+			};
+		});
+
+		// Calculate slopes (deltaK) and initialize tangents (mK)
+		var pointsLen = pointsWithTangents.length;
+		var i, pointBefore, pointCurrent, pointAfter;
+		for (i = 0; i < pointsLen; ++i) {
+			pointCurrent = pointsWithTangents[i];
+			if (pointCurrent.model.skip) {
+				continue;
+			}
+
+			pointBefore = i > 0 ? pointsWithTangents[i - 1] : null;
+			pointAfter = i < pointsLen - 1 ? pointsWithTangents[i + 1] : null;
+			if (pointAfter && !pointAfter.model.skip) {
+				var slopeDeltaX = (pointAfter.model.x - pointCurrent.model.x);
+
+				// In the case of two points that appear at the same x pixel, slopeDeltaX is 0
+				pointCurrent.deltaK = slopeDeltaX !== 0 ? (pointAfter.model.y - pointCurrent.model.y) / slopeDeltaX : 0;
+			}
+
+			if (!pointBefore || pointBefore.model.skip) {
+				pointCurrent.mK = pointCurrent.deltaK;
+			} else if (!pointAfter || pointAfter.model.skip) {
+				pointCurrent.mK = pointBefore.deltaK;
+			} else if (this.sign(pointBefore.deltaK) !== this.sign(pointCurrent.deltaK)) {
+				pointCurrent.mK = 0;
+			} else {
+				pointCurrent.mK = (pointBefore.deltaK + pointCurrent.deltaK) / 2;
+			}
+		}
+
+		// Adjust tangents to ensure monotonic properties
+		var alphaK, betaK, tauK, squaredMagnitude;
+		for (i = 0; i < pointsLen - 1; ++i) {
+			pointCurrent = pointsWithTangents[i];
+			pointAfter = pointsWithTangents[i + 1];
+			if (pointCurrent.model.skip || pointAfter.model.skip) {
+				continue;
+			}
+
+			if (helpers.almostEquals(pointCurrent.deltaK, 0, this.EPSILON)) {
+				pointCurrent.mK = pointAfter.mK = 0;
+				continue;
+			}
+
+			alphaK = pointCurrent.mK / pointCurrent.deltaK;
+			betaK = pointAfter.mK / pointCurrent.deltaK;
+			squaredMagnitude = Math.pow(alphaK, 2) + Math.pow(betaK, 2);
+			if (squaredMagnitude <= 9) {
+				continue;
+			}
+
+			tauK = 3 / Math.sqrt(squaredMagnitude);
+			pointCurrent.mK = alphaK * tauK * pointCurrent.deltaK;
+			pointAfter.mK = betaK * tauK * pointCurrent.deltaK;
+		}
+
+		// Compute control points
+		var deltaX;
+		for (i = 0; i < pointsLen; ++i) {
+			pointCurrent = pointsWithTangents[i];
+			if (pointCurrent.model.skip) {
+				continue;
+			}
+
+			pointBefore = i > 0 ? pointsWithTangents[i - 1] : null;
+			pointAfter = i < pointsLen - 1 ? pointsWithTangents[i + 1] : null;
+			if (pointBefore && !pointBefore.model.skip) {
+				deltaX = (pointCurrent.model.x - pointBefore.model.x) / 3;
+				pointCurrent.model.controlPointPreviousX = pointCurrent.model.x - deltaX;
+				pointCurrent.model.controlPointPreviousY = pointCurrent.model.y - deltaX * pointCurrent.mK;
+			}
+			if (pointAfter && !pointAfter.model.skip) {
+				deltaX = (pointAfter.model.x - pointCurrent.model.x) / 3;
+				pointCurrent.model.controlPointNextX = pointCurrent.model.x + deltaX;
+				pointCurrent.model.controlPointNextY = pointCurrent.model.y + deltaX * pointCurrent.mK;
+			}
+		}
+	};
+	helpers.nextItem = function(collection, index, loop) {
+		if (loop) {
+			return index >= collection.length - 1 ? collection[0] : collection[index + 1];
+		}
+		return index >= collection.length - 1 ? collection[collection.length - 1] : collection[index + 1];
+	};
+	helpers.previousItem = function(collection, index, loop) {
+		if (loop) {
+			return index <= 0 ? collection[collection.length - 1] : collection[index - 1];
+		}
+		return index <= 0 ? collection[0] : collection[index - 1];
+	};
+	// Implementation of the nice number algorithm used in determining where axis labels will go
+	helpers.niceNum = function(range, round) {
+		var exponent = Math.floor(helpers.log10(range));
+		var fraction = range / Math.pow(10, exponent);
+		var niceFraction;
+
+		if (round) {
+			if (fraction < 1.5) {
+				niceFraction = 1;
+			} else if (fraction < 3) {
+				niceFraction = 2;
+			} else if (fraction < 7) {
+				niceFraction = 5;
+			} else {
+				niceFraction = 10;
+			}
+		} else if (fraction <= 1.0) {
+			niceFraction = 1;
+		} else if (fraction <= 2) {
+			niceFraction = 2;
+		} else if (fraction <= 5) {
+			niceFraction = 5;
+		} else {
+			niceFraction = 10;
+		}
+
+		return niceFraction * Math.pow(10, exponent);
+	};
+	// Easing functions adapted from Robert Penner's easing equations
+	// http://www.robertpenner.com/easing/
+	var easingEffects = helpers.easingEffects = {
+		linear: function(t) {
+			return t;
+		},
+		easeInQuad: function(t) {
+			return t * t;
+		},
+		easeOutQuad: function(t) {
+			return -1 * t * (t - 2);
+		},
+		easeInOutQuad: function(t) {
+			if ((t /= 1 / 2) < 1) {
+				return 1 / 2 * t * t;
+			}
+			return -1 / 2 * ((--t) * (t - 2) - 1);
+		},
+		easeInCubic: function(t) {
+			return t * t * t;
+		},
+		easeOutCubic: function(t) {
+			return 1 * ((t = t / 1 - 1) * t * t + 1);
+		},
+		easeInOutCubic: function(t) {
+			if ((t /= 1 / 2) < 1) {
+				return 1 / 2 * t * t * t;
+			}
+			return 1 / 2 * ((t -= 2) * t * t + 2);
+		},
+		easeInQuart: function(t) {
+			return t * t * t * t;
+		},
+		easeOutQuart: function(t) {
+			return -1 * ((t = t / 1 - 1) * t * t * t - 1);
+		},
+		easeInOutQuart: function(t) {
+			if ((t /= 1 / 2) < 1) {
+				return 1 / 2 * t * t * t * t;
+			}
+			return -1 / 2 * ((t -= 2) * t * t * t - 2);
+		},
+		easeInQuint: function(t) {
+			return 1 * (t /= 1) * t * t * t * t;
+		},
+		easeOutQuint: function(t) {
+			return 1 * ((t = t / 1 - 1) * t * t * t * t + 1);
+		},
+		easeInOutQuint: function(t) {
+			if ((t /= 1 / 2) < 1) {
+				return 1 / 2 * t * t * t * t * t;
+			}
+			return 1 / 2 * ((t -= 2) * t * t * t * t + 2);
+		},
+		easeInSine: function(t) {
+			return -1 * Math.cos(t / 1 * (Math.PI / 2)) + 1;
+		},
+		easeOutSine: function(t) {
+			return 1 * Math.sin(t / 1 * (Math.PI / 2));
+		},
+		easeInOutSine: function(t) {
+			return -1 / 2 * (Math.cos(Math.PI * t / 1) - 1);
+		},
+		easeInExpo: function(t) {
+			return (t === 0) ? 1 : 1 * Math.pow(2, 10 * (t / 1 - 1));
+		},
+		easeOutExpo: function(t) {
+			return (t === 1) ? 1 : 1 * (-Math.pow(2, -10 * t / 1) + 1);
+		},
+		easeInOutExpo: function(t) {
+			if (t === 0) {
+				return 0;
+			}
+			if (t === 1) {
+				return 1;
+			}
+			if ((t /= 1 / 2) < 1) {
+				return 1 / 2 * Math.pow(2, 10 * (t - 1));
+			}
+			return 1 / 2 * (-Math.pow(2, -10 * --t) + 2);
+		},
+		easeInCirc: function(t) {
+			if (t >= 1) {
+				return t;
+			}
+			return -1 * (Math.sqrt(1 - (t /= 1) * t) - 1);
+		},
+		easeOutCirc: function(t) {
+			return 1 * Math.sqrt(1 - (t = t / 1 - 1) * t);
+		},
+		easeInOutCirc: function(t) {
+			if ((t /= 1 / 2) < 1) {
+				return -1 / 2 * (Math.sqrt(1 - t * t) - 1);
+			}
+			return 1 / 2 * (Math.sqrt(1 - (t -= 2) * t) + 1);
+		},
+		easeInElastic: function(t) {
+			var s = 1.70158;
+			var p = 0;
+			var a = 1;
+			if (t === 0) {
+				return 0;
+			}
+			if ((t /= 1) === 1) {
+				return 1;
+			}
+			if (!p) {
+				p = 1 * 0.3;
+			}
+			if (a < Math.abs(1)) {
+				a = 1;
+				s = p / 4;
+			} else {
+				s = p / (2 * Math.PI) * Math.asin(1 / a);
+			}
+			return -(a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * 1 - s) * (2 * Math.PI) / p));
+		},
+		easeOutElastic: function(t) {
+			var s = 1.70158;
+			var p = 0;
+			var a = 1;
+			if (t === 0) {
+				return 0;
+			}
+			if ((t /= 1) === 1) {
+				return 1;
+			}
+			if (!p) {
+				p = 1 * 0.3;
+			}
+			if (a < Math.abs(1)) {
+				a = 1;
+				s = p / 4;
+			} else {
+				s = p / (2 * Math.PI) * Math.asin(1 / a);
+			}
+			return a * Math.pow(2, -10 * t) * Math.sin((t * 1 - s) * (2 * Math.PI) / p) + 1;
+		},
+		easeInOutElastic: function(t) {
+			var s = 1.70158;
+			var p = 0;
+			var a = 1;
+			if (t === 0) {
+				return 0;
+			}
+			if ((t /= 1 / 2) === 2) {
+				return 1;
+			}
+			if (!p) {
+				p = 1 * (0.3 * 1.5);
+			}
+			if (a < Math.abs(1)) {
+				a = 1;
+				s = p / 4;
+			} else {
+				s = p / (2 * Math.PI) * Math.asin(1 / a);
+			}
+			if (t < 1) {
+				return -0.5 * (a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * 1 - s) * (2 * Math.PI) / p));
+			}
+			return a * Math.pow(2, -10 * (t -= 1)) * Math.sin((t * 1 - s) * (2 * Math.PI) / p) * 0.5 + 1;
+		},
+		easeInBack: function(t) {
+			var s = 1.70158;
+			return 1 * (t /= 1) * t * ((s + 1) * t - s);
+		},
+		easeOutBack: function(t) {
+			var s = 1.70158;
+			return 1 * ((t = t / 1 - 1) * t * ((s + 1) * t + s) + 1);
+		},
+		easeInOutBack: function(t) {
+			var s = 1.70158;
+			if ((t /= 1 / 2) < 1) {
+				return 1 / 2 * (t * t * (((s *= (1.525)) + 1) * t - s));
+			}
+			return 1 / 2 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2);
+		},
+		easeInBounce: function(t) {
+			return 1 - easingEffects.easeOutBounce(1 - t);
+		},
+		easeOutBounce: function(t) {
+			if ((t /= 1) < (1 / 2.75)) {
+				return 1 * (7.5625 * t * t);
+			} else if (t < (2 / 2.75)) {
+				return 1 * (7.5625 * (t -= (1.5 / 2.75)) * t + 0.75);
+			} else if (t < (2.5 / 2.75)) {
+				return 1 * (7.5625 * (t -= (2.25 / 2.75)) * t + 0.9375);
+			}
+			return 1 * (7.5625 * (t -= (2.625 / 2.75)) * t + 0.984375);
+		},
+		easeInOutBounce: function(t) {
+			if (t < 1 / 2) {
+				return easingEffects.easeInBounce(t * 2) * 0.5;
+			}
+			return easingEffects.easeOutBounce(t * 2 - 1) * 0.5 + 1 * 0.5;
+		}
+	};
+	// Request animation polyfill - http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
+	helpers.requestAnimFrame = (function() {
+		return window.requestAnimationFrame ||
+			window.webkitRequestAnimationFrame ||
+			window.mozRequestAnimationFrame ||
+			window.oRequestAnimationFrame ||
+			window.msRequestAnimationFrame ||
+			function(callback) {
+				return window.setTimeout(callback, 1000 / 60);
+			};
+	}());
+	// -- DOM methods
+	helpers.getRelativePosition = function(evt, chart) {
+		var mouseX, mouseY;
+		var e = evt.originalEvent || evt,
+			canvas = evt.currentTarget || evt.srcElement,
+			boundingRect = canvas.getBoundingClientRect();
+
+		var touches = e.touches;
+		if (touches && touches.length > 0) {
+			mouseX = touches[0].clientX;
+			mouseY = touches[0].clientY;
+
+		} else {
+			mouseX = e.clientX;
+			mouseY = e.clientY;
+		}
+
+		// Scale mouse coordinates into canvas coordinates
+		// by following the pattern laid out by 'jerryj' in the comments of
+		// http://www.html5canvastutorials.com/advanced/html5-canvas-mouse-coordinates/
+		var paddingLeft = parseFloat(helpers.getStyle(canvas, 'padding-left'));
+		var paddingTop = parseFloat(helpers.getStyle(canvas, 'padding-top'));
+		var paddingRight = parseFloat(helpers.getStyle(canvas, 'padding-right'));
+		var paddingBottom = parseFloat(helpers.getStyle(canvas, 'padding-bottom'));
+		var width = boundingRect.right - boundingRect.left - paddingLeft - paddingRight;
+		var height = boundingRect.bottom - boundingRect.top - paddingTop - paddingBottom;
+
+		// We divide by the current device pixel ratio, because the canvas is scaled up by that amount in each direction. However
+		// the backend model is in unscaled coordinates. Since we are going to deal with our model coordinates, we go back here
+		mouseX = Math.round((mouseX - boundingRect.left - paddingLeft) / (width) * canvas.width / chart.currentDevicePixelRatio);
+		mouseY = Math.round((mouseY - boundingRect.top - paddingTop) / (height) * canvas.height / chart.currentDevicePixelRatio);
+
+		return {
+			x: mouseX,
+			y: mouseY
+		};
+
+	};
+	helpers.addEvent = function(node, eventType, method) {
+		if (node.addEventListener) {
+			node.addEventListener(eventType, method);
+		} else if (node.attachEvent) {
+			node.attachEvent('on' + eventType, method);
+		} else {
+			node['on' + eventType] = method;
+		}
+	};
+	helpers.removeEvent = function(node, eventType, handler) {
+		if (node.removeEventListener) {
+			node.removeEventListener(eventType, handler, false);
+		} else if (node.detachEvent) {
+			node.detachEvent('on' + eventType, handler);
+		} else {
+			node['on' + eventType] = helpers.noop;
+		}
+	};
+
+	// Private helper function to convert max-width/max-height values that may be percentages into a number
+	function parseMaxStyle(styleValue, node, parentProperty) {
+		var valueInPixels;
+		if (typeof(styleValue) === 'string') {
+			valueInPixels = parseInt(styleValue, 10);
+
+			if (styleValue.indexOf('%') !== -1) {
+				// percentage * size in dimension
+				valueInPixels = valueInPixels / 100 * node.parentNode[parentProperty];
+			}
+		} else {
+			valueInPixels = styleValue;
+		}
+
+		return valueInPixels;
+	}
+
+	/**
+	 * Returns if the given value contains an effective constraint.
+	 * @private
+	 */
+	function isConstrainedValue(value) {
+		return value !== undefined && value !== null && value !== 'none';
+	}
+
+	// Private helper to get a constraint dimension
+	// @param domNode : the node to check the constraint on
+	// @param maxStyle : the style that defines the maximum for the direction we are using (maxWidth / maxHeight)
+	// @param percentageProperty : property of parent to use when calculating width as a percentage
+	// @see http://www.nathanaeljones.com/blog/2013/reading-max-width-cross-browser
+	function getConstraintDimension(domNode, maxStyle, percentageProperty) {
+		var view = document.defaultView;
+		var parentNode = domNode.parentNode;
+		var constrainedNode = view.getComputedStyle(domNode)[maxStyle];
+		var constrainedContainer = view.getComputedStyle(parentNode)[maxStyle];
+		var hasCNode = isConstrainedValue(constrainedNode);
+		var hasCContainer = isConstrainedValue(constrainedContainer);
+		var infinity = Number.POSITIVE_INFINITY;
+
+		if (hasCNode || hasCContainer) {
+			return Math.min(
+				hasCNode? parseMaxStyle(constrainedNode, domNode, percentageProperty) : infinity,
+				hasCContainer? parseMaxStyle(constrainedContainer, parentNode, percentageProperty) : infinity);
+		}
+
+		return 'none';
+	}
+	// returns Number or undefined if no constraint
+	helpers.getConstraintWidth = function(domNode) {
+		return getConstraintDimension(domNode, 'max-width', 'clientWidth');
+	};
+	// returns Number or undefined if no constraint
+	helpers.getConstraintHeight = function(domNode) {
+		return getConstraintDimension(domNode, 'max-height', 'clientHeight');
+	};
+	helpers.getMaximumWidth = function(domNode) {
+		var container = domNode.parentNode;
+		var paddingLeft = parseInt(helpers.getStyle(container, 'padding-left'), 10);
+		var paddingRight = parseInt(helpers.getStyle(container, 'padding-right'), 10);
+		var w = container.clientWidth - paddingLeft - paddingRight;
+		var cw = helpers.getConstraintWidth(domNode);
+		return isNaN(cw)? w : Math.min(w, cw);
+	};
+	helpers.getMaximumHeight = function(domNode) {
+		var container = domNode.parentNode;
+		var paddingTop = parseInt(helpers.getStyle(container, 'padding-top'), 10);
+		var paddingBottom = parseInt(helpers.getStyle(container, 'padding-bottom'), 10);
+		var h = container.clientHeight - paddingTop - paddingBottom;
+		var ch = helpers.getConstraintHeight(domNode);
+		return isNaN(ch)? h : Math.min(h, ch);
+	};
+	helpers.getStyle = function(el, property) {
+		return el.currentStyle ?
+			el.currentStyle[property] :
+			document.defaultView.getComputedStyle(el, null).getPropertyValue(property);
+	};
+	helpers.retinaScale = function(chart) {
+		var pixelRatio = chart.currentDevicePixelRatio = window.devicePixelRatio || 1;
+		if (pixelRatio === 1) {
+			return;
+		}
+
+		var canvas = chart.canvas;
+		var height = chart.height;
+		var width = chart.width;
+
+		canvas.height = height * pixelRatio;
+		canvas.width = width * pixelRatio;
+		chart.ctx.scale(pixelRatio, pixelRatio);
+
+		// If no style has been set on the canvas, the render size is used as display size,
+		// making the chart visually bigger, so let's enforce it to the "correct" values.
+		// See https://github.com/chartjs/Chart.js/issues/3575
+		canvas.style.height = height + 'px';
+		canvas.style.width = width + 'px';
+	};
+	// -- Canvas methods
+	helpers.clear = function(chart) {
+		chart.ctx.clearRect(0, 0, chart.width, chart.height);
+	};
+	helpers.fontString = function(pixelSize, fontStyle, fontFamily) {
+		return fontStyle + ' ' + pixelSize + 'px ' + fontFamily;
+	};
+	helpers.longestText = function(ctx, font, arrayOfThings, cache) {
+		cache = cache || {};
+		var data = cache.data = cache.data || {};
+		var gc = cache.garbageCollect = cache.garbageCollect || [];
+
+		if (cache.font !== font) {
+			data = cache.data = {};
+			gc = cache.garbageCollect = [];
+			cache.font = font;
+		}
+
+		ctx.font = font;
+		var longest = 0;
+		helpers.each(arrayOfThings, function(thing) {
+			// Undefined strings and arrays should not be measured
+			if (thing !== undefined && thing !== null && helpers.isArray(thing) !== true) {
+				longest = helpers.measureText(ctx, data, gc, longest, thing);
+			} else if (helpers.isArray(thing)) {
+				// if it is an array lets measure each element
+				// to do maybe simplify this function a bit so we can do this more recursively?
+				helpers.each(thing, function(nestedThing) {
+					// Undefined strings and arrays should not be measured
+					if (nestedThing !== undefined && nestedThing !== null && !helpers.isArray(nestedThing)) {
+						longest = helpers.measureText(ctx, data, gc, longest, nestedThing);
+					}
+				});
+			}
+		});
+
+		var gcLen = gc.length / 2;
+		if (gcLen > arrayOfThings.length) {
+			for (var i = 0; i < gcLen; i++) {
+				delete data[gc[i]];
+			}
+			gc.splice(0, gcLen);
+		}
+		return longest;
+	};
+	helpers.measureText = function(ctx, data, gc, longest, string) {
+		var textWidth = data[string];
+		if (!textWidth) {
+			textWidth = data[string] = ctx.measureText(string).width;
+			gc.push(string);
+		}
+		if (textWidth > longest) {
+			longest = textWidth;
+		}
+		return longest;
+	};
+	helpers.numberOfLabelLines = function(arrayOfThings) {
+		var numberOfLines = 1;
+		helpers.each(arrayOfThings, function(thing) {
+			if (helpers.isArray(thing)) {
+				if (thing.length > numberOfLines) {
+					numberOfLines = thing.length;
+				}
+			}
+		});
+		return numberOfLines;
+	};
+	helpers.drawRoundedRectangle = function(ctx, x, y, width, height, radius) {
+		ctx.beginPath();
+		ctx.moveTo(x + radius, y);
+		ctx.lineTo(x + width - radius, y);
+		ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
+		ctx.lineTo(x + width, y + height - radius);
+		ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
+		ctx.lineTo(x + radius, y + height);
+		ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
+		ctx.lineTo(x, y + radius);
+		ctx.quadraticCurveTo(x, y, x + radius, y);
+		ctx.closePath();
+	};
+	helpers.color = function(c) {
+		if (!color) {
+			console.error('Color.js not found!');
+			return c;
+		}
+
+		/* global CanvasGradient */
+		if (c instanceof CanvasGradient) {
+			return color(Chart.defaults.global.defaultColor);
+		}
+
+		return color(c);
+	};
+	helpers.isArray = Array.isArray?
+		function(obj) {
+			return Array.isArray(obj);
+		} :
+		function(obj) {
+			return Object.prototype.toString.call(obj) === '[object Array]';
+		};
+	// ! @see http://stackoverflow.com/a/14853974
+	helpers.arrayEquals = function(a0, a1) {
+		var i, ilen, v0, v1;
+
+		if (!a0 || !a1 || a0.length !== a1.length) {
+			return false;
+		}
+
+		for (i = 0, ilen=a0.length; i < ilen; ++i) {
+			v0 = a0[i];
+			v1 = a1[i];
+
+			if (v0 instanceof Array && v1 instanceof Array) {
+				if (!helpers.arrayEquals(v0, v1)) {
+					return false;
+				}
+			} else if (v0 !== v1) {
+				// NOTE: two different object instances will never be equal: {x:20} != {x:20}
+				return false;
+			}
+		}
+
+		return true;
+	};
+	helpers.callCallback = function(fn, args, _tArg) {
+		if (fn && typeof fn.call === 'function') {
+			fn.apply(_tArg, args);
+		}
+	};
+	helpers.getHoverColor = function(colorValue) {
+		/* global CanvasPattern */
+		return (colorValue instanceof CanvasPattern) ?
+			colorValue :
+			helpers.color(colorValue).saturate(0.5).darken(0.1).rgbString();
+	};
+};
+
+},{"3":3}],27:[function(require,module,exports){
+'use strict';
+
+module.exports = function(Chart) {
+	var helpers = Chart.helpers;
+
+	/**
+	 * Helper function to get relative position for an event
+	 * @param {Event|IEvent} event - The event to get the position for
+	 * @param {Chart} chart - The chart
+	 * @returns {Point} the event position
+	 */
+	function getRelativePosition(e, chart) {
+		if (e.native) {
+			return {
+				x: e.x,
+				y: e.y
+			};
+		}
+
+		return helpers.getRelativePosition(e, chart);
+	}
+
+	/**
+	 * Helper function to traverse all of the visible elements in the chart
+	 * @param chart {chart} the chart
+	 * @param handler {Function} the callback to execute for each visible item
+	 */
+	function parseVisibleItems(chart, handler) {
+		var datasets = chart.data.datasets;
+		var meta, i, j, ilen, jlen;
+
+		for (i = 0, ilen = datasets.length; i < ilen; ++i) {
+			if (!chart.isDatasetVisible(i)) {
+				continue;
+			}
+
+			meta = chart.getDatasetMeta(i);
+			for (j = 0, jlen = meta.data.length; j < jlen; ++j) {
+				var element = meta.data[j];
+				if (!element._view.skip) {
+					handler(element);
+				}
+			}
+		}
+	}
+
+	/**
+	 * Helper function to get the items that intersect the event position
+	 * @param items {ChartElement[]} elements to filter
+	 * @param position {Point} the point to be nearest to
+	 * @return {ChartElement[]} the nearest items
+	 */
+	function getIntersectItems(chart, position) {
+		var elements = [];
+
+		parseVisibleItems(chart, function(element) {
+			if (element.inRange(position.x, position.y)) {
+				elements.push(element);
+			}
+		});
+
+		return elements;
+	}
+
+	/**
+	 * Helper function to get the items nearest to the event position considering all visible items in teh chart
+	 * @param chart {Chart} the chart to look at elements from
+	 * @param position {Point} the point to be nearest to
+	 * @param intersect {Boolean} if true, only consider items that intersect the position
+	 * @param distanceMetric {Function} Optional function to provide the distance between
+	 * @return {ChartElement[]} the nearest items
+	 */
+	function getNearestItems(chart, position, intersect, distanceMetric) {
+		var minDistance = Number.POSITIVE_INFINITY;
+		var nearestItems = [];
+
+		if (!distanceMetric) {
+			distanceMetric = helpers.distanceBetweenPoints;
+		}
+
+		parseVisibleItems(chart, function(element) {
+			if (intersect && !element.inRange(position.x, position.y)) {
+				return;
+			}
+
+			var center = element.getCenterPoint();
+			var distance = distanceMetric(position, center);
+
+			if (distance < minDistance) {
+				nearestItems = [element];
+				minDistance = distance;
+			} else if (distance === minDistance) {
+				// Can have multiple items at the same distance in which case we sort by size
+				nearestItems.push(element);
+			}
+		});
+
+		return nearestItems;
+	}
+
+	function indexMode(chart, e, options) {
+		var position = getRelativePosition(e, chart.chart);
+		var distanceMetric = function(pt1, pt2) {
+			return Math.abs(pt1.x - pt2.x);
+		};
+		var items = options.intersect ? getIntersectItems(chart, position) : getNearestItems(chart, position, false, distanceMetric);
+		var elements = [];
+
+		if (!items.length) {
+			return [];
+		}
+
+		chart.data.datasets.forEach(function(dataset, datasetIndex) {
+			if (chart.isDatasetVisible(datasetIndex)) {
+				var meta = chart.getDatasetMeta(datasetIndex),
+					element = meta.data[items[0]._index];
+
+				// don't count items that are skipped (null data)
+				if (element && !element._view.skip) {
+					elements.push(element);
+				}
+			}
+		});
+
+		return elements;
+	}
+
+	/**
+	 * @interface IInteractionOptions
+	 */
+	/**
+	 * If true, only consider items that intersect the point
+	 * @name IInterfaceOptions#boolean
+	 * @type Boolean
+	 */
+
+	/**
+	 * Contains interaction related functions
+	 * @namespace Chart.Interaction
+	 */
+	Chart.Interaction = {
+		// Helper function for different modes
+		modes: {
+			single: function(chart, e) {
+				var position = getRelativePosition(e, chart.chart);
+				var elements = [];
+
+				parseVisibleItems(chart, function(element) {
+					if (element.inRange(position.x, position.y)) {
+						elements.push(element);
+						return elements;
+					}
+				});
+
+				return elements.slice(0, 1);
+			},
+
+			/**
+			 * @function Chart.Interaction.modes.label
+			 * @deprecated since version 2.4.0
+			 */
+			label: indexMode,
+
+			/**
+			 * Returns items at the same index. If the options.intersect parameter is true, we only return items if we intersect something
+			 * If the options.intersect mode is false, we find the nearest item and return the items at the same index as that item
+			 * @function Chart.Interaction.modes.index
+			 * @since v2.4.0
+			 * @param chart {chart} the chart we are returning items from
+			 * @param e {Event} the event we are find things at
+			 * @param options {IInteractionOptions} options to use during interaction
+			 * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
+			 */
+			index: indexMode,
+
+			/**
+			 * Returns items in the same dataset. If the options.intersect parameter is true, we only return items if we intersect something
+			 * If the options.intersect is false, we find the nearest item and return the items in that dataset
+			 * @function Chart.Interaction.modes.dataset
+			 * @param chart {chart} the chart we are returning items from
+			 * @param e {Event} the event we are find things at
+			 * @param options {IInteractionOptions} options to use during interaction
+			 * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
+			 */
+			dataset: function(chart, e, options) {
+				var position = getRelativePosition(e, chart.chart);
+				var items = options.intersect ? getIntersectItems(chart, position) : getNearestItems(chart, position, false);
+
+				if (items.length > 0) {
+					items = chart.getDatasetMeta(items[0]._datasetIndex).data;
+				}
+
+				return items;
+			},
+
+			/**
+			 * @function Chart.Interaction.modes.x-axis
+			 * @deprecated since version 2.4.0. Use index mode and intersect == true
+			 */
+			'x-axis': function(chart, e) {
+				return indexMode(chart, e, true);
+			},
+
+			/**
+			 * Point mode returns all elements that hit test based on the event position
+			 * of the event
+			 * @function Chart.Interaction.modes.intersect
+			 * @param chart {chart} the chart we are returning items from
+			 * @param e {Event} the event we are find things at
+			 * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
+			 */
+			point: function(chart, e) {
+				var position = getRelativePosition(e, chart.chart);
+				return getIntersectItems(chart, position);
+			},
+
+			/**
+			 * nearest mode returns the element closest to the point
+			 * @function Chart.Interaction.modes.intersect
+			 * @param chart {chart} the chart we are returning items from
+			 * @param e {Event} the event we are find things at
+			 * @param options {IInteractionOptions} options to use
+			 * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
+			 */
+			nearest: function(chart, e, options) {
+				var position = getRelativePosition(e, chart.chart);
+				var nearestItems = getNearestItems(chart, position, options.intersect);
+
+				// We have multiple items at the same distance from the event. Now sort by smallest
+				if (nearestItems.length > 1) {
+					nearestItems.sort(function(a, b) {
+						var sizeA = a.getArea();
+						var sizeB = b.getArea();
+						var ret = sizeA - sizeB;
+
+						if (ret === 0) {
+							// if equal sort by dataset index
+							ret = a._datasetIndex - b._datasetIndex;
+						}
+
+						return ret;
+					});
+				}
+
+				// Return only 1 item
+				return nearestItems.slice(0, 1);
+			},
+
+			/**
+			 * x mode returns the elements that hit-test at the current x coordinate
+			 * @function Chart.Interaction.modes.x
+			 * @param chart {chart} the chart we are returning items from
+			 * @param e {Event} the event we are find things at
+			 * @param options {IInteractionOptions} options to use
+			 * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
+			 */
+			x: function(chart, e, options) {
+				var position = getRelativePosition(e, chart.chart);
+				var items = [];
+				var intersectsItem = false;
+
+				parseVisibleItems(chart, function(element) {
+					if (element.inXRange(position.x)) {
+						items.push(element);
+					}
+
+					if (element.inRange(position.x, position.y)) {
+						intersectsItem = true;
+					}
+				});
+
+				// If we want to trigger on an intersect and we don't have any items
+				// that intersect the position, return nothing
+				if (options.intersect && !intersectsItem) {
+					items = [];
+				}
+				return items;
+			},
+
+			/**
+			 * y mode returns the elements that hit-test at the current y coordinate
+			 * @function Chart.Interaction.modes.y
+			 * @param chart {chart} the chart we are returning items from
+			 * @param e {Event} the event we are find things at
+			 * @param options {IInteractionOptions} options to use
+			 * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
+			 */
+			y: function(chart, e, options) {
+				var position = getRelativePosition(e, chart.chart);
+				var items = [];
+				var intersectsItem = false;
+
+				parseVisibleItems(chart, function(element) {
+					if (element.inYRange(position.y)) {
+						items.push(element);
+					}
+
+					if (element.inRange(position.x, position.y)) {
+						intersectsItem = true;
+					}
+				});
+
+				// If we want to trigger on an intersect and we don't have any items
+				// that intersect the position, return nothing
+				if (options.intersect && !intersectsItem) {
+					items = [];
+				}
+				return items;
+			}
+		}
+	};
+};
+
+},{}],28:[function(require,module,exports){
+'use strict';
+
+module.exports = function() {
+
+	// Occupy the global variable of Chart, and create a simple base class
+	var Chart = function(item, config) {
+		this.controller = new Chart.Controller(item, config, this);
+		return this.controller;
+	};
+
+	// Globally expose the defaults to allow for user updating/changing
+	Chart.defaults = {
+		global: {
+			responsive: true,
+			responsiveAnimationDuration: 0,
+			maintainAspectRatio: true,
+			events: ['mousemove', 'mouseout', 'click', 'touchstart', 'touchmove'],
+			hover: {
+				onHover: null,
+				mode: 'nearest',
+				intersect: true,
+				animationDuration: 400
+			},
+			onClick: null,
+			defaultColor: 'rgba(0,0,0,0.1)',
+			defaultFontColor: '#666',
+			defaultFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
+			defaultFontSize: 12,
+			defaultFontStyle: 'normal',
+			showLines: true,
+
+			// Element defaults defined in element extensions
+			elements: {},
+
+			// Legend callback string
+			legendCallback: function(chart) {
+				var text = [];
+				text.push('<ul class="' + chart.id + '-legend">');
+				for (var i = 0; i < chart.data.datasets.length; i++) {
+					text.push('<li><span style="background-color:' + chart.data.datasets[i].backgroundColor + '"></span>');
+					if (chart.data.datasets[i].label) {
+						text.push(chart.data.datasets[i].label);
+					}
+					text.push('</li>');
+				}
+				text.push('</ul>');
+
+				return text.join('');
+			}
+		}
+	};
+
+	Chart.Chart = Chart;
+
+	return Chart;
+};
+
+},{}],29:[function(require,module,exports){
+'use strict';
+
+module.exports = function(Chart) {
+
+	var helpers = Chart.helpers;
+
+	// The layout service is very self explanatory.  It's responsible for the layout within a chart.
+	// Scales, Legends and Plugins all rely on the layout service and can easily register to be placed anywhere they need
+	// It is this service's responsibility of carrying out that layout.
+	Chart.layoutService = {
+		defaults: {},
+
+		// Register a box to a chartInstance. A box is simply a reference to an object that requires layout. eg. Scales, Legend, Plugins.
+		addBox: function(chartInstance, box) {
+			if (!chartInstance.boxes) {
+				chartInstance.boxes = [];
+			}
+			chartInstance.boxes.push(box);
+		},
+
+		removeBox: function(chartInstance, box) {
+			if (!chartInstance.boxes) {
+				return;
+			}
+			chartInstance.boxes.splice(chartInstance.boxes.indexOf(box), 1);
+		},
+
+		// The most important function
+		update: function(chartInstance, width, height) {
+
+			if (!chartInstance) {
+				return;
+			}
+
+			var layoutOptions = chartInstance.options.layout;
+			var padding = layoutOptions ? layoutOptions.padding : null;
+
+			var leftPadding = 0;
+			var rightPadding = 0;
+			var topPadding = 0;
+			var bottomPadding = 0;
+
+			if (!isNaN(padding)) {
+				// options.layout.padding is a number. assign to all
+				leftPadding = padding;
+				rightPadding = padding;
+				topPadding = padding;
+				bottomPadding = padding;
+			} else {
+				leftPadding = padding.left || 0;
+				rightPadding = padding.right || 0;
+				topPadding = padding.top || 0;
+				bottomPadding = padding.bottom || 0;
+			}
+
+			var leftBoxes = helpers.where(chartInstance.boxes, function(box) {
+				return box.options.position === 'left';
+			});
+			var rightBoxes = helpers.where(chartInstance.boxes, function(box) {
+				return box.options.position === 'right';
+			});
+			var topBoxes = helpers.where(chartInstance.boxes, function(box) {
+				return box.options.position === 'top';
+			});
+			var bottomBoxes = helpers.where(chartInstance.boxes, function(box) {
+				return box.options.position === 'bottom';
+			});
+
+			// Boxes that overlay the chartarea such as the radialLinear scale
+			var chartAreaBoxes = helpers.where(chartInstance.boxes, function(box) {
+				return box.options.position === 'chartArea';
+			});
+
+			// Ensure that full width boxes are at the very top / bottom
+			topBoxes.sort(function(a, b) {
+				return (b.options.fullWidth ? 1 : 0) - (a.options.fullWidth ? 1 : 0);
+			});
+			bottomBoxes.sort(function(a, b) {
+				return (a.options.fullWidth ? 1 : 0) - (b.options.fullWidth ? 1 : 0);
+			});
+
+			// Essentially we now have any number of boxes on each of the 4 sides.
+			// Our canvas looks like the following.
+			// The areas L1 and L2 are the left axes. R1 is the right axis, T1 is the top axis and
+			// B1 is the bottom axis
+			// There are also 4 quadrant-like locations (left to right instead of clockwise) reserved for chart overlays
+			// These locations are single-box locations only, when trying to register a chartArea location that is already taken,
+			// an error will be thrown.
+			//
+			// |----------------------------------------------------|
+			// |                  T1 (Full Width)                   |
+			// |----------------------------------------------------|
+			// |    |    |                 T2                  |    |
+			// |    |----|-------------------------------------|----|
+			// |    |    | C1 |                           | C2 |    |
+			// |    |    |----|                           |----|    |
+			// |    |    |                                     |    |
+			// | L1 | L2 |           ChartArea (C0)            | R1 |
+			// |    |    |                                     |    |
+			// |    |    |----|                           |----|    |
+			// |    |    | C3 |                           | C4 |    |
+			// |    |----|-------------------------------------|----|
+			// |    |    |                 B1                  |    |
+			// |----------------------------------------------------|
+			// |                  B2 (Full Width)                   |
+			// |----------------------------------------------------|
+			//
+			// What we do to find the best sizing, we do the following
+			// 1. Determine the minimum size of the chart area.
+			// 2. Split the remaining width equally between each vertical axis
+			// 3. Split the remaining height equally between each horizontal axis
+			// 4. Give each layout the maximum size it can be. The layout will return it's minimum size
+			// 5. Adjust the sizes of each axis based on it's minimum reported size.
+			// 6. Refit each axis
+			// 7. Position each axis in the final location
+			// 8. Tell the chart the final location of the chart area
+			// 9. Tell any axes that overlay the chart area the positions of the chart area
+
+			// Step 1
+			var chartWidth = width - leftPadding - rightPadding;
+			var chartHeight = height - topPadding - bottomPadding;
+			var chartAreaWidth = chartWidth / 2; // min 50%
+			var chartAreaHeight = chartHeight / 2; // min 50%
+
+			// Step 2
+			var verticalBoxWidth = (width - chartAreaWidth) / (leftBoxes.length + rightBoxes.length);
+
+			// Step 3
+			var horizontalBoxHeight = (height - chartAreaHeight) / (topBoxes.length + bottomBoxes.length);
+
+			// Step 4
+			var maxChartAreaWidth = chartWidth;
+			var maxChartAreaHeight = chartHeight;
+			var minBoxSizes = [];
+
+			function getMinimumBoxSize(box) {
+				var minSize;
+				var isHorizontal = box.isHorizontal();
+
+				if (isHorizontal) {
+					minSize = box.update(box.options.fullWidth ? chartWidth : maxChartAreaWidth, horizontalBoxHeight);
+					maxChartAreaHeight -= minSize.height;
+				} else {
+					minSize = box.update(verticalBoxWidth, chartAreaHeight);
+					maxChartAreaWidth -= minSize.width;
+				}
+
+				minBoxSizes.push({
+					horizontal: isHorizontal,
+					minSize: minSize,
+					box: box,
+				});
+			}
+
+			helpers.each(leftBoxes.concat(rightBoxes, topBoxes, bottomBoxes), getMinimumBoxSize);
+
+			// If a horizontal box has padding, we move the left boxes over to avoid ugly charts (see issue #2478)
+			var maxHorizontalLeftPadding = 0;
+			var maxHorizontalRightPadding = 0;
+			var maxVerticalTopPadding = 0;
+			var maxVerticalBottomPadding = 0;
+
+			helpers.each(topBoxes.concat(bottomBoxes), function(horizontalBox) {
+				if (horizontalBox.getPadding) {
+					var boxPadding = horizontalBox.getPadding();
+					maxHorizontalLeftPadding = Math.max(maxHorizontalLeftPadding, boxPadding.left);
+					maxHorizontalRightPadding = Math.max(maxHorizontalRightPadding, boxPadding.right);
+				}
+			});
+
+			helpers.each(leftBoxes.concat(rightBoxes), function(verticalBox) {
+				if (verticalBox.getPadding) {
+					var boxPadding = verticalBox.getPadding();
+					maxVerticalTopPadding = Math.max(maxVerticalTopPadding, boxPadding.top);
+					maxVerticalBottomPadding = Math.max(maxVerticalBottomPadding, boxPadding.bottom);
+				}
+			});
+
+			// At this point, maxChartAreaHeight and maxChartAreaWidth are the size the chart area could
+			// be if the axes are drawn at their minimum sizes.
+			// Steps 5 & 6
+			var totalLeftBoxesWidth = leftPadding;
+			var totalRightBoxesWidth = rightPadding;
+			var totalTopBoxesHeight = topPadding;
+			var totalBottomBoxesHeight = bottomPadding;
+
+			// Function to fit a box
+			function fitBox(box) {
+				var minBoxSize = helpers.findNextWhere(minBoxSizes, function(minBox) {
+					return minBox.box === box;
+				});
+
+				if (minBoxSize) {
+					if (box.isHorizontal()) {
+						var scaleMargin = {
+							left: Math.max(totalLeftBoxesWidth, maxHorizontalLeftPadding),
+							right: Math.max(totalRightBoxesWidth, maxHorizontalRightPadding),
+							top: 0,
+							bottom: 0
+						};
+
+						// Don't use min size here because of label rotation. When the labels are rotated, their rotation highly depends
+						// on the margin. Sometimes they need to increase in size slightly
+						box.update(box.options.fullWidth ? chartWidth : maxChartAreaWidth, chartHeight / 2, scaleMargin);
+					} else {
+						box.update(minBoxSize.minSize.width, maxChartAreaHeight);
+					}
+				}
+			}
+
+			// Update, and calculate the left and right margins for the horizontal boxes
+			helpers.each(leftBoxes.concat(rightBoxes), fitBox);
+
+			helpers.each(leftBoxes, function(box) {
+				totalLeftBoxesWidth += box.width;
+			});
+
+			helpers.each(rightBoxes, function(box) {
+				totalRightBoxesWidth += box.width;
+			});
+
+			// Set the Left and Right margins for the horizontal boxes
+			helpers.each(topBoxes.concat(bottomBoxes), fitBox);
+
+			// Figure out how much margin is on the top and bottom of the vertical boxes
+			helpers.each(topBoxes, function(box) {
+				totalTopBoxesHeight += box.height;
+			});
+
+			helpers.each(bottomBoxes, function(box) {
+				totalBottomBoxesHeight += box.height;
+			});
+
+			function finalFitVerticalBox(box) {
+				var minBoxSize = helpers.findNextWhere(minBoxSizes, function(minSize) {
+					return minSize.box === box;
+				});
+
+				var scaleMargin = {
+					left: 0,
+					right: 0,
+					top: totalTopBoxesHeight,
+					bottom: totalBottomBoxesHeight
+				};
+
+				if (minBoxSize) {
+					box.update(minBoxSize.minSize.width, maxChartAreaHeight, scaleMargin);
+				}
+			}
+
+			// Let the left layout know the final margin
+			helpers.each(leftBoxes.concat(rightBoxes), finalFitVerticalBox);
+
+			// Recalculate because the size of each layout might have changed slightly due to the margins (label rotation for instance)
+			totalLeftBoxesWidth = leftPadding;
+			totalRightBoxesWidth = rightPadding;
+			totalTopBoxesHeight = topPadding;
+			totalBottomBoxesHeight = bottomPadding;
+
+			helpers.each(leftBoxes, function(box) {
+				totalLeftBoxesWidth += box.width;
+			});
+
+			helpers.each(rightBoxes, function(box) {
+				totalRightBoxesWidth += box.width;
+			});
+
+			helpers.each(topBoxes, function(box) {
+				totalTopBoxesHeight += box.height;
+			});
+			helpers.each(bottomBoxes, function(box) {
+				totalBottomBoxesHeight += box.height;
+			});
+
+			// We may be adding some padding to account for rotated x axis labels
+			var leftPaddingAddition = Math.max(maxHorizontalLeftPadding - totalLeftBoxesWidth, 0);
+			totalLeftBoxesWidth += leftPaddingAddition;
+			totalRightBoxesWidth += Math.max(maxHorizontalRightPadding - totalRightBoxesWidth, 0);
+
+			var topPaddingAddition = Math.max(maxVerticalTopPadding - totalTopBoxesHeight, 0);
+			totalTopBoxesHeight += topPaddingAddition;
+			totalBottomBoxesHeight += Math.max(maxVerticalBottomPadding - totalBottomBoxesHeight, 0);
+
+			// Figure out if our chart area changed. This would occur if the dataset layout label rotation
+			// changed due to the application of the margins in step 6. Since we can only get bigger, this is safe to do
+			// without calling `fit` again
+			var newMaxChartAreaHeight = height - totalTopBoxesHeight - totalBottomBoxesHeight;
+			var newMaxChartAreaWidth = width - totalLeftBoxesWidth - totalRightBoxesWidth;
+
+			if (newMaxChartAreaWidth !== maxChartAreaWidth || newMaxChartAreaHeight !== maxChartAreaHeight) {
+				helpers.each(leftBoxes, function(box) {
+					box.height = newMaxChartAreaHeight;
+				});
+
+				helpers.each(rightBoxes, function(box) {
+					box.height = newMaxChartAreaHeight;
+				});
+
+				helpers.each(topBoxes, function(box) {
+					if (!box.options.fullWidth) {
+						box.width = newMaxChartAreaWidth;
+					}
+				});
+
+				helpers.each(bottomBoxes, function(box) {
+					if (!box.options.fullWidth) {
+						box.width = newMaxChartAreaWidth;
+					}
+				});
+
+				maxChartAreaHeight = newMaxChartAreaHeight;
+				maxChartAreaWidth = newMaxChartAreaWidth;
+			}
+
+			// Step 7 - Position the boxes
+			var left = leftPadding + leftPaddingAddition;
+			var top = topPadding + topPaddingAddition;
+
+			function placeBox(box) {
+				if (box.isHorizontal()) {
+					box.left = box.options.fullWidth ? leftPadding : totalLeftBoxesWidth;
+					box.right = box.options.fullWidth ? width - rightPadding : totalLeftBoxesWidth + maxChartAreaWidth;
+					box.top = top;
+					box.bottom = top + box.height;
+
+					// Move to next point
+					top = box.bottom;
+
+				} else {
+
+					box.left = left;
+					box.right = left + box.width;
+					box.top = totalTopBoxesHeight;
+					box.bottom = totalTopBoxesHeight + maxChartAreaHeight;
+
+					// Move to next point
+					left = box.right;
+				}
+			}
+
+			helpers.each(leftBoxes.concat(topBoxes), placeBox);
+
+			// Account for chart width and height
+			left += maxChartAreaWidth;
+			top += maxChartAreaHeight;
+
+			helpers.each(rightBoxes, placeBox);
+			helpers.each(bottomBoxes, placeBox);
+
+			// Step 8
+			chartInstance.chartArea = {
+				left: totalLeftBoxesWidth,
+				top: totalTopBoxesHeight,
+				right: totalLeftBoxesWidth + maxChartAreaWidth,
+				bottom: totalTopBoxesHeight + maxChartAreaHeight
+			};
+
+			// Step 9
+			helpers.each(chartAreaBoxes, function(box) {
+				box.left = chartInstance.chartArea.left;
+				box.top = chartInstance.chartArea.top;
+				box.right = chartInstance.chartArea.right;
+				box.bottom = chartInstance.chartArea.bottom;
+
+				box.update(maxChartAreaWidth, maxChartAreaHeight);
+			});
+		}
+	};
+};
+
+},{}],30:[function(require,module,exports){
+'use strict';
+
+module.exports = function(Chart) {
+
+	var helpers = Chart.helpers;
+	var noop = helpers.noop;
+
+	Chart.defaults.global.legend = {
+
+		display: true,
+		position: 'top',
+		fullWidth: true, // marks that this box should take the full width of the canvas (pushing down other boxes)
+		reverse: false,
+
+		// a callback that will handle
+		onClick: function(e, legendItem) {
+			var index = legendItem.datasetIndex;
+			var ci = this.chart;
+			var meta = ci.getDatasetMeta(index);
+
+			// See controller.isDatasetVisible comment
+			meta.hidden = meta.hidden === null? !ci.data.datasets[index].hidden : null;
+
+			// We hid a dataset ... rerender the chart
+			ci.update();
+		},
+
+		onHover: null,
+
+		labels: {
+			boxWidth: 40,
+			padding: 10,
+			// Generates labels shown in the legend
+			// Valid properties to return:
+			// text : text to display
+			// fillStyle : fill of coloured box
+			// strokeStyle: stroke of coloured box
+			// hidden : if this legend item refers to a hidden item
+			// lineCap : cap style for line
+			// lineDash
+			// lineDashOffset :
+			// lineJoin :
+			// lineWidth :
+			generateLabels: function(chart) {
+				var data = chart.data;
+				return helpers.isArray(data.datasets) ? data.datasets.map(function(dataset, i) {
+					return {
+						text: dataset.label,
+						fillStyle: (!helpers.isArray(dataset.backgroundColor) ? dataset.backgroundColor : dataset.backgroundColor[0]),
+						hidden: !chart.isDatasetVisible(i),
+						lineCap: dataset.borderCapStyle,
+						lineDash: dataset.borderDash,
+						lineDashOffset: dataset.borderDashOffset,
+						lineJoin: dataset.borderJoinStyle,
+						lineWidth: dataset.borderWidth,
+						strokeStyle: dataset.borderColor,
+						pointStyle: dataset.pointStyle,
+
+						// Below is extra data used for toggling the datasets
+						datasetIndex: i
+					};
+				}, this) : [];
+			}
+		}
+	};
+
+	/**
+	 * Helper function to get the box width based on the usePointStyle option
+	 * @param labelopts {Object} the label options on the legend
+	 * @param fontSize {Number} the label font size
+	 * @return {Number} width of the color box area
+	 */
+	function getBoxWidth(labelOpts, fontSize) {
+		return labelOpts.usePointStyle ?
+			fontSize * Math.SQRT2 :
+			labelOpts.boxWidth;
+	}
+
+	Chart.Legend = Chart.Element.extend({
+
+		initialize: function(config) {
+			helpers.extend(this, config);
+
+			// Contains hit boxes for each dataset (in dataset order)
+			this.legendHitBoxes = [];
+
+			// Are we in doughnut mode which has a different data type
+			this.doughnutMode = false;
+		},
+
+		// These methods are ordered by lifecycle. Utilities then follow.
+		// Any function defined here is inherited by all legend types.
+		// Any function can be extended by the legend type
+
+		beforeUpdate: noop,
+		update: function(maxWidth, maxHeight, margins) {
+			var me = this;
+
+			// Update Lifecycle - Probably don't want to ever extend or overwrite this function ;)
+			me.beforeUpdate();
+
+			// Absorb the master measurements
+			me.maxWidth = maxWidth;
+			me.maxHeight = maxHeight;
+			me.margins = margins;
+
+			// Dimensions
+			me.beforeSetDimensions();
+			me.setDimensions();
+			me.afterSetDimensions();
+			// Labels
+			me.beforeBuildLabels();
+			me.buildLabels();
+			me.afterBuildLabels();
+
+			// Fit
+			me.beforeFit();
+			me.fit();
+			me.afterFit();
+			//
+			me.afterUpdate();
+
+			return me.minSize;
+		},
+		afterUpdate: noop,
+
+		//
+
+		beforeSetDimensions: noop,
+		setDimensions: function() {
+			var me = this;
+			// Set the unconstrained dimension before label rotation
+			if (me.isHorizontal()) {
+				// Reset position before calculating rotation
+				me.width = me.maxWidth;
+				me.left = 0;
+				me.right = me.width;
+			} else {
+				me.height = me.maxHeight;
+
+				// Reset position before calculating rotation
+				me.top = 0;
+				me.bottom = me.height;
+			}
+
+			// Reset padding
+			me.paddingLeft = 0;
+			me.paddingTop = 0;
+			me.paddingRight = 0;
+			me.paddingBottom = 0;
+
+			// Reset minSize
+			me.minSize = {
+				width: 0,
+				height: 0
+			};
+		},
+		afterSetDimensions: noop,
+
+		//
+
+		beforeBuildLabels: noop,
+		buildLabels: function() {
+			var me = this;
+			var labelOpts = me.options.labels;
+			var legendItems = labelOpts.generateLabels.call(me, me.chart);
+
+			if (labelOpts.filter) {
+				legendItems = legendItems.filter(function(item) {
+					return labelOpts.filter(item, me.chart.data);
+				});
+			}
+
+			if (me.options.reverse) {
+				legendItems.reverse();
+			}
+
+			me.legendItems = legendItems;
+		},
+		afterBuildLabels: noop,
+
+		//
+
+		beforeFit: noop,
+		fit: function() {
+			var me = this;
+			var opts = me.options;
+			var labelOpts = opts.labels;
+			var display = opts.display;
+
+			var ctx = me.ctx;
+
+			var globalDefault = Chart.defaults.global,
+				itemOrDefault = helpers.getValueOrDefault,
+				fontSize = itemOrDefault(labelOpts.fontSize, globalDefault.defaultFontSize),
+				fontStyle = itemOrDefault(labelOpts.fontStyle, globalDefault.defaultFontStyle),
+				fontFamily = itemOrDefault(labelOpts.fontFamily, globalDefault.defaultFontFamily),
+				labelFont = helpers.fontString(fontSize, fontStyle, fontFamily);
+
+			// Reset hit boxes
+			var hitboxes = me.legendHitBoxes = [];
+
+			var minSize = me.minSize;
+			var isHorizontal = me.isHorizontal();
+
+			if (isHorizontal) {
+				minSize.width = me.maxWidth; // fill all the width
+				minSize.height = display ? 10 : 0;
+			} else {
+				minSize.width = display ? 10 : 0;
+				minSize.height = me.maxHeight; // fill all the height
+			}
+
+			// Increase sizes here
+			if (display) {
+				ctx.font = labelFont;
+
+				if (isHorizontal) {
+					// Labels
+
+					// Width of each line of legend boxes. Labels wrap onto multiple lines when there are too many to fit on one
+					var lineWidths = me.lineWidths = [0];
+					var totalHeight = me.legendItems.length ? fontSize + (labelOpts.padding) : 0;
+
+					ctx.textAlign = 'left';
+					ctx.textBaseline = 'top';
+
+					helpers.each(me.legendItems, function(legendItem, i) {
+						var boxWidth = getBoxWidth(labelOpts, fontSize);
+						var width = boxWidth + (fontSize / 2) + ctx.measureText(legendItem.text).width;
+
+						if (lineWidths[lineWidths.length - 1] + width + labelOpts.padding >= me.width) {
+							totalHeight += fontSize + (labelOpts.padding);
+							lineWidths[lineWidths.length] = me.left;
+						}
+
+						// Store the hitbox width and height here. Final position will be updated in `draw`
+						hitboxes[i] = {
+							left: 0,
+							top: 0,
+							width: width,
+							height: fontSize
+						};
+
+						lineWidths[lineWidths.length - 1] += width + labelOpts.padding;
+					});
+
+					minSize.height += totalHeight;
+
+				} else {
+					var vPadding = labelOpts.padding;
+					var columnWidths = me.columnWidths = [];
+					var totalWidth = labelOpts.padding;
+					var currentColWidth = 0;
+					var currentColHeight = 0;
+					var itemHeight = fontSize + vPadding;
+
+					helpers.each(me.legendItems, function(legendItem, i) {
+						var boxWidth = getBoxWidth(labelOpts, fontSize);
+						var itemWidth = boxWidth + (fontSize / 2) + ctx.measureText(legendItem.text).width;
+
+						// If too tall, go to new column
+						if (currentColHeight + itemHeight > minSize.height) {
+							totalWidth += currentColWidth + labelOpts.padding;
+							columnWidths.push(currentColWidth); // previous column width
+
+							currentColWidth = 0;
+							currentColHeight = 0;
+						}
+
+						// Get max width
+						currentColWidth = Math.max(currentColWidth, itemWidth);
+						currentColHeight += itemHeight;
+
+						// Store the hitbox width and height here. Final position will be updated in `draw`
+						hitboxes[i] = {
+							left: 0,
+							top: 0,
+							width: itemWidth,
+							height: fontSize
+						};
+					});
+
+					totalWidth += currentColWidth;
+					columnWidths.push(currentColWidth);
+					minSize.width += totalWidth;
+				}
+			}
+
+			me.width = minSize.width;
+			me.height = minSize.height;
+		},
+		afterFit: noop,
+
+		// Shared Methods
+		isHorizontal: function() {
+			return this.options.position === 'top' || this.options.position === 'bottom';
+		},
+
+		// Actually draw the legend on the canvas
+		draw: function() {
+			var me = this;
+			var opts = me.options;
+			var labelOpts = opts.labels;
+			var globalDefault = Chart.defaults.global,
+				lineDefault = globalDefault.elements.line,
+				legendWidth = me.width,
+				lineWidths = me.lineWidths;
+
+			if (opts.display) {
+				var ctx = me.ctx,
+					cursor,
+					itemOrDefault = helpers.getValueOrDefault,
+					fontColor = itemOrDefault(labelOpts.fontColor, globalDefault.defaultFontColor),
+					fontSize = itemOrDefault(labelOpts.fontSize, globalDefault.defaultFontSize),
+					fontStyle = itemOrDefault(labelOpts.fontStyle, globalDefault.defaultFontStyle),
+					fontFamily = itemOrDefault(labelOpts.fontFamily, globalDefault.defaultFontFamily),
+					labelFont = helpers.fontString(fontSize, fontStyle, fontFamily);
+
+				// Canvas setup
+				ctx.textAlign = 'left';
+				ctx.textBaseline = 'top';
+				ctx.lineWidth = 0.5;
+				ctx.strokeStyle = fontColor; // for strikethrough effect
+				ctx.fillStyle = fontColor; // render in correct colour
+				ctx.font = labelFont;
+
+				var boxWidth = getBoxWidth(labelOpts, fontSize),
+					hitboxes = me.legendHitBoxes;
+
+				// current position
+				var drawLegendBox = function(x, y, legendItem) {
+					if (isNaN(boxWidth) || boxWidth <= 0) {
+						return;
+					}
+
+					// Set the ctx for the box
+					ctx.save();
+
+					ctx.fillStyle = itemOrDefault(legendItem.fillStyle, globalDefault.defaultColor);
+					ctx.lineCap = itemOrDefault(legendItem.lineCap, lineDefault.borderCapStyle);
+					ctx.lineDashOffset = itemOrDefault(legendItem.lineDashOffset, lineDefault.borderDashOffset);
+					ctx.lineJoin = itemOrDefault(legendItem.lineJoin, lineDefault.borderJoinStyle);
+					ctx.lineWidth = itemOrDefault(legendItem.lineWidth, lineDefault.borderWidth);
+					ctx.strokeStyle = itemOrDefault(legendItem.strokeStyle, globalDefault.defaultColor);
+					var isLineWidthZero = (itemOrDefault(legendItem.lineWidth, lineDefault.borderWidth) === 0);
+
+					if (ctx.setLineDash) {
+						// IE 9 and 10 do not support line dash
+						ctx.setLineDash(itemOrDefault(legendItem.lineDash, lineDefault.borderDash));
+					}
+
+					if (opts.labels && opts.labels.usePointStyle) {
+						// Recalculate x and y for drawPoint() because its expecting
+						// x and y to be center of figure (instead of top left)
+						var radius = fontSize * Math.SQRT2 / 2;
+						var offSet = radius / Math.SQRT2;
+						var centerX = x + offSet;
+						var centerY = y + offSet;
+
+						// Draw pointStyle as legend symbol
+						Chart.canvasHelpers.drawPoint(ctx, legendItem.pointStyle, radius, centerX, centerY);
+					} else {
+						// Draw box as legend symbol
+						if (!isLineWidthZero) {
+							ctx.strokeRect(x, y, boxWidth, fontSize);
+						}
+						ctx.fillRect(x, y, boxWidth, fontSize);
+					}
+
+					ctx.restore();
+				};
+				var fillText = function(x, y, legendItem, textWidth) {
+					ctx.fillText(legendItem.text, boxWidth + (fontSize / 2) + x, y);
+
+					if (legendItem.hidden) {
+						// Strikethrough the text if hidden
+						ctx.beginPath();
+						ctx.lineWidth = 2;
+						ctx.moveTo(boxWidth + (fontSize / 2) + x, y + (fontSize / 2));
+						ctx.lineTo(boxWidth + (fontSize / 2) + x + textWidth, y + (fontSize / 2));
+						ctx.stroke();
+					}
+				};
+
+				// Horizontal
+				var isHorizontal = me.isHorizontal();
+				if (isHorizontal) {
+					cursor = {
+						x: me.left + ((legendWidth - lineWidths[0]) / 2),
+						y: me.top + labelOpts.padding,
+						line: 0
+					};
+				} else {
+					cursor = {
+						x: me.left + labelOpts.padding,
+						y: me.top + labelOpts.padding,
+						line: 0
+					};
+				}
+
+				var itemHeight = fontSize + labelOpts.padding;
+				helpers.each(me.legendItems, function(legendItem, i) {
+					var textWidth = ctx.measureText(legendItem.text).width,
+						width = boxWidth + (fontSize / 2) + textWidth,
+						x = cursor.x,
+						y = cursor.y;
+
+					if (isHorizontal) {
+						if (x + width >= legendWidth) {
+							y = cursor.y += itemHeight;
+							cursor.line++;
+							x = cursor.x = me.left + ((legendWidth - lineWidths[cursor.line]) / 2);
+						}
+					} else if (y + itemHeight > me.bottom) {
+						x = cursor.x = x + me.columnWidths[cursor.line] + labelOpts.padding;
+						y = cursor.y = me.top + labelOpts.padding;
+						cursor.line++;
+					}
+
+					drawLegendBox(x, y, legendItem);
+
+					hitboxes[i].left = x;
+					hitboxes[i].top = y;
+
+					// Fill the actual label
+					fillText(x, y, legendItem, textWidth);
+
+					if (isHorizontal) {
+						cursor.x += width + (labelOpts.padding);
+					} else {
+						cursor.y += itemHeight;
+					}
+
+				});
+			}
+		},
+
+		/**
+		 * Handle an event
+		 * @private
+		 * @param {IEvent} event - The event to handle
+		 * @return {Boolean} true if a change occured
+		 */
+		handleEvent: function(e) {
+			var me = this;
+			var opts = me.options;
+			var type = e.type === 'mouseup' ? 'click' : e.type;
+			var changed = false;
+
+			if (type === 'mousemove') {
+				if (!opts.onHover) {
+					return;
+				}
+			} else if (type === 'click') {
+				if (!opts.onClick) {
+					return;
+				}
+			} else {
+				return;
+			}
+
+			// Chart event already has relative position in it
+			var x = e.x,
+				y = e.y;
+
+			if (x >= me.left && x <= me.right && y >= me.top && y <= me.bottom) {
+				// See if we are touching one of the dataset boxes
+				var lh = me.legendHitBoxes;
+				for (var i = 0; i < lh.length; ++i) {
+					var hitBox = lh[i];
+
+					if (x >= hitBox.left && x <= hitBox.left + hitBox.width && y >= hitBox.top && y <= hitBox.top + hitBox.height) {
+						// Touching an element
+						if (type === 'click') {
+							// use e.native for backwards compatibility
+							opts.onClick.call(me, e.native, me.legendItems[i]);
+							changed = true;
+							break;
+						} else if (type === 'mousemove') {
+							// use e.native for backwards compatibility
+							opts.onHover.call(me, e.native, me.legendItems[i]);
+							changed = true;
+							break;
+						}
+					}
+				}
+			}
+
+			return changed;
+		}
+	});
+
+	function createNewLegendAndAttach(chartInstance, legendOpts) {
+		var legend = new Chart.Legend({
+			ctx: chartInstance.chart.ctx,
+			options: legendOpts,
+			chart: chartInstance
+		});
+		chartInstance.legend = legend;
+		Chart.layoutService.addBox(chartInstance, legend);
+	}
+
+	// Register the legend plugin
+	Chart.plugins.register({
+		beforeInit: function(chartInstance) {
+			var legendOpts = chartInstance.options.legend;
+
+			if (legendOpts) {
+				createNewLegendAndAttach(chartInstance, legendOpts);
+			}
+		},
+		beforeUpdate: function(chartInstance) {
+			var legendOpts = chartInstance.options.legend;
+
+			if (legendOpts) {
+				legendOpts = helpers.configMerge(Chart.defaults.global.legend, legendOpts);
+
+				if (chartInstance.legend) {
+					chartInstance.legend.options = legendOpts;
+				} else {
+					createNewLegendAndAttach(chartInstance, legendOpts);
+				}
+			} else {
+				Chart.layoutService.removeBox(chartInstance, chartInstance.legend);
+				delete chartInstance.legend;
+			}
+		},
+		afterEvent: function(chartInstance, e) {
+			var legend = chartInstance.legend;
+			if (legend) {
+				legend.handleEvent(e);
+			}
+		}
+	});
+};
+
+},{}],31:[function(require,module,exports){
+'use strict';
+
+module.exports = function(Chart) {
+
+	var helpers = Chart.helpers;
+
+	Chart.defaults.global.plugins = {};
+
+	/**
+	 * The plugin service singleton
+	 * @namespace Chart.plugins
+	 * @since 2.1.0
+	 */
+	Chart.plugins = {
+		/**
+		 * Globally registered plugins.
+		 * @private
+		 */
+		_plugins: [],
+
+		/**
+		 * This identifier is used to invalidate the descriptors cache attached to each chart
+		 * when a global plugin is registered or unregistered. In this case, the cache ID is
+		 * incremented and descriptors are regenerated during following API calls.
+		 * @private
+		 */
+		_cacheId: 0,
+
+		/**
+		 * Registers the given plugin(s) if not already registered.
+		 * @param {Array|Object} plugins plugin instance(s).
+		 */
+		register: function(plugins) {
+			var p = this._plugins;
+			([]).concat(plugins).forEach(function(plugin) {
+				if (p.indexOf(plugin) === -1) {
+					p.push(plugin);
+				}
+			});
+
+			this._cacheId++;
+		},
+
+		/**
+		 * Unregisters the given plugin(s) only if registered.
+		 * @param {Array|Object} plugins plugin instance(s).
+		 */
+		unregister: function(plugins) {
+			var p = this._plugins;
+			([]).concat(plugins).forEach(function(plugin) {
+				var idx = p.indexOf(plugin);
+				if (idx !== -1) {
+					p.splice(idx, 1);
+				}
+			});
+
+			this._cacheId++;
+		},
+
+		/**
+		 * Remove all registered plugins.
+		 * @since 2.1.5
+		 */
+		clear: function() {
+			this._plugins = [];
+			this._cacheId++;
+		},
+
+		/**
+		 * Returns the number of registered plugins?
+		 * @returns {Number}
+		 * @since 2.1.5
+		 */
+		count: function() {
+			return this._plugins.length;
+		},
+
+		/**
+		 * Returns all registered plugin instances.
+		 * @returns {Array} array of plugin objects.
+		 * @since 2.1.5
+		 */
+		getAll: function() {
+			return this._plugins;
+		},
+
+		/**
+		 * Calls enabled plugins for `chart` on the specified hook and with the given args.
+		 * This method immediately returns as soon as a plugin explicitly returns false. The
+		 * returned value can be used, for instance, to interrupt the current action.
+		 * @param {Object} chart - The chart instance for which plugins should be called.
+		 * @param {String} hook - The name of the plugin method to call (e.g. 'beforeUpdate').
+		 * @param {Array} [args] - Extra arguments to apply to the hook call.
+		 * @returns {Boolean} false if any of the plugins return false, else returns true.
+		 */
+		notify: function(chart, hook, args) {
+			var descriptors = this.descriptors(chart);
+			var ilen = descriptors.length;
+			var i, descriptor, plugin, params, method;
+
+			for (i=0; i<ilen; ++i) {
+				descriptor = descriptors[i];
+				plugin = descriptor.plugin;
+				method = plugin[hook];
+				if (typeof method === 'function') {
+					params = [chart].concat(args || []);
+					params.push(descriptor.options);
+					if (method.apply(plugin, params) === false) {
+						return false;
+					}
+				}
+			}
+
+			return true;
+		},
+
+		/**
+		 * Returns descriptors of enabled plugins for the given chart.
+		 * @returns {Array} [{ plugin, options }]
+		 * @private
+		 */
+		descriptors: function(chart) {
+			var cache = chart._plugins || (chart._plugins = {});
+			if (cache.id === this._cacheId) {
+				return cache.descriptors;
+			}
+
+			var plugins = [];
+			var descriptors = [];
+			var config = (chart && chart.config) || {};
+			var defaults = Chart.defaults.global.plugins;
+			var options = (config.options && config.options.plugins) || {};
+
+			this._plugins.concat(config.plugins || []).forEach(function(plugin) {
+				var idx = plugins.indexOf(plugin);
+				if (idx !== -1) {
+					return;
+				}
+
+				var id = plugin.id;
+				var opts = options[id];
+				if (opts === false) {
+					return;
+				}
+
+				if (opts === true) {
+					opts = helpers.clone(defaults[id]);
+				}
+
+				plugins.push(plugin);
+				descriptors.push({
+					plugin: plugin,
+					options: opts || {}
+				});
+			});
+
+			cache.descriptors = descriptors;
+			cache.id = this._cacheId;
+			return descriptors;
+		}
+	};
+
+	/**
+	 * Plugin extension hooks.
+	 * @interface IPlugin
+	 * @since 2.1.0
+	 */
+	/**
+	 * @method IPlugin#beforeInit
+	 * @desc Called before initializing `chart`.
+	 * @param {Chart.Controller} chart - The chart instance.
+	 * @param {Object} options - The plugin options.
+	 */
+	/**
+	 * @method IPlugin#afterInit
+	 * @desc Called after `chart` has been initialized and before the first update.
+	 * @param {Chart.Controller} chart - The chart instance.
+	 * @param {Object} options - The plugin options.
+	 */
+	/**
+	 * @method IPlugin#beforeUpdate
+	 * @desc Called before updating `chart`. If any plugin returns `false`, the update
+	 * is cancelled (and thus subsequent render(s)) until another `update` is triggered.
+	 * @param {Chart.Controller} chart - The chart instance.
+	 * @param {Object} options - The plugin options.
+	 * @returns {Boolean} `false` to cancel the chart update.
+	 */
+	/**
+	 * @method IPlugin#afterUpdate
+	 * @desc Called after `chart` has been updated and before rendering. Note that this
+	 * hook will not be called if the chart update has been previously cancelled.
+	 * @param {Chart.Controller} chart - The chart instance.
+	 * @param {Object} options - The plugin options.
+	 */
+	/**
+	 * @method IPlugin#beforeDatasetsUpdate
+ 	 * @desc Called before updating the `chart` datasets. If any plugin returns `false`,
+	 * the datasets update is cancelled until another `update` is triggered.
+	 * @param {Chart.Controller} chart - The chart instance.
+	 * @param {Object} options - The plugin options.
+	 * @returns {Boolean} false to cancel the datasets update.
+	 * @since version 2.1.5
+	 */
+	/**
+	 * @method IPlugin#afterDatasetsUpdate
+	 * @desc Called after the `chart` datasets have been updated. Note that this hook
+	 * will not be called if the datasets update has been previously cancelled.
+	 * @param {Chart.Controller} chart - The chart instance.
+	 * @param {Object} options - The plugin options.
+	 * @since version 2.1.5
+	 */
+	/**
+	 * @method IPlugin#beforeLayout
+	 * @desc Called before laying out `chart`. If any plugin returns `false`,
+	 * the layout update is cancelled until another `update` is triggered.
+	 * @param {Chart.Controller} chart - The chart instance.
+	 * @param {Object} options - The plugin options.
+	 * @returns {Boolean} `false` to cancel the chart layout.
+	 */
+	/**
+	 * @method IPlugin#afterLayout
+	 * @desc Called after the `chart` has been layed out. Note that this hook will not
+	 * be called if the layout update has been previously cancelled.
+	 * @param {Chart.Controller} chart - The chart instance.
+	 * @param {Object} options - The plugin options.
+	 */
+	/**
+	 * @method IPlugin#beforeRender
+	 * @desc Called before rendering `chart`. If any plugin returns `false`,
+	 * the rendering is cancelled until another `render` is triggered.
+	 * @param {Chart.Controller} chart - The chart instance.
+	 * @param {Object} options - The plugin options.
+	 * @returns {Boolean} `false` to cancel the chart rendering.
+	 */
+	/**
+	 * @method IPlugin#afterRender
+	 * @desc Called after the `chart` has been fully rendered (and animation completed). Note
+	 * that this hook will not be called if the rendering has been previously cancelled.
+	 * @param {Chart.Controller} chart - The chart instance.
+	 * @param {Object} options - The plugin options.
+	 */
+	/**
+	 * @method IPlugin#beforeDraw
+	 * @desc Called before drawing `chart` at every animation frame specified by the given
+	 * easing value. If any plugin returns `false`, the frame drawing is cancelled until
+	 * another `render` is triggered.
+	 * @param {Chart.Controller} chart - The chart instance.
+	 * @param {Number} easingValue - The current animation value, between 0.0 and 1.0.
+	 * @param {Object} options - The plugin options.
+	 * @returns {Boolean} `false` to cancel the chart drawing.
+	 */
+	/**
+	 * @method IPlugin#afterDraw
+	 * @desc Called after the `chart` has been drawn for the specific easing value. Note
+	 * that this hook will not be called if the drawing has been previously cancelled.
+	 * @param {Chart.Controller} chart - The chart instance.
+	 * @param {Number} easingValue - The current animation value, between 0.0 and 1.0.
+	 * @param {Object} options - The plugin options.
+	 */
+	/**
+	 * @method IPlugin#beforeDatasetsDraw
+ 	 * @desc Called before drawing the `chart` datasets. If any plugin returns `false`,
+	 * the datasets drawing is cancelled until another `render` is triggered.
+	 * @param {Chart.Controller} chart - The chart instance.
+	 * @param {Number} easingValue - The current animation value, between 0.0 and 1.0.
+	 * @param {Object} options - The plugin options.
+	 * @returns {Boolean} `false` to cancel the chart datasets drawing.
+	 */
+	/**
+	 * @method IPlugin#afterDatasetsDraw
+	 * @desc Called after the `chart` datasets have been drawn. Note that this hook
+	 * will not be called if the datasets drawing has been previously cancelled.
+	 * @param {Chart.Controller} chart - The chart instance.
+	 * @param {Number} easingValue - The current animation value, between 0.0 and 1.0.
+	 * @param {Object} options - The plugin options.
+	 */
+	/**
+	 * @method IPlugin#beforeEvent
+ 	 * @desc Called before processing the specified `event`. If any plugin returns `false`,
+	 * the event will be discarded.
+	 * @param {Chart.Controller} chart - The chart instance.
+	 * @param {IEvent} event - The event object.
+	 * @param {Object} options - The plugin options.
+	 */
+	/**
+	 * @method IPlugin#afterEvent
+	 * @desc Called after the `event` has been consumed. Note that this hook
+	 * will not be called if the `event` has been previously discarded.
+	 * @param {Chart.Controller} chart - The chart instance.
+	 * @param {IEvent} event - The event object.
+	 * @param {Object} options - The plugin options.
+	 */
+	/**
+	 * @method IPlugin#resize
+	 * @desc Called after the chart as been resized.
+	 * @param {Chart.Controller} chart - The chart instance.
+	 * @param {Number} size - The new canvas display size (eq. canvas.style width & height).
+	 * @param {Object} options - The plugin options.
+	 */
+	/**
+	 * @method IPlugin#destroy
+	 * @desc Called after the chart as been destroyed.
+	 * @param {Chart.Controller} chart - The chart instance.
+	 * @param {Object} options - The plugin options.
+	 */
+
+	/**
+	 * Provided for backward compatibility, use Chart.plugins instead
+	 * @namespace Chart.pluginService
+	 * @deprecated since version 2.1.5
+	 * @todo remove at version 3
+	 * @private
+	 */
+	Chart.pluginService = Chart.plugins;
+
+	/**
+	 * Provided for backward compatibility, inheriting from Chart.PlugingBase has no
+	 * effect, instead simply create/register plugins via plain JavaScript objects.
+	 * @interface Chart.PluginBase
+	 * @deprecated since version 2.5.0
+	 * @todo remove at version 3
+	 * @private
+	 */
+	Chart.PluginBase = helpers.inherits({});
+};
+
+},{}],32:[function(require,module,exports){
+'use strict';
+
+module.exports = function(Chart) {
+
+	var helpers = Chart.helpers;
+
+	Chart.defaults.scale = {
+		display: true,
+		position: 'left',
+
+		// grid line settings
+		gridLines: {
+			display: true,
+			color: 'rgba(0, 0, 0, 0.1)',
+			lineWidth: 1,
+			drawBorder: true,
+			drawOnChartArea: true,
+			drawTicks: true,
+			tickMarkLength: 10,
+			zeroLineWidth: 1,
+			zeroLineColor: 'rgba(0,0,0,0.25)',
+			offsetGridLines: false,
+			borderDash: [],
+			borderDashOffset: 0.0
+		},
+
+		// scale label
+		scaleLabel: {
+			// actual label
+			labelString: '',
+
+			// display property
+			display: false
+		},
+
+		// label settings
+		ticks: {
+			beginAtZero: false,
+			minRotation: 0,
+			maxRotation: 50,
+			mirror: false,
+			padding: 0,
+			reverse: false,
+			display: true,
+			autoSkip: true,
+			autoSkipPadding: 0,
+			labelOffset: 0,
+			// We pass through arrays to be rendered as multiline labels, we convert Others to strings here.
+			callback: Chart.Ticks.formatters.values
+		}
+	};
+
+	function computeTextSize(context, tick, font) {
+		return helpers.isArray(tick) ?
+			helpers.longestText(context, font, tick) :
+			context.measureText(tick).width;
+	}
+
+	function parseFontOptions(options) {
+		var getValueOrDefault = helpers.getValueOrDefault;
+		var globalDefaults = Chart.defaults.global;
+		var size = getValueOrDefault(options.fontSize, globalDefaults.defaultFontSize);
+		var style = getValueOrDefault(options.fontStyle, globalDefaults.defaultFontStyle);
+		var family = getValueOrDefault(options.fontFamily, globalDefaults.defaultFontFamily);
+
+		return {
+			size: size,
+			style: style,
+			family: family,
+			font: helpers.fontString(size, style, family)
+		};
+	}
+
+	Chart.Scale = Chart.Element.extend({
+		/**
+		 * Get the padding needed for the scale
+		 * @method getPadding
+		 * @private
+		 * @returns {Padding} the necessary padding
+		 */
+		getPadding: function() {
+			var me = this;
+			return {
+				left: me.paddingLeft || 0,
+				top: me.paddingTop || 0,
+				right: me.paddingRight || 0,
+				bottom: me.paddingBottom || 0
+			};
+		},
+
+		// These methods are ordered by lifecyle. Utilities then follow.
+		// Any function defined here is inherited by all scale types.
+		// Any function can be extended by the scale type
+
+		beforeUpdate: function() {
+			helpers.callCallback(this.options.beforeUpdate, [this]);
+		},
+		update: function(maxWidth, maxHeight, margins) {
+			var me = this;
+
+			// Update Lifecycle - Probably don't want to ever extend or overwrite this function ;)
+			me.beforeUpdate();
+
+			// Absorb the master measurements
+			me.maxWidth = maxWidth;
+			me.maxHeight = maxHeight;
+			me.margins = helpers.extend({
+				left: 0,
+				right: 0,
+				top: 0,
+				bottom: 0
+			}, margins);
+			me.longestTextCache = me.longestTextCache || {};
+
+			// Dimensions
+			me.beforeSetDimensions();
+			me.setDimensions();
+			me.afterSetDimensions();
+
+			// Data min/max
+			me.beforeDataLimits();
+			me.determineDataLimits();
+			me.afterDataLimits();
+
+			// Ticks
+			me.beforeBuildTicks();
+			me.buildTicks();
+			me.afterBuildTicks();
+
+			me.beforeTickToLabelConversion();
+			me.convertTicksToLabels();
+			me.afterTickToLabelConversion();
+
+			// Tick Rotation
+			me.beforeCalculateTickRotation();
+			me.calculateTickRotation();
+			me.afterCalculateTickRotation();
+			// Fit
+			me.beforeFit();
+			me.fit();
+			me.afterFit();
+			//
+			me.afterUpdate();
+
+			return me.minSize;
+
+		},
+		afterUpdate: function() {
+			helpers.callCallback(this.options.afterUpdate, [this]);
+		},
+
+		//
+
+		beforeSetDimensions: function() {
+			helpers.callCallback(this.options.beforeSetDimensions, [this]);
+		},
+		setDimensions: function() {
+			var me = this;
+			// Set the unconstrained dimension before label rotation
+			if (me.isHorizontal()) {
+				// Reset position before calculating rotation
+				me.width = me.maxWidth;
+				me.left = 0;
+				me.right = me.width;
+			} else {
+				me.height = me.maxHeight;
+
+				// Reset position before calculating rotation
+				me.top = 0;
+				me.bottom = me.height;
+			}
+
+			// Reset padding
+			me.paddingLeft = 0;
+			me.paddingTop = 0;
+			me.paddingRight = 0;
+			me.paddingBottom = 0;
+		},
+		afterSetDimensions: function() {
+			helpers.callCallback(this.options.afterSetDimensions, [this]);
+		},
+
+		// Data limits
+		beforeDataLimits: function() {
+			helpers.callCallback(this.options.beforeDataLimits, [this]);
+		},
+		determineDataLimits: helpers.noop,
+		afterDataLimits: function() {
+			helpers.callCallback(this.options.afterDataLimits, [this]);
+		},
+
+		//
+		beforeBuildTicks: function() {
+			helpers.callCallback(this.options.beforeBuildTicks, [this]);
+		},
+		buildTicks: helpers.noop,
+		afterBuildTicks: function() {
+			helpers.callCallback(this.options.afterBuildTicks, [this]);
+		},
+
+		beforeTickToLabelConversion: function() {
+			helpers.callCallback(this.options.beforeTickToLabelConversion, [this]);
+		},
+		convertTicksToLabels: function() {
+			var me = this;
+			// Convert ticks to strings
+			var tickOpts = me.options.ticks;
+			me.ticks = me.ticks.map(tickOpts.userCallback || tickOpts.callback);
+		},
+		afterTickToLabelConversion: function() {
+			helpers.callCallback(this.options.afterTickToLabelConversion, [this]);
+		},
+
+		//
+
+		beforeCalculateTickRotation: function() {
+			helpers.callCallback(this.options.beforeCalculateTickRotation, [this]);
+		},
+		calculateTickRotation: function() {
+			var me = this;
+			var context = me.ctx;
+			var tickOpts = me.options.ticks;
+
+			// Get the width of each grid by calculating the difference
+			// between x offsets between 0 and 1.
+			var tickFont = parseFontOptions(tickOpts);
+			context.font = tickFont.font;
+
+			var labelRotation = tickOpts.minRotation || 0;
+
+			if (me.options.display && me.isHorizontal()) {
+				var originalLabelWidth = helpers.longestText(context, tickFont.font, me.ticks, me.longestTextCache);
+				var labelWidth = originalLabelWidth;
+				var cosRotation;
+				var sinRotation;
+
+				// Allow 3 pixels x2 padding either side for label readability
+				var tickWidth = me.getPixelForTick(1) - me.getPixelForTick(0) - 6;
+
+				// Max label rotation can be set or default to 90 - also act as a loop counter
+				while (labelWidth > tickWidth && labelRotation < tickOpts.maxRotation) {
+					var angleRadians = helpers.toRadians(labelRotation);
+					cosRotation = Math.cos(angleRadians);
+					sinRotation = Math.sin(angleRadians);
+
+					if (sinRotation * originalLabelWidth > me.maxHeight) {
+						// go back one step
+						labelRotation--;
+						break;
+					}
+
+					labelRotation++;
+					labelWidth = cosRotation * originalLabelWidth;
+				}
+			}
+
+			me.labelRotation = labelRotation;
+		},
+		afterCalculateTickRotation: function() {
+			helpers.callCallback(this.options.afterCalculateTickRotation, [this]);
+		},
+
+		//
+
+		beforeFit: function() {
+			helpers.callCallback(this.options.beforeFit, [this]);
+		},
+		fit: function() {
+			var me = this;
+			// Reset
+			var minSize = me.minSize = {
+				width: 0,
+				height: 0
+			};
+
+			var opts = me.options;
+			var tickOpts = opts.ticks;
+			var scaleLabelOpts = opts.scaleLabel;
+			var gridLineOpts = opts.gridLines;
+			var display = opts.display;
+			var isHorizontal = me.isHorizontal();
+
+			var tickFont = parseFontOptions(tickOpts);
+			var scaleLabelFontSize = parseFontOptions(scaleLabelOpts).size * 1.5;
+			var tickMarkLength = opts.gridLines.tickMarkLength;
+
+			// Width
+			if (isHorizontal) {
+				// subtract the margins to line up with the chartArea if we are a full width scale
+				minSize.width = me.isFullWidth() ? me.maxWidth - me.margins.left - me.margins.right : me.maxWidth;
+			} else {
+				minSize.width = display && gridLineOpts.drawTicks ? tickMarkLength : 0;
+			}
+
+			// height
+			if (isHorizontal) {
+				minSize.height = display && gridLineOpts.drawTicks ? tickMarkLength : 0;
+			} else {
+				minSize.height = me.maxHeight; // fill all the height
+			}
+
+			// Are we showing a title for the scale?
+			if (scaleLabelOpts.display && display) {
+				if (isHorizontal) {
+					minSize.height += scaleLabelFontSize;
+				} else {
+					minSize.width += scaleLabelFontSize;
+				}
+			}
+
+			// Don't bother fitting the ticks if we are not showing them
+			if (tickOpts.display && display) {
+				var largestTextWidth = helpers.longestText(me.ctx, tickFont.font, me.ticks, me.longestTextCache);
+				var tallestLabelHeightInLines = helpers.numberOfLabelLines(me.ticks);
+				var lineSpace = tickFont.size * 0.5;
+
+				if (isHorizontal) {
+					// A horizontal axis is more constrained by the height.
+					me.longestLabelWidth = largestTextWidth;
+
+					var angleRadians = helpers.toRadians(me.labelRotation);
+					var cosRotation = Math.cos(angleRadians);
+					var sinRotation = Math.sin(angleRadians);
+
+					// TODO - improve this calculation
+					var labelHeight = (sinRotation * largestTextWidth)
+						+ (tickFont.size * tallestLabelHeightInLines)
+						+ (lineSpace * tallestLabelHeightInLines);
+
+					minSize.height = Math.min(me.maxHeight, minSize.height + labelHeight);
+					me.ctx.font = tickFont.font;
+
+					var firstTick = me.ticks[0];
+					var firstLabelWidth = computeTextSize(me.ctx, firstTick, tickFont.font);
+
+					var lastTick = me.ticks[me.ticks.length - 1];
+					var lastLabelWidth = computeTextSize(me.ctx, lastTick, tickFont.font);
+
+					// Ensure that our ticks are always inside the canvas. When rotated, ticks are right aligned which means that the right padding is dominated
+					// by the font height
+					if (me.labelRotation !== 0) {
+						me.paddingLeft = opts.position === 'bottom'? (cosRotation * firstLabelWidth) + 3: (cosRotation * lineSpace) + 3; // add 3 px to move away from canvas edges
+						me.paddingRight = opts.position === 'bottom'? (cosRotation * lineSpace) + 3: (cosRotation * lastLabelWidth) + 3;
+					} else {
+						me.paddingLeft = firstLabelWidth / 2 + 3; // add 3 px to move away from canvas edges
+						me.paddingRight = lastLabelWidth / 2 + 3;
+					}
+				} else {
+					// A vertical axis is more constrained by the width. Labels are the dominant factor here, so get that length first
+					// Account for padding
+
+					if (tickOpts.mirror) {
+						largestTextWidth = 0;
+					} else {
+						largestTextWidth += me.options.ticks.padding;
+					}
+					minSize.width += largestTextWidth;
+					me.paddingTop = tickFont.size / 2;
+					me.paddingBottom = tickFont.size / 2;
+				}
+			}
+
+			me.handleMargins();
+
+			me.width = minSize.width;
+			me.height = minSize.height;
+		},
+
+		/**
+		 * Handle margins and padding interactions
+		 * @private
+		 */
+		handleMargins: function() {
+			var me = this;
+			if (me.margins) {
+				me.paddingLeft = Math.max(me.paddingLeft - me.margins.left, 0);
+				me.paddingTop = Math.max(me.paddingTop - me.margins.top, 0);
+				me.paddingRight = Math.max(me.paddingRight - me.margins.right, 0);
+				me.paddingBottom = Math.max(me.paddingBottom - me.margins.bottom, 0);
+			}
+		},
+
+		afterFit: function() {
+			helpers.callCallback(this.options.afterFit, [this]);
+		},
+
+		// Shared Methods
+		isHorizontal: function() {
+			return this.options.position === 'top' || this.options.position === 'bottom';
+		},
+		isFullWidth: function() {
+			return (this.options.fullWidth);
+		},
+
+		// Get the correct value. NaN bad inputs, If the value type is object get the x or y based on whether we are horizontal or not
+		getRightValue: function(rawValue) {
+			// Null and undefined values first
+			if (rawValue === null || typeof(rawValue) === 'undefined') {
+				return NaN;
+			}
+			// isNaN(object) returns true, so make sure NaN is checking for a number; Discard Infinite values
+			if (typeof(rawValue) === 'number' && !isFinite(rawValue)) {
+				return NaN;
+			}
+			// If it is in fact an object, dive in one more level
+			if (typeof(rawValue) === 'object') {
+				if ((rawValue instanceof Date) || (rawValue.isValid)) {
+					return rawValue;
+				}
+				return this.getRightValue(this.isHorizontal() ? rawValue.x : rawValue.y);
+			}
+
+			// Value is good, return it
+			return rawValue;
+		},
+
+		// Used to get the value to display in the tooltip for the data at the given index
+		// function getLabelForIndex(index, datasetIndex)
+		getLabelForIndex: helpers.noop,
+
+		// Used to get data value locations.  Value can either be an index or a numerical value
+		getPixelForValue: helpers.noop,
+
+		// Used to get the data value from a given pixel. This is the inverse of getPixelForValue
+		getValueForPixel: helpers.noop,
+
+		// Used for tick location, should
+		getPixelForTick: function(index, includeOffset) {
+			var me = this;
+			if (me.isHorizontal()) {
+				var innerWidth = me.width - (me.paddingLeft + me.paddingRight);
+				var tickWidth = innerWidth / Math.max((me.ticks.length - ((me.options.gridLines.offsetGridLines) ? 0 : 1)), 1);
+				var pixel = (tickWidth * index) + me.paddingLeft;
+
+				if (includeOffset) {
+					pixel += tickWidth / 2;
+				}
+
+				var finalVal = me.left + Math.round(pixel);
+				finalVal += me.isFullWidth() ? me.margins.left : 0;
+				return finalVal;
+			}
+			var innerHeight = me.height - (me.paddingTop + me.paddingBottom);
+			return me.top + (index * (innerHeight / (me.ticks.length - 1)));
+		},
+
+		// Utility for getting the pixel location of a percentage of scale
+		getPixelForDecimal: function(decimal /* , includeOffset*/) {
+			var me = this;
+			if (me.isHorizontal()) {
+				var innerWidth = me.width - (me.paddingLeft + me.paddingRight);
+				var valueOffset = (innerWidth * decimal) + me.paddingLeft;
+
+				var finalVal = me.left + Math.round(valueOffset);
+				finalVal += me.isFullWidth() ? me.margins.left : 0;
+				return finalVal;
+			}
+			return me.top + (decimal * me.height);
+		},
+
+		getBasePixel: function() {
+			return this.getPixelForValue(this.getBaseValue());
+		},
+
+		getBaseValue: function() {
+			var me = this;
+			var min = me.min;
+			var max = me.max;
+
+			return me.beginAtZero ? 0:
+				min < 0 && max < 0? max :
+				min > 0 && max > 0? min :
+				0;
+		},
+
+		// Actually draw the scale on the canvas
+		// @param {rectangle} chartArea : the area of the chart to draw full grid lines on
+		draw: function(chartArea) {
+			var me = this;
+			var options = me.options;
+			if (!options.display) {
+				return;
+			}
+
+			var context = me.ctx;
+			var globalDefaults = Chart.defaults.global;
+			var optionTicks = options.ticks;
+			var gridLines = options.gridLines;
+			var scaleLabel = options.scaleLabel;
+
+			var isRotated = me.labelRotation !== 0;
+			var skipRatio;
+			var useAutoskipper = optionTicks.autoSkip;
+			var isHorizontal = me.isHorizontal();
+
+			// figure out the maximum number of gridlines to show
+			var maxTicks;
+			if (optionTicks.maxTicksLimit) {
+				maxTicks = optionTicks.maxTicksLimit;
+			}
+
+			var tickFontColor = helpers.getValueOrDefault(optionTicks.fontColor, globalDefaults.defaultFontColor);
+			var tickFont = parseFontOptions(optionTicks);
+
+			var tl = gridLines.drawTicks ? gridLines.tickMarkLength : 0;
+			var borderDash = helpers.getValueOrDefault(gridLines.borderDash, globalDefaults.borderDash);
+			var borderDashOffset = helpers.getValueOrDefault(gridLines.borderDashOffset, globalDefaults.borderDashOffset);
+
+			var scaleLabelFontColor = helpers.getValueOrDefault(scaleLabel.fontColor, globalDefaults.defaultFontColor);
+			var scaleLabelFont = parseFontOptions(scaleLabel);
+
+			var labelRotationRadians = helpers.toRadians(me.labelRotation);
+			var cosRotation = Math.cos(labelRotationRadians);
+			var longestRotatedLabel = me.longestLabelWidth * cosRotation;
+
+			// Make sure we draw text in the correct color and font
+			context.fillStyle = tickFontColor;
+
+			var itemsToDraw = [];
+
+			if (isHorizontal) {
+				skipRatio = false;
+
+				// Only calculate the skip ratio with the half width of longestRotateLabel if we got an actual rotation
+				// See #2584
+				if (isRotated) {
+					longestRotatedLabel /= 2;
+				}
+
+				if ((longestRotatedLabel + optionTicks.autoSkipPadding) * me.ticks.length > (me.width - (me.paddingLeft + me.paddingRight))) {
+					skipRatio = 1 + Math.floor(((longestRotatedLabel + optionTicks.autoSkipPadding) * me.ticks.length) / (me.width - (me.paddingLeft + me.paddingRight)));
+				}
+
+				// if they defined a max number of optionTicks,
+				// increase skipRatio until that number is met
+				if (maxTicks && me.ticks.length > maxTicks) {
+					while (!skipRatio || me.ticks.length / (skipRatio || 1) > maxTicks) {
+						if (!skipRatio) {
+							skipRatio = 1;
+						}
+						skipRatio += 1;
+					}
+				}
+
+				if (!useAutoskipper) {
+					skipRatio = false;
+				}
+			}
+
+
+			var xTickStart = options.position === 'right' ? me.left : me.right - tl;
+			var xTickEnd = options.position === 'right' ? me.left + tl : me.right;
+			var yTickStart = options.position === 'bottom' ? me.top : me.bottom - tl;
+			var yTickEnd = options.position === 'bottom' ? me.top + tl : me.bottom;
+
+			helpers.each(me.ticks, function(label, index) {
+				// If the callback returned a null or undefined value, do not draw this line
+				if (label === undefined || label === null) {
+					return;
+				}
+
+				var isLastTick = me.ticks.length === index + 1;
+
+				// Since we always show the last tick,we need may need to hide the last shown one before
+				var shouldSkip = (skipRatio > 1 && index % skipRatio > 0) || (index % skipRatio === 0 && index + skipRatio >= me.ticks.length);
+				if (shouldSkip && !isLastTick || (label === undefined || label === null)) {
+					return;
+				}
+
+				var lineWidth, lineColor;
+				if (index === (typeof me.zeroLineIndex !== 'undefined' ? me.zeroLineIndex : 0)) {
+					// Draw the first index specially
+					lineWidth = gridLines.zeroLineWidth;
+					lineColor = gridLines.zeroLineColor;
+				} else {
+					lineWidth = helpers.getValueAtIndexOrDefault(gridLines.lineWidth, index);
+					lineColor = helpers.getValueAtIndexOrDefault(gridLines.color, index);
+				}
+
+				// Common properties
+				var tx1, ty1, tx2, ty2, x1, y1, x2, y2, labelX, labelY;
+				var textAlign = 'middle';
+				var textBaseline = 'middle';
+
+				if (isHorizontal) {
+
+					if (options.position === 'bottom') {
+						// bottom
+						textBaseline = !isRotated? 'top':'middle';
+						textAlign = !isRotated? 'center': 'right';
+						labelY = me.top + tl;
+					} else {
+						// top
+						textBaseline = !isRotated? 'bottom':'middle';
+						textAlign = !isRotated? 'center': 'left';
+						labelY = me.bottom - tl;
+					}
+
+					var xLineValue = me.getPixelForTick(index) + helpers.aliasPixel(lineWidth); // xvalues for grid lines
+					labelX = me.getPixelForTick(index, gridLines.offsetGridLines) + optionTicks.labelOffset; // x values for optionTicks (need to consider offsetLabel option)
+
+					tx1 = tx2 = x1 = x2 = xLineValue;
+					ty1 = yTickStart;
+					ty2 = yTickEnd;
+					y1 = chartArea.top;
+					y2 = chartArea.bottom;
+				} else {
+					var isLeft = options.position === 'left';
+					var tickPadding = optionTicks.padding;
+					var labelXOffset;
+
+					if (optionTicks.mirror) {
+						textAlign = isLeft ? 'left' : 'right';
+						labelXOffset = tickPadding;
+					} else {
+						textAlign = isLeft ? 'right' : 'left';
+						labelXOffset = tl + tickPadding;
+					}
+
+					labelX = isLeft ? me.right - labelXOffset : me.left + labelXOffset;
+
+					var yLineValue = me.getPixelForTick(index); // xvalues for grid lines
+					yLineValue += helpers.aliasPixel(lineWidth);
+					labelY = me.getPixelForTick(index, gridLines.offsetGridLines);
+
+					tx1 = xTickStart;
+					tx2 = xTickEnd;
+					x1 = chartArea.left;
+					x2 = chartArea.right;
+					ty1 = ty2 = y1 = y2 = yLineValue;
+				}
+
+				itemsToDraw.push({
+					tx1: tx1,
+					ty1: ty1,
+					tx2: tx2,
+					ty2: ty2,
+					x1: x1,
+					y1: y1,
+					x2: x2,
+					y2: y2,
+					labelX: labelX,
+					labelY: labelY,
+					glWidth: lineWidth,
+					glColor: lineColor,
+					glBorderDash: borderDash,
+					glBorderDashOffset: borderDashOffset,
+					rotation: -1 * labelRotationRadians,
+					label: label,
+					textBaseline: textBaseline,
+					textAlign: textAlign
+				});
+			});
+
+			// Draw all of the tick labels, tick marks, and grid lines at the correct places
+			helpers.each(itemsToDraw, function(itemToDraw) {
+				if (gridLines.display) {
+					context.save();
+					context.lineWidth = itemToDraw.glWidth;
+					context.strokeStyle = itemToDraw.glColor;
+					if (context.setLineDash) {
+						context.setLineDash(itemToDraw.glBorderDash);
+						context.lineDashOffset = itemToDraw.glBorderDashOffset;
+					}
+
+					context.beginPath();
+
+					if (gridLines.drawTicks) {
+						context.moveTo(itemToDraw.tx1, itemToDraw.ty1);
+						context.lineTo(itemToDraw.tx2, itemToDraw.ty2);
+					}
+
+					if (gridLines.drawOnChartArea) {
+						context.moveTo(itemToDraw.x1, itemToDraw.y1);
+						context.lineTo(itemToDraw.x2, itemToDraw.y2);
+					}
+
+					context.stroke();
+					context.restore();
+				}
+
+				if (optionTicks.display) {
+					context.save();
+					context.translate(itemToDraw.labelX, itemToDraw.labelY);
+					context.rotate(itemToDraw.rotation);
+					context.font = tickFont.font;
+					context.textBaseline = itemToDraw.textBaseline;
+					context.textAlign = itemToDraw.textAlign;
+
+					var label = itemToDraw.label;
+					if (helpers.isArray(label)) {
+						for (var i = 0, y = 0; i < label.length; ++i) {
+							// We just make sure the multiline element is a string here..
+							context.fillText('' + label[i], 0, y);
+							// apply same lineSpacing as calculated @ L#320
+							y += (tickFont.size * 1.5);
+						}
+					} else {
+						context.fillText(label, 0, 0);
+					}
+					context.restore();
+				}
+			});
+
+			if (scaleLabel.display) {
+				// Draw the scale label
+				var scaleLabelX;
+				var scaleLabelY;
+				var rotation = 0;
+
+				if (isHorizontal) {
+					scaleLabelX = me.left + ((me.right - me.left) / 2); // midpoint of the width
+					scaleLabelY = options.position === 'bottom' ? me.bottom - (scaleLabelFont.size / 2) : me.top + (scaleLabelFont.size / 2);
+				} else {
+					var isLeft = options.position === 'left';
+					scaleLabelX = isLeft ? me.left + (scaleLabelFont.size / 2) : me.right - (scaleLabelFont.size / 2);
+					scaleLabelY = me.top + ((me.bottom - me.top) / 2);
+					rotation = isLeft ? -0.5 * Math.PI : 0.5 * Math.PI;
+				}
+
+				context.save();
+				context.translate(scaleLabelX, scaleLabelY);
+				context.rotate(rotation);
+				context.textAlign = 'center';
+				context.textBaseline = 'middle';
+				context.fillStyle = scaleLabelFontColor; // render in correct colour
+				context.font = scaleLabelFont.font;
+				context.fillText(scaleLabel.labelString, 0, 0);
+				context.restore();
+			}
+
+			if (gridLines.drawBorder) {
+				// Draw the line at the edge of the axis
+				context.lineWidth = helpers.getValueAtIndexOrDefault(gridLines.lineWidth, 0);
+				context.strokeStyle = helpers.getValueAtIndexOrDefault(gridLines.color, 0);
+				var x1 = me.left,
+					x2 = me.right,
+					y1 = me.top,
+					y2 = me.bottom;
+
+				var aliasPixel = helpers.aliasPixel(context.lineWidth);
+				if (isHorizontal) {
+					y1 = y2 = options.position === 'top' ? me.bottom : me.top;
+					y1 += aliasPixel;
+					y2 += aliasPixel;
+				} else {
+					x1 = x2 = options.position === 'left' ? me.right : me.left;
+					x1 += aliasPixel;
+					x2 += aliasPixel;
+				}
+
+				context.beginPath();
+				context.moveTo(x1, y1);
+				context.lineTo(x2, y2);
+				context.stroke();
+			}
+		}
+	});
+};
+
+},{}],33:[function(require,module,exports){
+'use strict';
+
+module.exports = function(Chart) {
+
+	var helpers = Chart.helpers;
+
+	Chart.scaleService = {
+		// Scale registration object. Extensions can register new scale types (such as log or DB scales) and then
+		// use the new chart options to grab the correct scale
+		constructors: {},
+		// Use a registration function so that we can move to an ES6 map when we no longer need to support
+		// old browsers
+
+		// Scale config defaults
+		defaults: {},
+		registerScaleType: function(type, scaleConstructor, defaults) {
+			this.constructors[type] = scaleConstructor;
+			this.defaults[type] = helpers.clone(defaults);
+		},
+		getScaleConstructor: function(type) {
+			return this.constructors.hasOwnProperty(type) ? this.constructors[type] : undefined;
+		},
+		getScaleDefaults: function(type) {
+			// Return the scale defaults merged with the global settings so that we always use the latest ones
+			return this.defaults.hasOwnProperty(type) ? helpers.scaleMerge(Chart.defaults.scale, this.defaults[type]) : {};
+		},
+		updateScaleDefaults: function(type, additions) {
+			var defaults = this.defaults;
+			if (defaults.hasOwnProperty(type)) {
+				defaults[type] = helpers.extend(defaults[type], additions);
+			}
+		},
+		addScalesToLayout: function(chartInstance) {
+			// Adds each scale to the chart.boxes array to be sized accordingly
+			helpers.each(chartInstance.scales, function(scale) {
+				Chart.layoutService.addBox(chartInstance, scale);
+			});
+		}
+	};
+};
+
+},{}],34:[function(require,module,exports){
+'use strict';
+
+module.exports = function(Chart) {
+
+	var helpers = Chart.helpers;
+
+	/**
+	 * Namespace to hold static tick generation functions
+	 * @namespace Chart.Ticks
+	 */
+	Chart.Ticks = {
+		/**
+		 * Namespace to hold generators for different types of ticks
+		 * @namespace Chart.Ticks.generators
+		 */
+		generators: {
+			/**
+			 * Interface for the options provided to the numeric tick generator
+			 * @interface INumericTickGenerationOptions
+			 */
+			/**
+			 * The maximum number of ticks to display
+			 * @name INumericTickGenerationOptions#maxTicks
+			 * @type Number
+			 */
+			/**
+			 * The distance between each tick.
+			 * @name INumericTickGenerationOptions#stepSize
+			 * @type Number
+			 * @optional
+			 */
+			/**
+			 * Forced minimum for the ticks. If not specified, the minimum of the data range is used to calculate the tick minimum
+			 * @name INumericTickGenerationOptions#min
+			 * @type Number
+			 * @optional
+			 */
+			/**
+			 * The maximum value of the ticks. If not specified, the maximum of the data range is used to calculate the tick maximum
+			 * @name INumericTickGenerationOptions#max
+			 * @type Number
+			 * @optional
+			 */
+
+			/**
+			 * Generate a set of linear ticks
+			 * @method Chart.Ticks.generators.linear
+			 * @param generationOptions {INumericTickGenerationOptions} the options used to generate the ticks
+			 * @param dataRange {IRange} the range of the data
+			 * @returns {Array<Number>} array of tick values
+			 */
+			linear: function(generationOptions, dataRange) {
+				var ticks = [];
+				// To get a "nice" value for the tick spacing, we will use the appropriately named
+				// "nice number" algorithm. See http://stackoverflow.com/questions/8506881/nice-label-algorithm-for-charts-with-minimum-ticks
+				// for details.
+
+				var spacing;
+				if (generationOptions.stepSize && generationOptions.stepSize > 0) {
+					spacing = generationOptions.stepSize;
+				} else {
+					var niceRange = helpers.niceNum(dataRange.max - dataRange.min, false);
+					spacing = helpers.niceNum(niceRange / (generationOptions.maxTicks - 1), true);
+				}
+				var niceMin = Math.floor(dataRange.min / spacing) * spacing;
+				var niceMax = Math.ceil(dataRange.max / spacing) * spacing;
+
+				// If min, max and stepSize is set and they make an evenly spaced scale use it.
+				if (generationOptions.min && generationOptions.max && generationOptions.stepSize) {
+					// If very close to our whole number, use it.
+					if (helpers.almostWhole((generationOptions.max - generationOptions.min) / generationOptions.stepSize, spacing / 1000)) {
+						niceMin = generationOptions.min;
+						niceMax = generationOptions.max;
+					}
+				}
+
+				var numSpaces = (niceMax - niceMin) / spacing;
+				// If very close to our rounded value, use it.
+				if (helpers.almostEquals(numSpaces, Math.round(numSpaces), spacing / 1000)) {
+					numSpaces = Math.round(numSpaces);
+				} else {
+					numSpaces = Math.ceil(numSpaces);
+				}
+
+				// Put the values into the ticks array
+				ticks.push(generationOptions.min !== undefined ? generationOptions.min : niceMin);
+				for (var j = 1; j < numSpaces; ++j) {
+					ticks.push(niceMin + (j * spacing));
+				}
+				ticks.push(generationOptions.max !== undefined ? generationOptions.max : niceMax);
+
+				return ticks;
+			},
+
+			/**
+			 * Generate a set of logarithmic ticks
+			 * @method Chart.Ticks.generators.logarithmic
+			 * @param generationOptions {INumericTickGenerationOptions} the options used to generate the ticks
+			 * @param dataRange {IRange} the range of the data
+			 * @returns {Array<Number>} array of tick values
+			 */
+			logarithmic: function(generationOptions, dataRange) {
+				var ticks = [];
+				var getValueOrDefault = helpers.getValueOrDefault;
+
+				// Figure out what the max number of ticks we can support it is based on the size of
+				// the axis area. For now, we say that the minimum tick spacing in pixels must be 50
+				// We also limit the maximum number of ticks to 11 which gives a nice 10 squares on
+				// the graph
+				var tickVal = getValueOrDefault(generationOptions.min, Math.pow(10, Math.floor(helpers.log10(dataRange.min))));
+
+				var endExp = Math.floor(helpers.log10(dataRange.max));
+				var endSignificand = Math.ceil(dataRange.max / Math.pow(10, endExp));
+				var exp;
+				var significand;
+
+				if (tickVal === 0) {
+					exp = Math.floor(helpers.log10(dataRange.minNotZero));
+					significand = Math.floor(dataRange.minNotZero / Math.pow(10, exp));
+
+					ticks.push(tickVal);
+					tickVal = significand * Math.pow(10, exp);
+				} else {
+					exp = Math.floor(helpers.log10(tickVal));
+					significand = Math.floor(tickVal / Math.pow(10, exp));
+				}
+
+				do {
+					ticks.push(tickVal);
+
+					++significand;
+					if (significand === 10) {
+						significand = 1;
+						++exp;
+					}
+
+					tickVal = significand * Math.pow(10, exp);
+				} while (exp < endExp || (exp === endExp && significand < endSignificand));
+
+				var lastTick = getValueOrDefault(generationOptions.max, tickVal);
+				ticks.push(lastTick);
+
+				return ticks;
+			}
+		},
+
+		/**
+		 * Namespace to hold formatters for different types of ticks
+		 * @namespace Chart.Ticks.formatters
+		 */
+		formatters: {
+			/**
+			 * Formatter for value labels
+			 * @method Chart.Ticks.formatters.values
+			 * @param value the value to display
+			 * @return {String|Array} the label to display
+			 */
+			values: function(value) {
+				return helpers.isArray(value) ? value : '' + value;
+			},
+
+			/**
+			 * Formatter for linear numeric ticks
+			 * @method Chart.Ticks.formatters.linear
+			 * @param tickValue {Number} the value to be formatted
+			 * @param index {Number} the position of the tickValue parameter in the ticks array
+			 * @param ticks {Array<Number>} the list of ticks being converted
+			 * @return {String} string representation of the tickValue parameter
+			 */
+			linear: function(tickValue, index, ticks) {
+				// If we have lots of ticks, don't use the ones
+				var delta = ticks.length > 3 ? ticks[2] - ticks[1] : ticks[1] - ticks[0];
+
+				// If we have a number like 2.5 as the delta, figure out how many decimal places we need
+				if (Math.abs(delta) > 1) {
+					if (tickValue !== Math.floor(tickValue)) {
+						// not an integer
+						delta = tickValue - Math.floor(tickValue);
+					}
+				}
+
+				var logDelta = helpers.log10(Math.abs(delta));
+				var tickString = '';
+
+				if (tickValue !== 0) {
+					var numDecimal = -1 * Math.floor(logDelta);
+					numDecimal = Math.max(Math.min(numDecimal, 20), 0); // toFixed has a max of 20 decimal places
+					tickString = tickValue.toFixed(numDecimal);
+				} else {
+					tickString = '0'; // never show decimal places for 0
+				}
+
+				return tickString;
+			},
+
+			logarithmic: function(tickValue, index, ticks) {
+				var remain = tickValue / (Math.pow(10, Math.floor(helpers.log10(tickValue))));
+
+				if (tickValue === 0) {
+					return '0';
+				} else if (remain === 1 || remain === 2 || remain === 5 || index === 0 || index === ticks.length - 1) {
+					return tickValue.toExponential();
+				}
+				return '';
+			}
+		}
+	};
+};
+
+},{}],35:[function(require,module,exports){
+'use strict';
+
+module.exports = function(Chart) {
+
+	var helpers = Chart.helpers;
+
+	Chart.defaults.global.title = {
+		display: false,
+		position: 'top',
+		fullWidth: true, // marks that this box should take the full width of the canvas (pushing down other boxes)
+
+		fontStyle: 'bold',
+		padding: 10,
+
+		// actual title
+		text: ''
+	};
+
+	var noop = helpers.noop;
+	Chart.Title = Chart.Element.extend({
+
+		initialize: function(config) {
+			var me = this;
+			helpers.extend(me, config);
+
+			// Contains hit boxes for each dataset (in dataset order)
+			me.legendHitBoxes = [];
+		},
+
+		// These methods are ordered by lifecycle. Utilities then follow.
+
+		beforeUpdate: noop,
+		update: function(maxWidth, maxHeight, margins) {
+			var me = this;
+
+			// Update Lifecycle - Probably don't want to ever extend or overwrite this function ;)
+			me.beforeUpdate();
+
+			// Absorb the master measurements
+			me.maxWidth = maxWidth;
+			me.maxHeight = maxHeight;
+			me.margins = margins;
+
+			// Dimensions
+			me.beforeSetDimensions();
+			me.setDimensions();
+			me.afterSetDimensions();
+			// Labels
+			me.beforeBuildLabels();
+			me.buildLabels();
+			me.afterBuildLabels();
+
+			// Fit
+			me.beforeFit();
+			me.fit();
+			me.afterFit();
+			//
+			me.afterUpdate();
+
+			return me.minSize;
+
+		},
+		afterUpdate: noop,
+
+		//
+
+		beforeSetDimensions: noop,
+		setDimensions: function() {
+			var me = this;
+			// Set the unconstrained dimension before label rotation
+			if (me.isHorizontal()) {
+				// Reset position before calculating rotation
+				me.width = me.maxWidth;
+				me.left = 0;
+				me.right = me.width;
+			} else {
+				me.height = me.maxHeight;
+
+				// Reset position before calculating rotation
+				me.top = 0;
+				me.bottom = me.height;
+			}
+
+			// Reset padding
+			me.paddingLeft = 0;
+			me.paddingTop = 0;
+			me.paddingRight = 0;
+			me.paddingBottom = 0;
+
+			// Reset minSize
+			me.minSize = {
+				width: 0,
+				height: 0
+			};
+		},
+		afterSetDimensions: noop,
+
+		//
+
+		beforeBuildLabels: noop,
+		buildLabels: noop,
+		afterBuildLabels: noop,
+
+		//
+
+		beforeFit: noop,
+		fit: function() {
+			var me = this,
+				valueOrDefault = helpers.getValueOrDefault,
+				opts = me.options,
+				globalDefaults = Chart.defaults.global,
+				display = opts.display,
+				fontSize = valueOrDefault(opts.fontSize, globalDefaults.defaultFontSize),
+				minSize = me.minSize;
+
+			if (me.isHorizontal()) {
+				minSize.width = me.maxWidth; // fill all the width
+				minSize.height = display ? fontSize + (opts.padding * 2) : 0;
+			} else {
+				minSize.width = display ? fontSize + (opts.padding * 2) : 0;
+				minSize.height = me.maxHeight; // fill all the height
+			}
+
+			me.width = minSize.width;
+			me.height = minSize.height;
+
+		},
+		afterFit: noop,
+
+		// Shared Methods
+		isHorizontal: function() {
+			var pos = this.options.position;
+			return pos === 'top' || pos === 'bottom';
+		},
+
+		// Actually draw the title block on the canvas
+		draw: function() {
+			var me = this,
+				ctx = me.ctx,
+				valueOrDefault = helpers.getValueOrDefault,
+				opts = me.options,
+				globalDefaults = Chart.defaults.global;
+
+			if (opts.display) {
+				var fontSize = valueOrDefault(opts.fontSize, globalDefaults.defaultFontSize),
+					fontStyle = valueOrDefault(opts.fontStyle, globalDefaults.defaultFontStyle),
+					fontFamily = valueOrDefault(opts.fontFamily, globalDefaults.defaultFontFamily),
+					titleFont = helpers.fontString(fontSize, fontStyle, fontFamily),
+					rotation = 0,
+					titleX,
+					titleY,
+					top = me.top,
+					left = me.left,
+					bottom = me.bottom,
+					right = me.right,
+					maxWidth;
+
+				ctx.fillStyle = valueOrDefault(opts.fontColor, globalDefaults.defaultFontColor); // render in correct colour
+				ctx.font = titleFont;
+
+				// Horizontal
+				if (me.isHorizontal()) {
+					titleX = left + ((right - left) / 2); // midpoint of the width
+					titleY = top + ((bottom - top) / 2); // midpoint of the height
+					maxWidth = right - left;
+				} else {
+					titleX = opts.position === 'left' ? left + (fontSize / 2) : right - (fontSize / 2);
+					titleY = top + ((bottom - top) / 2);
+					maxWidth = bottom - top;
+					rotation = Math.PI * (opts.position === 'left' ? -0.5 : 0.5);
+				}
+
+				ctx.save();
+				ctx.translate(titleX, titleY);
+				ctx.rotate(rotation);
+				ctx.textAlign = 'center';
+				ctx.textBaseline = 'middle';
+				ctx.fillText(opts.text, 0, 0, maxWidth);
+				ctx.restore();
+			}
+		}
+	});
+
+	function createNewTitleBlockAndAttach(chartInstance, titleOpts) {
+		var title = new Chart.Title({
+			ctx: chartInstance.chart.ctx,
+			options: titleOpts,
+			chart: chartInstance
+		});
+		chartInstance.titleBlock = title;
+		Chart.layoutService.addBox(chartInstance, title);
+	}
+
+	// Register the title plugin
+	Chart.plugins.register({
+		beforeInit: function(chartInstance) {
+			var titleOpts = chartInstance.options.title;
+
+			if (titleOpts) {
+				createNewTitleBlockAndAttach(chartInstance, titleOpts);
+			}
+		},
+		beforeUpdate: function(chartInstance) {
+			var titleOpts = chartInstance.options.title;
+
+			if (titleOpts) {
+				titleOpts = helpers.configMerge(Chart.defaults.global.title, titleOpts);
+
+				if (chartInstance.titleBlock) {
+					chartInstance.titleBlock.options = titleOpts;
+				} else {
+					createNewTitleBlockAndAttach(chartInstance, titleOpts);
+				}
+			} else {
+				Chart.layoutService.removeBox(chartInstance, chartInstance.titleBlock);
+				delete chartInstance.titleBlock;
+			}
+		}
+	});
+};
+
+},{}],36:[function(require,module,exports){
+'use strict';
+
+module.exports = function(Chart) {
+
+	var helpers = Chart.helpers;
+
+	/**
+ 	 * Helper method to merge the opacity into a color
+ 	 */
+	function mergeOpacity(colorString, opacity) {
+		var color = helpers.color(colorString);
+		return color.alpha(opacity * color.alpha()).rgbaString();
+	}
+
+	Chart.defaults.global.tooltips = {
+		enabled: true,
+		custom: null,
+		mode: 'nearest',
+		position: 'average',
+		intersect: true,
+		backgroundColor: 'rgba(0,0,0,0.8)',
+		titleFontStyle: 'bold',
+		titleSpacing: 2,
+		titleMarginBottom: 6,
+		titleFontColor: '#fff',
+		titleAlign: 'left',
+		bodySpacing: 2,
+		bodyFontColor: '#fff',
+		bodyAlign: 'left',
+		footerFontStyle: 'bold',
+		footerSpacing: 2,
+		footerMarginTop: 6,
+		footerFontColor: '#fff',
+		footerAlign: 'left',
+		yPadding: 6,
+		xPadding: 6,
+		caretSize: 5,
+		cornerRadius: 6,
+		multiKeyBackground: '#fff',
+		displayColors: true,
+		callbacks: {
+			// Args are: (tooltipItems, data)
+			beforeTitle: helpers.noop,
+			title: function(tooltipItems, data) {
+				// Pick first xLabel for now
+				var title = '';
+				var labels = data.labels;
+				var labelCount = labels ? labels.length : 0;
+
+				if (tooltipItems.length > 0) {
+					var item = tooltipItems[0];
+
+					if (item.xLabel) {
+						title = item.xLabel;
+					} else if (labelCount > 0 && item.index < labelCount) {
+						title = labels[item.index];
+					}
+				}
+
+				return title;
+			},
+			afterTitle: helpers.noop,
+
+			// Args are: (tooltipItems, data)
+			beforeBody: helpers.noop,
+
+			// Args are: (tooltipItem, data)
+			beforeLabel: helpers.noop,
+			label: function(tooltipItem, data) {
+				var datasetLabel = data.datasets[tooltipItem.datasetIndex].label || '';
+				return datasetLabel + ': ' + tooltipItem.yLabel;
+			},
+			labelColor: function(tooltipItem, chartInstance) {
+				var meta = chartInstance.getDatasetMeta(tooltipItem.datasetIndex);
+				var activeElement = meta.data[tooltipItem.index];
+				var view = activeElement._view;
+				return {
+					borderColor: view.borderColor,
+					backgroundColor: view.backgroundColor
+				};
+			},
+			afterLabel: helpers.noop,
+
+			// Args are: (tooltipItems, data)
+			afterBody: helpers.noop,
+
+			// Args are: (tooltipItems, data)
+			beforeFooter: helpers.noop,
+			footer: helpers.noop,
+			afterFooter: helpers.noop
+		}
+	};
+
+	// Helper to push or concat based on if the 2nd parameter is an array or not
+	function pushOrConcat(base, toPush) {
+		if (toPush) {
+			if (helpers.isArray(toPush)) {
+				// base = base.concat(toPush);
+				Array.prototype.push.apply(base, toPush);
+			} else {
+				base.push(toPush);
+			}
+		}
+
+		return base;
+	}
+
+	// Private helper to create a tooltip item model
+	// @param element : the chart element (point, arc, bar) to create the tooltip item for
+	// @return : new tooltip item
+	function createTooltipItem(element) {
+		var xScale = element._xScale;
+		var yScale = element._yScale || element._scale; // handle radar || polarArea charts
+		var index = element._index,
+			datasetIndex = element._datasetIndex;
+
+		return {
+			xLabel: xScale ? xScale.getLabelForIndex(index, datasetIndex) : '',
+			yLabel: yScale ? yScale.getLabelForIndex(index, datasetIndex) : '',
+			index: index,
+			datasetIndex: datasetIndex,
+			x: element._model.x,
+			y: element._model.y
+		};
+	}
+
+	/**
+	 * Helper to get the reset model for the tooltip
+	 * @param tooltipOpts {Object} the tooltip options
+	 */
+	function getBaseModel(tooltipOpts) {
+		var globalDefaults = Chart.defaults.global;
+		var getValueOrDefault = helpers.getValueOrDefault;
+
+		return {
+			// Positioning
+			xPadding: tooltipOpts.xPadding,
+			yPadding: tooltipOpts.yPadding,
+			xAlign: tooltipOpts.xAlign,
+			yAlign: tooltipOpts.yAlign,
+
+			// Body
+			bodyFontColor: tooltipOpts.bodyFontColor,
+			_bodyFontFamily: getValueOrDefault(tooltipOpts.bodyFontFamily, globalDefaults.defaultFontFamily),
+			_bodyFontStyle: getValueOrDefault(tooltipOpts.bodyFontStyle, globalDefaults.defaultFontStyle),
+			_bodyAlign: tooltipOpts.bodyAlign,
+			bodyFontSize: getValueOrDefault(tooltipOpts.bodyFontSize, globalDefaults.defaultFontSize),
+			bodySpacing: tooltipOpts.bodySpacing,
+
+			// Title
+			titleFontColor: tooltipOpts.titleFontColor,
+			_titleFontFamily: getValueOrDefault(tooltipOpts.titleFontFamily, globalDefaults.defaultFontFamily),
+			_titleFontStyle: getValueOrDefault(tooltipOpts.titleFontStyle, globalDefaults.defaultFontStyle),
+			titleFontSize: getValueOrDefault(tooltipOpts.titleFontSize, globalDefaults.defaultFontSize),
+			_titleAlign: tooltipOpts.titleAlign,
+			titleSpacing: tooltipOpts.titleSpacing,
+			titleMarginBottom: tooltipOpts.titleMarginBottom,
+
+			// Footer
+			footerFontColor: tooltipOpts.footerFontColor,
+			_footerFontFamily: getValueOrDefault(tooltipOpts.footerFontFamily, globalDefaults.defaultFontFamily),
+			_footerFontStyle: getValueOrDefault(tooltipOpts.footerFontStyle, globalDefaults.defaultFontStyle),
+			footerFontSize: getValueOrDefault(tooltipOpts.footerFontSize, globalDefaults.defaultFontSize),
+			_footerAlign: tooltipOpts.footerAlign,
+			footerSpacing: tooltipOpts.footerSpacing,
+			footerMarginTop: tooltipOpts.footerMarginTop,
+
+			// Appearance
+			caretSize: tooltipOpts.caretSize,
+			cornerRadius: tooltipOpts.cornerRadius,
+			backgroundColor: tooltipOpts.backgroundColor,
+			opacity: 0,
+			legendColorBackground: tooltipOpts.multiKeyBackground,
+			displayColors: tooltipOpts.displayColors
+		};
+	}
+
+	/**
+	 * Get the size of the tooltip
+	 */
+	function getTooltipSize(tooltip, model) {
+		var ctx = tooltip._chart.ctx;
+
+		var height = model.yPadding * 2; // Tooltip Padding
+		var width = 0;
+
+		// Count of all lines in the body
+		var body = model.body;
+		var combinedBodyLength = body.reduce(function(count, bodyItem) {
+			return count + bodyItem.before.length + bodyItem.lines.length + bodyItem.after.length;
+		}, 0);
+		combinedBodyLength += model.beforeBody.length + model.afterBody.length;
+
+		var titleLineCount = model.title.length;
+		var footerLineCount = model.footer.length;
+		var titleFontSize = model.titleFontSize,
+			bodyFontSize = model.bodyFontSize,
+			footerFontSize = model.footerFontSize;
+
+		height += titleLineCount * titleFontSize; // Title Lines
+		height += titleLineCount ? (titleLineCount - 1) * model.titleSpacing : 0; // Title Line Spacing
+		height += titleLineCount ? model.titleMarginBottom : 0; // Title's bottom Margin
+		height += combinedBodyLength * bodyFontSize; // Body Lines
+		height += combinedBodyLength ? (combinedBodyLength - 1) * model.bodySpacing : 0; // Body Line Spacing
+		height += footerLineCount ? model.footerMarginTop : 0; // Footer Margin
+		height += footerLineCount * (footerFontSize); // Footer Lines
+		height += footerLineCount ? (footerLineCount - 1) * model.footerSpacing : 0; // Footer Line Spacing
+
+		// Title width
+		var widthPadding = 0;
+		var maxLineWidth = function(line) {
+			width = Math.max(width, ctx.measureText(line).width + widthPadding);
+		};
+
+		ctx.font = helpers.fontString(titleFontSize, model._titleFontStyle, model._titleFontFamily);
+		helpers.each(model.title, maxLineWidth);
+
+		// Body width
+		ctx.font = helpers.fontString(bodyFontSize, model._bodyFontStyle, model._bodyFontFamily);
+		helpers.each(model.beforeBody.concat(model.afterBody), maxLineWidth);
+
+		// Body lines may include some extra width due to the color box
+		widthPadding = model.displayColors ? (bodyFontSize + 2) : 0;
+		helpers.each(body, function(bodyItem) {
+			helpers.each(bodyItem.before, maxLineWidth);
+			helpers.each(bodyItem.lines, maxLineWidth);
+			helpers.each(bodyItem.after, maxLineWidth);
+		});
+
+		// Reset back to 0
+		widthPadding = 0;
+
+		// Footer width
+		ctx.font = helpers.fontString(footerFontSize, model._footerFontStyle, model._footerFontFamily);
+		helpers.each(model.footer, maxLineWidth);
+
+		// Add padding
+		width += 2 * model.xPadding;
+
+		return {
+			width: width,
+			height: height
+		};
+	}
+
+	/**
+	 * Helper to get the alignment of a tooltip given the size
+	 */
+	function determineAlignment(tooltip, size) {
+		var model = tooltip._model;
+		var chart = tooltip._chart;
+		var chartArea = tooltip._chartInstance.chartArea;
+		var xAlign = 'center';
+		var yAlign = 'center';
+
+		if (model.y < size.height) {
+			yAlign = 'top';
+		} else if (model.y > (chart.height - size.height)) {
+			yAlign = 'bottom';
+		}
+
+		var lf, rf; // functions to determine left, right alignment
+		var olf, orf; // functions to determine if left/right alignment causes tooltip to go outside chart
+		var yf; // function to get the y alignment if the tooltip goes outside of the left or right edges
+		var midX = (chartArea.left + chartArea.right) / 2;
+		var midY = (chartArea.top + chartArea.bottom) / 2;
+
+		if (yAlign === 'center') {
+			lf = function(x) {
+				return x <= midX;
+			};
+			rf = function(x) {
+				return x > midX;
+			};
+		} else {
+			lf = function(x) {
+				return x <= (size.width / 2);
+			};
+			rf = function(x) {
+				return x >= (chart.width - (size.width / 2));
+			};
+		}
+
+		olf = function(x) {
+			return x + size.width > chart.width;
+		};
+		orf = function(x) {
+			return x - size.width < 0;
+		};
+		yf = function(y) {
+			return y <= midY ? 'top' : 'bottom';
+		};
+
+		if (lf(model.x)) {
+			xAlign = 'left';
+
+			// Is tooltip too wide and goes over the right side of the chart.?
+			if (olf(model.x)) {
+				xAlign = 'center';
+				yAlign = yf(model.y);
+			}
+		} else if (rf(model.x)) {
+			xAlign = 'right';
+
+			// Is tooltip too wide and goes outside left edge of canvas?
+			if (orf(model.x)) {
+				xAlign = 'center';
+				yAlign = yf(model.y);
+			}
+		}
+
+		var opts = tooltip._options;
+		return {
+			xAlign: opts.xAlign ? opts.xAlign : xAlign,
+			yAlign: opts.yAlign ? opts.yAlign : yAlign
+		};
+	}
+
+	/**
+	 * @Helper to get the location a tooltip needs to be placed at given the initial position (via the vm) and the size and alignment
+	 */
+	function getBackgroundPoint(vm, size, alignment) {
+		// Background Position
+		var x = vm.x;
+		var y = vm.y;
+
+		var caretSize = vm.caretSize,
+			caretPadding = vm.caretPadding,
+			cornerRadius = vm.cornerRadius,
+			xAlign = alignment.xAlign,
+			yAlign = alignment.yAlign,
+			paddingAndSize = caretSize + caretPadding,
+			radiusAndPadding = cornerRadius + caretPadding;
+
+		if (xAlign === 'right') {
+			x -= size.width;
+		} else if (xAlign === 'center') {
+			x -= (size.width / 2);
+		}
+
+		if (yAlign === 'top') {
+			y += paddingAndSize;
+		} else if (yAlign === 'bottom') {
+			y -= size.height + paddingAndSize;
+		} else {
+			y -= (size.height / 2);
+		}
+
+		if (yAlign === 'center') {
+			if (xAlign === 'left') {
+				x += paddingAndSize;
+			} else if (xAlign === 'right') {
+				x -= paddingAndSize;
+			}
+		} else if (xAlign === 'left') {
+			x -= radiusAndPadding;
+		} else if (xAlign === 'right') {
+			x += radiusAndPadding;
+		}
+
+		return {
+			x: x,
+			y: y
+		};
+	}
+
+	Chart.Tooltip = Chart.Element.extend({
+		initialize: function() {
+			this._model = getBaseModel(this._options);
+		},
+
+		// Get the title
+		// Args are: (tooltipItem, data)
+		getTitle: function() {
+			var me = this;
+			var opts = me._options;
+			var callbacks = opts.callbacks;
+
+			var beforeTitle = callbacks.beforeTitle.apply(me, arguments),
+				title = callbacks.title.apply(me, arguments),
+				afterTitle = callbacks.afterTitle.apply(me, arguments);
+
+			var lines = [];
+			lines = pushOrConcat(lines, beforeTitle);
+			lines = pushOrConcat(lines, title);
+			lines = pushOrConcat(lines, afterTitle);
+
+			return lines;
+		},
+
+		// Args are: (tooltipItem, data)
+		getBeforeBody: function() {
+			var lines = this._options.callbacks.beforeBody.apply(this, arguments);
+			return helpers.isArray(lines) ? lines : lines !== undefined ? [lines] : [];
+		},
+
+		// Args are: (tooltipItem, data)
+		getBody: function(tooltipItems, data) {
+			var me = this;
+			var callbacks = me._options.callbacks;
+			var bodyItems = [];
+
+			helpers.each(tooltipItems, function(tooltipItem) {
+				var bodyItem = {
+					before: [],
+					lines: [],
+					after: []
+				};
+				pushOrConcat(bodyItem.before, callbacks.beforeLabel.call(me, tooltipItem, data));
+				pushOrConcat(bodyItem.lines, callbacks.label.call(me, tooltipItem, data));
+				pushOrConcat(bodyItem.after, callbacks.afterLabel.call(me, tooltipItem, data));
+
+				bodyItems.push(bodyItem);
+			});
+
+			return bodyItems;
+		},
+
+		// Args are: (tooltipItem, data)
+		getAfterBody: function() {
+			var lines = this._options.callbacks.afterBody.apply(this, arguments);
+			return helpers.isArray(lines) ? lines : lines !== undefined ? [lines] : [];
+		},
+
+		// Get the footer and beforeFooter and afterFooter lines
+		// Args are: (tooltipItem, data)
+		getFooter: function() {
+			var me = this;
+			var callbacks = me._options.callbacks;
+
+			var beforeFooter = callbacks.beforeFooter.apply(me, arguments);
+			var footer = callbacks.footer.apply(me, arguments);
+			var afterFooter = callbacks.afterFooter.apply(me, arguments);
+
+			var lines = [];
+			lines = pushOrConcat(lines, beforeFooter);
+			lines = pushOrConcat(lines, footer);
+			lines = pushOrConcat(lines, afterFooter);
+
+			return lines;
+		},
+
+		update: function(changed) {
+			var me = this;
+			var opts = me._options;
+
+			// Need to regenerate the model because its faster than using extend and it is necessary due to the optimization in Chart.Element.transition
+			// that does _view = _model if ease === 1. This causes the 2nd tooltip update to set properties in both the view and model at the same time
+			// which breaks any animations.
+			var existingModel = me._model;
+			var model = me._model = getBaseModel(opts);
+			var active = me._active;
+
+			var data = me._data;
+			var chartInstance = me._chartInstance;
+
+			// In the case where active.length === 0 we need to keep these at existing values for good animations
+			var alignment = {
+				xAlign: existingModel.xAlign,
+				yAlign: existingModel.yAlign
+			};
+			var backgroundPoint = {
+				x: existingModel.x,
+				y: existingModel.y
+			};
+			var tooltipSize = {
+				width: existingModel.width,
+				height: existingModel.height
+			};
+			var tooltipPosition = {
+				x: existingModel.caretX,
+				y: existingModel.caretY
+			};
+
+			var i, len;
+
+			if (active.length) {
+				model.opacity = 1;
+
+				var labelColors = [];
+				tooltipPosition = Chart.Tooltip.positioners[opts.position](active, me._eventPosition);
+
+				var tooltipItems = [];
+				for (i = 0, len = active.length; i < len; ++i) {
+					tooltipItems.push(createTooltipItem(active[i]));
+				}
+
+				// If the user provided a filter function, use it to modify the tooltip items
+				if (opts.filter) {
+					tooltipItems = tooltipItems.filter(function(a) {
+						return opts.filter(a, data);
+					});
+				}
+
+				// If the user provided a sorting function, use it to modify the tooltip items
+				if (opts.itemSort) {
+					tooltipItems = tooltipItems.sort(function(a, b) {
+						return opts.itemSort(a, b, data);
+					});
+				}
+
+				// Determine colors for boxes
+				helpers.each(tooltipItems, function(tooltipItem) {
+					labelColors.push(opts.callbacks.labelColor.call(me, tooltipItem, chartInstance));
+				});
+
+				// Build the Text Lines
+				model.title = me.getTitle(tooltipItems, data);
+				model.beforeBody = me.getBeforeBody(tooltipItems, data);
+				model.body = me.getBody(tooltipItems, data);
+				model.afterBody = me.getAfterBody(tooltipItems, data);
+				model.footer = me.getFooter(tooltipItems, data);
+
+				// Initial positioning and colors
+				model.x = Math.round(tooltipPosition.x);
+				model.y = Math.round(tooltipPosition.y);
+				model.caretPadding = helpers.getValueOrDefault(tooltipPosition.padding, 2);
+				model.labelColors = labelColors;
+
+				// data points
+				model.dataPoints = tooltipItems;
+
+				// We need to determine alignment of the tooltip
+				tooltipSize = getTooltipSize(this, model);
+				alignment = determineAlignment(this, tooltipSize);
+				// Final Size and Position
+				backgroundPoint = getBackgroundPoint(model, tooltipSize, alignment);
+			} else {
+				model.opacity = 0;
+			}
+
+			model.xAlign = alignment.xAlign;
+			model.yAlign = alignment.yAlign;
+			model.x = backgroundPoint.x;
+			model.y = backgroundPoint.y;
+			model.width = tooltipSize.width;
+			model.height = tooltipSize.height;
+
+			// Point where the caret on the tooltip points to
+			model.caretX = tooltipPosition.x;
+			model.caretY = tooltipPosition.y;
+
+			me._model = model;
+
+			if (changed && opts.custom) {
+				opts.custom.call(me, model);
+			}
+
+			return me;
+		},
+		drawCaret: function(tooltipPoint, size, opacity) {
+			var vm = this._view;
+			var ctx = this._chart.ctx;
+			var x1, x2, x3;
+			var y1, y2, y3;
+			var caretSize = vm.caretSize;
+			var cornerRadius = vm.cornerRadius;
+			var xAlign = vm.xAlign,
+				yAlign = vm.yAlign;
+			var ptX = tooltipPoint.x,
+				ptY = tooltipPoint.y;
+			var width = size.width,
+				height = size.height;
+
+			if (yAlign === 'center') {
+				// Left or right side
+				if (xAlign === 'left') {
+					x1 = ptX;
+					x2 = x1 - caretSize;
+					x3 = x1;
+				} else {
+					x1 = ptX + width;
+					x2 = x1 + caretSize;
+					x3 = x1;
+				}
+
+				y2 = ptY + (height / 2);
+				y1 = y2 - caretSize;
+				y3 = y2 + caretSize;
+			} else {
+				if (xAlign === 'left') {
+					x1 = ptX + cornerRadius;
+					x2 = x1 + caretSize;
+					x3 = x2 + caretSize;
+				} else if (xAlign === 'right') {
+					x1 = ptX + width - cornerRadius;
+					x2 = x1 - caretSize;
+					x3 = x2 - caretSize;
+				} else {
+					x2 = ptX + (width / 2);
+					x1 = x2 - caretSize;
+					x3 = x2 + caretSize;
+				}
+
+				if (yAlign === 'top') {
+					y1 = ptY;
+					y2 = y1 - caretSize;
+					y3 = y1;
+				} else {
+					y1 = ptY + height;
+					y2 = y1 + caretSize;
+					y3 = y1;
+				}
+			}
+
+			ctx.fillStyle = mergeOpacity(vm.backgroundColor, opacity);
+			ctx.beginPath();
+			ctx.moveTo(x1, y1);
+			ctx.lineTo(x2, y2);
+			ctx.lineTo(x3, y3);
+			ctx.closePath();
+			ctx.fill();
+		},
+		drawTitle: function(pt, vm, ctx, opacity) {
+			var title = vm.title;
+
+			if (title.length) {
+				ctx.textAlign = vm._titleAlign;
+				ctx.textBaseline = 'top';
+
+				var titleFontSize = vm.titleFontSize,
+					titleSpacing = vm.titleSpacing;
+
+				ctx.fillStyle = mergeOpacity(vm.titleFontColor, opacity);
+				ctx.font = helpers.fontString(titleFontSize, vm._titleFontStyle, vm._titleFontFamily);
+
+				var i, len;
+				for (i = 0, len = title.length; i < len; ++i) {
+					ctx.fillText(title[i], pt.x, pt.y);
+					pt.y += titleFontSize + titleSpacing; // Line Height and spacing
+
+					if (i + 1 === title.length) {
+						pt.y += vm.titleMarginBottom - titleSpacing; // If Last, add margin, remove spacing
+					}
+				}
+			}
+		},
+		drawBody: function(pt, vm, ctx, opacity) {
+			var bodyFontSize = vm.bodyFontSize;
+			var bodySpacing = vm.bodySpacing;
+			var body = vm.body;
+
+			ctx.textAlign = vm._bodyAlign;
+			ctx.textBaseline = 'top';
+
+			var textColor = mergeOpacity(vm.bodyFontColor, opacity);
+			ctx.fillStyle = textColor;
+			ctx.font = helpers.fontString(bodyFontSize, vm._bodyFontStyle, vm._bodyFontFamily);
+
+			// Before Body
+			var xLinePadding = 0;
+			var fillLineOfText = function(line) {
+				ctx.fillText(line, pt.x + xLinePadding, pt.y);
+				pt.y += bodyFontSize + bodySpacing;
+			};
+
+			// Before body lines
+			helpers.each(vm.beforeBody, fillLineOfText);
+
+			var drawColorBoxes = vm.displayColors;
+			xLinePadding = drawColorBoxes ? (bodyFontSize + 2) : 0;
+
+			// Draw body lines now
+			helpers.each(body, function(bodyItem, i) {
+				helpers.each(bodyItem.before, fillLineOfText);
+
+				helpers.each(bodyItem.lines, function(line) {
+					// Draw Legend-like boxes if needed
+					if (drawColorBoxes) {
+						// Fill a white rect so that colours merge nicely if the opacity is < 1
+						ctx.fillStyle = mergeOpacity(vm.legendColorBackground, opacity);
+						ctx.fillRect(pt.x, pt.y, bodyFontSize, bodyFontSize);
+
+						// Border
+						ctx.strokeStyle = mergeOpacity(vm.labelColors[i].borderColor, opacity);
+						ctx.strokeRect(pt.x, pt.y, bodyFontSize, bodyFontSize);
+
+						// Inner square
+						ctx.fillStyle = mergeOpacity(vm.labelColors[i].backgroundColor, opacity);
+						ctx.fillRect(pt.x + 1, pt.y + 1, bodyFontSize - 2, bodyFontSize - 2);
+
+						ctx.fillStyle = textColor;
+					}
+
+					fillLineOfText(line);
+				});
+
+				helpers.each(bodyItem.after, fillLineOfText);
+			});
+
+			// Reset back to 0 for after body
+			xLinePadding = 0;
+
+			// After body lines
+			helpers.each(vm.afterBody, fillLineOfText);
+			pt.y -= bodySpacing; // Remove last body spacing
+		},
+		drawFooter: function(pt, vm, ctx, opacity) {
+			var footer = vm.footer;
+
+			if (footer.length) {
+				pt.y += vm.footerMarginTop;
+
+				ctx.textAlign = vm._footerAlign;
+				ctx.textBaseline = 'top';
+
+				ctx.fillStyle = mergeOpacity(vm.footerFontColor, opacity);
+				ctx.font = helpers.fontString(vm.footerFontSize, vm._footerFontStyle, vm._footerFontFamily);
+
+				helpers.each(footer, function(line) {
+					ctx.fillText(line, pt.x, pt.y);
+					pt.y += vm.footerFontSize + vm.footerSpacing;
+				});
+			}
+		},
+		drawBackground: function(pt, vm, ctx, tooltipSize, opacity) {
+			ctx.fillStyle = mergeOpacity(vm.backgroundColor, opacity);
+			helpers.drawRoundedRectangle(ctx, pt.x, pt.y, tooltipSize.width, tooltipSize.height, vm.cornerRadius);
+			ctx.fill();
+		},
+		draw: function() {
+			var ctx = this._chart.ctx;
+			var vm = this._view;
+
+			if (vm.opacity === 0) {
+				return;
+			}
+
+			var tooltipSize = {
+				width: vm.width,
+				height: vm.height
+			};
+			var pt = {
+				x: vm.x,
+				y: vm.y
+			};
+
+			// IE11/Edge does not like very small opacities, so snap to 0
+			var opacity = Math.abs(vm.opacity < 1e-3) ? 0 : vm.opacity;
+
+			if (this._options.enabled) {
+				// Draw Background
+				this.drawBackground(pt, vm, ctx, tooltipSize, opacity);
+
+				// Draw Caret
+				this.drawCaret(pt, tooltipSize, opacity);
+
+				// Draw Title, Body, and Footer
+				pt.x += vm.xPadding;
+				pt.y += vm.yPadding;
+
+				// Titles
+				this.drawTitle(pt, vm, ctx, opacity);
+
+				// Body
+				this.drawBody(pt, vm, ctx, opacity);
+
+				// Footer
+				this.drawFooter(pt, vm, ctx, opacity);
+			}
+		},
+
+		/**
+		 * Handle an event
+		 * @private
+		 * @param {IEvent} event - The event to handle
+		 * @returns {Boolean} true if the tooltip changed
+		 */
+		handleEvent: function(e) {
+			var me = this;
+			var options = me._options;
+			var changed = false;
+
+			me._lastActive = me._lastActive || [];
+
+			// Find Active Elements for tooltips
+			if (e.type === 'mouseout') {
+				me._active = [];
+			} else {
+				me._active = me._chartInstance.getElementsAtEventForMode(e, options.mode, options);
+			}
+
+			// Remember Last Actives
+			changed = !helpers.arrayEquals(me._active, me._lastActive);
+			me._lastActive = me._active;
+
+			if (options.enabled || options.custom) {
+				me._eventPosition = {
+					x: e.x,
+					y: e.y
+				};
+
+				var model = me._model;
+				me.update(true);
+				me.pivot();
+
+				// See if our tooltip position changed
+				changed |= (model.x !== me._model.x) || (model.y !== me._model.y);
+			}
+
+			return changed;
+		}
+	});
+
+	/**
+	 * @namespace Chart.Tooltip.positioners
+	 */
+	Chart.Tooltip.positioners = {
+		/**
+		 * Average mode places the tooltip at the average position of the elements shown
+		 * @function Chart.Tooltip.positioners.average
+		 * @param elements {ChartElement[]} the elements being displayed in the tooltip
+		 * @returns {Point} tooltip position
+		 */
+		average: function(elements) {
+			if (!elements.length) {
+				return false;
+			}
+
+			var i, len;
+			var x = 0;
+			var y = 0;
+			var count = 0;
+
+			for (i = 0, len = elements.length; i < len; ++i) {
+				var el = elements[i];
+				if (el && el.hasValue()) {
+					var pos = el.tooltipPosition();
+					x += pos.x;
+					y += pos.y;
+					++count;
+				}
+			}
+
+			return {
+				x: Math.round(x / count),
+				y: Math.round(y / count)
+			};
+		},
+
+		/**
+		 * Gets the tooltip position nearest of the item nearest to the event position
+		 * @function Chart.Tooltip.positioners.nearest
+		 * @param elements {Chart.Element[]} the tooltip elements
+		 * @param eventPosition {Point} the position of the event in canvas coordinates
+		 * @returns {Point} the tooltip position
+		 */
+		nearest: function(elements, eventPosition) {
+			var x = eventPosition.x;
+			var y = eventPosition.y;
+
+			var nearestElement;
+			var minDistance = Number.POSITIVE_INFINITY;
+			var i, len;
+			for (i = 0, len = elements.length; i < len; ++i) {
+				var el = elements[i];
+				if (el && el.hasValue()) {
+					var center = el.getCenterPoint();
+					var d = helpers.distanceBetweenPoints(eventPosition, center);
+
+					if (d < minDistance) {
+						minDistance = d;
+						nearestElement = el;
+					}
+				}
+			}
+
+			if (nearestElement) {
+				var tp = nearestElement.tooltipPosition();
+				x = tp.x;
+				y = tp.y;
+			}
+
+			return {
+				x: x,
+				y: y
+			};
+		}
+	};
+};
+
+},{}],37:[function(require,module,exports){
+'use strict';
+
+module.exports = function(Chart) {
+
+	var helpers = Chart.helpers,
+		globalOpts = Chart.defaults.global;
+
+	globalOpts.elements.arc = {
+		backgroundColor: globalOpts.defaultColor,
+		borderColor: '#fff',
+		borderWidth: 2
+	};
+
+	Chart.elements.Arc = Chart.Element.extend({
+		inLabelRange: function(mouseX) {
+			var vm = this._view;
+
+			if (vm) {
+				return (Math.pow(mouseX - vm.x, 2) < Math.pow(vm.radius + vm.hoverRadius, 2));
+			}
+			return false;
+		},
+		inRange: function(chartX, chartY) {
+			var vm = this._view;
+
+			if (vm) {
+				var pointRelativePosition = helpers.getAngleFromPoint(vm, {
+						x: chartX,
+						y: chartY
+					}),
+					angle = pointRelativePosition.angle,
+					distance = pointRelativePosition.distance;
+
+				// Sanitise angle range
+				var startAngle = vm.startAngle;
+				var endAngle = vm.endAngle;
+				while (endAngle < startAngle) {
+					endAngle += 2.0 * Math.PI;
+				}
+				while (angle > endAngle) {
+					angle -= 2.0 * Math.PI;
+				}
+				while (angle < startAngle) {
+					angle += 2.0 * Math.PI;
+				}
+
+				// Check if within the range of the open/close angle
+				var betweenAngles = (angle >= startAngle && angle <= endAngle),
+					withinRadius = (distance >= vm.innerRadius && distance <= vm.outerRadius);
+
+				return (betweenAngles && withinRadius);
+			}
+			return false;
+		},
+		getCenterPoint: function() {
+			var vm = this._view;
+			var halfAngle = (vm.startAngle + vm.endAngle) / 2;
+			var halfRadius = (vm.innerRadius + vm.outerRadius) / 2;
+			return {
+				x: vm.x + Math.cos(halfAngle) * halfRadius,
+				y: vm.y + Math.sin(halfAngle) * halfRadius
+			};
+		},
+		getArea: function() {
+			var vm = this._view;
+			return Math.PI * ((vm.endAngle - vm.startAngle) / (2 * Math.PI)) * (Math.pow(vm.outerRadius, 2) - Math.pow(vm.innerRadius, 2));
+		},
+		tooltipPosition: function() {
+			var vm = this._view;
+
+			var centreAngle = vm.startAngle + ((vm.endAngle - vm.startAngle) / 2),
+				rangeFromCentre = (vm.outerRadius - vm.innerRadius) / 2 + vm.innerRadius;
+			return {
+				x: vm.x + (Math.cos(centreAngle) * rangeFromCentre),
+				y: vm.y + (Math.sin(centreAngle) * rangeFromCentre)
+			};
+		},
+		draw: function() {
+
+			var ctx = this._chart.ctx,
+				vm = this._view,
+				sA = vm.startAngle,
+				eA = vm.endAngle;
+
+			ctx.beginPath();
+
+			ctx.arc(vm.x, vm.y, vm.outerRadius, sA, eA);
+			ctx.arc(vm.x, vm.y, vm.innerRadius, eA, sA, true);
+
+			ctx.closePath();
+			ctx.strokeStyle = vm.borderColor;
+			ctx.lineWidth = vm.borderWidth;
+
+			ctx.fillStyle = vm.backgroundColor;
+
+			ctx.fill();
+			ctx.lineJoin = 'bevel';
+
+			if (vm.borderWidth) {
+				ctx.stroke();
+			}
+		}
+	});
+};
+
+},{}],38:[function(require,module,exports){
+'use strict';
+
+module.exports = function(Chart) {
+
+	var helpers = Chart.helpers;
+	var globalDefaults = Chart.defaults.global;
+
+	Chart.defaults.global.elements.line = {
+		tension: 0.4,
+		backgroundColor: globalDefaults.defaultColor,
+		borderWidth: 3,
+		borderColor: globalDefaults.defaultColor,
+		borderCapStyle: 'butt',
+		borderDash: [],
+		borderDashOffset: 0.0,
+		borderJoinStyle: 'miter',
+		capBezierPoints: true,
+		fill: true, // do we fill in the area between the line and its base axis
+	};
+
+	Chart.elements.Line = Chart.Element.extend({
+		draw: function() {
+			var me = this;
+			var vm = me._view;
+			var spanGaps = vm.spanGaps;
+			var fillPoint = vm.scaleZero;
+			var loop = me._loop;
+
+			// Handle different fill modes for cartesian lines
+			if (!loop) {
+				if (vm.fill === 'top') {
+					fillPoint = vm.scaleTop;
+				} else if (vm.fill === 'bottom') {
+					fillPoint = vm.scaleBottom;
+				}
+			}
+
+			var ctx = me._chart.ctx;
+			ctx.save();
+
+			// Helper function to draw a line to a point
+			function lineToPoint(previousPoint, point) {
+				var pointVM = point._view;
+				if (point._view.steppedLine === true) {
+					ctx.lineTo(pointVM.x, previousPoint._view.y);
+					ctx.lineTo(pointVM.x, pointVM.y);
+				} else if (point._view.tension === 0) {
+					ctx.lineTo(pointVM.x, pointVM.y);
+				} else {
+					ctx.bezierCurveTo(
+						previousPoint._view.controlPointNextX,
+						previousPoint._view.controlPointNextY,
+						pointVM.controlPointPreviousX,
+						pointVM.controlPointPreviousY,
+						pointVM.x,
+						pointVM.y
+					);
+				}
+			}
+
+			var points = me._children.slice(); // clone array
+			var lastDrawnIndex = -1;
+
+			// If we are looping, adding the first point again
+			if (loop && points.length) {
+				points.push(points[0]);
+			}
+
+			var index, current, previous, currentVM;
+
+			// Fill Line
+			if (points.length && vm.fill) {
+				ctx.beginPath();
+
+				for (index = 0; index < points.length; ++index) {
+					current = points[index];
+					previous = helpers.previousItem(points, index);
+					currentVM = current._view;
+
+					// First point moves to it's starting position no matter what
+					if (index === 0) {
+						if (loop) {
+							ctx.moveTo(fillPoint.x, fillPoint.y);
+						} else {
+							ctx.moveTo(currentVM.x, fillPoint);
+						}
+
+						if (!currentVM.skip) {
+							lastDrawnIndex = index;
+							ctx.lineTo(currentVM.x, currentVM.y);
+						}
+					} else {
+						previous = lastDrawnIndex === -1 ? previous : points[lastDrawnIndex];
+
+						if (currentVM.skip) {
+							// Only do this if this is the first point that is skipped
+							if (!spanGaps && lastDrawnIndex === (index - 1)) {
+								if (loop) {
+									ctx.lineTo(fillPoint.x, fillPoint.y);
+								} else {
+									ctx.lineTo(previous._view.x, fillPoint);
+								}
+							}
+						} else {
+							if (lastDrawnIndex !== (index - 1)) {
+								// There was a gap and this is the first point after the gap. If we've never drawn a point, this is a special case.
+								// If the first data point is NaN, then there is no real gap to skip
+								if (spanGaps && lastDrawnIndex !== -1) {
+									// We are spanning the gap, so simple draw a line to this point
+									lineToPoint(previous, current);
+								} else if (loop) {
+									ctx.lineTo(currentVM.x, currentVM.y);
+								} else {
+									ctx.lineTo(currentVM.x, fillPoint);
+									ctx.lineTo(currentVM.x, currentVM.y);
+								}
+							} else {
+								// Line to next point
+								lineToPoint(previous, current);
+							}
+							lastDrawnIndex = index;
+						}
+					}
+				}
+
+				if (!loop && lastDrawnIndex !== -1) {
+					ctx.lineTo(points[lastDrawnIndex]._view.x, fillPoint);
+				}
+
+				ctx.fillStyle = vm.backgroundColor || globalDefaults.defaultColor;
+				ctx.closePath();
+				ctx.fill();
+			}
+
+			// Stroke Line Options
+			var globalOptionLineElements = globalDefaults.elements.line;
+			ctx.lineCap = vm.borderCapStyle || globalOptionLineElements.borderCapStyle;
+
+			// IE 9 and 10 do not support line dash
+			if (ctx.setLineDash) {
+				ctx.setLineDash(vm.borderDash || globalOptionLineElements.borderDash);
+			}
+
+			ctx.lineDashOffset = vm.borderDashOffset || globalOptionLineElements.borderDashOffset;
+			ctx.lineJoin = vm.borderJoinStyle || globalOptionLineElements.borderJoinStyle;
+			ctx.lineWidth = vm.borderWidth || globalOptionLineElements.borderWidth;
+			ctx.strokeStyle = vm.borderColor || globalDefaults.defaultColor;
+
+			// Stroke Line
+			ctx.beginPath();
+			lastDrawnIndex = -1;
+
+			for (index = 0; index < points.length; ++index) {
+				current = points[index];
+				previous = helpers.previousItem(points, index);
+				currentVM = current._view;
+
+				// First point moves to it's starting position no matter what
+				if (index === 0) {
+					if (!currentVM.skip) {
+						ctx.moveTo(currentVM.x, currentVM.y);
+						lastDrawnIndex = index;
+					}
+				} else {
+					previous = lastDrawnIndex === -1 ? previous : points[lastDrawnIndex];
+
+					if (!currentVM.skip) {
+						if ((lastDrawnIndex !== (index - 1) && !spanGaps) || lastDrawnIndex === -1) {
+							// There was a gap and this is the first point after the gap
+							ctx.moveTo(currentVM.x, currentVM.y);
+						} else {
+							// Line to next point
+							lineToPoint(previous, current);
+						}
+						lastDrawnIndex = index;
+					}
+				}
+			}
+
+			ctx.stroke();
+			ctx.restore();
+		}
+	});
+};
+
+},{}],39:[function(require,module,exports){
+'use strict';
+
+module.exports = function(Chart) {
+
+	var helpers = Chart.helpers,
+		globalOpts = Chart.defaults.global,
+		defaultColor = globalOpts.defaultColor;
+
+	globalOpts.elements.point = {
+		radius: 3,
+		pointStyle: 'circle',
+		backgroundColor: defaultColor,
+		borderWidth: 1,
+		borderColor: defaultColor,
+		// Hover
+		hitRadius: 1,
+		hoverRadius: 4,
+		hoverBorderWidth: 1
+	};
+
+	function xRange(mouseX) {
+		var vm = this._view;
+		return vm ? (Math.pow(mouseX - vm.x, 2) < Math.pow(vm.radius + vm.hitRadius, 2)) : false;
+	}
+
+	function yRange(mouseY) {
+		var vm = this._view;
+		return vm ? (Math.pow(mouseY - vm.y, 2) < Math.pow(vm.radius + vm.hitRadius, 2)) : false;
+	}
+
+	Chart.elements.Point = Chart.Element.extend({
+		inRange: function(mouseX, mouseY) {
+			var vm = this._view;
+			return vm ? ((Math.pow(mouseX - vm.x, 2) + Math.pow(mouseY - vm.y, 2)) < Math.pow(vm.hitRadius + vm.radius, 2)) : false;
+		},
+
+		inLabelRange: xRange,
+		inXRange: xRange,
+		inYRange: yRange,
+
+		getCenterPoint: function() {
+			var vm = this._view;
+			return {
+				x: vm.x,
+				y: vm.y
+			};
+		},
+		getArea: function() {
+			return Math.PI * Math.pow(this._view.radius, 2);
+		},
+		tooltipPosition: function() {
+			var vm = this._view;
+			return {
+				x: vm.x,
+				y: vm.y,
+				padding: vm.radius + vm.borderWidth
+			};
+		},
+		draw: function(chartArea) {
+			var vm = this._view;
+			var model = this._model;
+			var ctx = this._chart.ctx;
+			var pointStyle = vm.pointStyle;
+			var radius = vm.radius;
+			var x = vm.x;
+			var y = vm.y;
+			var color = Chart.helpers.color;
+			var errMargin = 1.01; // 1.01 is margin for Accumulated error. (Especially Edge, IE.)
+			var ratio = 0;
+
+			if (vm.skip) {
+				return;
+			}
+
+			ctx.strokeStyle = vm.borderColor || defaultColor;
+			ctx.lineWidth = helpers.getValueOrDefault(vm.borderWidth, globalOpts.elements.point.borderWidth);
+			ctx.fillStyle = vm.backgroundColor || defaultColor;
+
+			// Cliping for Points.
+			// going out from inner charArea?
+			if ((chartArea !== undefined) && ((model.x < chartArea.left) || (chartArea.right*errMargin < model.x) || (model.y < chartArea.top) || (chartArea.bottom*errMargin < model.y))) {
+				// Point fade out
+				if (model.x < chartArea.left) {
+					ratio = (x - model.x) / (chartArea.left - model.x);
+				} else if (chartArea.right*errMargin < model.x) {
+					ratio = (model.x - x) / (model.x - chartArea.right);
+				} else if (model.y < chartArea.top) {
+					ratio = (y - model.y) / (chartArea.top - model.y);
+				} else if (chartArea.bottom*errMargin < model.y) {
+					ratio = (model.y - y) / (model.y - chartArea.bottom);
+				}
+				ratio = Math.round(ratio*100) / 100;
+				ctx.strokeStyle = color(ctx.strokeStyle).alpha(ratio).rgbString();
+				ctx.fillStyle = color(ctx.fillStyle).alpha(ratio).rgbString();
+			}
+
+			Chart.canvasHelpers.drawPoint(ctx, pointStyle, radius, x, y);
+		}
+	});
+};
+
+},{}],40:[function(require,module,exports){
+'use strict';
+
+module.exports = function(Chart) {
+
+	var globalOpts = Chart.defaults.global;
+
+	globalOpts.elements.rectangle = {
+		backgroundColor: globalOpts.defaultColor,
+		borderWidth: 0,
+		borderColor: globalOpts.defaultColor,
+		borderSkipped: 'bottom'
+	};
+
+	function isVertical(bar) {
+		return bar._view.width !== undefined;
+	}
+
+	/**
+	 * Helper function to get the bounds of the bar regardless of the orientation
+	 * @private
+	 * @param bar {Chart.Element.Rectangle} the bar
+	 * @return {Bounds} bounds of the bar
+	 */
+	function getBarBounds(bar) {
+		var vm = bar._view;
+		var x1, x2, y1, y2;
+
+		if (isVertical(bar)) {
+			// vertical
+			var halfWidth = vm.width / 2;
+			x1 = vm.x - halfWidth;
+			x2 = vm.x + halfWidth;
+			y1 = Math.min(vm.y, vm.base);
+			y2 = Math.max(vm.y, vm.base);
+		} else {
+			// horizontal bar
+			var halfHeight = vm.height / 2;
+			x1 = Math.min(vm.x, vm.base);
+			x2 = Math.max(vm.x, vm.base);
+			y1 = vm.y - halfHeight;
+			y2 = vm.y + halfHeight;
+		}
+
+		return {
+			left: x1,
+			top: y1,
+			right: x2,
+			bottom: y2
+		};
+	}
+
+	Chart.elements.Rectangle = Chart.Element.extend({
+		draw: function() {
+			var ctx = this._chart.ctx;
+			var vm = this._view;
+			var left, right, top, bottom, signX, signY, borderSkipped;
+			var borderWidth = vm.borderWidth;
+
+			if (!vm.horizontal) {
+				// bar
+				left = vm.x - vm.width / 2;
+				right = vm.x + vm.width / 2;
+				top = vm.y;
+				bottom = vm.base;
+				signX = 1;
+				signY = bottom > top? 1: -1;
+				borderSkipped = vm.borderSkipped || 'bottom';
+			} else {
+				// horizontal bar
+				left = vm.base;
+				right = vm.x;
+				top = vm.y - vm.height / 2;
+				bottom = vm.y + vm.height / 2;
+				signX = right > left? 1: -1;
+				signY = 1;
+				borderSkipped = vm.borderSkipped || 'left';
+			}
+
+			// Canvas doesn't allow us to stroke inside the width so we can
+			// adjust the sizes to fit if we're setting a stroke on the line
+			if (borderWidth) {
+				// borderWidth shold be less than bar width and bar height.
+				var barSize = Math.min(Math.abs(left - right), Math.abs(top - bottom));
+				borderWidth = borderWidth > barSize? barSize: borderWidth;
+				var halfStroke = borderWidth / 2;
+				// Adjust borderWidth when bar top position is near vm.base(zero).
+				var borderLeft = left + (borderSkipped !== 'left'? halfStroke * signX: 0);
+				var borderRight = right + (borderSkipped !== 'right'? -halfStroke * signX: 0);
+				var borderTop = top + (borderSkipped !== 'top'? halfStroke * signY: 0);
+				var borderBottom = bottom + (borderSkipped !== 'bottom'? -halfStroke * signY: 0);
+				// not become a vertical line?
+				if (borderLeft !== borderRight) {
+					top = borderTop;
+					bottom = borderBottom;
+				}
+				// not become a horizontal line?
+				if (borderTop !== borderBottom) {
+					left = borderLeft;
+					right = borderRight;
+				}
+			}
+
+			ctx.beginPath();
+			ctx.fillStyle = vm.backgroundColor;
+			ctx.strokeStyle = vm.borderColor;
+			ctx.lineWidth = borderWidth;
+
+			// Corner points, from bottom-left to bottom-right clockwise
+			// | 1 2 |
+			// | 0 3 |
+			var corners = [
+				[left, bottom],
+				[left, top],
+				[right, top],
+				[right, bottom]
+			];
+
+			// Find first (starting) corner with fallback to 'bottom'
+			var borders = ['bottom', 'left', 'top', 'right'];
+			var startCorner = borders.indexOf(borderSkipped, 0);
+			if (startCorner === -1) {
+				startCorner = 0;
+			}
+
+			function cornerAt(index) {
+				return corners[(startCorner + index) % 4];
+			}
+
+			// Draw rectangle from 'startCorner'
+			var corner = cornerAt(0);
+			ctx.moveTo(corner[0], corner[1]);
+
+			for (var i = 1; i < 4; i++) {
+				corner = cornerAt(i);
+				ctx.lineTo(corner[0], corner[1]);
+			}
+
+			ctx.fill();
+			if (borderWidth) {
+				ctx.stroke();
+			}
+		},
+		height: function() {
+			var vm = this._view;
+			return vm.base - vm.y;
+		},
+		inRange: function(mouseX, mouseY) {
+			var inRange = false;
+
+			if (this._view) {
+				var bounds = getBarBounds(this);
+				inRange = mouseX >= bounds.left && mouseX <= bounds.right && mouseY >= bounds.top && mouseY <= bounds.bottom;
+			}
+
+			return inRange;
+		},
+		inLabelRange: function(mouseX, mouseY) {
+			var me = this;
+			if (!me._view) {
+				return false;
+			}
+
+			var inRange = false;
+			var bounds = getBarBounds(me);
+
+			if (isVertical(me)) {
+				inRange = mouseX >= bounds.left && mouseX <= bounds.right;
+			} else {
+				inRange = mouseY >= bounds.top && mouseY <= bounds.bottom;
+			}
+
+			return inRange;
+		},
+		inXRange: function(mouseX) {
+			var bounds = getBarBounds(this);
+			return mouseX >= bounds.left && mouseX <= bounds.right;
+		},
+		inYRange: function(mouseY) {
+			var bounds = getBarBounds(this);
+			return mouseY >= bounds.top && mouseY <= bounds.bottom;
+		},
+		getCenterPoint: function() {
+			var vm = this._view;
+			var x, y;
+			if (isVertical(this)) {
+				x = vm.x;
+				y = (vm.y + vm.base) / 2;
+			} else {
+				x = (vm.x + vm.base) / 2;
+				y = vm.y;
+			}
+
+			return {x: x, y: y};
+		},
+		getArea: function() {
+			var vm = this._view;
+			return vm.width * Math.abs(vm.y - vm.base);
+		},
+		tooltipPosition: function() {
+			var vm = this._view;
+			return {
+				x: vm.x,
+				y: vm.y
+			};
+		}
+	});
+
+};
+
+},{}],41:[function(require,module,exports){
+'use strict';
+
+// Chart.Platform implementation for targeting a web browser
+module.exports = function(Chart) {
+	var helpers = Chart.helpers;
+
+	// DOM event types -> Chart.js event types.
+	// Note: only events with different types are mapped.
+	// https://developer.mozilla.org/en-US/docs/Web/Events
+	var eventTypeMap = {
+		// Touch events
+		touchstart: 'mousedown',
+		touchmove: 'mousemove',
+		touchend: 'mouseup',
+
+		// Pointer events
+		pointerenter: 'mouseenter',
+		pointerdown: 'mousedown',
+		pointermove: 'mousemove',
+		pointerup: 'mouseup',
+		pointerleave: 'mouseout',
+		pointerout: 'mouseout'
+	};
+
+	/**
+	 * The "used" size is the final value of a dimension property after all calculations have
+	 * been performed. This method uses the computed style of `element` but returns undefined
+	 * if the computed style is not expressed in pixels. That can happen in some cases where
+	 * `element` has a size relative to its parent and this last one is not yet displayed,
+	 * for example because of `display: none` on a parent node.
+	 * @see https://developer.mozilla.org/en-US/docs/Web/CSS/used_value
+	 * @returns {Number} Size in pixels or undefined if unknown.
+	 */
+	function readUsedSize(element, property) {
+		var value = helpers.getStyle(element, property);
+		var matches = value && value.match(/(\d+)px/);
+		return matches? Number(matches[1]) : undefined;
+	}
+
+	/**
+	 * Initializes the canvas style and render size without modifying the canvas display size,
+	 * since responsiveness is handled by the controller.resize() method. The config is used
+	 * to determine the aspect ratio to apply in case no explicit height has been specified.
+	 */
+	function initCanvas(canvas, config) {
+		var style = canvas.style;
+
+		// NOTE(SB) canvas.getAttribute('width') !== canvas.width: in the first case it
+		// returns null or '' if no explicit value has been set to the canvas attribute.
+		var renderHeight = canvas.getAttribute('height');
+		var renderWidth = canvas.getAttribute('width');
+
+		// Chart.js modifies some canvas values that we want to restore on destroy
+		canvas._chartjs = {
+			initial: {
+				height: renderHeight,
+				width: renderWidth,
+				style: {
+					display: style.display,
+					height: style.height,
+					width: style.width
+				}
+			}
+		};
+
+		// Force canvas to display as block to avoid extra space caused by inline
+		// elements, which would interfere with the responsive resize process.
+		// https://github.com/chartjs/Chart.js/issues/2538
+		style.display = style.display || 'block';
+
+		if (renderWidth === null || renderWidth === '') {
+			var displayWidth = readUsedSize(canvas, 'width');
+			if (displayWidth !== undefined) {
+				canvas.width = displayWidth;
+			}
+		}
+
+		if (renderHeight === null || renderHeight === '') {
+			if (canvas.style.height === '') {
+				// If no explicit render height and style height, let's apply the aspect ratio,
+				// which one can be specified by the user but also by charts as default option
+				// (i.e. options.aspectRatio). If not specified, use canvas aspect ratio of 2.
+				canvas.height = canvas.width / (config.options.aspectRatio || 2);
+			} else {
+				var displayHeight = readUsedSize(canvas, 'height');
+				if (displayWidth !== undefined) {
+					canvas.height = displayHeight;
+				}
+			}
+		}
+
+		return canvas;
+	}
+
+	function createEvent(type, chart, x, y, native) {
+		return {
+			type: type,
+			chart: chart,
+			native: native || null,
+			x: x !== undefined? x : null,
+			y: y !== undefined? y : null,
+		};
+	}
+
+	function fromNativeEvent(event, chart) {
+		var type = eventTypeMap[event.type] || event.type;
+		var pos = helpers.getRelativePosition(event, chart);
+		return createEvent(type, chart, pos.x, pos.y, event);
+	}
+
+	function createResizer(handler) {
+		var iframe = document.createElement('iframe');
+		iframe.className = 'chartjs-hidden-iframe';
+		iframe.style.cssText =
+			'display:block;'+
+			'overflow:hidden;'+
+			'border:0;'+
+			'margin:0;'+
+			'top:0;'+
+			'left:0;'+
+			'bottom:0;'+
+			'right:0;'+
+			'height:100%;'+
+			'width:100%;'+
+			'position:absolute;'+
+			'pointer-events:none;'+
+			'z-index:-1;';
+
+		// Prevent the iframe to gain focus on tab.
+		// https://github.com/chartjs/Chart.js/issues/3090
+		iframe.tabIndex = -1;
+
+		// If the iframe is re-attached to the DOM, the resize listener is removed because the
+		// content is reloaded, so make sure to install the handler after the iframe is loaded.
+		// https://github.com/chartjs/Chart.js/issues/3521
+		helpers.addEvent(iframe, 'load', function() {
+			helpers.addEvent(iframe.contentWindow || iframe, 'resize', handler);
+
+			// The iframe size might have changed while loading, which can also
+			// happen if the size has been changed while detached from the DOM.
+			handler();
+		});
+
+		return iframe;
+	}
+
+	function addResizeListener(node, listener, chart) {
+		var stub = node._chartjs = {
+			ticking: false
+		};
+
+		// Throttle the callback notification until the next animation frame.
+		var notify = function() {
+			if (!stub.ticking) {
+				stub.ticking = true;
+				helpers.requestAnimFrame.call(window, function() {
+					if (stub.resizer) {
+						stub.ticking = false;
+						return listener(createEvent('resize', chart));
+					}
+				});
+			}
+		};
+
+		// Let's keep track of this added iframe and thus avoid DOM query when removing it.
+		stub.resizer = createResizer(notify);
+
+		node.insertBefore(stub.resizer, node.firstChild);
+	}
+
+	function removeResizeListener(node) {
+		if (!node || !node._chartjs) {
+			return;
+		}
+
+		var resizer = node._chartjs.resizer;
+		if (resizer) {
+			resizer.parentNode.removeChild(resizer);
+			node._chartjs.resizer = null;
+		}
+
+		delete node._chartjs;
+	}
+
+	return {
+		acquireContext: function(item, config) {
+			if (typeof item === 'string') {
+				item = document.getElementById(item);
+			} else if (item.length) {
+				// Support for array based queries (such as jQuery)
+				item = item[0];
+			}
+
+			if (item && item.canvas) {
+				// Support for any object associated to a canvas (including a context2d)
+				item = item.canvas;
+			}
+
+			if (item instanceof HTMLCanvasElement) {
+				// To prevent canvas fingerprinting, some add-ons undefine the getContext
+				// method, for example: https://github.com/kkapsner/CanvasBlocker
+				// https://github.com/chartjs/Chart.js/issues/2807
+				var context = item.getContext && item.getContext('2d');
+				if (context instanceof CanvasRenderingContext2D) {
+					initCanvas(item, config);
+					return context;
+				}
+			}
+
+			return null;
+		},
+
+		releaseContext: function(context) {
+			var canvas = context.canvas;
+			if (!canvas._chartjs) {
+				return;
+			}
+
+			var initial = canvas._chartjs.initial;
+			['height', 'width'].forEach(function(prop) {
+				var value = initial[prop];
+				if (value === undefined || value === null) {
+					canvas.removeAttribute(prop);
+				} else {
+					canvas.setAttribute(prop, value);
+				}
+			});
+
+			helpers.each(initial.style || {}, function(value, key) {
+				canvas.style[key] = value;
+			});
+
+			// The canvas render size might have been changed (and thus the state stack discarded),
+			// we can't use save() and restore() to restore the initial state. So make sure that at
+			// least the canvas context is reset to the default state by setting the canvas width.
+			// https://www.w3.org/TR/2011/WD-html5-20110525/the-canvas-element.html
+			canvas.width = canvas.width;
+
+			delete canvas._chartjs;
+		},
+
+		addEventListener: function(chart, type, listener) {
+			var canvas = chart.chart.canvas;
+			if (type === 'resize') {
+				// Note: the resize event is not supported on all browsers.
+				addResizeListener(canvas.parentNode, listener, chart.chart);
+				return;
+			}
+
+			var stub = listener._chartjs || (listener._chartjs = {});
+			var proxies = stub.proxies || (stub.proxies = {});
+			var proxy = proxies[chart.id + '_' + type] = function(event) {
+				listener(fromNativeEvent(event, chart.chart));
+			};
+
+			helpers.addEvent(canvas, type, proxy);
+		},
+
+		removeEventListener: function(chart, type, listener) {
+			var canvas = chart.chart.canvas;
+			if (type === 'resize') {
+				// Note: the resize event is not supported on all browsers.
+				removeResizeListener(canvas.parentNode, listener);
+				return;
+			}
+
+			var stub = listener._chartjs || {};
+			var proxies = stub.proxies || {};
+			var proxy = proxies[chart.id + '_' + type];
+			if (!proxy) {
+				return;
+			}
+
+			helpers.removeEvent(canvas, type, proxy);
+		}
+	};
+};
+
+},{}],42:[function(require,module,exports){
+'use strict';
+
+// By default, select the browser (DOM) platform.
+// @TODO Make possible to select another platform at build time.
+var implementation = require(41);
+
+module.exports = function(Chart) {
+	/**
+	 * @namespace Chart.platform
+	 * @see https://chartjs.gitbooks.io/proposals/content/Platform.html
+	 * @since 2.4.0
+	 */
+	Chart.platform = {
+		/**
+		 * Called at chart construction time, returns a context2d instance implementing
+		 * the [W3C Canvas 2D Context API standard]{@link https://www.w3.org/TR/2dcontext/}.
+		 * @param {*} item - The native item from which to acquire context (platform specific)
+		 * @param {Object} options - The chart options
+		 * @returns {CanvasRenderingContext2D} context2d instance
+		 */
+		acquireContext: function() {},
+
+		/**
+		 * Called at chart destruction time, releases any resources associated to the context
+		 * previously returned by the acquireContext() method.
+		 * @param {CanvasRenderingContext2D} context - The context2d instance
+		 * @returns {Boolean} true if the method succeeded, else false
+		 */
+		releaseContext: function() {},
+
+		/**
+		 * Registers the specified listener on the given chart.
+		 * @param {Chart} chart - Chart from which to listen for event
+		 * @param {String} type - The ({@link IEvent}) type to listen for
+		 * @param {Function} listener - Receives a notification (an object that implements
+		 * the {@link IEvent} interface) when an event of the specified type occurs.
+		 */
+		addEventListener: function() {},
+
+		/**
+		 * Removes the specified listener previously registered with addEventListener.
+		 * @param {Chart} chart -Chart from which to remove the listener
+		 * @param {String} type - The ({@link IEvent}) type to remove
+		 * @param {Function} listener - The listener function to remove from the event target.
+		 */
+		removeEventListener: function() {}
+	};
+
+	/**
+	 * @interface IPlatform
+	 * Allows abstracting platform dependencies away from the chart
+	 * @borrows Chart.platform.acquireContext as acquireContext
+	 * @borrows Chart.platform.releaseContext as releaseContext
+	 * @borrows Chart.platform.addEventListener as addEventListener
+	 * @borrows Chart.platform.removeEventListener as removeEventListener
+	 */
+
+	/**
+	 * @interface IEvent
+	 * @prop {String} type - The event type name, possible values are:
+	 * 'contextmenu', 'mouseenter', 'mousedown', 'mousemove', 'mouseup', 'mouseout',
+	 * 'click', 'dblclick', 'keydown', 'keypress', 'keyup' and 'resize'
+	 * @prop {*} native - The original native event (null for emulated events, e.g. 'resize')
+	 * @prop {Number} x - The mouse x position, relative to the canvas (null for incompatible events)
+	 * @prop {Number} y - The mouse y position, relative to the canvas (null for incompatible events)
+	 */
+
+	Chart.helpers.extend(Chart.platform, implementation(Chart));
+};
+
+},{"41":41}],43:[function(require,module,exports){
+'use strict';
+
+module.exports = function(Chart) {
+
+	var helpers = Chart.helpers;
+	// Default config for a category scale
+	var defaultConfig = {
+		position: 'bottom'
+	};
+
+	var DatasetScale = Chart.Scale.extend({
+		/**
+		* Internal function to get the correct labels. If data.xLabels or data.yLabels are defined, use those
+		* else fall back to data.labels
+		* @private
+		*/
+		getLabels: function() {
+			var data = this.chart.data;
+			return (this.isHorizontal() ? data.xLabels : data.yLabels) || data.labels;
+		},
+		// Implement this so that
+		determineDataLimits: function() {
+			var me = this;
+			var labels = me.getLabels();
+			me.minIndex = 0;
+			me.maxIndex = labels.length - 1;
+			var findIndex;
+
+			if (me.options.ticks.min !== undefined) {
+				// user specified min value
+				findIndex = helpers.indexOf(labels, me.options.ticks.min);
+				me.minIndex = findIndex !== -1 ? findIndex : me.minIndex;
+			}
+
+			if (me.options.ticks.max !== undefined) {
+				// user specified max value
+				findIndex = helpers.indexOf(labels, me.options.ticks.max);
+				me.maxIndex = findIndex !== -1 ? findIndex : me.maxIndex;
+			}
+
+			me.min = labels[me.minIndex];
+			me.max = labels[me.maxIndex];
+		},
+
+		buildTicks: function() {
+			var me = this;
+			var labels = me.getLabels();
+			// If we are viewing some subset of labels, slice the original array
+			me.ticks = (me.minIndex === 0 && me.maxIndex === labels.length - 1) ? labels : labels.slice(me.minIndex, me.maxIndex + 1);
+		},
+
+		getLabelForIndex: function(index, datasetIndex) {
+			var me = this;
+			var data = me.chart.data;
+			var isHorizontal = me.isHorizontal();
+
+			if (data.yLabels && !isHorizontal) {
+				return me.getRightValue(data.datasets[datasetIndex].data[index]);
+			}
+			return me.ticks[index - me.minIndex];
+		},
+
+		// Used to get data value locations.  Value can either be an index or a numerical value
+		getPixelForValue: function(value, index, datasetIndex, includeOffset) {
+			var me = this;
+			// 1 is added because we need the length but we have the indexes
+			var offsetAmt = Math.max((me.maxIndex + 1 - me.minIndex - ((me.options.gridLines.offsetGridLines) ? 0 : 1)), 1);
+
+			if (value !== undefined && isNaN(index)) {
+				var labels = me.getLabels();
+				var idx = labels.indexOf(value);
+				index = idx !== -1 ? idx : index;
+			}
+
+			if (me.isHorizontal()) {
+				var valueWidth = me.width / offsetAmt;
+				var widthOffset = (valueWidth * (index - me.minIndex));
+
+				if (me.options.gridLines.offsetGridLines && includeOffset || me.maxIndex === me.minIndex && includeOffset) {
+					widthOffset += (valueWidth / 2);
+				}
+
+				return me.left + Math.round(widthOffset);
+			}
+			var valueHeight = me.height / offsetAmt;
+			var heightOffset = (valueHeight * (index - me.minIndex));
+
+			if (me.options.gridLines.offsetGridLines && includeOffset) {
+				heightOffset += (valueHeight / 2);
+			}
+
+			return me.top + Math.round(heightOffset);
+		},
+		getPixelForTick: function(index, includeOffset) {
+			return this.getPixelForValue(this.ticks[index], index + this.minIndex, null, includeOffset);
+		},
+		getValueForPixel: function(pixel) {
+			var me = this;
+			var value;
+			var offsetAmt = Math.max((me.ticks.length - ((me.options.gridLines.offsetGridLines) ? 0 : 1)), 1);
+			var horz = me.isHorizontal();
+			var valueDimension = (horz ? me.width : me.height) / offsetAmt;
+
+			pixel -= horz ? me.left : me.top;
+
+			if (me.options.gridLines.offsetGridLines) {
+				pixel -= (valueDimension / 2);
+			}
+
+			if (pixel <= 0) {
+				value = 0;
+			} else {
+				value = Math.round(pixel / valueDimension);
+			}
+
+			return value;
+		},
+		getBasePixel: function() {
+			return this.bottom;
+		}
+	});
+
+	Chart.scaleService.registerScaleType('category', DatasetScale, defaultConfig);
+
+};
+
+},{}],44:[function(require,module,exports){
+'use strict';
+
+module.exports = function(Chart) {
+
+	var helpers = Chart.helpers;
+
+	var defaultConfig = {
+		position: 'left',
+		ticks: {
+			callback: Chart.Ticks.formatters.linear
+		}
+	};
+
+	var LinearScale = Chart.LinearScaleBase.extend({
+		determineDataLimits: function() {
+			var me = this;
+			var opts = me.options;
+			var chart = me.chart;
+			var data = chart.data;
+			var datasets = data.datasets;
+			var isHorizontal = me.isHorizontal();
+
+			function IDMatches(meta) {
+				return isHorizontal ? meta.xAxisID === me.id : meta.yAxisID === me.id;
+			}
+
+			// First Calculate the range
+			me.min = null;
+			me.max = null;
+
+			var hasStacks = opts.stacked;
+			if (hasStacks === undefined) {
+				helpers.each(datasets, function(dataset, datasetIndex) {
+					if (hasStacks) {
+						return;
+					}
+
+					var meta = chart.getDatasetMeta(datasetIndex);
+					if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta) &&
+						meta.stack !== undefined) {
+						hasStacks = true;
+					}
+				});
+			}
+
+			if (opts.stacked || hasStacks) {
+				var valuesPerStack = {};
+
+				helpers.each(datasets, function(dataset, datasetIndex) {
+					var meta = chart.getDatasetMeta(datasetIndex);
+					var key = [
+						meta.type,
+						// we have a separate stack for stack=undefined datasets when the opts.stacked is undefined
+						((opts.stacked === undefined && meta.stack === undefined) ? datasetIndex : ''),
+						meta.stack
+					].join('.');
+
+					if (valuesPerStack[key] === undefined) {
+						valuesPerStack[key] = {
+							positiveValues: [],
+							negativeValues: []
+						};
+					}
+
+					// Store these per type
+					var positiveValues = valuesPerStack[key].positiveValues;
+					var negativeValues = valuesPerStack[key].negativeValues;
+
+					if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) {
+						helpers.each(dataset.data, function(rawValue, index) {
+							var value = +me.getRightValue(rawValue);
+							if (isNaN(value) || meta.data[index].hidden) {
+								return;
+							}
+
+							positiveValues[index] = positiveValues[index] || 0;
+							negativeValues[index] = negativeValues[index] || 0;
+
+							if (opts.relativePoints) {
+								positiveValues[index] = 100;
+							} else if (value < 0) {
+								negativeValues[index] += value;
+							} else {
+								positiveValues[index] += value;
+							}
+						});
+					}
+				});
+
+				helpers.each(valuesPerStack, function(valuesForType) {
+					var values = valuesForType.positiveValues.concat(valuesForType.negativeValues);
+					var minVal = helpers.min(values);
+					var maxVal = helpers.max(values);
+					me.min = me.min === null ? minVal : Math.min(me.min, minVal);
+					me.max = me.max === null ? maxVal : Math.max(me.max, maxVal);
+				});
+
+			} else {
+				helpers.each(datasets, function(dataset, datasetIndex) {
+					var meta = chart.getDatasetMeta(datasetIndex);
+					if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) {
+						helpers.each(dataset.data, function(rawValue, index) {
+							var value = +me.getRightValue(rawValue);
+							if (isNaN(value) || meta.data[index].hidden) {
+								return;
+							}
+
+							if (me.min === null) {
+								me.min = value;
+							} else if (value < me.min) {
+								me.min = value;
+							}
+
+							if (me.max === null) {
+								me.max = value;
+							} else if (value > me.max) {
+								me.max = value;
+							}
+						});
+					}
+				});
+			}
+
+			// Common base implementation to handle ticks.min, ticks.max, ticks.beginAtZero
+			this.handleTickRangeOptions();
+		},
+		getTickLimit: function() {
+			var maxTicks;
+			var me = this;
+			var tickOpts = me.options.ticks;
+
+			if (me.isHorizontal()) {
+				maxTicks = Math.min(tickOpts.maxTicksLimit ? tickOpts.maxTicksLimit : 11, Math.ceil(me.width / 50));
+			} else {
+				// The factor of 2 used to scale the font size has been experimentally determined.
+				var tickFontSize = helpers.getValueOrDefault(tickOpts.fontSize, Chart.defaults.global.defaultFontSize);
+				maxTicks = Math.min(tickOpts.maxTicksLimit ? tickOpts.maxTicksLimit : 11, Math.ceil(me.height / (2 * tickFontSize)));
+			}
+
+			return maxTicks;
+		},
+		// Called after the ticks are built. We need
+		handleDirectionalChanges: function() {
+			if (!this.isHorizontal()) {
+				// We are in a vertical orientation. The top value is the highest. So reverse the array
+				this.ticks.reverse();
+			}
+		},
+		getLabelForIndex: function(index, datasetIndex) {
+			return +this.getRightValue(this.chart.data.datasets[datasetIndex].data[index]);
+		},
+		// Utils
+		getPixelForValue: function(value) {
+			// This must be called after fit has been run so that
+			// this.left, this.top, this.right, and this.bottom have been defined
+			var me = this;
+			var start = me.start;
+
+			var rightValue = +me.getRightValue(value);
+			var pixel;
+			var range = me.end - start;
+
+			if (me.isHorizontal()) {
+				pixel = me.left + (me.width / range * (rightValue - start));
+				return Math.round(pixel);
+			}
+
+			pixel = me.bottom - (me.height / range * (rightValue - start));
+			return Math.round(pixel);
+		},
+		getValueForPixel: function(pixel) {
+			var me = this;
+			var isHorizontal = me.isHorizontal();
+			var innerDimension = isHorizontal ? me.width : me.height;
+			var offset = (isHorizontal ? pixel - me.left : me.bottom - pixel) / innerDimension;
+			return me.start + ((me.end - me.start) * offset);
+		},
+		getPixelForTick: function(index) {
+			return this.getPixelForValue(this.ticksAsNumbers[index]);
+		}
+	});
+	Chart.scaleService.registerScaleType('linear', LinearScale, defaultConfig);
+
+};
+
+},{}],45:[function(require,module,exports){
+'use strict';
+
+module.exports = function(Chart) {
+
+	var helpers = Chart.helpers,
+		noop = helpers.noop;
+
+	Chart.LinearScaleBase = Chart.Scale.extend({
+		handleTickRangeOptions: function() {
+			var me = this;
+			var opts = me.options;
+			var tickOpts = opts.ticks;
+
+			// If we are forcing it to begin at 0, but 0 will already be rendered on the chart,
+			// do nothing since that would make the chart weird. If the user really wants a weird chart
+			// axis, they can manually override it
+			if (tickOpts.beginAtZero) {
+				var minSign = helpers.sign(me.min);
+				var maxSign = helpers.sign(me.max);
+
+				if (minSign < 0 && maxSign < 0) {
+					// move the top up to 0
+					me.max = 0;
+				} else if (minSign > 0 && maxSign > 0) {
+					// move the bottom down to 0
+					me.min = 0;
+				}
+			}
+
+			if (tickOpts.min !== undefined) {
+				me.min = tickOpts.min;
+			} else if (tickOpts.suggestedMin !== undefined) {
+				me.min = Math.min(me.min, tickOpts.suggestedMin);
+			}
+
+			if (tickOpts.max !== undefined) {
+				me.max = tickOpts.max;
+			} else if (tickOpts.suggestedMax !== undefined) {
+				me.max = Math.max(me.max, tickOpts.suggestedMax);
+			}
+
+			if (me.min === me.max) {
+				me.max++;
+
+				if (!tickOpts.beginAtZero) {
+					me.min--;
+				}
+			}
+		},
+		getTickLimit: noop,
+		handleDirectionalChanges: noop,
+
+		buildTicks: function() {
+			var me = this;
+			var opts = me.options;
+			var tickOpts = opts.ticks;
+
+			// Figure out what the max number of ticks we can support it is based on the size of
+			// the axis area. For now, we say that the minimum tick spacing in pixels must be 50
+			// We also limit the maximum number of ticks to 11 which gives a nice 10 squares on
+			// the graph. Make sure we always have at least 2 ticks
+			var maxTicks = me.getTickLimit();
+			maxTicks = Math.max(2, maxTicks);
+
+			var numericGeneratorOptions = {
+				maxTicks: maxTicks,
+				min: tickOpts.min,
+				max: tickOpts.max,
+				stepSize: helpers.getValueOrDefault(tickOpts.fixedStepSize, tickOpts.stepSize)
+			};
+			var ticks = me.ticks = Chart.Ticks.generators.linear(numericGeneratorOptions, me);
+
+			me.handleDirectionalChanges();
+
+			// At this point, we need to update our max and min given the tick values since we have expanded the
+			// range of the scale
+			me.max = helpers.max(ticks);
+			me.min = helpers.min(ticks);
+
+			if (tickOpts.reverse) {
+				ticks.reverse();
+
+				me.start = me.max;
+				me.end = me.min;
+			} else {
+				me.start = me.min;
+				me.end = me.max;
+			}
+		},
+		convertTicksToLabels: function() {
+			var me = this;
+			me.ticksAsNumbers = me.ticks.slice();
+			me.zeroLineIndex = me.ticks.indexOf(0);
+
+			Chart.Scale.prototype.convertTicksToLabels.call(me);
+		}
+	});
+};
+
+},{}],46:[function(require,module,exports){
+'use strict';
+
+module.exports = function(Chart) {
+
+	var helpers = Chart.helpers;
+
+	var defaultConfig = {
+		position: 'left',
+
+		// label settings
+		ticks: {
+			callback: Chart.Ticks.formatters.logarithmic
+		}
+	};
+
+	var LogarithmicScale = Chart.Scale.extend({
+		determineDataLimits: function() {
+			var me = this;
+			var opts = me.options;
+			var tickOpts = opts.ticks;
+			var chart = me.chart;
+			var data = chart.data;
+			var datasets = data.datasets;
+			var getValueOrDefault = helpers.getValueOrDefault;
+			var isHorizontal = me.isHorizontal();
+			function IDMatches(meta) {
+				return isHorizontal ? meta.xAxisID === me.id : meta.yAxisID === me.id;
+			}
+
+			// Calculate Range
+			me.min = null;
+			me.max = null;
+			me.minNotZero = null;
+
+			var hasStacks = opts.stacked;
+			if (hasStacks === undefined) {
+				helpers.each(datasets, function(dataset, datasetIndex) {
+					if (hasStacks) {
+						return;
+					}
+
+					var meta = chart.getDatasetMeta(datasetIndex);
+					if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta) &&
+						meta.stack !== undefined) {
+						hasStacks = true;
+					}
+				});
+			}
+
+			if (opts.stacked || hasStacks) {
+				var valuesPerStack = {};
+
+				helpers.each(datasets, function(dataset, datasetIndex) {
+					var meta = chart.getDatasetMeta(datasetIndex);
+					var key = [
+						meta.type,
+						// we have a separate stack for stack=undefined datasets when the opts.stacked is undefined
+						((opts.stacked === undefined && meta.stack === undefined) ? datasetIndex : ''),
+						meta.stack
+					].join('.');
+
+					if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) {
+						if (valuesPerStack[key] === undefined) {
+							valuesPerStack[key] = [];
+						}
+
+						helpers.each(dataset.data, function(rawValue, index) {
+							var values = valuesPerStack[key];
+							var value = +me.getRightValue(rawValue);
+							if (isNaN(value) || meta.data[index].hidden) {
+								return;
+							}
+
+							values[index] = values[index] || 0;
+
+							if (opts.relativePoints) {
+								values[index] = 100;
+							} else {
+								// Don't need to split positive and negative since the log scale can't handle a 0 crossing
+								values[index] += value;
+							}
+						});
+					}
+				});
+
+				helpers.each(valuesPerStack, function(valuesForType) {
+					var minVal = helpers.min(valuesForType);
+					var maxVal = helpers.max(valuesForType);
+					me.min = me.min === null ? minVal : Math.min(me.min, minVal);
+					me.max = me.max === null ? maxVal : Math.max(me.max, maxVal);
+				});
+
+			} else {
+				helpers.each(datasets, function(dataset, datasetIndex) {
+					var meta = chart.getDatasetMeta(datasetIndex);
+					if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) {
+						helpers.each(dataset.data, function(rawValue, index) {
+							var value = +me.getRightValue(rawValue);
+							if (isNaN(value) || meta.data[index].hidden) {
+								return;
+							}
+
+							if (me.min === null) {
+								me.min = value;
+							} else if (value < me.min) {
+								me.min = value;
+							}
+
+							if (me.max === null) {
+								me.max = value;
+							} else if (value > me.max) {
+								me.max = value;
+							}
+
+							if (value !== 0 && (me.minNotZero === null || value < me.minNotZero)) {
+								me.minNotZero = value;
+							}
+						});
+					}
+				});
+			}
+
+			me.min = getValueOrDefault(tickOpts.min, me.min);
+			me.max = getValueOrDefault(tickOpts.max, me.max);
+
+			if (me.min === me.max) {
+				if (me.min !== 0 && me.min !== null) {
+					me.min = Math.pow(10, Math.floor(helpers.log10(me.min)) - 1);
+					me.max = Math.pow(10, Math.floor(helpers.log10(me.max)) + 1);
+				} else {
+					me.min = 1;
+					me.max = 10;
+				}
+			}
+		},
+		buildTicks: function() {
+			var me = this;
+			var opts = me.options;
+			var tickOpts = opts.ticks;
+
+			var generationOptions = {
+				min: tickOpts.min,
+				max: tickOpts.max
+			};
+			var ticks = me.ticks = Chart.Ticks.generators.logarithmic(generationOptions, me);
+
+			if (!me.isHorizontal()) {
+				// We are in a vertical orientation. The top value is the highest. So reverse the array
+				ticks.reverse();
+			}
+
+			// At this point, we need to update our max and min given the tick values since we have expanded the
+			// range of the scale
+			me.max = helpers.max(ticks);
+			me.min = helpers.min(ticks);
+
+			if (tickOpts.reverse) {
+				ticks.reverse();
+
+				me.start = me.max;
+				me.end = me.min;
+			} else {
+				me.start = me.min;
+				me.end = me.max;
+			}
+		},
+		convertTicksToLabels: function() {
+			this.tickValues = this.ticks.slice();
+
+			Chart.Scale.prototype.convertTicksToLabels.call(this);
+		},
+		// Get the correct tooltip label
+		getLabelForIndex: function(index, datasetIndex) {
+			return +this.getRightValue(this.chart.data.datasets[datasetIndex].data[index]);
+		},
+		getPixelForTick: function(index) {
+			return this.getPixelForValue(this.tickValues[index]);
+		},
+		getPixelForValue: function(value) {
+			var me = this;
+			var innerDimension;
+			var pixel;
+
+			var start = me.start;
+			var newVal = +me.getRightValue(value);
+			var range;
+			var opts = me.options;
+			var tickOpts = opts.ticks;
+
+			if (me.isHorizontal()) {
+				range = helpers.log10(me.end) - helpers.log10(start); // todo: if start === 0
+				if (newVal === 0) {
+					pixel = me.left;
+				} else {
+					innerDimension = me.width;
+					pixel = me.left + (innerDimension / range * (helpers.log10(newVal) - helpers.log10(start)));
+				}
+			} else {
+				// Bottom - top since pixels increase downward on a screen
+				innerDimension = me.height;
+				if (start === 0 && !tickOpts.reverse) {
+					range = helpers.log10(me.end) - helpers.log10(me.minNotZero);
+					if (newVal === start) {
+						pixel = me.bottom;
+					} else if (newVal === me.minNotZero) {
+						pixel = me.bottom - innerDimension * 0.02;
+					} else {
+						pixel = me.bottom - innerDimension * 0.02 - (innerDimension * 0.98/ range * (helpers.log10(newVal)-helpers.log10(me.minNotZero)));
+					}
+				} else if (me.end === 0 && tickOpts.reverse) {
+					range = helpers.log10(me.start) - helpers.log10(me.minNotZero);
+					if (newVal === me.end) {
+						pixel = me.top;
+					} else if (newVal === me.minNotZero) {
+						pixel = me.top + innerDimension * 0.02;
+					} else {
+						pixel = me.top + innerDimension * 0.02 + (innerDimension * 0.98/ range * (helpers.log10(newVal)-helpers.log10(me.minNotZero)));
+					}
+				} else {
+					range = helpers.log10(me.end) - helpers.log10(start);
+					innerDimension = me.height;
+					pixel = me.bottom - (innerDimension / range * (helpers.log10(newVal) - helpers.log10(start)));
+				}
+			}
+			return pixel;
+		},
+		getValueForPixel: function(pixel) {
+			var me = this;
+			var range = helpers.log10(me.end) - helpers.log10(me.start);
+			var value, innerDimension;
+
+			if (me.isHorizontal()) {
+				innerDimension = me.width;
+				value = me.start * Math.pow(10, (pixel - me.left) * range / innerDimension);
+			} else {  // todo: if start === 0
+				innerDimension = me.height;
+				value = Math.pow(10, (me.bottom - pixel) * range / innerDimension) / me.start;
+			}
+			return value;
+		}
+	});
+	Chart.scaleService.registerScaleType('logarithmic', LogarithmicScale, defaultConfig);
+
+};
+
+},{}],47:[function(require,module,exports){
+'use strict';
+
+module.exports = function(Chart) {
+
+	var helpers = Chart.helpers;
+	var globalDefaults = Chart.defaults.global;
+
+	var defaultConfig = {
+		display: true,
+
+		// Boolean - Whether to animate scaling the chart from the centre
+		animate: true,
+		lineArc: false,
+		position: 'chartArea',
+
+		angleLines: {
+			display: true,
+			color: 'rgba(0, 0, 0, 0.1)',
+			lineWidth: 1
+		},
+
+		// label settings
+		ticks: {
+			// Boolean - Show a backdrop to the scale label
+			showLabelBackdrop: true,
+
+			// String - The colour of the label backdrop
+			backdropColor: 'rgba(255,255,255,0.75)',
+
+			// Number - The backdrop padding above & below the label in pixels
+			backdropPaddingY: 2,
+
+			// Number - The backdrop padding to the side of the label in pixels
+			backdropPaddingX: 2,
+
+			callback: Chart.Ticks.formatters.linear
+		},
+
+		pointLabels: {
+			// Number - Point label font size in pixels
+			fontSize: 10,
+
+			// Function - Used to convert point labels
+			callback: function(label) {
+				return label;
+			}
+		}
+	};
+
+	function getValueCount(scale) {
+		return !scale.options.lineArc ? scale.chart.data.labels.length : 0;
+	}
+
+	function getPointLabelFontOptions(scale) {
+		var pointLabelOptions = scale.options.pointLabels;
+		var fontSize = helpers.getValueOrDefault(pointLabelOptions.fontSize, globalDefaults.defaultFontSize);
+		var fontStyle = helpers.getValueOrDefault(pointLabelOptions.fontStyle, globalDefaults.defaultFontStyle);
+		var fontFamily = helpers.getValueOrDefault(pointLabelOptions.fontFamily, globalDefaults.defaultFontFamily);
+		var font = helpers.fontString(fontSize, fontStyle, fontFamily);
+
+		return {
+			size: fontSize,
+			style: fontStyle,
+			family: fontFamily,
+			font: font
+		};
+	}
+
+	function measureLabelSize(ctx, fontSize, label) {
+		if (helpers.isArray(label)) {
+			return {
+				w: helpers.longestText(ctx, ctx.font, label),
+				h: (label.length * fontSize) + ((label.length - 1) * 1.5 * fontSize)
+			};
+		}
+
+		return {
+			w: ctx.measureText(label).width,
+			h: fontSize
+		};
+	}
+
+	function determineLimits(angle, pos, size, min, max) {
+		if (angle === min || angle === max) {
+			return {
+				start: pos - (size / 2),
+				end: pos + (size / 2)
+			};
+		} else if (angle < min || angle > max) {
+			return {
+				start: pos - size - 5,
+				end: pos
+			};
+		}
+
+		return {
+			start: pos,
+			end: pos + size + 5
+		};
+	}
+
+	/**
+	 * Helper function to fit a radial linear scale with point labels
+	 */
+	function fitWithPointLabels(scale) {
+		/*
+		 * Right, this is really confusing and there is a lot of maths going on here
+		 * The gist of the problem is here: https://gist.github.com/nnnick/696cc9c55f4b0beb8fe9
+		 *
+		 * Reaction: https://dl.dropboxusercontent.com/u/34601363/toomuchscience.gif
+		 *
+		 * Solution:
+		 *
+		 * We assume the radius of the polygon is half the size of the canvas at first
+		 * at each index we check if the text overlaps.
+		 *
+		 * Where it does, we store that angle and that index.
+		 *
+		 * After finding the largest index and angle we calculate how much we need to remove
+		 * from the shape radius to move the point inwards by that x.
+		 *
+		 * We average the left and right distances to get the maximum shape radius that can fit in the box
+		 * along with labels.
+		 *
+		 * Once we have that, we can find the centre point for the chart, by taking the x text protrusion
+		 * on each side, removing that from the size, halving it and adding the left x protrusion width.
+		 *
+		 * This will mean we have a shape fitted to the canvas, as large as it can be with the labels
+		 * and position it in the most space efficient manner
+		 *
+		 * https://dl.dropboxusercontent.com/u/34601363/yeahscience.gif
+		 */
+
+		var plFont = getPointLabelFontOptions(scale);
+
+		// Get maximum radius of the polygon. Either half the height (minus the text width) or half the width.
+		// Use this to calculate the offset + change. - Make sure L/R protrusion is at least 0 to stop issues with centre points
+		var largestPossibleRadius = Math.min(scale.height / 2, scale.width / 2);
+		var furthestLimits = {
+			l: scale.width,
+			r: 0,
+			t: scale.height,
+			b: 0
+		};
+		var furthestAngles = {};
+		var i;
+		var textSize;
+		var pointPosition;
+
+		scale.ctx.font = plFont.font;
+		scale._pointLabelSizes = [];
+
+		var valueCount = getValueCount(scale);
+		for (i = 0; i < valueCount; i++) {
+			pointPosition = scale.getPointPosition(i, largestPossibleRadius);
+			textSize = measureLabelSize(scale.ctx, plFont.size, scale.pointLabels[i] || '');
+			scale._pointLabelSizes[i] = textSize;
+
+			// Add quarter circle to make degree 0 mean top of circle
+			var angleRadians = scale.getIndexAngle(i);
+			var angle = helpers.toDegrees(angleRadians) % 360;
+			var hLimits = determineLimits(angle, pointPosition.x, textSize.w, 0, 180);
+			var vLimits = determineLimits(angle, pointPosition.y, textSize.h, 90, 270);
+
+			if (hLimits.start < furthestLimits.l) {
+				furthestLimits.l = hLimits.start;
+				furthestAngles.l = angleRadians;
+			}
+
+			if (hLimits.end > furthestLimits.r) {
+				furthestLimits.r = hLimits.end;
+				furthestAngles.r = angleRadians;
+			}
+
+			if (vLimits.start < furthestLimits.t) {
+				furthestLimits.t = vLimits.start;
+				furthestAngles.t = angleRadians;
+			}
+
+			if (vLimits.end > furthestLimits.b) {
+				furthestLimits.b = vLimits.end;
+				furthestAngles.b = angleRadians;
+			}
+		}
+
+		scale.setReductions(largestPossibleRadius, furthestLimits, furthestAngles);
+	}
+
+	/**
+	 * Helper function to fit a radial linear scale with no point labels
+	 */
+	function fit(scale) {
+		var largestPossibleRadius = Math.min(scale.height / 2, scale.width / 2);
+		scale.drawingArea = Math.round(largestPossibleRadius);
+		scale.setCenterPoint(0, 0, 0, 0);
+	}
+
+	function getTextAlignForAngle(angle) {
+		if (angle === 0 || angle === 180) {
+			return 'center';
+		} else if (angle < 180) {
+			return 'left';
+		}
+
+		return 'right';
+	}
+
+	function fillText(ctx, text, position, fontSize) {
+		if (helpers.isArray(text)) {
+			var y = position.y;
+			var spacing = 1.5 * fontSize;
+
+			for (var i = 0; i < text.length; ++i) {
+				ctx.fillText(text[i], position.x, y);
+				y+= spacing;
+			}
+		} else {
+			ctx.fillText(text, position.x, position.y);
+		}
+	}
+
+	function adjustPointPositionForLabelHeight(angle, textSize, position) {
+		if (angle === 90 || angle === 270) {
+			position.y -= (textSize.h / 2);
+		} else if (angle > 270 || angle < 90) {
+			position.y -= textSize.h;
+		}
+	}
+
+	function drawPointLabels(scale) {
+		var ctx = scale.ctx;
+		var getValueOrDefault = helpers.getValueOrDefault;
+		var opts = scale.options;
+		var angleLineOpts = opts.angleLines;
+		var pointLabelOpts = opts.pointLabels;
+
+		ctx.lineWidth = angleLineOpts.lineWidth;
+		ctx.strokeStyle = angleLineOpts.color;
+
+		var outerDistance = scale.getDistanceFromCenterForValue(opts.reverse ? scale.min : scale.max);
+
+		// Point Label Font
+		var plFont = getPointLabelFontOptions(scale);
+
+		ctx.textBaseline = 'top';
+
+		for (var i = getValueCount(scale) - 1; i >= 0; i--) {
+			if (angleLineOpts.display) {
+				var outerPosition = scale.getPointPosition(i, outerDistance);
+				ctx.beginPath();
+				ctx.moveTo(scale.xCenter, scale.yCenter);
+				ctx.lineTo(outerPosition.x, outerPosition.y);
+				ctx.stroke();
+				ctx.closePath();
+			}
+			// Extra 3px out for some label spacing
+			var pointLabelPosition = scale.getPointPosition(i, outerDistance + 5);
+
+			// Keep this in loop since we may support array properties here
+			var pointLabelFontColor = getValueOrDefault(pointLabelOpts.fontColor, globalDefaults.defaultFontColor);
+			ctx.font = plFont.font;
+			ctx.fillStyle = pointLabelFontColor;
+
+			var angleRadians = scale.getIndexAngle(i);
+			var angle = helpers.toDegrees(angleRadians);
+			ctx.textAlign = getTextAlignForAngle(angle);
+			adjustPointPositionForLabelHeight(angle, scale._pointLabelSizes[i], pointLabelPosition);
+			fillText(ctx, scale.pointLabels[i] || '', pointLabelPosition, plFont.size);
+		}
+	}
+
+	function drawRadiusLine(scale, gridLineOpts, radius, index) {
+		var ctx = scale.ctx;
+		ctx.strokeStyle = helpers.getValueAtIndexOrDefault(gridLineOpts.color, index - 1);
+		ctx.lineWidth = helpers.getValueAtIndexOrDefault(gridLineOpts.lineWidth, index - 1);
+
+		if (scale.options.lineArc) {
+			// Draw circular arcs between the points
+			ctx.beginPath();
+			ctx.arc(scale.xCenter, scale.yCenter, radius, 0, Math.PI * 2);
+			ctx.closePath();
+			ctx.stroke();
+		} else {
+			// Draw straight lines connecting each index
+			var valueCount = getValueCount(scale);
+
+			if (valueCount === 0) {
+				return;
+			}
+
+			ctx.beginPath();
+			var pointPosition = scale.getPointPosition(0, radius);
+			ctx.moveTo(pointPosition.x, pointPosition.y);
+
+			for (var i = 1; i < valueCount; i++) {
+				pointPosition = scale.getPointPosition(i, radius);
+				ctx.lineTo(pointPosition.x, pointPosition.y);
+			}
+
+			ctx.closePath();
+			ctx.stroke();
+		}
+	}
+
+	function numberOrZero(param) {
+		return helpers.isNumber(param) ? param : 0;
+	}
+
+	var LinearRadialScale = Chart.LinearScaleBase.extend({
+		setDimensions: function() {
+			var me = this;
+			var opts = me.options;
+			var tickOpts = opts.ticks;
+			// Set the unconstrained dimension before label rotation
+			me.width = me.maxWidth;
+			me.height = me.maxHeight;
+			me.xCenter = Math.round(me.width / 2);
+			me.yCenter = Math.round(me.height / 2);
+
+			var minSize = helpers.min([me.height, me.width]);
+			var tickFontSize = helpers.getValueOrDefault(tickOpts.fontSize, globalDefaults.defaultFontSize);
+			me.drawingArea = opts.display ? (minSize / 2) - (tickFontSize / 2 + tickOpts.backdropPaddingY) : (minSize / 2);
+		},
+		determineDataLimits: function() {
+			var me = this;
+			var chart = me.chart;
+			var min = Number.POSITIVE_INFINITY;
+			var max = Number.NEGATIVE_INFINITY;
+
+			helpers.each(chart.data.datasets, function(dataset, datasetIndex) {
+				if (chart.isDatasetVisible(datasetIndex)) {
+					var meta = chart.getDatasetMeta(datasetIndex);
+
+					helpers.each(dataset.data, function(rawValue, index) {
+						var value = +me.getRightValue(rawValue);
+						if (isNaN(value) || meta.data[index].hidden) {
+							return;
+						}
+
+						min = Math.min(value, min);
+						max = Math.max(value, max);
+					});
+				}
+			});
+
+			me.min = (min === Number.POSITIVE_INFINITY ? 0 : min);
+			me.max = (max === Number.NEGATIVE_INFINITY ? 0 : max);
+
+			// Common base implementation to handle ticks.min, ticks.max, ticks.beginAtZero
+			me.handleTickRangeOptions();
+		},
+		getTickLimit: function() {
+			var tickOpts = this.options.ticks;
+			var tickFontSize = helpers.getValueOrDefault(tickOpts.fontSize, globalDefaults.defaultFontSize);
+			return Math.min(tickOpts.maxTicksLimit ? tickOpts.maxTicksLimit : 11, Math.ceil(this.drawingArea / (1.5 * tickFontSize)));
+		},
+		convertTicksToLabels: function() {
+			var me = this;
+			Chart.LinearScaleBase.prototype.convertTicksToLabels.call(me);
+
+			// Point labels
+			me.pointLabels = me.chart.data.labels.map(me.options.pointLabels.callback, me);
+		},
+		getLabelForIndex: function(index, datasetIndex) {
+			return +this.getRightValue(this.chart.data.datasets[datasetIndex].data[index]);
+		},
+		fit: function() {
+			if (this.options.lineArc) {
+				fit(this);
+			} else {
+				fitWithPointLabels(this);
+			}
+		},
+		/**
+		 * Set radius reductions and determine new radius and center point
+		 * @private
+		 */
+		setReductions: function(largestPossibleRadius, furthestLimits, furthestAngles) {
+			var me = this;
+			var radiusReductionLeft = furthestLimits.l / Math.sin(furthestAngles.l);
+			var radiusReductionRight = Math.max(furthestLimits.r - me.width, 0) / Math.sin(furthestAngles.r);
+			var radiusReductionTop = -furthestLimits.t / Math.cos(furthestAngles.t);
+			var radiusReductionBottom = -Math.max(furthestLimits.b - me.height, 0) / Math.cos(furthestAngles.b);
+
+			radiusReductionLeft = numberOrZero(radiusReductionLeft);
+			radiusReductionRight = numberOrZero(radiusReductionRight);
+			radiusReductionTop = numberOrZero(radiusReductionTop);
+			radiusReductionBottom = numberOrZero(radiusReductionBottom);
+
+			me.drawingArea = Math.min(
+				Math.round(largestPossibleRadius - (radiusReductionLeft + radiusReductionRight) / 2),
+				Math.round(largestPossibleRadius - (radiusReductionTop + radiusReductionBottom) / 2));
+			me.setCenterPoint(radiusReductionLeft, radiusReductionRight, radiusReductionTop, radiusReductionBottom);
+		},
+		setCenterPoint: function(leftMovement, rightMovement, topMovement, bottomMovement) {
+			var me = this;
+			var maxRight = me.width - rightMovement - me.drawingArea,
+				maxLeft = leftMovement + me.drawingArea,
+				maxTop = topMovement + me.drawingArea,
+				maxBottom = me.height - bottomMovement - me.drawingArea;
+
+			me.xCenter = Math.round(((maxLeft + maxRight) / 2) + me.left);
+			me.yCenter = Math.round(((maxTop + maxBottom) / 2) + me.top);
+		},
+
+		getIndexAngle: function(index) {
+			var angleMultiplier = (Math.PI * 2) / getValueCount(this);
+			var startAngle = this.chart.options && this.chart.options.startAngle ?
+				this.chart.options.startAngle :
+				0;
+
+			var startAngleRadians = startAngle * Math.PI * 2 / 360;
+
+			// Start from the top instead of right, so remove a quarter of the circle
+			return index * angleMultiplier + startAngleRadians;
+		},
+		getDistanceFromCenterForValue: function(value) {
+			var me = this;
+
+			if (value === null) {
+				return 0; // null always in center
+			}
+
+			// Take into account half font size + the yPadding of the top value
+			var scalingFactor = me.drawingArea / (me.max - me.min);
+			if (me.options.reverse) {
+				return (me.max - value) * scalingFactor;
+			}
+			return (value - me.min) * scalingFactor;
+		},
+		getPointPosition: function(index, distanceFromCenter) {
+			var me = this;
+			var thisAngle = me.getIndexAngle(index) - (Math.PI / 2);
+			return {
+				x: Math.round(Math.cos(thisAngle) * distanceFromCenter) + me.xCenter,
+				y: Math.round(Math.sin(thisAngle) * distanceFromCenter) + me.yCenter
+			};
+		},
+		getPointPositionForValue: function(index, value) {
+			return this.getPointPosition(index, this.getDistanceFromCenterForValue(value));
+		},
+
+		getBasePosition: function() {
+			var me = this;
+			var min = me.min;
+			var max = me.max;
+
+			return me.getPointPositionForValue(0,
+				me.beginAtZero? 0:
+				min < 0 && max < 0? max :
+				min > 0 && max > 0? min :
+				0);
+		},
+
+		draw: function() {
+			var me = this;
+			var opts = me.options;
+			var gridLineOpts = opts.gridLines;
+			var tickOpts = opts.ticks;
+			var getValueOrDefault = helpers.getValueOrDefault;
+
+			if (opts.display) {
+				var ctx = me.ctx;
+
+				// Tick Font
+				var tickFontSize = getValueOrDefault(tickOpts.fontSize, globalDefaults.defaultFontSize);
+				var tickFontStyle = getValueOrDefault(tickOpts.fontStyle, globalDefaults.defaultFontStyle);
+				var tickFontFamily = getValueOrDefault(tickOpts.fontFamily, globalDefaults.defaultFontFamily);
+				var tickLabelFont = helpers.fontString(tickFontSize, tickFontStyle, tickFontFamily);
+
+				helpers.each(me.ticks, function(label, index) {
+					// Don't draw a centre value (if it is minimum)
+					if (index > 0 || opts.reverse) {
+						var yCenterOffset = me.getDistanceFromCenterForValue(me.ticksAsNumbers[index]);
+						var yHeight = me.yCenter - yCenterOffset;
+
+						// Draw circular lines around the scale
+						if (gridLineOpts.display && index !== 0) {
+							drawRadiusLine(me, gridLineOpts, yCenterOffset, index);
+						}
+
+						if (tickOpts.display) {
+							var tickFontColor = getValueOrDefault(tickOpts.fontColor, globalDefaults.defaultFontColor);
+							ctx.font = tickLabelFont;
+
+							if (tickOpts.showLabelBackdrop) {
+								var labelWidth = ctx.measureText(label).width;
+								ctx.fillStyle = tickOpts.backdropColor;
+								ctx.fillRect(
+									me.xCenter - labelWidth / 2 - tickOpts.backdropPaddingX,
+									yHeight - tickFontSize / 2 - tickOpts.backdropPaddingY,
+									labelWidth + tickOpts.backdropPaddingX * 2,
+									tickFontSize + tickOpts.backdropPaddingY * 2
+								);
+							}
+
+							ctx.textAlign = 'center';
+							ctx.textBaseline = 'middle';
+							ctx.fillStyle = tickFontColor;
+							ctx.fillText(label, me.xCenter, yHeight);
+						}
+					}
+				});
+
+				if (!opts.lineArc) {
+					drawPointLabels(me);
+				}
+			}
+		}
+	});
+	Chart.scaleService.registerScaleType('radialLinear', LinearRadialScale, defaultConfig);
+
+};
+
+},{}],48:[function(require,module,exports){
+/* global window: false */
+'use strict';
+
+var moment = require(1);
+moment = typeof(moment) === 'function' ? moment : window.moment;
+
+module.exports = function(Chart) {
+
+	var helpers = Chart.helpers;
+	var time = {
+		units: [{
+			name: 'millisecond',
+			steps: [1, 2, 5, 10, 20, 50, 100, 250, 500]
+		}, {
+			name: 'second',
+			steps: [1, 2, 5, 10, 30]
+		}, {
+			name: 'minute',
+			steps: [1, 2, 5, 10, 30]
+		}, {
+			name: 'hour',
+			steps: [1, 2, 3, 6, 12]
+		}, {
+			name: 'day',
+			steps: [1, 2, 5]
+		}, {
+			name: 'week',
+			maxStep: 4
+		}, {
+			name: 'month',
+			maxStep: 3
+		}, {
+			name: 'quarter',
+			maxStep: 4
+		}, {
+			name: 'year',
+			maxStep: false
+		}]
+	};
+
+	var defaultConfig = {
+		position: 'bottom',
+
+		time: {
+			parser: false, // false == a pattern string from http://momentjs.com/docs/#/parsing/string-format/ or a custom callback that converts its argument to a moment
+			format: false, // DEPRECATED false == date objects, moment object, callback or a pattern string from http://momentjs.com/docs/#/parsing/string-format/
+			unit: false, // false == automatic or override with week, month, year, etc.
+			round: false, // none, or override with week, month, year, etc.
+			displayFormat: false, // DEPRECATED
+			isoWeekday: false, // override week start day - see http://momentjs.com/docs/#/get-set/iso-weekday/
+			minUnit: 'millisecond',
+
+			// defaults to unit's corresponding unitFormat below or override using pattern string from http://momentjs.com/docs/#/displaying/format/
+			displayFormats: {
+				millisecond: 'h:mm:ss.SSS a', // 11:20:01.123 AM,
+				second: 'h:mm:ss a', // 11:20:01 AM
+				minute: 'h:mm:ss a', // 11:20:01 AM
+				hour: 'MMM D, hA', // Sept 4, 5PM
+				day: 'll', // Sep 4 2015
+				week: 'll', // Week 46, or maybe "[W]WW - YYYY" ?
+				month: 'MMM YYYY', // Sept 2015
+				quarter: '[Q]Q - YYYY', // Q3
+				year: 'YYYY' // 2015
+			}
+		},
+		ticks: {
+			autoSkip: false
+		}
+	};
+
+	var TimeScale = Chart.Scale.extend({
+		initialize: function() {
+			if (!moment) {
+				throw new Error('Chart.js - Moment.js could not be found! You must include it before Chart.js to use the time scale. Download at https://momentjs.com');
+			}
+
+			Chart.Scale.prototype.initialize.call(this);
+		},
+		getLabelMoment: function(datasetIndex, index) {
+			if (datasetIndex === null || index === null) {
+				return null;
+			}
+
+			if (typeof this.labelMoments[datasetIndex] !== 'undefined') {
+				return this.labelMoments[datasetIndex][index];
+			}
+
+			return null;
+		},
+		getLabelDiff: function(datasetIndex, index) {
+			var me = this;
+			if (datasetIndex === null || index === null) {
+				return null;
+			}
+
+			if (me.labelDiffs === undefined) {
+				me.buildLabelDiffs();
+			}
+
+			if (typeof me.labelDiffs[datasetIndex] !== 'undefined') {
+				return me.labelDiffs[datasetIndex][index];
+			}
+
+			return null;
+		},
+		getMomentStartOf: function(tick) {
+			var me = this;
+			if (me.options.time.unit === 'week' && me.options.time.isoWeekday !== false) {
+				return tick.clone().startOf('isoWeek').isoWeekday(me.options.time.isoWeekday);
+			}
+			return tick.clone().startOf(me.tickUnit);
+		},
+		determineDataLimits: function() {
+			var me = this;
+			me.labelMoments = [];
+
+			// Only parse these once. If the dataset does not have data as x,y pairs, we will use
+			// these
+			var scaleLabelMoments = [];
+			if (me.chart.data.labels && me.chart.data.labels.length > 0) {
+				helpers.each(me.chart.data.labels, function(label) {
+					var labelMoment = me.parseTime(label);
+
+					if (labelMoment.isValid()) {
+						if (me.options.time.round) {
+							labelMoment.startOf(me.options.time.round);
+						}
+						scaleLabelMoments.push(labelMoment);
+					}
+				}, me);
+
+				me.firstTick = moment.min.call(me, scaleLabelMoments);
+				me.lastTick = moment.max.call(me, scaleLabelMoments);
+			} else {
+				me.firstTick = null;
+				me.lastTick = null;
+			}
+
+			helpers.each(me.chart.data.datasets, function(dataset, datasetIndex) {
+				var momentsForDataset = [];
+				var datasetVisible = me.chart.isDatasetVisible(datasetIndex);
+
+				if (typeof dataset.data[0] === 'object' && dataset.data[0] !== null) {
+					helpers.each(dataset.data, function(value) {
+						var labelMoment = me.parseTime(me.getRightValue(value));
+
+						if (labelMoment.isValid()) {
+							if (me.options.time.round) {
+								labelMoment.startOf(me.options.time.round);
+							}
+							momentsForDataset.push(labelMoment);
+
+							if (datasetVisible) {
+								// May have gone outside the scale ranges, make sure we keep the first and last ticks updated
+								me.firstTick = me.firstTick !== null ? moment.min(me.firstTick, labelMoment) : labelMoment;
+								me.lastTick = me.lastTick !== null ? moment.max(me.lastTick, labelMoment) : labelMoment;
+							}
+						}
+					}, me);
+				} else {
+					// We have no labels. Use the ones from the scale
+					momentsForDataset = scaleLabelMoments;
+				}
+
+				me.labelMoments.push(momentsForDataset);
+			}, me);
+
+			// Set these after we've done all the data
+			if (me.options.time.min) {
+				me.firstTick = me.parseTime(me.options.time.min);
+			}
+
+			if (me.options.time.max) {
+				me.lastTick = me.parseTime(me.options.time.max);
+			}
+
+			// We will modify these, so clone for later
+			me.firstTick = (me.firstTick || moment()).clone();
+			me.lastTick = (me.lastTick || moment()).clone();
+		},
+		buildLabelDiffs: function() {
+			var me = this;
+			me.labelDiffs = [];
+			var scaleLabelDiffs = [];
+			// Parse common labels once
+			if (me.chart.data.labels && me.chart.data.labels.length > 0) {
+				helpers.each(me.chart.data.labels, function(label) {
+					var labelMoment = me.parseTime(label);
+
+					if (labelMoment.isValid()) {
+						if (me.options.time.round) {
+							labelMoment.startOf(me.options.time.round);
+						}
+						scaleLabelDiffs.push(labelMoment.diff(me.firstTick, me.tickUnit, true));
+					}
+				}, me);
+			}
+
+			helpers.each(me.chart.data.datasets, function(dataset) {
+				var diffsForDataset = [];
+
+				if (typeof dataset.data[0] === 'object' && dataset.data[0] !== null) {
+					helpers.each(dataset.data, function(value) {
+						var labelMoment = me.parseTime(me.getRightValue(value));
+
+						if (labelMoment.isValid()) {
+							if (me.options.time.round) {
+								labelMoment.startOf(me.options.time.round);
+							}
+							diffsForDataset.push(labelMoment.diff(me.firstTick, me.tickUnit, true));
+						}
+					}, me);
+				} else {
+					// We have no labels. Use common ones
+					diffsForDataset = scaleLabelDiffs;
+				}
+
+				me.labelDiffs.push(diffsForDataset);
+			}, me);
+		},
+		buildTicks: function() {
+			var me = this;
+
+			me.ctx.save();
+			var tickFontSize = helpers.getValueOrDefault(me.options.ticks.fontSize, Chart.defaults.global.defaultFontSize);
+			var tickFontStyle = helpers.getValueOrDefault(me.options.ticks.fontStyle, Chart.defaults.global.defaultFontStyle);
+			var tickFontFamily = helpers.getValueOrDefault(me.options.ticks.fontFamily, Chart.defaults.global.defaultFontFamily);
+			var tickLabelFont = helpers.fontString(tickFontSize, tickFontStyle, tickFontFamily);
+			me.ctx.font = tickLabelFont;
+
+			me.ticks = [];
+			me.unitScale = 1; // How much we scale the unit by, ie 2 means 2x unit per step
+			me.scaleSizeInUnits = 0; // How large the scale is in the base unit (seconds, minutes, etc)
+
+			// Set unit override if applicable
+			if (me.options.time.unit) {
+				me.tickUnit = me.options.time.unit || 'day';
+				me.displayFormat = me.options.time.displayFormats[me.tickUnit];
+				me.scaleSizeInUnits = me.lastTick.diff(me.firstTick, me.tickUnit, true);
+				me.unitScale = helpers.getValueOrDefault(me.options.time.unitStepSize, 1);
+			} else {
+				// Determine the smallest needed unit of the time
+				var innerWidth = me.isHorizontal() ? me.width : me.height;
+
+				// Crude approximation of what the label length might be
+				var tempFirstLabel = me.tickFormatFunction(me.firstTick, 0, []);
+				var tickLabelWidth = me.ctx.measureText(tempFirstLabel).width;
+				var cosRotation = Math.cos(helpers.toRadians(me.options.ticks.maxRotation));
+				var sinRotation = Math.sin(helpers.toRadians(me.options.ticks.maxRotation));
+				tickLabelWidth = (tickLabelWidth * cosRotation) + (tickFontSize * sinRotation);
+				var labelCapacity = innerWidth / (tickLabelWidth);
+
+				// Start as small as possible
+				me.tickUnit = me.options.time.minUnit;
+				me.scaleSizeInUnits = me.lastTick.diff(me.firstTick, me.tickUnit, true);
+				me.displayFormat = me.options.time.displayFormats[me.tickUnit];
+
+				var unitDefinitionIndex = 0;
+				var unitDefinition = time.units[unitDefinitionIndex];
+
+				// While we aren't ideal and we don't have units left
+				while (unitDefinitionIndex < time.units.length) {
+					// Can we scale this unit. If `false` we can scale infinitely
+					me.unitScale = 1;
+
+					if (helpers.isArray(unitDefinition.steps) && Math.ceil(me.scaleSizeInUnits / labelCapacity) < helpers.max(unitDefinition.steps)) {
+						// Use one of the predefined steps
+						for (var idx = 0; idx < unitDefinition.steps.length; ++idx) {
+							if (unitDefinition.steps[idx] >= Math.ceil(me.scaleSizeInUnits / labelCapacity)) {
+								me.unitScale = helpers.getValueOrDefault(me.options.time.unitStepSize, unitDefinition.steps[idx]);
+								break;
+							}
+						}
+
+						break;
+					} else if ((unitDefinition.maxStep === false) || (Math.ceil(me.scaleSizeInUnits / labelCapacity) < unitDefinition.maxStep)) {
+						// We have a max step. Scale this unit
+						me.unitScale = helpers.getValueOrDefault(me.options.time.unitStepSize, Math.ceil(me.scaleSizeInUnits / labelCapacity));
+						break;
+					} else {
+						// Move to the next unit up
+						++unitDefinitionIndex;
+						unitDefinition = time.units[unitDefinitionIndex];
+
+						me.tickUnit = unitDefinition.name;
+						var leadingUnitBuffer = me.firstTick.diff(me.getMomentStartOf(me.firstTick), me.tickUnit, true);
+						var trailingUnitBuffer = me.getMomentStartOf(me.lastTick.clone().add(1, me.tickUnit)).diff(me.lastTick, me.tickUnit, true);
+						me.scaleSizeInUnits = me.lastTick.diff(me.firstTick, me.tickUnit, true) + leadingUnitBuffer + trailingUnitBuffer;
+						me.displayFormat = me.options.time.displayFormats[unitDefinition.name];
+					}
+				}
+			}
+
+			var roundedStart;
+
+			// Only round the first tick if we have no hard minimum
+			if (!me.options.time.min) {
+				me.firstTick = me.getMomentStartOf(me.firstTick);
+				roundedStart = me.firstTick;
+			} else {
+				roundedStart = me.getMomentStartOf(me.firstTick);
+			}
+
+			// Only round the last tick if we have no hard maximum
+			if (!me.options.time.max) {
+				var roundedEnd = me.getMomentStartOf(me.lastTick);
+				var delta = roundedEnd.diff(me.lastTick, me.tickUnit, true);
+				if (delta < 0) {
+					// Do not use end of because we need me to be in the next time unit
+					me.lastTick = me.getMomentStartOf(me.lastTick.add(1, me.tickUnit));
+				} else if (delta >= 0) {
+					me.lastTick = roundedEnd;
+				}
+
+				me.scaleSizeInUnits = me.lastTick.diff(me.firstTick, me.tickUnit, true);
+			}
+
+			// Tick displayFormat override
+			if (me.options.time.displayFormat) {
+				me.displayFormat = me.options.time.displayFormat;
+			}
+
+			// first tick. will have been rounded correctly if options.time.min is not specified
+			me.ticks.push(me.firstTick.clone());
+
+			// For every unit in between the first and last moment, create a moment and add it to the ticks tick
+			for (var i = me.unitScale; i <= me.scaleSizeInUnits; i += me.unitScale) {
+				var newTick = roundedStart.clone().add(i, me.tickUnit);
+
+				// Are we greater than the max time
+				if (me.options.time.max && newTick.diff(me.lastTick, me.tickUnit, true) >= 0) {
+					break;
+				}
+
+				me.ticks.push(newTick);
+			}
+
+			// Always show the right tick
+			var diff = me.ticks[me.ticks.length - 1].diff(me.lastTick, me.tickUnit);
+			if (diff !== 0 || me.scaleSizeInUnits === 0) {
+				// this is a weird case. If the <max> option is the same as the end option, we can't just diff the times because the tick was created from the roundedStart
+				// but the last tick was not rounded.
+				if (me.options.time.max) {
+					me.ticks.push(me.lastTick.clone());
+					me.scaleSizeInUnits = me.lastTick.diff(me.ticks[0], me.tickUnit, true);
+				} else {
+					me.ticks.push(me.lastTick.clone());
+					me.scaleSizeInUnits = me.lastTick.diff(me.firstTick, me.tickUnit, true);
+				}
+			}
+
+			me.ctx.restore();
+
+			// Invalidate label diffs cache
+			me.labelDiffs = undefined;
+		},
+		// Get tooltip label
+		getLabelForIndex: function(index, datasetIndex) {
+			var me = this;
+			var label = me.chart.data.labels && index < me.chart.data.labels.length ? me.chart.data.labels[index] : '';
+			var value = me.chart.data.datasets[datasetIndex].data[index];
+
+			if (value !== null && typeof value === 'object') {
+				label = me.getRightValue(value);
+			}
+
+			// Format nicely
+			if (me.options.time.tooltipFormat) {
+				label = me.parseTime(label).format(me.options.time.tooltipFormat);
+			}
+
+			return label;
+		},
+		// Function to format an individual tick mark
+		tickFormatFunction: function(tick, index, ticks) {
+			var formattedTick = tick.format(this.displayFormat);
+			var tickOpts = this.options.ticks;
+			var callback = helpers.getValueOrDefault(tickOpts.callback, tickOpts.userCallback);
+
+			if (callback) {
+				return callback(formattedTick, index, ticks);
+			}
+			return formattedTick;
+		},
+		convertTicksToLabels: function() {
+			var me = this;
+			me.tickMoments = me.ticks;
+			me.ticks = me.ticks.map(me.tickFormatFunction, me);
+		},
+		getPixelForValue: function(value, index, datasetIndex) {
+			var me = this;
+			var offset = null;
+			if (index !== undefined && datasetIndex !== undefined) {
+				offset = me.getLabelDiff(datasetIndex, index);
+			}
+
+			if (offset === null) {
+				if (!value || !value.isValid) {
+					// not already a moment object
+					value = me.parseTime(me.getRightValue(value));
+				}
+				if (value && value.isValid && value.isValid()) {
+					offset = value.diff(me.firstTick, me.tickUnit, true);
+				}
+			}
+
+			if (offset !== null) {
+				var decimal = offset !== 0 ? offset / me.scaleSizeInUnits : offset;
+
+				if (me.isHorizontal()) {
+					var valueOffset = (me.width * decimal);
+					return me.left + Math.round(valueOffset);
+				}
+
+				var heightOffset = (me.height * decimal);
+				return me.top + Math.round(heightOffset);
+			}
+		},
+		getPixelForTick: function(index) {
+			return this.getPixelForValue(this.tickMoments[index], null, null);
+		},
+		getValueForPixel: function(pixel) {
+			var me = this;
+			var innerDimension = me.isHorizontal() ? me.width : me.height;
+			var offset = (pixel - (me.isHorizontal() ? me.left : me.top)) / innerDimension;
+			offset *= me.scaleSizeInUnits;
+			return me.firstTick.clone().add(moment.duration(offset, me.tickUnit).asSeconds(), 'seconds');
+		},
+		parseTime: function(label) {
+			var me = this;
+			if (typeof me.options.time.parser === 'string') {
+				return moment(label, me.options.time.parser);
+			}
+			if (typeof me.options.time.parser === 'function') {
+				return me.options.time.parser(label);
+			}
+			// Date objects
+			if (typeof label.getMonth === 'function' || typeof label === 'number') {
+				return moment(label);
+			}
+			// Moment support
+			if (label.isValid && label.isValid()) {
+				return label;
+			}
+			// Custom parsing (return an instance of moment)
+			if (typeof me.options.time.format !== 'string' && me.options.time.format.call) {
+				console.warn('options.time.format is deprecated and replaced by options.time.parser. See http://nnnick.github.io/Chart.js/docs-v2/#scales-time-scale');
+				return me.options.time.format(label);
+			}
+			// Moment format parsing
+			return moment(label, me.options.time.format);
+		}
+	});
+	Chart.scaleService.registerScaleType('time', TimeScale, defaultConfig);
+
+};
+
+},{"1":1}]},{},[7])(7)
+});

+ 1295 - 0
static/lib/gridstack/gridstack-extra.css

@@ -0,0 +1,1295 @@
+.grid-stack.grid-stack-1 > .grid-stack-item {
+  min-width: 100%;
+}
+
+.grid-stack.grid-stack-1 > .grid-stack-item[data-gs-width='1'] {
+  width: 100%;
+}
+
+.grid-stack.grid-stack-1 > .grid-stack-item[data-gs-x='1'] {
+  left: 100%;
+}
+
+.grid-stack.grid-stack-1 > .grid-stack-item[data-gs-min-width='1'] {
+  min-width: 100%;
+}
+
+.grid-stack.grid-stack-1 > .grid-stack-item[data-gs-max-width='1'] {
+  max-width: 100%;
+}
+
+.grid-stack.grid-stack-2 > .grid-stack-item {
+  min-width: 50%;
+}
+
+.grid-stack.grid-stack-2 > .grid-stack-item[data-gs-width='1'] {
+  width: 50%;
+}
+
+.grid-stack.grid-stack-2 > .grid-stack-item[data-gs-x='1'] {
+  left: 50%;
+}
+
+.grid-stack.grid-stack-2 > .grid-stack-item[data-gs-min-width='1'] {
+  min-width: 50%;
+}
+
+.grid-stack.grid-stack-2 > .grid-stack-item[data-gs-max-width='1'] {
+  max-width: 50%;
+}
+
+.grid-stack.grid-stack-2 > .grid-stack-item[data-gs-width='2'] {
+  width: 100%;
+}
+
+.grid-stack.grid-stack-2 > .grid-stack-item[data-gs-x='2'] {
+  left: 100%;
+}
+
+.grid-stack.grid-stack-2 > .grid-stack-item[data-gs-min-width='2'] {
+  min-width: 100%;
+}
+
+.grid-stack.grid-stack-2 > .grid-stack-item[data-gs-max-width='2'] {
+  max-width: 100%;
+}
+
+.grid-stack.grid-stack-3 > .grid-stack-item {
+  min-width: 33.3333333333%;
+}
+
+.grid-stack.grid-stack-3 > .grid-stack-item[data-gs-width='1'] {
+  width: 33.3333333333%;
+}
+
+.grid-stack.grid-stack-3 > .grid-stack-item[data-gs-x='1'] {
+  left: 33.3333333333%;
+}
+
+.grid-stack.grid-stack-3 > .grid-stack-item[data-gs-min-width='1'] {
+  min-width: 33.3333333333%;
+}
+
+.grid-stack.grid-stack-3 > .grid-stack-item[data-gs-max-width='1'] {
+  max-width: 33.3333333333%;
+}
+
+.grid-stack.grid-stack-3 > .grid-stack-item[data-gs-width='2'] {
+  width: 66.6666666667%;
+}
+
+.grid-stack.grid-stack-3 > .grid-stack-item[data-gs-x='2'] {
+  left: 66.6666666667%;
+}
+
+.grid-stack.grid-stack-3 > .grid-stack-item[data-gs-min-width='2'] {
+  min-width: 66.6666666667%;
+}
+
+.grid-stack.grid-stack-3 > .grid-stack-item[data-gs-max-width='2'] {
+  max-width: 66.6666666667%;
+}
+
+.grid-stack.grid-stack-3 > .grid-stack-item[data-gs-width='3'] {
+  width: 100%;
+}
+
+.grid-stack.grid-stack-3 > .grid-stack-item[data-gs-x='3'] {
+  left: 100%;
+}
+
+.grid-stack.grid-stack-3 > .grid-stack-item[data-gs-min-width='3'] {
+  min-width: 100%;
+}
+
+.grid-stack.grid-stack-3 > .grid-stack-item[data-gs-max-width='3'] {
+  max-width: 100%;
+}
+
+.grid-stack.grid-stack-4 > .grid-stack-item {
+  min-width: 25%;
+}
+
+.grid-stack.grid-stack-4 > .grid-stack-item[data-gs-width='1'] {
+  width: 25%;
+}
+
+.grid-stack.grid-stack-4 > .grid-stack-item[data-gs-x='1'] {
+  left: 25%;
+}
+
+.grid-stack.grid-stack-4 > .grid-stack-item[data-gs-min-width='1'] {
+  min-width: 25%;
+}
+
+.grid-stack.grid-stack-4 > .grid-stack-item[data-gs-max-width='1'] {
+  max-width: 25%;
+}
+
+.grid-stack.grid-stack-4 > .grid-stack-item[data-gs-width='2'] {
+  width: 50%;
+}
+
+.grid-stack.grid-stack-4 > .grid-stack-item[data-gs-x='2'] {
+  left: 50%;
+}
+
+.grid-stack.grid-stack-4 > .grid-stack-item[data-gs-min-width='2'] {
+  min-width: 50%;
+}
+
+.grid-stack.grid-stack-4 > .grid-stack-item[data-gs-max-width='2'] {
+  max-width: 50%;
+}
+
+.grid-stack.grid-stack-4 > .grid-stack-item[data-gs-width='3'] {
+  width: 75%;
+}
+
+.grid-stack.grid-stack-4 > .grid-stack-item[data-gs-x='3'] {
+  left: 75%;
+}
+
+.grid-stack.grid-stack-4 > .grid-stack-item[data-gs-min-width='3'] {
+  min-width: 75%;
+}
+
+.grid-stack.grid-stack-4 > .grid-stack-item[data-gs-max-width='3'] {
+  max-width: 75%;
+}
+
+.grid-stack.grid-stack-4 > .grid-stack-item[data-gs-width='4'] {
+  width: 100%;
+}
+
+.grid-stack.grid-stack-4 > .grid-stack-item[data-gs-x='4'] {
+  left: 100%;
+}
+
+.grid-stack.grid-stack-4 > .grid-stack-item[data-gs-min-width='4'] {
+  min-width: 100%;
+}
+
+.grid-stack.grid-stack-4 > .grid-stack-item[data-gs-max-width='4'] {
+  max-width: 100%;
+}
+
+.grid-stack.grid-stack-5 > .grid-stack-item {
+  min-width: 20%;
+}
+
+.grid-stack.grid-stack-5 > .grid-stack-item[data-gs-width='1'] {
+  width: 20%;
+}
+
+.grid-stack.grid-stack-5 > .grid-stack-item[data-gs-x='1'] {
+  left: 20%;
+}
+
+.grid-stack.grid-stack-5 > .grid-stack-item[data-gs-min-width='1'] {
+  min-width: 20%;
+}
+
+.grid-stack.grid-stack-5 > .grid-stack-item[data-gs-max-width='1'] {
+  max-width: 20%;
+}
+
+.grid-stack.grid-stack-5 > .grid-stack-item[data-gs-width='2'] {
+  width: 40%;
+}
+
+.grid-stack.grid-stack-5 > .grid-stack-item[data-gs-x='2'] {
+  left: 40%;
+}
+
+.grid-stack.grid-stack-5 > .grid-stack-item[data-gs-min-width='2'] {
+  min-width: 40%;
+}
+
+.grid-stack.grid-stack-5 > .grid-stack-item[data-gs-max-width='2'] {
+  max-width: 40%;
+}
+
+.grid-stack.grid-stack-5 > .grid-stack-item[data-gs-width='3'] {
+  width: 60%;
+}
+
+.grid-stack.grid-stack-5 > .grid-stack-item[data-gs-x='3'] {
+  left: 60%;
+}
+
+.grid-stack.grid-stack-5 > .grid-stack-item[data-gs-min-width='3'] {
+  min-width: 60%;
+}
+
+.grid-stack.grid-stack-5 > .grid-stack-item[data-gs-max-width='3'] {
+  max-width: 60%;
+}
+
+.grid-stack.grid-stack-5 > .grid-stack-item[data-gs-width='4'] {
+  width: 80%;
+}
+
+.grid-stack.grid-stack-5 > .grid-stack-item[data-gs-x='4'] {
+  left: 80%;
+}
+
+.grid-stack.grid-stack-5 > .grid-stack-item[data-gs-min-width='4'] {
+  min-width: 80%;
+}
+
+.grid-stack.grid-stack-5 > .grid-stack-item[data-gs-max-width='4'] {
+  max-width: 80%;
+}
+
+.grid-stack.grid-stack-5 > .grid-stack-item[data-gs-width='5'] {
+  width: 100%;
+}
+
+.grid-stack.grid-stack-5 > .grid-stack-item[data-gs-x='5'] {
+  left: 100%;
+}
+
+.grid-stack.grid-stack-5 > .grid-stack-item[data-gs-min-width='5'] {
+  min-width: 100%;
+}
+
+.grid-stack.grid-stack-5 > .grid-stack-item[data-gs-max-width='5'] {
+  max-width: 100%;
+}
+
+.grid-stack.grid-stack-6 > .grid-stack-item {
+  min-width: 16.6666666667%;
+}
+
+.grid-stack.grid-stack-6 > .grid-stack-item[data-gs-width='1'] {
+  width: 16.6666666667%;
+}
+
+.grid-stack.grid-stack-6 > .grid-stack-item[data-gs-x='1'] {
+  left: 16.6666666667%;
+}
+
+.grid-stack.grid-stack-6 > .grid-stack-item[data-gs-min-width='1'] {
+  min-width: 16.6666666667%;
+}
+
+.grid-stack.grid-stack-6 > .grid-stack-item[data-gs-max-width='1'] {
+  max-width: 16.6666666667%;
+}
+
+.grid-stack.grid-stack-6 > .grid-stack-item[data-gs-width='2'] {
+  width: 33.3333333333%;
+}
+
+.grid-stack.grid-stack-6 > .grid-stack-item[data-gs-x='2'] {
+  left: 33.3333333333%;
+}
+
+.grid-stack.grid-stack-6 > .grid-stack-item[data-gs-min-width='2'] {
+  min-width: 33.3333333333%;
+}
+
+.grid-stack.grid-stack-6 > .grid-stack-item[data-gs-max-width='2'] {
+  max-width: 33.3333333333%;
+}
+
+.grid-stack.grid-stack-6 > .grid-stack-item[data-gs-width='3'] {
+  width: 50%;
+}
+
+.grid-stack.grid-stack-6 > .grid-stack-item[data-gs-x='3'] {
+  left: 50%;
+}
+
+.grid-stack.grid-stack-6 > .grid-stack-item[data-gs-min-width='3'] {
+  min-width: 50%;
+}
+
+.grid-stack.grid-stack-6 > .grid-stack-item[data-gs-max-width='3'] {
+  max-width: 50%;
+}
+
+.grid-stack.grid-stack-6 > .grid-stack-item[data-gs-width='4'] {
+  width: 66.6666666667%;
+}
+
+.grid-stack.grid-stack-6 > .grid-stack-item[data-gs-x='4'] {
+  left: 66.6666666667%;
+}
+
+.grid-stack.grid-stack-6 > .grid-stack-item[data-gs-min-width='4'] {
+  min-width: 66.6666666667%;
+}
+
+.grid-stack.grid-stack-6 > .grid-stack-item[data-gs-max-width='4'] {
+  max-width: 66.6666666667%;
+}
+
+.grid-stack.grid-stack-6 > .grid-stack-item[data-gs-width='5'] {
+  width: 83.3333333333%;
+}
+
+.grid-stack.grid-stack-6 > .grid-stack-item[data-gs-x='5'] {
+  left: 83.3333333333%;
+}
+
+.grid-stack.grid-stack-6 > .grid-stack-item[data-gs-min-width='5'] {
+  min-width: 83.3333333333%;
+}
+
+.grid-stack.grid-stack-6 > .grid-stack-item[data-gs-max-width='5'] {
+  max-width: 83.3333333333%;
+}
+
+.grid-stack.grid-stack-6 > .grid-stack-item[data-gs-width='6'] {
+  width: 100%;
+}
+
+.grid-stack.grid-stack-6 > .grid-stack-item[data-gs-x='6'] {
+  left: 100%;
+}
+
+.grid-stack.grid-stack-6 > .grid-stack-item[data-gs-min-width='6'] {
+  min-width: 100%;
+}
+
+.grid-stack.grid-stack-6 > .grid-stack-item[data-gs-max-width='6'] {
+  max-width: 100%;
+}
+
+.grid-stack.grid-stack-7 > .grid-stack-item {
+  min-width: 14.2857142857%;
+}
+
+.grid-stack.grid-stack-7 > .grid-stack-item[data-gs-width='1'] {
+  width: 14.2857142857%;
+}
+
+.grid-stack.grid-stack-7 > .grid-stack-item[data-gs-x='1'] {
+  left: 14.2857142857%;
+}
+
+.grid-stack.grid-stack-7 > .grid-stack-item[data-gs-min-width='1'] {
+  min-width: 14.2857142857%;
+}
+
+.grid-stack.grid-stack-7 > .grid-stack-item[data-gs-max-width='1'] {
+  max-width: 14.2857142857%;
+}
+
+.grid-stack.grid-stack-7 > .grid-stack-item[data-gs-width='2'] {
+  width: 28.5714285714%;
+}
+
+.grid-stack.grid-stack-7 > .grid-stack-item[data-gs-x='2'] {
+  left: 28.5714285714%;
+}
+
+.grid-stack.grid-stack-7 > .grid-stack-item[data-gs-min-width='2'] {
+  min-width: 28.5714285714%;
+}
+
+.grid-stack.grid-stack-7 > .grid-stack-item[data-gs-max-width='2'] {
+  max-width: 28.5714285714%;
+}
+
+.grid-stack.grid-stack-7 > .grid-stack-item[data-gs-width='3'] {
+  width: 42.8571428571%;
+}
+
+.grid-stack.grid-stack-7 > .grid-stack-item[data-gs-x='3'] {
+  left: 42.8571428571%;
+}
+
+.grid-stack.grid-stack-7 > .grid-stack-item[data-gs-min-width='3'] {
+  min-width: 42.8571428571%;
+}
+
+.grid-stack.grid-stack-7 > .grid-stack-item[data-gs-max-width='3'] {
+  max-width: 42.8571428571%;
+}
+
+.grid-stack.grid-stack-7 > .grid-stack-item[data-gs-width='4'] {
+  width: 57.1428571429%;
+}
+
+.grid-stack.grid-stack-7 > .grid-stack-item[data-gs-x='4'] {
+  left: 57.1428571429%;
+}
+
+.grid-stack.grid-stack-7 > .grid-stack-item[data-gs-min-width='4'] {
+  min-width: 57.1428571429%;
+}
+
+.grid-stack.grid-stack-7 > .grid-stack-item[data-gs-max-width='4'] {
+  max-width: 57.1428571429%;
+}
+
+.grid-stack.grid-stack-7 > .grid-stack-item[data-gs-width='5'] {
+  width: 71.4285714286%;
+}
+
+.grid-stack.grid-stack-7 > .grid-stack-item[data-gs-x='5'] {
+  left: 71.4285714286%;
+}
+
+.grid-stack.grid-stack-7 > .grid-stack-item[data-gs-min-width='5'] {
+  min-width: 71.4285714286%;
+}
+
+.grid-stack.grid-stack-7 > .grid-stack-item[data-gs-max-width='5'] {
+  max-width: 71.4285714286%;
+}
+
+.grid-stack.grid-stack-7 > .grid-stack-item[data-gs-width='6'] {
+  width: 85.7142857143%;
+}
+
+.grid-stack.grid-stack-7 > .grid-stack-item[data-gs-x='6'] {
+  left: 85.7142857143%;
+}
+
+.grid-stack.grid-stack-7 > .grid-stack-item[data-gs-min-width='6'] {
+  min-width: 85.7142857143%;
+}
+
+.grid-stack.grid-stack-7 > .grid-stack-item[data-gs-max-width='6'] {
+  max-width: 85.7142857143%;
+}
+
+.grid-stack.grid-stack-7 > .grid-stack-item[data-gs-width='7'] {
+  width: 100%;
+}
+
+.grid-stack.grid-stack-7 > .grid-stack-item[data-gs-x='7'] {
+  left: 100%;
+}
+
+.grid-stack.grid-stack-7 > .grid-stack-item[data-gs-min-width='7'] {
+  min-width: 100%;
+}
+
+.grid-stack.grid-stack-7 > .grid-stack-item[data-gs-max-width='7'] {
+  max-width: 100%;
+}
+
+.grid-stack.grid-stack-8 > .grid-stack-item {
+  min-width: 12.5%;
+}
+
+.grid-stack.grid-stack-8 > .grid-stack-item[data-gs-width='1'] {
+  width: 12.5%;
+}
+
+.grid-stack.grid-stack-8 > .grid-stack-item[data-gs-x='1'] {
+  left: 12.5%;
+}
+
+.grid-stack.grid-stack-8 > .grid-stack-item[data-gs-min-width='1'] {
+  min-width: 12.5%;
+}
+
+.grid-stack.grid-stack-8 > .grid-stack-item[data-gs-max-width='1'] {
+  max-width: 12.5%;
+}
+
+.grid-stack.grid-stack-8 > .grid-stack-item[data-gs-width='2'] {
+  width: 25%;
+}
+
+.grid-stack.grid-stack-8 > .grid-stack-item[data-gs-x='2'] {
+  left: 25%;
+}
+
+.grid-stack.grid-stack-8 > .grid-stack-item[data-gs-min-width='2'] {
+  min-width: 25%;
+}
+
+.grid-stack.grid-stack-8 > .grid-stack-item[data-gs-max-width='2'] {
+  max-width: 25%;
+}
+
+.grid-stack.grid-stack-8 > .grid-stack-item[data-gs-width='3'] {
+  width: 37.5%;
+}
+
+.grid-stack.grid-stack-8 > .grid-stack-item[data-gs-x='3'] {
+  left: 37.5%;
+}
+
+.grid-stack.grid-stack-8 > .grid-stack-item[data-gs-min-width='3'] {
+  min-width: 37.5%;
+}
+
+.grid-stack.grid-stack-8 > .grid-stack-item[data-gs-max-width='3'] {
+  max-width: 37.5%;
+}
+
+.grid-stack.grid-stack-8 > .grid-stack-item[data-gs-width='4'] {
+  width: 50%;
+}
+
+.grid-stack.grid-stack-8 > .grid-stack-item[data-gs-x='4'] {
+  left: 50%;
+}
+
+.grid-stack.grid-stack-8 > .grid-stack-item[data-gs-min-width='4'] {
+  min-width: 50%;
+}
+
+.grid-stack.grid-stack-8 > .grid-stack-item[data-gs-max-width='4'] {
+  max-width: 50%;
+}
+
+.grid-stack.grid-stack-8 > .grid-stack-item[data-gs-width='5'] {
+  width: 62.5%;
+}
+
+.grid-stack.grid-stack-8 > .grid-stack-item[data-gs-x='5'] {
+  left: 62.5%;
+}
+
+.grid-stack.grid-stack-8 > .grid-stack-item[data-gs-min-width='5'] {
+  min-width: 62.5%;
+}
+
+.grid-stack.grid-stack-8 > .grid-stack-item[data-gs-max-width='5'] {
+  max-width: 62.5%;
+}
+
+.grid-stack.grid-stack-8 > .grid-stack-item[data-gs-width='6'] {
+  width: 75%;
+}
+
+.grid-stack.grid-stack-8 > .grid-stack-item[data-gs-x='6'] {
+  left: 75%;
+}
+
+.grid-stack.grid-stack-8 > .grid-stack-item[data-gs-min-width='6'] {
+  min-width: 75%;
+}
+
+.grid-stack.grid-stack-8 > .grid-stack-item[data-gs-max-width='6'] {
+  max-width: 75%;
+}
+
+.grid-stack.grid-stack-8 > .grid-stack-item[data-gs-width='7'] {
+  width: 87.5%;
+}
+
+.grid-stack.grid-stack-8 > .grid-stack-item[data-gs-x='7'] {
+  left: 87.5%;
+}
+
+.grid-stack.grid-stack-8 > .grid-stack-item[data-gs-min-width='7'] {
+  min-width: 87.5%;
+}
+
+.grid-stack.grid-stack-8 > .grid-stack-item[data-gs-max-width='7'] {
+  max-width: 87.5%;
+}
+
+.grid-stack.grid-stack-8 > .grid-stack-item[data-gs-width='8'] {
+  width: 100%;
+}
+
+.grid-stack.grid-stack-8 > .grid-stack-item[data-gs-x='8'] {
+  left: 100%;
+}
+
+.grid-stack.grid-stack-8 > .grid-stack-item[data-gs-min-width='8'] {
+  min-width: 100%;
+}
+
+.grid-stack.grid-stack-8 > .grid-stack-item[data-gs-max-width='8'] {
+  max-width: 100%;
+}
+
+.grid-stack.grid-stack-9 > .grid-stack-item {
+  min-width: 11.1111111111%;
+}
+
+.grid-stack.grid-stack-9 > .grid-stack-item[data-gs-width='1'] {
+  width: 11.1111111111%;
+}
+
+.grid-stack.grid-stack-9 > .grid-stack-item[data-gs-x='1'] {
+  left: 11.1111111111%;
+}
+
+.grid-stack.grid-stack-9 > .grid-stack-item[data-gs-min-width='1'] {
+  min-width: 11.1111111111%;
+}
+
+.grid-stack.grid-stack-9 > .grid-stack-item[data-gs-max-width='1'] {
+  max-width: 11.1111111111%;
+}
+
+.grid-stack.grid-stack-9 > .grid-stack-item[data-gs-width='2'] {
+  width: 22.2222222222%;
+}
+
+.grid-stack.grid-stack-9 > .grid-stack-item[data-gs-x='2'] {
+  left: 22.2222222222%;
+}
+
+.grid-stack.grid-stack-9 > .grid-stack-item[data-gs-min-width='2'] {
+  min-width: 22.2222222222%;
+}
+
+.grid-stack.grid-stack-9 > .grid-stack-item[data-gs-max-width='2'] {
+  max-width: 22.2222222222%;
+}
+
+.grid-stack.grid-stack-9 > .grid-stack-item[data-gs-width='3'] {
+  width: 33.3333333333%;
+}
+
+.grid-stack.grid-stack-9 > .grid-stack-item[data-gs-x='3'] {
+  left: 33.3333333333%;
+}
+
+.grid-stack.grid-stack-9 > .grid-stack-item[data-gs-min-width='3'] {
+  min-width: 33.3333333333%;
+}
+
+.grid-stack.grid-stack-9 > .grid-stack-item[data-gs-max-width='3'] {
+  max-width: 33.3333333333%;
+}
+
+.grid-stack.grid-stack-9 > .grid-stack-item[data-gs-width='4'] {
+  width: 44.4444444444%;
+}
+
+.grid-stack.grid-stack-9 > .grid-stack-item[data-gs-x='4'] {
+  left: 44.4444444444%;
+}
+
+.grid-stack.grid-stack-9 > .grid-stack-item[data-gs-min-width='4'] {
+  min-width: 44.4444444444%;
+}
+
+.grid-stack.grid-stack-9 > .grid-stack-item[data-gs-max-width='4'] {
+  max-width: 44.4444444444%;
+}
+
+.grid-stack.grid-stack-9 > .grid-stack-item[data-gs-width='5'] {
+  width: 55.5555555556%;
+}
+
+.grid-stack.grid-stack-9 > .grid-stack-item[data-gs-x='5'] {
+  left: 55.5555555556%;
+}
+
+.grid-stack.grid-stack-9 > .grid-stack-item[data-gs-min-width='5'] {
+  min-width: 55.5555555556%;
+}
+
+.grid-stack.grid-stack-9 > .grid-stack-item[data-gs-max-width='5'] {
+  max-width: 55.5555555556%;
+}
+
+.grid-stack.grid-stack-9 > .grid-stack-item[data-gs-width='6'] {
+  width: 66.6666666667%;
+}
+
+.grid-stack.grid-stack-9 > .grid-stack-item[data-gs-x='6'] {
+  left: 66.6666666667%;
+}
+
+.grid-stack.grid-stack-9 > .grid-stack-item[data-gs-min-width='6'] {
+  min-width: 66.6666666667%;
+}
+
+.grid-stack.grid-stack-9 > .grid-stack-item[data-gs-max-width='6'] {
+  max-width: 66.6666666667%;
+}
+
+.grid-stack.grid-stack-9 > .grid-stack-item[data-gs-width='7'] {
+  width: 77.7777777778%;
+}
+
+.grid-stack.grid-stack-9 > .grid-stack-item[data-gs-x='7'] {
+  left: 77.7777777778%;
+}
+
+.grid-stack.grid-stack-9 > .grid-stack-item[data-gs-min-width='7'] {
+  min-width: 77.7777777778%;
+}
+
+.grid-stack.grid-stack-9 > .grid-stack-item[data-gs-max-width='7'] {
+  max-width: 77.7777777778%;
+}
+
+.grid-stack.grid-stack-9 > .grid-stack-item[data-gs-width='8'] {
+  width: 88.8888888889%;
+}
+
+.grid-stack.grid-stack-9 > .grid-stack-item[data-gs-x='8'] {
+  left: 88.8888888889%;
+}
+
+.grid-stack.grid-stack-9 > .grid-stack-item[data-gs-min-width='8'] {
+  min-width: 88.8888888889%;
+}
+
+.grid-stack.grid-stack-9 > .grid-stack-item[data-gs-max-width='8'] {
+  max-width: 88.8888888889%;
+}
+
+.grid-stack.grid-stack-9 > .grid-stack-item[data-gs-width='9'] {
+  width: 100%;
+}
+
+.grid-stack.grid-stack-9 > .grid-stack-item[data-gs-x='9'] {
+  left: 100%;
+}
+
+.grid-stack.grid-stack-9 > .grid-stack-item[data-gs-min-width='9'] {
+  min-width: 100%;
+}
+
+.grid-stack.grid-stack-9 > .grid-stack-item[data-gs-max-width='9'] {
+  max-width: 100%;
+}
+
+.grid-stack.grid-stack-10 > .grid-stack-item {
+  min-width: 10%;
+}
+
+.grid-stack.grid-stack-10 > .grid-stack-item[data-gs-width='1'] {
+  width: 10%;
+}
+
+.grid-stack.grid-stack-10 > .grid-stack-item[data-gs-x='1'] {
+  left: 10%;
+}
+
+.grid-stack.grid-stack-10 > .grid-stack-item[data-gs-min-width='1'] {
+  min-width: 10%;
+}
+
+.grid-stack.grid-stack-10 > .grid-stack-item[data-gs-max-width='1'] {
+  max-width: 10%;
+}
+
+.grid-stack.grid-stack-10 > .grid-stack-item[data-gs-width='2'] {
+  width: 20%;
+}
+
+.grid-stack.grid-stack-10 > .grid-stack-item[data-gs-x='2'] {
+  left: 20%;
+}
+
+.grid-stack.grid-stack-10 > .grid-stack-item[data-gs-min-width='2'] {
+  min-width: 20%;
+}
+
+.grid-stack.grid-stack-10 > .grid-stack-item[data-gs-max-width='2'] {
+  max-width: 20%;
+}
+
+.grid-stack.grid-stack-10 > .grid-stack-item[data-gs-width='3'] {
+  width: 30%;
+}
+
+.grid-stack.grid-stack-10 > .grid-stack-item[data-gs-x='3'] {
+  left: 30%;
+}
+
+.grid-stack.grid-stack-10 > .grid-stack-item[data-gs-min-width='3'] {
+  min-width: 30%;
+}
+
+.grid-stack.grid-stack-10 > .grid-stack-item[data-gs-max-width='3'] {
+  max-width: 30%;
+}
+
+.grid-stack.grid-stack-10 > .grid-stack-item[data-gs-width='4'] {
+  width: 40%;
+}
+
+.grid-stack.grid-stack-10 > .grid-stack-item[data-gs-x='4'] {
+  left: 40%;
+}
+
+.grid-stack.grid-stack-10 > .grid-stack-item[data-gs-min-width='4'] {
+  min-width: 40%;
+}
+
+.grid-stack.grid-stack-10 > .grid-stack-item[data-gs-max-width='4'] {
+  max-width: 40%;
+}
+
+.grid-stack.grid-stack-10 > .grid-stack-item[data-gs-width='5'] {
+  width: 50%;
+}
+
+.grid-stack.grid-stack-10 > .grid-stack-item[data-gs-x='5'] {
+  left: 50%;
+}
+
+.grid-stack.grid-stack-10 > .grid-stack-item[data-gs-min-width='5'] {
+  min-width: 50%;
+}
+
+.grid-stack.grid-stack-10 > .grid-stack-item[data-gs-max-width='5'] {
+  max-width: 50%;
+}
+
+.grid-stack.grid-stack-10 > .grid-stack-item[data-gs-width='6'] {
+  width: 60%;
+}
+
+.grid-stack.grid-stack-10 > .grid-stack-item[data-gs-x='6'] {
+  left: 60%;
+}
+
+.grid-stack.grid-stack-10 > .grid-stack-item[data-gs-min-width='6'] {
+  min-width: 60%;
+}
+
+.grid-stack.grid-stack-10 > .grid-stack-item[data-gs-max-width='6'] {
+  max-width: 60%;
+}
+
+.grid-stack.grid-stack-10 > .grid-stack-item[data-gs-width='7'] {
+  width: 70%;
+}
+
+.grid-stack.grid-stack-10 > .grid-stack-item[data-gs-x='7'] {
+  left: 70%;
+}
+
+.grid-stack.grid-stack-10 > .grid-stack-item[data-gs-min-width='7'] {
+  min-width: 70%;
+}
+
+.grid-stack.grid-stack-10 > .grid-stack-item[data-gs-max-width='7'] {
+  max-width: 70%;
+}
+
+.grid-stack.grid-stack-10 > .grid-stack-item[data-gs-width='8'] {
+  width: 80%;
+}
+
+.grid-stack.grid-stack-10 > .grid-stack-item[data-gs-x='8'] {
+  left: 80%;
+}
+
+.grid-stack.grid-stack-10 > .grid-stack-item[data-gs-min-width='8'] {
+  min-width: 80%;
+}
+
+.grid-stack.grid-stack-10 > .grid-stack-item[data-gs-max-width='8'] {
+  max-width: 80%;
+}
+
+.grid-stack.grid-stack-10 > .grid-stack-item[data-gs-width='9'] {
+  width: 90%;
+}
+
+.grid-stack.grid-stack-10 > .grid-stack-item[data-gs-x='9'] {
+  left: 90%;
+}
+
+.grid-stack.grid-stack-10 > .grid-stack-item[data-gs-min-width='9'] {
+  min-width: 90%;
+}
+
+.grid-stack.grid-stack-10 > .grid-stack-item[data-gs-max-width='9'] {
+  max-width: 90%;
+}
+
+.grid-stack.grid-stack-10 > .grid-stack-item[data-gs-width='10'] {
+  width: 100%;
+}
+
+.grid-stack.grid-stack-10 > .grid-stack-item[data-gs-x='10'] {
+  left: 100%;
+}
+
+.grid-stack.grid-stack-10 > .grid-stack-item[data-gs-min-width='10'] {
+  min-width: 100%;
+}
+
+.grid-stack.grid-stack-10 > .grid-stack-item[data-gs-max-width='10'] {
+  max-width: 100%;
+}
+
+.grid-stack.grid-stack-11 > .grid-stack-item {
+  min-width: 9.0909090909%;
+}
+
+.grid-stack.grid-stack-11 > .grid-stack-item[data-gs-width='1'] {
+  width: 9.0909090909%;
+}
+
+.grid-stack.grid-stack-11 > .grid-stack-item[data-gs-x='1'] {
+  left: 9.0909090909%;
+}
+
+.grid-stack.grid-stack-11 > .grid-stack-item[data-gs-min-width='1'] {
+  min-width: 9.0909090909%;
+}
+
+.grid-stack.grid-stack-11 > .grid-stack-item[data-gs-max-width='1'] {
+  max-width: 9.0909090909%;
+}
+
+.grid-stack.grid-stack-11 > .grid-stack-item[data-gs-width='2'] {
+  width: 18.1818181818%;
+}
+
+.grid-stack.grid-stack-11 > .grid-stack-item[data-gs-x='2'] {
+  left: 18.1818181818%;
+}
+
+.grid-stack.grid-stack-11 > .grid-stack-item[data-gs-min-width='2'] {
+  min-width: 18.1818181818%;
+}
+
+.grid-stack.grid-stack-11 > .grid-stack-item[data-gs-max-width='2'] {
+  max-width: 18.1818181818%;
+}
+
+.grid-stack.grid-stack-11 > .grid-stack-item[data-gs-width='3'] {
+  width: 27.2727272727%;
+}
+
+.grid-stack.grid-stack-11 > .grid-stack-item[data-gs-x='3'] {
+  left: 27.2727272727%;
+}
+
+.grid-stack.grid-stack-11 > .grid-stack-item[data-gs-min-width='3'] {
+  min-width: 27.2727272727%;
+}
+
+.grid-stack.grid-stack-11 > .grid-stack-item[data-gs-max-width='3'] {
+  max-width: 27.2727272727%;
+}
+
+.grid-stack.grid-stack-11 > .grid-stack-item[data-gs-width='4'] {
+  width: 36.3636363636%;
+}
+
+.grid-stack.grid-stack-11 > .grid-stack-item[data-gs-x='4'] {
+  left: 36.3636363636%;
+}
+
+.grid-stack.grid-stack-11 > .grid-stack-item[data-gs-min-width='4'] {
+  min-width: 36.3636363636%;
+}
+
+.grid-stack.grid-stack-11 > .grid-stack-item[data-gs-max-width='4'] {
+  max-width: 36.3636363636%;
+}
+
+.grid-stack.grid-stack-11 > .grid-stack-item[data-gs-width='5'] {
+  width: 45.4545454545%;
+}
+
+.grid-stack.grid-stack-11 > .grid-stack-item[data-gs-x='5'] {
+  left: 45.4545454545%;
+}
+
+.grid-stack.grid-stack-11 > .grid-stack-item[data-gs-min-width='5'] {
+  min-width: 45.4545454545%;
+}
+
+.grid-stack.grid-stack-11 > .grid-stack-item[data-gs-max-width='5'] {
+  max-width: 45.4545454545%;
+}
+
+.grid-stack.grid-stack-11 > .grid-stack-item[data-gs-width='6'] {
+  width: 54.5454545455%;
+}
+
+.grid-stack.grid-stack-11 > .grid-stack-item[data-gs-x='6'] {
+  left: 54.5454545455%;
+}
+
+.grid-stack.grid-stack-11 > .grid-stack-item[data-gs-min-width='6'] {
+  min-width: 54.5454545455%;
+}
+
+.grid-stack.grid-stack-11 > .grid-stack-item[data-gs-max-width='6'] {
+  max-width: 54.5454545455%;
+}
+
+.grid-stack.grid-stack-11 > .grid-stack-item[data-gs-width='7'] {
+  width: 63.6363636364%;
+}
+
+.grid-stack.grid-stack-11 > .grid-stack-item[data-gs-x='7'] {
+  left: 63.6363636364%;
+}
+
+.grid-stack.grid-stack-11 > .grid-stack-item[data-gs-min-width='7'] {
+  min-width: 63.6363636364%;
+}
+
+.grid-stack.grid-stack-11 > .grid-stack-item[data-gs-max-width='7'] {
+  max-width: 63.6363636364%;
+}
+
+.grid-stack.grid-stack-11 > .grid-stack-item[data-gs-width='8'] {
+  width: 72.7272727273%;
+}
+
+.grid-stack.grid-stack-11 > .grid-stack-item[data-gs-x='8'] {
+  left: 72.7272727273%;
+}
+
+.grid-stack.grid-stack-11 > .grid-stack-item[data-gs-min-width='8'] {
+  min-width: 72.7272727273%;
+}
+
+.grid-stack.grid-stack-11 > .grid-stack-item[data-gs-max-width='8'] {
+  max-width: 72.7272727273%;
+}
+
+.grid-stack.grid-stack-11 > .grid-stack-item[data-gs-width='9'] {
+  width: 81.8181818182%;
+}
+
+.grid-stack.grid-stack-11 > .grid-stack-item[data-gs-x='9'] {
+  left: 81.8181818182%;
+}
+
+.grid-stack.grid-stack-11 > .grid-stack-item[data-gs-min-width='9'] {
+  min-width: 81.8181818182%;
+}
+
+.grid-stack.grid-stack-11 > .grid-stack-item[data-gs-max-width='9'] {
+  max-width: 81.8181818182%;
+}
+
+.grid-stack.grid-stack-11 > .grid-stack-item[data-gs-width='10'] {
+  width: 90.9090909091%;
+}
+
+.grid-stack.grid-stack-11 > .grid-stack-item[data-gs-x='10'] {
+  left: 90.9090909091%;
+}
+
+.grid-stack.grid-stack-11 > .grid-stack-item[data-gs-min-width='10'] {
+  min-width: 90.9090909091%;
+}
+
+.grid-stack.grid-stack-11 > .grid-stack-item[data-gs-max-width='10'] {
+  max-width: 90.9090909091%;
+}
+
+.grid-stack.grid-stack-11 > .grid-stack-item[data-gs-width='11'] {
+  width: 100%;
+}
+
+.grid-stack.grid-stack-11 > .grid-stack-item[data-gs-x='11'] {
+  left: 100%;
+}
+
+.grid-stack.grid-stack-11 > .grid-stack-item[data-gs-min-width='11'] {
+  min-width: 100%;
+}
+
+.grid-stack.grid-stack-11 > .grid-stack-item[data-gs-max-width='11'] {
+  max-width: 100%;
+}
+
+.grid-stack.grid-stack-12 > .grid-stack-item {
+  min-width: 8.3333333333%;
+}
+
+.grid-stack.grid-stack-12 > .grid-stack-item[data-gs-width='1'] {
+  width: 8.3333333333%;
+}
+
+.grid-stack.grid-stack-12 > .grid-stack-item[data-gs-x='1'] {
+  left: 8.3333333333%;
+}
+
+.grid-stack.grid-stack-12 > .grid-stack-item[data-gs-min-width='1'] {
+  min-width: 8.3333333333%;
+}
+
+.grid-stack.grid-stack-12 > .grid-stack-item[data-gs-max-width='1'] {
+  max-width: 8.3333333333%;
+}
+
+.grid-stack.grid-stack-12 > .grid-stack-item[data-gs-width='2'] {
+  width: 16.6666666667%;
+}
+
+.grid-stack.grid-stack-12 > .grid-stack-item[data-gs-x='2'] {
+  left: 16.6666666667%;
+}
+
+.grid-stack.grid-stack-12 > .grid-stack-item[data-gs-min-width='2'] {
+  min-width: 16.6666666667%;
+}
+
+.grid-stack.grid-stack-12 > .grid-stack-item[data-gs-max-width='2'] {
+  max-width: 16.6666666667%;
+}
+
+.grid-stack.grid-stack-12 > .grid-stack-item[data-gs-width='3'] {
+  width: 25%;
+}
+
+.grid-stack.grid-stack-12 > .grid-stack-item[data-gs-x='3'] {
+  left: 25%;
+}
+
+.grid-stack.grid-stack-12 > .grid-stack-item[data-gs-min-width='3'] {
+  min-width: 25%;
+}
+
+.grid-stack.grid-stack-12 > .grid-stack-item[data-gs-max-width='3'] {
+  max-width: 25%;
+}
+
+.grid-stack.grid-stack-12 > .grid-stack-item[data-gs-width='4'] {
+  width: 33.3333333333%;
+}
+
+.grid-stack.grid-stack-12 > .grid-stack-item[data-gs-x='4'] {
+  left: 33.3333333333%;
+}
+
+.grid-stack.grid-stack-12 > .grid-stack-item[data-gs-min-width='4'] {
+  min-width: 33.3333333333%;
+}
+
+.grid-stack.grid-stack-12 > .grid-stack-item[data-gs-max-width='4'] {
+  max-width: 33.3333333333%;
+}
+
+.grid-stack.grid-stack-12 > .grid-stack-item[data-gs-width='5'] {
+  width: 41.6666666667%;
+}
+
+.grid-stack.grid-stack-12 > .grid-stack-item[data-gs-x='5'] {
+  left: 41.6666666667%;
+}
+
+.grid-stack.grid-stack-12 > .grid-stack-item[data-gs-min-width='5'] {
+  min-width: 41.6666666667%;
+}
+
+.grid-stack.grid-stack-12 > .grid-stack-item[data-gs-max-width='5'] {
+  max-width: 41.6666666667%;
+}
+
+.grid-stack.grid-stack-12 > .grid-stack-item[data-gs-width='6'] {
+  width: 50%;
+}
+
+.grid-stack.grid-stack-12 > .grid-stack-item[data-gs-x='6'] {
+  left: 50%;
+}
+
+.grid-stack.grid-stack-12 > .grid-stack-item[data-gs-min-width='6'] {
+  min-width: 50%;
+}
+
+.grid-stack.grid-stack-12 > .grid-stack-item[data-gs-max-width='6'] {
+  max-width: 50%;
+}
+
+.grid-stack.grid-stack-12 > .grid-stack-item[data-gs-width='7'] {
+  width: 58.3333333333%;
+}
+
+.grid-stack.grid-stack-12 > .grid-stack-item[data-gs-x='7'] {
+  left: 58.3333333333%;
+}
+
+.grid-stack.grid-stack-12 > .grid-stack-item[data-gs-min-width='7'] {
+  min-width: 58.3333333333%;
+}
+
+.grid-stack.grid-stack-12 > .grid-stack-item[data-gs-max-width='7'] {
+  max-width: 58.3333333333%;
+}
+
+.grid-stack.grid-stack-12 > .grid-stack-item[data-gs-width='8'] {
+  width: 66.6666666667%;
+}
+
+.grid-stack.grid-stack-12 > .grid-stack-item[data-gs-x='8'] {
+  left: 66.6666666667%;
+}
+
+.grid-stack.grid-stack-12 > .grid-stack-item[data-gs-min-width='8'] {
+  min-width: 66.6666666667%;
+}
+
+.grid-stack.grid-stack-12 > .grid-stack-item[data-gs-max-width='8'] {
+  max-width: 66.6666666667%;
+}
+
+.grid-stack.grid-stack-12 > .grid-stack-item[data-gs-width='9'] {
+  width: 75%;
+}
+
+.grid-stack.grid-stack-12 > .grid-stack-item[data-gs-x='9'] {
+  left: 75%;
+}
+
+.grid-stack.grid-stack-12 > .grid-stack-item[data-gs-min-width='9'] {
+  min-width: 75%;
+}
+
+.grid-stack.grid-stack-12 > .grid-stack-item[data-gs-max-width='9'] {
+  max-width: 75%;
+}
+
+.grid-stack.grid-stack-12 > .grid-stack-item[data-gs-width='10'] {
+  width: 83.3333333333%;
+}
+
+.grid-stack.grid-stack-12 > .grid-stack-item[data-gs-x='10'] {
+  left: 83.3333333333%;
+}
+
+.grid-stack.grid-stack-12 > .grid-stack-item[data-gs-min-width='10'] {
+  min-width: 83.3333333333%;
+}
+
+.grid-stack.grid-stack-12 > .grid-stack-item[data-gs-max-width='10'] {
+  max-width: 83.3333333333%;
+}
+
+.grid-stack.grid-stack-12 > .grid-stack-item[data-gs-width='11'] {
+  width: 91.6666666667%;
+}
+
+.grid-stack.grid-stack-12 > .grid-stack-item[data-gs-x='11'] {
+  left: 91.6666666667%;
+}
+
+.grid-stack.grid-stack-12 > .grid-stack-item[data-gs-min-width='11'] {
+  min-width: 91.6666666667%;
+}
+
+.grid-stack.grid-stack-12 > .grid-stack-item[data-gs-max-width='11'] {
+  max-width: 91.6666666667%;
+}
+
+.grid-stack.grid-stack-12 > .grid-stack-item[data-gs-width='12'] {
+  width: 100%;
+}
+
+.grid-stack.grid-stack-12 > .grid-stack-item[data-gs-x='12'] {
+  left: 100%;
+}
+
+.grid-stack.grid-stack-12 > .grid-stack-item[data-gs-min-width='12'] {
+  min-width: 100%;
+}
+
+.grid-stack.grid-stack-12 > .grid-stack-item[data-gs-max-width='12'] {
+  max-width: 100%;
+}

+ 387 - 0
static/lib/gridstack/gridstack.css

@@ -0,0 +1,387 @@
+:root .grid-stack-item > .ui-resizable-handle {
+  filter: none;
+}
+
+.grid-stack {
+  position: relative;
+}
+
+.grid-stack.grid-stack-rtl {
+  direction: ltr;
+}
+
+.grid-stack.grid-stack-rtl > .grid-stack-item {
+  direction: rtl;
+}
+
+.grid-stack .grid-stack-placeholder > .placeholder-content {
+  border: 1px dashed lightgray;
+  margin: 0;
+  position: absolute;
+  top: 0;
+  left: 10px;
+  right: 10px;
+  bottom: 0;
+  width: auto;
+  z-index: 0 !important;
+  text-align: center;
+}
+
+.grid-stack > .grid-stack-item {
+  min-width: 8.3333333333%;
+  position: absolute;
+  padding: 0;
+}
+
+.grid-stack > .grid-stack-item > .grid-stack-item-content {
+  margin: 0;
+  position: absolute;
+  top: 0;
+  left: 10px;
+  right: 10px;
+  bottom: 0;
+  width: auto;
+  z-index: 0 !important;
+  overflow-x: hidden;
+  overflow-y: auto;
+}
+
+.grid-stack > .grid-stack-item > .ui-resizable-handle {
+  position: absolute;
+  font-size: 0.1px;
+  display: block;
+  -ms-touch-action: none;
+  touch-action: none;
+}
+
+.grid-stack > .grid-stack-item.ui-resizable-disabled > .ui-resizable-handle,
+.grid-stack > .grid-stack-item.ui-resizable-autohide > .ui-resizable-handle {
+  display: none;
+}
+
+.grid-stack > .grid-stack-item.ui-draggable-dragging, .grid-stack > .grid-stack-item.ui-resizable-resizing {
+  z-index: 100;
+}
+
+.grid-stack > .grid-stack-item.ui-draggable-dragging > .grid-stack-item-content,
+.grid-stack > .grid-stack-item.ui-draggable-dragging > .grid-stack-item-content, .grid-stack > .grid-stack-item.ui-resizable-resizing > .grid-stack-item-content,
+.grid-stack > .grid-stack-item.ui-resizable-resizing > .grid-stack-item-content {
+  box-shadow: 1px 4px 6px rgba(0, 0, 0, 0.2);
+  opacity: 0.8;
+}
+
+.grid-stack > .grid-stack-item > .ui-resizable-se,
+.grid-stack > .grid-stack-item > .ui-resizable-sw {
+  background-image: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pgo8IS0tIEdlbmVyYXRvcjogQWRvYmUgSWxsdXN0cmF0b3IgMTYuMC4wLCBTVkcgRXhwb3J0IFBsdWctSW4gLiBTVkcgVmVyc2lvbjogNi4wMCBCdWlsZCAwKSAgLS0+CjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+CjxzdmcgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgdmVyc2lvbj0iMS4xIiBpZD0iQ2FwYV8xIiB4PSIwcHgiIHk9IjBweCIgd2lkdGg9IjE2cHgiIGhlaWdodD0iMTZweCIgdmlld0JveD0iMCAwIDUxMS42MjYgNTExLjYyNyIgc3R5bGU9ImVuYWJsZS1iYWNrZ3JvdW5kOm5ldyAwIDAgNTExLjYyNiA1MTEuNjI3OyIgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+CjxnPgoJPHBhdGggZD0iTTMyOC45MDYsNDAxLjk5NGgtMzYuNTUzVjEwOS42MzZoMzYuNTUzYzQuOTQ4LDAsOS4yMzYtMS44MDksMTIuODQ3LTUuNDI2YzMuNjEzLTMuNjE1LDUuNDIxLTcuODk4LDUuNDIxLTEyLjg0NSAgIGMwLTQuOTQ5LTEuODAxLTkuMjMxLTUuNDI4LTEyLjg1MWwtNzMuMDg3LTczLjA5QzI2NS4wNDQsMS44MDksMjYwLjc2LDAsMjU1LjgxMywwYy00Ljk0OCwwLTkuMjI5LDEuODA5LTEyLjg0Nyw1LjQyNCAgIGwtNzMuMDg4LDczLjA5Yy0zLjYxOCwzLjYxOS01LjQyNCw3LjkwMi01LjQyNCwxMi44NTFjMCw0Ljk0NiwxLjgwNyw5LjIyOSw1LjQyNCwxMi44NDVjMy42MTksMy42MTcsNy45MDEsNS40MjYsMTIuODUsNS40MjYgICBoMzYuNTQ1djI5Mi4zNThoLTM2LjU0MmMtNC45NTIsMC05LjIzNSwxLjgwOC0xMi44NSw1LjQyMWMtMy42MTcsMy42MjEtNS40MjQsNy45MDUtNS40MjQsMTIuODU0ICAgYzAsNC45NDUsMS44MDcsOS4yMjcsNS40MjQsMTIuODQ3bDczLjA4OSw3My4wODhjMy42MTcsMy42MTcsNy44OTgsNS40MjQsMTIuODQ3LDUuNDI0YzQuOTUsMCw5LjIzNC0xLjgwNywxMi44NDktNS40MjQgICBsNzMuMDg3LTczLjA4OGMzLjYxMy0zLjYyLDUuNDIxLTcuOTAxLDUuNDIxLTEyLjg0N2MwLTQuOTQ4LTEuODA4LTkuMjMyLTUuNDIxLTEyLjg1NCAgIEMzMzguMTQyLDQwMy44MDIsMzMzLjg1Nyw0MDEuOTk0LDMyOC45MDYsNDAxLjk5NHoiIGZpbGw9IiM2NjY2NjYiLz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8L3N2Zz4K);
+  background-repeat: no-repeat;
+  background-position: center;
+  -webkit-transform: rotate(45deg);
+  -moz-transform: rotate(45deg);
+  -ms-transform: rotate(45deg);
+  -o-transform: rotate(45deg);
+  transform: rotate(45deg);
+}
+
+.grid-stack > .grid-stack-item > .ui-resizable-se {
+  -webkit-transform: rotate(-45deg);
+  -moz-transform: rotate(-45deg);
+  -ms-transform: rotate(-45deg);
+  -o-transform: rotate(-45deg);
+  transform: rotate(-45deg);
+}
+
+.grid-stack > .grid-stack-item > .ui-resizable-nw {
+  cursor: nw-resize;
+  width: 20px;
+  height: 20px;
+  left: 10px;
+  top: 0;
+}
+
+.grid-stack > .grid-stack-item > .ui-resizable-n {
+  cursor: n-resize;
+  height: 10px;
+  top: 0;
+  left: 25px;
+  right: 25px;
+}
+
+.grid-stack > .grid-stack-item > .ui-resizable-ne {
+  cursor: ne-resize;
+  width: 20px;
+  height: 20px;
+  right: 10px;
+  top: 0;
+}
+
+.grid-stack > .grid-stack-item > .ui-resizable-e {
+  cursor: e-resize;
+  width: 10px;
+  right: 10px;
+  top: 15px;
+  bottom: 15px;
+}
+
+.grid-stack > .grid-stack-item > .ui-resizable-se {
+  cursor: se-resize;
+  width: 20px;
+  height: 20px;
+  right: 10px;
+  bottom: 0;
+}
+
+.grid-stack > .grid-stack-item > .ui-resizable-s {
+  cursor: s-resize;
+  height: 10px;
+  left: 25px;
+  bottom: 0;
+  right: 25px;
+}
+
+.grid-stack > .grid-stack-item > .ui-resizable-sw {
+  cursor: sw-resize;
+  width: 20px;
+  height: 20px;
+  left: 10px;
+  bottom: 0;
+}
+
+.grid-stack > .grid-stack-item > .ui-resizable-w {
+  cursor: w-resize;
+  width: 10px;
+  left: 10px;
+  top: 15px;
+  bottom: 15px;
+}
+
+.grid-stack > .grid-stack-item.ui-draggable-dragging > .ui-resizable-handle {
+  display: none !important;
+}
+
+.grid-stack > .grid-stack-item[data-gs-width='1'] {
+  width: 8.3333333333%;
+}
+
+.grid-stack > .grid-stack-item[data-gs-x='1'] {
+  left: 8.3333333333%;
+}
+
+.grid-stack > .grid-stack-item[data-gs-min-width='1'] {
+  min-width: 8.3333333333%;
+}
+
+.grid-stack > .grid-stack-item[data-gs-max-width='1'] {
+  max-width: 8.3333333333%;
+}
+
+.grid-stack > .grid-stack-item[data-gs-width='2'] {
+  width: 16.6666666667%;
+}
+
+.grid-stack > .grid-stack-item[data-gs-x='2'] {
+  left: 16.6666666667%;
+}
+
+.grid-stack > .grid-stack-item[data-gs-min-width='2'] {
+  min-width: 16.6666666667%;
+}
+
+.grid-stack > .grid-stack-item[data-gs-max-width='2'] {
+  max-width: 16.6666666667%;
+}
+
+.grid-stack > .grid-stack-item[data-gs-width='3'] {
+  width: 25%;
+}
+
+.grid-stack > .grid-stack-item[data-gs-x='3'] {
+  left: 25%;
+}
+
+.grid-stack > .grid-stack-item[data-gs-min-width='3'] {
+  min-width: 25%;
+}
+
+.grid-stack > .grid-stack-item[data-gs-max-width='3'] {
+  max-width: 25%;
+}
+
+.grid-stack > .grid-stack-item[data-gs-width='4'] {
+  width: 33.3333333333%;
+}
+
+.grid-stack > .grid-stack-item[data-gs-x='4'] {
+  left: 33.3333333333%;
+}
+
+.grid-stack > .grid-stack-item[data-gs-min-width='4'] {
+  min-width: 33.3333333333%;
+}
+
+.grid-stack > .grid-stack-item[data-gs-max-width='4'] {
+  max-width: 33.3333333333%;
+}
+
+.grid-stack > .grid-stack-item[data-gs-width='5'] {
+  width: 41.6666666667%;
+}
+
+.grid-stack > .grid-stack-item[data-gs-x='5'] {
+  left: 41.6666666667%;
+}
+
+.grid-stack > .grid-stack-item[data-gs-min-width='5'] {
+  min-width: 41.6666666667%;
+}
+
+.grid-stack > .grid-stack-item[data-gs-max-width='5'] {
+  max-width: 41.6666666667%;
+}
+
+.grid-stack > .grid-stack-item[data-gs-width='6'] {
+  width: 50%;
+}
+
+.grid-stack > .grid-stack-item[data-gs-x='6'] {
+  left: 50%;
+}
+
+.grid-stack > .grid-stack-item[data-gs-min-width='6'] {
+  min-width: 50%;
+}
+
+.grid-stack > .grid-stack-item[data-gs-max-width='6'] {
+  max-width: 50%;
+}
+
+.grid-stack > .grid-stack-item[data-gs-width='7'] {
+  width: 58.3333333333%;
+}
+
+.grid-stack > .grid-stack-item[data-gs-x='7'] {
+  left: 58.3333333333%;
+}
+
+.grid-stack > .grid-stack-item[data-gs-min-width='7'] {
+  min-width: 58.3333333333%;
+}
+
+.grid-stack > .grid-stack-item[data-gs-max-width='7'] {
+  max-width: 58.3333333333%;
+}
+
+.grid-stack > .grid-stack-item[data-gs-width='8'] {
+  width: 66.6666666667%;
+}
+
+.grid-stack > .grid-stack-item[data-gs-x='8'] {
+  left: 66.6666666667%;
+}
+
+.grid-stack > .grid-stack-item[data-gs-min-width='8'] {
+  min-width: 66.6666666667%;
+}
+
+.grid-stack > .grid-stack-item[data-gs-max-width='8'] {
+  max-width: 66.6666666667%;
+}
+
+.grid-stack > .grid-stack-item[data-gs-width='9'] {
+  width: 75%;
+}
+
+.grid-stack > .grid-stack-item[data-gs-x='9'] {
+  left: 75%;
+}
+
+.grid-stack > .grid-stack-item[data-gs-min-width='9'] {
+  min-width: 75%;
+}
+
+.grid-stack > .grid-stack-item[data-gs-max-width='9'] {
+  max-width: 75%;
+}
+
+.grid-stack > .grid-stack-item[data-gs-width='10'] {
+  width: 83.3333333333%;
+}
+
+.grid-stack > .grid-stack-item[data-gs-x='10'] {
+  left: 83.3333333333%;
+}
+
+.grid-stack > .grid-stack-item[data-gs-min-width='10'] {
+  min-width: 83.3333333333%;
+}
+
+.grid-stack > .grid-stack-item[data-gs-max-width='10'] {
+  max-width: 83.3333333333%;
+}
+
+.grid-stack > .grid-stack-item[data-gs-width='11'] {
+  width: 91.6666666667%;
+}
+
+.grid-stack > .grid-stack-item[data-gs-x='11'] {
+  left: 91.6666666667%;
+}
+
+.grid-stack > .grid-stack-item[data-gs-min-width='11'] {
+  min-width: 91.6666666667%;
+}
+
+.grid-stack > .grid-stack-item[data-gs-max-width='11'] {
+  max-width: 91.6666666667%;
+}
+
+.grid-stack > .grid-stack-item[data-gs-width='12'] {
+  width: 100%;
+}
+
+.grid-stack > .grid-stack-item[data-gs-x='12'] {
+  left: 100%;
+}
+
+.grid-stack > .grid-stack-item[data-gs-min-width='12'] {
+  min-width: 100%;
+}
+
+.grid-stack > .grid-stack-item[data-gs-max-width='12'] {
+  max-width: 100%;
+}
+
+.grid-stack.grid-stack-animate,
+.grid-stack.grid-stack-animate .grid-stack-item {
+  -webkit-transition: left 0.3s, top 0.3s, height 0.3s, width 0.3s;
+  -moz-transition: left 0.3s, top 0.3s, height 0.3s, width 0.3s;
+  -ms-transition: left 0.3s, top 0.3s, height 0.3s, width 0.3s;
+  -o-transition: left 0.3s, top 0.3s, height 0.3s, width 0.3s;
+  transition: left 0.3s, top 0.3s, height 0.3s, width 0.3s;
+}
+
+.grid-stack.grid-stack-animate .grid-stack-item.ui-draggable-dragging,
+.grid-stack.grid-stack-animate .grid-stack-item.ui-resizable-resizing,
+.grid-stack.grid-stack-animate .grid-stack-item.grid-stack-placeholder {
+  -webkit-transition: left 0s, top 0s, height 0s, width 0s;
+  -moz-transition: left 0s, top 0s, height 0s, width 0s;
+  -ms-transition: left 0s, top 0s, height 0s, width 0s;
+  -o-transition: left 0s, top 0s, height 0s, width 0s;
+  transition: left 0s, top 0s, height 0s, width 0s;
+}
+
+.grid-stack.grid-stack-one-column-mode {
+  height: auto !important;
+}
+
+.grid-stack.grid-stack-one-column-mode > .grid-stack-item {
+  position: relative !important;
+  width: auto !important;
+  left: 0 !important;
+  top: auto !important;
+  margin-bottom: 20px;
+  max-width: none !important;
+}
+
+.grid-stack.grid-stack-one-column-mode > .grid-stack-item > .ui-resizable-handle {
+  display: none;
+}

+ 97 - 0
static/lib/gridstack/gridstack.jQueryUI.js

@@ -0,0 +1,97 @@
+/**
+ * gridstack.js 1.0.0-dev
+ * http://troolee.github.io/gridstack.js/
+ * (c) 2014-2017 Pavel Reznikov, Dylan Weiss
+ * gridstack.js may be freely distributed under the MIT license.
+ * @preserve
+*/
+(function(factory) {
+    if (typeof define === 'function' && define.amd) {
+        define(['jquery', 'lodash', 'gridstack', 'jquery-ui/data', 'jquery-ui/disable-selection', 'jquery-ui/focusable',
+            'jquery-ui/form', 'jquery-ui/ie', 'jquery-ui/keycode', 'jquery-ui/labels', 'jquery-ui/jquery-1-7',
+            'jquery-ui/plugin', 'jquery-ui/safe-active-element', 'jquery-ui/safe-blur', 'jquery-ui/scroll-parent',
+            'jquery-ui/tabbable', 'jquery-ui/unique-id', 'jquery-ui/version', 'jquery-ui/widget',
+            'jquery-ui/widgets/mouse', 'jquery-ui/widgets/draggable', 'jquery-ui/widgets/droppable',
+            'jquery-ui/widgets/resizable'], factory);
+    } else if (typeof exports !== 'undefined') {
+        try { jQuery = require('jquery'); } catch (e) {}
+        try { _ = require('lodash'); } catch (e) {}
+        try { GridStackUI = require('gridstack'); } catch (e) {}
+        factory(jQuery, _, GridStackUI);
+    } else {
+        factory(jQuery, _, GridStackUI);
+    }
+})(function($, _, GridStackUI) {
+
+    var scope = window;
+
+    /**
+    * @class JQueryUIGridStackDragDropPlugin
+    * jQuery UI implementation of drag'n'drop gridstack plugin.
+    */
+    function JQueryUIGridStackDragDropPlugin(grid) {
+        GridStackUI.GridStackDragDropPlugin.call(this, grid);
+    }
+
+    GridStackUI.GridStackDragDropPlugin.registerPlugin(JQueryUIGridStackDragDropPlugin);
+
+    JQueryUIGridStackDragDropPlugin.prototype = Object.create(GridStackUI.GridStackDragDropPlugin.prototype);
+    JQueryUIGridStackDragDropPlugin.prototype.constructor = JQueryUIGridStackDragDropPlugin;
+
+    JQueryUIGridStackDragDropPlugin.prototype.resizable = function(el, opts) {
+        el = $(el);
+        if (opts === 'disable' || opts === 'enable') {
+            el.resizable(opts);
+        } else if (opts === 'option') {
+            var key = arguments[2];
+            var value = arguments[3];
+            el.resizable(opts, key, value);
+        } else {
+            el.resizable(_.extend({}, this.grid.opts.resizable, {
+                start: opts.start || function() {},
+                stop: opts.stop || function() {},
+                resize: opts.resize || function() {}
+            }));
+        }
+        return this;
+    };
+
+    JQueryUIGridStackDragDropPlugin.prototype.draggable = function(el, opts) {
+        el = $(el);
+        if (opts === 'disable' || opts === 'enable') {
+            el.draggable(opts);
+        } else {
+            el.draggable(_.extend({}, this.grid.opts.draggable, {
+                containment: this.grid.opts.isNested ? this.grid.container.parent() : null,
+                start: opts.start || function() {},
+                stop: opts.stop || function() {},
+                drag: opts.drag || function() {}
+            }));
+        }
+        return this;
+    };
+
+    JQueryUIGridStackDragDropPlugin.prototype.droppable = function(el, opts) {
+        el = $(el);
+        if (opts === 'disable' || opts === 'enable') {
+            el.droppable(opts);
+        } else {
+            el.droppable({
+                accept: opts.accept
+            });
+        }
+        return this;
+    };
+
+    JQueryUIGridStackDragDropPlugin.prototype.isDroppable = function(el, opts) {
+        el = $(el);
+        return Boolean(el.data('droppable'));
+    };
+
+    JQueryUIGridStackDragDropPlugin.prototype.on = function(el, eventName, callback) {
+        $(el).on(eventName, callback);
+        return this;
+    };
+
+    return JQueryUIGridStackDragDropPlugin;
+});

+ 1746 - 0
static/lib/gridstack/gridstack.js

@@ -0,0 +1,1746 @@
+/**
+ * gridstack.js 1.0.0-dev
+ * http://troolee.github.io/gridstack.js/
+ * (c) 2014-2017 Pavel Reznikov, Dylan Weiss
+ * gridstack.js may be freely distributed under the MIT license.
+ * @preserve
+*/
+(function(factory) {
+    if (typeof define === 'function' && define.amd) {
+        define(['jquery', 'lodash'], factory);
+    } else if (typeof exports !== 'undefined') {
+        try { jQuery = require('jquery'); } catch (e) {}
+        try { _ = require('lodash'); } catch (e) {}
+        factory(jQuery, _);
+    } else {
+        factory(jQuery, _);
+    }
+})(function($, _) {
+
+    var scope = window;
+
+    var obsolete = function(f, oldName, newName) {
+        var wrapper = function() {
+            console.warn('gridstack.js: Function `' + oldName + '` is deprecated as of v0.2.5 and has been replaced ' +
+            'with `' + newName + '`. It will be **completely** removed in v1.0.');
+            return f.apply(this, arguments);
+        };
+        wrapper.prototype = f.prototype;
+
+        return wrapper;
+    };
+
+    var obsoleteOpts = function(oldName, newName) {
+        console.warn('gridstack.js: Option `' + oldName + '` is deprecated as of v0.2.5 and has been replaced with `' +
+            newName + '`. It will be **completely** removed in v1.0.');
+    };
+
+    var Utils = {
+        isIntercepted: function(a, b) {
+            return !(a.x + a.width <= b.x || b.x + b.width <= a.x || a.y + a.height <= b.y || b.y + b.height <= a.y);
+        },
+
+        sort: function(nodes, dir, width) {
+            width = width || _.chain(nodes).map(function(node) { return node.x + node.width; }).max().value();
+            dir = dir != -1 ? 1 : -1;
+            return _.sortBy(nodes, function(n) { return dir * (n.x + n.y * width); });
+        },
+
+        createStylesheet: function(id) {
+            var style = document.createElement('style');
+            style.setAttribute('type', 'text/css');
+            style.setAttribute('data-gs-style-id', id);
+            if (style.styleSheet) {
+                style.styleSheet.cssText = '';
+            } else {
+                style.appendChild(document.createTextNode(''));
+            }
+            document.getElementsByTagName('head')[0].appendChild(style);
+            return style.sheet;
+        },
+
+        removeStylesheet: function(id) {
+            $('STYLE[data-gs-style-id=' + id + ']').remove();
+        },
+
+        insertCSSRule: function(sheet, selector, rules, index) {
+            if (typeof sheet.insertRule === 'function') {
+                sheet.insertRule(selector + '{' + rules + '}', index);
+            } else if (typeof sheet.addRule === 'function') {
+                sheet.addRule(selector, rules, index);
+            }
+        },
+
+        toBool: function(v) {
+            if (typeof v == 'boolean') {
+                return v;
+            }
+            if (typeof v == 'string') {
+                v = v.toLowerCase();
+                return !(v === '' || v == 'no' || v == 'false' || v == '0');
+            }
+            return Boolean(v);
+        },
+
+        _collisionNodeCheck: function(n) {
+            return n != this.node && Utils.isIntercepted(n, this.nn);
+        },
+
+        _didCollide: function(bn) {
+            return Utils.isIntercepted({x: this.n.x, y: this.newY, width: this.n.width, height: this.n.height}, bn);
+        },
+
+        _isAddNodeIntercepted: function(n) {
+            return Utils.isIntercepted({x: this.x, y: this.y, width: this.node.width, height: this.node.height}, n);
+        },
+
+        parseHeight: function(val) {
+            var height = val;
+            var heightUnit = 'px';
+            if (height && _.isString(height)) {
+                var match = height.match(/^(-[0-9]+\.[0-9]+|[0-9]*\.[0-9]+|-[0-9]+|[0-9]+)(px|em|rem|vh|vw)?$/);
+                if (!match) {
+                    throw new Error('Invalid height');
+                }
+                heightUnit = match[2] || 'px';
+                height = parseFloat(match[1]);
+            }
+            return {height: height, unit: heightUnit};
+        }
+    };
+
+    // jscs:disable requireCamelCaseOrUpperCaseIdentifiers
+    Utils.is_intercepted = obsolete(Utils.isIntercepted, 'is_intercepted', 'isIntercepted');
+
+    Utils.create_stylesheet = obsolete(Utils.createStylesheet, 'create_stylesheet', 'createStylesheet');
+
+    Utils.remove_stylesheet = obsolete(Utils.removeStylesheet, 'remove_stylesheet', 'removeStylesheet');
+
+    Utils.insert_css_rule = obsolete(Utils.insertCSSRule, 'insert_css_rule', 'insertCSSRule');
+    // jscs:enable requireCamelCaseOrUpperCaseIdentifiers
+
+    /**
+    * @class GridStackDragDropPlugin
+    * Base class for drag'n'drop plugin.
+    */
+    function GridStackDragDropPlugin(grid) {
+        this.grid = grid;
+    }
+
+    GridStackDragDropPlugin.registeredPlugins = [];
+
+    GridStackDragDropPlugin.registerPlugin = function(pluginClass) {
+        GridStackDragDropPlugin.registeredPlugins.push(pluginClass);
+    };
+
+    GridStackDragDropPlugin.prototype.resizable = function(el, opts) {
+        return this;
+    };
+
+    GridStackDragDropPlugin.prototype.draggable = function(el, opts) {
+        return this;
+    };
+
+    GridStackDragDropPlugin.prototype.droppable = function(el, opts) {
+        return this;
+    };
+
+    GridStackDragDropPlugin.prototype.isDroppable = function(el) {
+        return false;
+    };
+
+    GridStackDragDropPlugin.prototype.on = function(el, eventName, callback) {
+        return this;
+    };
+
+
+    var idSeq = 0;
+
+    var GridStackEngine = function(width, onchange, floatMode, height, items) {
+        this.width = width;
+        this.float = floatMode || false;
+        this.height = height || 0;
+
+        this.nodes = items || [];
+        this.onchange = onchange || function() {};
+
+        this._updateCounter = 0;
+        this._float = this.float;
+
+        this._addedNodes = [];
+        this._removedNodes = [];
+    };
+
+    GridStackEngine.prototype.batchUpdate = function() {
+        this._updateCounter = 1;
+        this.float = true;
+    };
+
+    GridStackEngine.prototype.commit = function() {
+        if (this._updateCounter !== 0) {
+            this._updateCounter = 0;
+            this.float = this._float;
+            this._packNodes();
+            this._notify();
+        }
+    };
+
+    // For Meteor support: https://github.com/troolee/gridstack.js/pull/272
+    GridStackEngine.prototype.getNodeDataByDOMEl = function(el) {
+        return _.find(this.nodes, function(n) { return el.get(0) === n.el.get(0); });
+    };
+
+    GridStackEngine.prototype._fixCollisions = function(node) {
+        var self = this;
+        this._sortNodes(-1);
+
+        var nn = node;
+        var hasLocked = Boolean(_.find(this.nodes, function(n) { return n.locked; }));
+        if (!this.float && !hasLocked) {
+            nn = {x: 0, y: node.y, width: this.width, height: node.height};
+        }
+        while (true) {
+            var collisionNode = _.find(this.nodes, _.bind(Utils._collisionNodeCheck, {node: node, nn: nn}));
+            if (typeof collisionNode == 'undefined') {
+                return;
+            }
+            this.moveNode(collisionNode, collisionNode.x, node.y + node.height,
+                collisionNode.width, collisionNode.height, true);
+        }
+    };
+
+    GridStackEngine.prototype.isAreaEmpty = function(x, y, width, height) {
+        var nn = {x: x || 0, y: y || 0, width: width || 1, height: height || 1};
+        var collisionNode = _.find(this.nodes, _.bind(function(n) {
+            return Utils.isIntercepted(n, nn);
+        }, this));
+        return collisionNode === null || typeof collisionNode === 'undefined';
+    };
+
+    GridStackEngine.prototype._sortNodes = function(dir) {
+        this.nodes = Utils.sort(this.nodes, dir, this.width);
+    };
+
+    GridStackEngine.prototype._packNodes = function() {
+        this._sortNodes();
+
+        if (this.float) {
+            _.each(this.nodes, _.bind(function(n, i) {
+                if (n._updating || typeof n._origY == 'undefined' || n.y == n._origY) {
+                    return;
+                }
+
+                var newY = n.y;
+                while (newY >= n._origY) {
+                    var collisionNode = _.chain(this.nodes)
+                        .find(_.bind(Utils._didCollide, {n: n, newY: newY}))
+                        .value();
+
+                    if (!collisionNode) {
+                        n._dirty = true;
+                        n.y = newY;
+                    }
+                    --newY;
+                }
+            }, this));
+        } else {
+            _.each(this.nodes, _.bind(function(n, i) {
+                if (n.locked) {
+                    return;
+                }
+                while (n.y > 0) {
+                    var newY = n.y - 1;
+                    var canBeMoved = i === 0;
+
+                    if (i > 0) {
+                        var collisionNode = _.chain(this.nodes)
+                            .take(i)
+                            .find(_.bind(Utils._didCollide, {n: n, newY: newY}))
+                            .value();
+                        canBeMoved = typeof collisionNode == 'undefined';
+                    }
+
+                    if (!canBeMoved) {
+                        break;
+                    }
+                    n._dirty = n.y != newY;
+                    n.y = newY;
+                }
+            }, this));
+        }
+    };
+
+    GridStackEngine.prototype._prepareNode = function(node, resizing) {
+        node = _.defaults(node || {}, {width: 1, height: 1, x: 0, y: 0});
+
+        node.x = parseInt('' + node.x);
+        node.y = parseInt('' + node.y);
+        node.width = parseInt('' + node.width);
+        node.height = parseInt('' + node.height);
+        node.autoPosition = node.autoPosition || false;
+        node.noResize = node.noResize || false;
+        node.noMove = node.noMove || false;
+
+        if (node.width > this.width) {
+            node.width = this.width;
+        } else if (node.width < 1) {
+            node.width = 1;
+        }
+
+        if (node.height < 1) {
+            node.height = 1;
+        }
+
+        if (node.x < 0) {
+            node.x = 0;
+        }
+
+        if (node.x + node.width > this.width) {
+            if (resizing) {
+                node.width = this.width - node.x;
+            } else {
+                node.x = this.width - node.width;
+            }
+        }
+
+        if (node.y < 0) {
+            node.y = 0;
+        }
+
+        return node;
+    };
+
+    GridStackEngine.prototype._notify = function() {
+        var args = Array.prototype.slice.call(arguments, 0);
+        args[0] = typeof args[0] === 'undefined' ? [] : [args[0]];
+        args[1] = typeof args[1] === 'undefined' ? true : args[1];
+        if (this._updateCounter) {
+            return;
+        }
+        var deletedNodes = args[0].concat(this.getDirtyNodes());
+        this.onchange(deletedNodes, args[1]);
+    };
+
+    GridStackEngine.prototype.cleanNodes = function() {
+        if (this._updateCounter) {
+            return;
+        }
+        _.each(this.nodes, function(n) {n._dirty = false; });
+    };
+
+    GridStackEngine.prototype.getDirtyNodes = function() {
+        return _.filter(this.nodes, function(n) { return n._dirty; });
+    };
+
+    GridStackEngine.prototype.addNode = function(node, triggerAddEvent) {
+        node = this._prepareNode(node);
+
+        if (typeof node.maxWidth != 'undefined') { node.width = Math.min(node.width, node.maxWidth); }
+        if (typeof node.maxHeight != 'undefined') { node.height = Math.min(node.height, node.maxHeight); }
+        if (typeof node.minWidth != 'undefined') { node.width = Math.max(node.width, node.minWidth); }
+        if (typeof node.minHeight != 'undefined') { node.height = Math.max(node.height, node.minHeight); }
+
+        node._id = ++idSeq;
+        node._dirty = true;
+
+        if (node.autoPosition) {
+            this._sortNodes();
+
+            for (var i = 0;; ++i) {
+                var x = i % this.width;
+                var y = Math.floor(i / this.width);
+                if (x + node.width > this.width) {
+                    continue;
+                }
+                if (!_.find(this.nodes, _.bind(Utils._isAddNodeIntercepted, {x: x, y: y, node: node}))) {
+                    node.x = x;
+                    node.y = y;
+                    break;
+                }
+            }
+        }
+
+        this.nodes.push(node);
+        if (typeof triggerAddEvent != 'undefined' && triggerAddEvent) {
+            this._addedNodes.push(_.clone(node));
+        }
+
+        this._fixCollisions(node);
+        this._packNodes();
+        this._notify();
+        return node;
+    };
+
+    GridStackEngine.prototype.removeNode = function(node, detachNode) {
+        detachNode = typeof detachNode === 'undefined' ? true : detachNode;
+        this._removedNodes.push(_.clone(node));
+        node._id = null;
+        this.nodes = _.without(this.nodes, node);
+        this._packNodes();
+        this._notify(node, detachNode);
+    };
+
+    GridStackEngine.prototype.canMoveNode = function(node, x, y, width, height) {
+        if (!this.isNodeChangedPosition(node, x, y, width, height)) {
+            return false;
+        }
+        var hasLocked = Boolean(_.find(this.nodes, function(n) { return n.locked; }));
+
+        if (!this.height && !hasLocked) {
+            return true;
+        }
+
+        var clonedNode;
+        var clone = new GridStackEngine(
+            this.width,
+            null,
+            this.float,
+            0,
+            _.map(this.nodes, function(n) {
+                if (n == node) {
+                    clonedNode = $.extend({}, n);
+                    return clonedNode;
+                }
+                return $.extend({}, n);
+            }));
+
+        if (typeof clonedNode === 'undefined') {
+            return true;
+        }
+
+        clone.moveNode(clonedNode, x, y, width, height);
+
+        var res = true;
+
+        if (hasLocked) {
+            res &= !Boolean(_.find(clone.nodes, function(n) {
+                return n != clonedNode && Boolean(n.locked) && Boolean(n._dirty);
+            }));
+        }
+        if (this.height) {
+            res &= clone.getGridHeight() <= this.height;
+        }
+
+        return res;
+    };
+
+    GridStackEngine.prototype.canBePlacedWithRespectToHeight = function(node) {
+        if (!this.height) {
+            return true;
+        }
+
+        var clone = new GridStackEngine(
+            this.width,
+            null,
+            this.float,
+            0,
+            _.map(this.nodes, function(n) { return $.extend({}, n); }));
+        clone.addNode(node);
+        return clone.getGridHeight() <= this.height;
+    };
+
+    GridStackEngine.prototype.isNodeChangedPosition = function(node, x, y, width, height) {
+        if (typeof x != 'number') { x = node.x; }
+        if (typeof y != 'number') { y = node.y; }
+        if (typeof width != 'number') { width = node.width; }
+        if (typeof height != 'number') { height = node.height; }
+
+        if (typeof node.maxWidth != 'undefined') { width = Math.min(width, node.maxWidth); }
+        if (typeof node.maxHeight != 'undefined') { height = Math.min(height, node.maxHeight); }
+        if (typeof node.minWidth != 'undefined') { width = Math.max(width, node.minWidth); }
+        if (typeof node.minHeight != 'undefined') { height = Math.max(height, node.minHeight); }
+
+        if (node.x == x && node.y == y && node.width == width && node.height == height) {
+            return false;
+        }
+        return true;
+    };
+
+    GridStackEngine.prototype.moveNode = function(node, x, y, width, height, noPack) {
+        if (!this.isNodeChangedPosition(node, x, y, width, height)) {
+            return node;
+        }
+        if (typeof x != 'number') { x = node.x; }
+        if (typeof y != 'number') { y = node.y; }
+        if (typeof width != 'number') { width = node.width; }
+        if (typeof height != 'number') { height = node.height; }
+
+        if (typeof node.maxWidth != 'undefined') { width = Math.min(width, node.maxWidth); }
+        if (typeof node.maxHeight != 'undefined') { height = Math.min(height, node.maxHeight); }
+        if (typeof node.minWidth != 'undefined') { width = Math.max(width, node.minWidth); }
+        if (typeof node.minHeight != 'undefined') { height = Math.max(height, node.minHeight); }
+
+        if (node.x == x && node.y == y && node.width == width && node.height == height) {
+            return node;
+        }
+
+        var resizing = node.width != width;
+        node._dirty = true;
+
+        node.x = x;
+        node.y = y;
+        node.width = width;
+        node.height = height;
+
+        node.lastTriedX = x;
+        node.lastTriedY = y;
+        node.lastTriedWidth = width;
+        node.lastTriedHeight = height;
+
+        node = this._prepareNode(node, resizing);
+
+        this._fixCollisions(node);
+        if (!noPack) {
+            this._packNodes();
+            this._notify();
+        }
+        return node;
+    };
+
+    GridStackEngine.prototype.getGridHeight = function() {
+        return _.reduce(this.nodes, function(memo, n) { return Math.max(memo, n.y + n.height); }, 0);
+    };
+
+    GridStackEngine.prototype.beginUpdate = function(node) {
+        _.each(this.nodes, function(n) {
+            n._origY = n.y;
+        });
+        node._updating = true;
+    };
+
+    GridStackEngine.prototype.endUpdate = function() {
+        _.each(this.nodes, function(n) {
+            n._origY = n.y;
+        });
+        var n = _.find(this.nodes, function(n) { return n._updating; });
+        if (n) {
+            n._updating = false;
+        }
+    };
+
+    var GridStack = function(el, opts) {
+        var self = this;
+        var oneColumnMode, isAutoCellHeight;
+
+        opts = opts || {};
+
+        this.container = $(el);
+
+        // jscs:disable requireCamelCaseOrUpperCaseIdentifiers
+        if (typeof opts.handle_class !== 'undefined') {
+            opts.handleClass = opts.handle_class;
+            obsoleteOpts('handle_class', 'handleClass');
+        }
+        if (typeof opts.item_class !== 'undefined') {
+            opts.itemClass = opts.item_class;
+            obsoleteOpts('item_class', 'itemClass');
+        }
+        if (typeof opts.placeholder_class !== 'undefined') {
+            opts.placeholderClass = opts.placeholder_class;
+            obsoleteOpts('placeholder_class', 'placeholderClass');
+        }
+        if (typeof opts.placeholder_text !== 'undefined') {
+            opts.placeholderText = opts.placeholder_text;
+            obsoleteOpts('placeholder_text', 'placeholderText');
+        }
+        if (typeof opts.cell_height !== 'undefined') {
+            opts.cellHeight = opts.cell_height;
+            obsoleteOpts('cell_height', 'cellHeight');
+        }
+        if (typeof opts.vertical_margin !== 'undefined') {
+            opts.verticalMargin = opts.vertical_margin;
+            obsoleteOpts('vertical_margin', 'verticalMargin');
+        }
+        if (typeof opts.min_width !== 'undefined') {
+            opts.minWidth = opts.min_width;
+            obsoleteOpts('min_width', 'minWidth');
+        }
+        if (typeof opts.static_grid !== 'undefined') {
+            opts.staticGrid = opts.static_grid;
+            obsoleteOpts('static_grid', 'staticGrid');
+        }
+        if (typeof opts.is_nested !== 'undefined') {
+            opts.isNested = opts.is_nested;
+            obsoleteOpts('is_nested', 'isNested');
+        }
+        if (typeof opts.always_show_resize_handle !== 'undefined') {
+            opts.alwaysShowResizeHandle = opts.always_show_resize_handle;
+            obsoleteOpts('always_show_resize_handle', 'alwaysShowResizeHandle');
+        }
+        // jscs:enable requireCamelCaseOrUpperCaseIdentifiers
+
+        opts.itemClass = opts.itemClass || 'grid-stack-item';
+        var isNested = this.container.closest('.' + opts.itemClass).length > 0;
+
+        this.opts = _.defaults(opts || {}, {
+            width: parseInt(this.container.attr('data-gs-width')) || 12,
+            height: parseInt(this.container.attr('data-gs-height')) || 0,
+            itemClass: 'grid-stack-item',
+            placeholderClass: 'grid-stack-placeholder',
+            placeholderText: '',
+            handle: '.grid-stack-item-content',
+            handleClass: null,
+            cellHeight: 60,
+            verticalMargin: 20,
+            auto: true,
+            minWidth: 768,
+            float: false,
+            staticGrid: false,
+            _class: 'grid-stack-instance-' + (Math.random() * 10000).toFixed(0),
+            animate: Boolean(this.container.attr('data-gs-animate')) || false,
+            alwaysShowResizeHandle: opts.alwaysShowResizeHandle || false,
+            resizable: _.defaults(opts.resizable || {}, {
+                autoHide: !(opts.alwaysShowResizeHandle || false),
+                handles: 'se'
+            }),
+            draggable: _.defaults(opts.draggable || {}, {
+                handle: (opts.handleClass ? '.' + opts.handleClass : (opts.handle ? opts.handle : '')) ||
+                    '.grid-stack-item-content',
+                scroll: false,
+                appendTo: 'body'
+            }),
+            disableDrag: opts.disableDrag || false,
+            disableResize: opts.disableResize || false,
+            rtl: 'auto',
+            removable: false,
+            removeTimeout: 2000,
+            verticalMarginUnit: 'px',
+            cellHeightUnit: 'px',
+            disableOneColumnMode: opts.disableOneColumnMode || false,
+            oneColumnModeClass: opts.oneColumnModeClass || 'grid-stack-one-column-mode',
+            ddPlugin: null
+        });
+
+        if (this.opts.ddPlugin === false) {
+            this.opts.ddPlugin = GridStackDragDropPlugin;
+        } else if (this.opts.ddPlugin === null) {
+            this.opts.ddPlugin = _.first(GridStackDragDropPlugin.registeredPlugins) || GridStackDragDropPlugin;
+        }
+
+        this.dd = new this.opts.ddPlugin(this);
+
+        if (this.opts.rtl === 'auto') {
+            this.opts.rtl = this.container.css('direction') === 'rtl';
+        }
+
+        if (this.opts.rtl) {
+            this.container.addClass('grid-stack-rtl');
+        }
+
+        this.opts.isNested = isNested;
+
+        isAutoCellHeight = this.opts.cellHeight === 'auto';
+        if (isAutoCellHeight) {
+            self.cellHeight(self.cellWidth(), true);
+        } else {
+            this.cellHeight(this.opts.cellHeight, true);
+        }
+        this.verticalMargin(this.opts.verticalMargin, true);
+
+        this.container.addClass(this.opts._class);
+
+        this._setStaticClass();
+
+        if (isNested) {
+            this.container.addClass('grid-stack-nested');
+        }
+
+        this._initStyles();
+
+        this.grid = new GridStackEngine(this.opts.width, function(nodes, detachNode) {
+            detachNode = typeof detachNode === 'undefined' ? true : detachNode;
+            var maxHeight = 0;
+            _.each(nodes, function(n) {
+                if (detachNode && n._id === null) {
+                    if (n.el) {
+                        n.el.remove();
+                    }
+                } else {
+                    n.el
+                        .attr('data-gs-x', n.x)
+                        .attr('data-gs-y', n.y)
+                        .attr('data-gs-width', n.width)
+                        .attr('data-gs-height', n.height);
+                    maxHeight = Math.max(maxHeight, n.y + n.height);
+                }
+            });
+            self._updateStyles(maxHeight + 10);
+        }, this.opts.float, this.opts.height);
+
+        if (this.opts.auto) {
+            var elements = [];
+            var _this = this;
+            this.container.children('.' + this.opts.itemClass + ':not(.' + this.opts.placeholderClass + ')')
+                .each(function(index, el) {
+                el = $(el);
+                elements.push({
+                    el: el,
+                    i: parseInt(el.attr('data-gs-x')) + parseInt(el.attr('data-gs-y')) * _this.opts.width
+                });
+            });
+            _.chain(elements).sortBy(function(x) { return x.i; }).each(function(i) {
+                self._prepareElement(i.el);
+            }).value();
+        }
+
+        this.setAnimation(this.opts.animate);
+
+        this.placeholder = $(
+            '<div class="' + this.opts.placeholderClass + ' ' + this.opts.itemClass + '">' +
+            '<div class="placeholder-content">' + this.opts.placeholderText + '</div></div>').hide();
+
+        this._updateContainerHeight();
+
+        this._updateHeightsOnResize = _.throttle(function() {
+            self.cellHeight(self.cellWidth(), false);
+        }, 100);
+
+        this.onResizeHandler = function() {
+            if (isAutoCellHeight) {
+                self._updateHeightsOnResize();
+            }
+
+            if (self._isOneColumnMode() && !self.opts.disableOneColumnMode) {
+                if (oneColumnMode) {
+                    return;
+                }
+                self.container.addClass(self.opts.oneColumnModeClass);
+                oneColumnMode = true;
+
+                self.grid._sortNodes();
+                _.each(self.grid.nodes, function(node) {
+                    self.container.append(node.el);
+
+                    if (self.opts.staticGrid) {
+                        return;
+                    }
+                    self.dd.draggable(node.el, 'disable');
+                    self.dd.resizable(node.el, 'disable');
+
+                    node.el.trigger('resize');
+                });
+            } else {
+                if (!oneColumnMode) {
+                    return;
+                }
+
+                self.container.removeClass(self.opts.oneColumnModeClass);
+                oneColumnMode = false;
+
+                if (self.opts.staticGrid) {
+                    return;
+                }
+
+                _.each(self.grid.nodes, function(node) {
+                    if (!node.noMove && !self.opts.disableDrag) {
+                        self.dd.draggable(node.el, 'enable');
+                    }
+                    if (!node.noResize && !self.opts.disableResize) {
+                        self.dd.resizable(node.el, 'enable');
+                    }
+
+                    node.el.trigger('resize');
+                });
+            }
+        };
+
+        $(window).resize(this.onResizeHandler);
+        this.onResizeHandler();
+
+        if (!self.opts.staticGrid && typeof self.opts.removable === 'string') {
+            var trashZone = $(self.opts.removable);
+            if (!this.dd.isDroppable(trashZone)) {
+                this.dd.droppable(trashZone, {
+                    accept: '.' + self.opts.itemClass
+                });
+            }
+            this.dd
+                .on(trashZone, 'dropover', function(event, ui) {
+                    var el = $(ui.draggable);
+                    var node = el.data('_gridstack_node');
+                    if (node._grid !== self) {
+                        return;
+                    }
+                    self._setupRemovingTimeout(el);
+                })
+                .on(trashZone, 'dropout', function(event, ui) {
+                    var el = $(ui.draggable);
+                    var node = el.data('_gridstack_node');
+                    if (node._grid !== self) {
+                        return;
+                    }
+                    self._clearRemovingTimeout(el);
+                });
+        }
+
+        if (!self.opts.staticGrid && self.opts.acceptWidgets) {
+            var draggingElement = null;
+
+            var onDrag = function(event, ui) {
+                var el = draggingElement;
+                var node = el.data('_gridstack_node');
+                var pos = self.getCellFromPixel(ui.offset, true);
+                var x = Math.max(0, pos.x);
+                var y = Math.max(0, pos.y);
+                if (!node._added) {
+                    node._added = true;
+
+                    node.el = el;
+                    node.x = x;
+                    node.y = y;
+                    self.grid.cleanNodes();
+                    self.grid.beginUpdate(node);
+                    self.grid.addNode(node);
+
+                    self.container.append(self.placeholder);
+                    self.placeholder
+                        .attr('data-gs-x', node.x)
+                        .attr('data-gs-y', node.y)
+                        .attr('data-gs-width', node.width)
+                        .attr('data-gs-height', node.height)
+                        .show();
+                    node.el = self.placeholder;
+                    node._beforeDragX = node.x;
+                    node._beforeDragY = node.y;
+
+                    self._updateContainerHeight();
+                } else {
+                    if (!self.grid.canMoveNode(node, x, y)) {
+                        return;
+                    }
+                    self.grid.moveNode(node, x, y);
+                    self._updateContainerHeight();
+                }
+            };
+
+            this.dd
+                .droppable(self.container, {
+                    accept: function(el) {
+                        el = $(el);
+                        var node = el.data('_gridstack_node');
+                        if (node && node._grid === self) {
+                            return false;
+                        }
+                        return el.is(self.opts.acceptWidgets === true ? '.grid-stack-item' : self.opts.acceptWidgets);
+                    }
+                })
+                .on(self.container, 'dropover', function(event, ui) {
+                    var offset = self.container.offset();
+                    var el = $(ui.draggable);
+                    var cellWidth = self.cellWidth();
+                    var cellHeight = self.cellHeight();
+                    var origNode = el.data('_gridstack_node');
+
+                    var width = origNode ? origNode.width : (Math.ceil(el.outerWidth() / cellWidth));
+                    var height = origNode ? origNode.height : (Math.ceil(el.outerHeight() / cellHeight));
+
+                    draggingElement = el;
+
+                    var node = self.grid._prepareNode({width: width, height: height, _added: false, _temporary: true});
+                    el.data('_gridstack_node', node);
+                    el.data('_gridstack_node_orig', origNode);
+
+                    el.on('drag', onDrag);
+                })
+                .on(self.container, 'dropout', function(event, ui) {
+                    var el = $(ui.draggable);
+                    el.unbind('drag', onDrag);
+                    var node = el.data('_gridstack_node');
+                    node.el = null;
+                    self.grid.removeNode(node);
+                    self.placeholder.detach();
+                    self._updateContainerHeight();
+                    el.data('_gridstack_node', el.data('_gridstack_node_orig'));
+                })
+                .on(self.container, 'drop', function(event, ui) {
+                    self.placeholder.detach();
+
+                    var node = $(ui.draggable).data('_gridstack_node');
+                    node._grid = self;
+                    var el = $(ui.draggable).clone(false);
+                    el.data('_gridstack_node', node);
+                    var originalNode = $(ui.draggable).data('_gridstack_node_orig');
+                    if (typeof originalNode !== 'undefined') {
+                        originalNode._grid._triggerRemoveEvent();
+                    }
+                    $(ui.draggable).remove();
+                    node.el = el;
+                    self.placeholder.hide();
+                    el
+                        .attr('data-gs-x', node.x)
+                        .attr('data-gs-y', node.y)
+                        .attr('data-gs-width', node.width)
+                        .attr('data-gs-height', node.height)
+                        .addClass(self.opts.itemClass)
+                        .removeAttr('style')
+                        .enableSelection()
+                        .removeData('draggable')
+                        .removeClass('ui-draggable ui-draggable-dragging ui-draggable-disabled')
+                        .unbind('drag', onDrag);
+                    self.container.append(el);
+                    self._prepareElementsByNode(el, node);
+                    self._updateContainerHeight();
+                    self.grid._addedNodes.push(node);
+                    self._triggerAddEvent();
+                    self._triggerChangeEvent();
+
+                    self.grid.endUpdate();
+                });
+        }
+    };
+
+    GridStack.prototype._triggerChangeEvent = function(forceTrigger) {
+        var elements = this.grid.getDirtyNodes();
+        var hasChanges = false;
+
+        var eventParams = [];
+        if (elements && elements.length) {
+            eventParams.push(elements);
+            hasChanges = true;
+        }
+
+        if (hasChanges || forceTrigger === true) {
+            this.container.trigger('change', eventParams);
+        }
+    };
+
+    GridStack.prototype._triggerAddEvent = function() {
+        if (this.grid._addedNodes && this.grid._addedNodes.length > 0) {
+            this.container.trigger('added', [_.map(this.grid._addedNodes, _.clone)]);
+            this.grid._addedNodes = [];
+        }
+    };
+
+    GridStack.prototype._triggerRemoveEvent = function() {
+        if (this.grid._removedNodes && this.grid._removedNodes.length > 0) {
+            this.container.trigger('removed', [_.map(this.grid._removedNodes, _.clone)]);
+            this.grid._removedNodes = [];
+        }
+    };
+
+    GridStack.prototype._initStyles = function() {
+        if (this._stylesId) {
+            Utils.removeStylesheet(this._stylesId);
+        }
+        this._stylesId = 'gridstack-style-' + (Math.random() * 100000).toFixed();
+        this._styles = Utils.createStylesheet(this._stylesId);
+        if (this._styles !== null) {
+            this._styles._max = 0;
+        }
+    };
+
+    GridStack.prototype._updateStyles = function(maxHeight) {
+        if (this._styles === null || typeof this._styles === 'undefined') {
+            return;
+        }
+
+        var prefix = '.' + this.opts._class + ' .' + this.opts.itemClass;
+        var self = this;
+        var getHeight;
+
+        if (typeof maxHeight == 'undefined') {
+            maxHeight = this._styles._max;
+        }
+        this._initStyles();
+        this._updateContainerHeight();
+        if (!this.opts.cellHeight) { // The rest will be handled by CSS
+            return ;
+        }
+        if (this._styles._max !== 0 && maxHeight <= this._styles._max) {
+            return ;
+        }
+
+        if (!this.opts.verticalMargin || this.opts.cellHeightUnit === this.opts.verticalMarginUnit) {
+            getHeight = function(nbRows, nbMargins) {
+                return (self.opts.cellHeight * nbRows + self.opts.verticalMargin * nbMargins) +
+                    self.opts.cellHeightUnit;
+            };
+        } else {
+            getHeight = function(nbRows, nbMargins) {
+                if (!nbRows || !nbMargins) {
+                    return (self.opts.cellHeight * nbRows + self.opts.verticalMargin * nbMargins) +
+                        self.opts.cellHeightUnit;
+                }
+                return 'calc(' + ((self.opts.cellHeight * nbRows) + self.opts.cellHeightUnit) + ' + ' +
+                    ((self.opts.verticalMargin * nbMargins) + self.opts.verticalMarginUnit) + ')';
+            };
+        }
+
+        if (this._styles._max === 0) {
+            Utils.insertCSSRule(this._styles, prefix, 'min-height: ' + getHeight(1, 0) + ';', 0);
+        }
+
+        if (maxHeight > this._styles._max) {
+            for (var i = this._styles._max; i < maxHeight; ++i) {
+                Utils.insertCSSRule(this._styles,
+                    prefix + '[data-gs-height="' + (i + 1) + '"]',
+                    'height: ' + getHeight(i + 1, i) + ';',
+                    i
+                );
+                Utils.insertCSSRule(this._styles,
+                    prefix + '[data-gs-min-height="' + (i + 1) + '"]',
+                    'min-height: ' + getHeight(i + 1, i) + ';',
+                    i
+                );
+                Utils.insertCSSRule(this._styles,
+                    prefix + '[data-gs-max-height="' + (i + 1) + '"]',
+                    'max-height: ' + getHeight(i + 1, i) + ';',
+                    i
+                );
+                Utils.insertCSSRule(this._styles,
+                    prefix + '[data-gs-y="' + i + '"]',
+                    'top: ' + getHeight(i, i) + ';',
+                    i
+                );
+            }
+            this._styles._max = maxHeight;
+        }
+    };
+
+    GridStack.prototype._updateContainerHeight = function() {
+        if (this.grid._updateCounter) {
+            return;
+        }
+        var height = this.grid.getGridHeight();
+        this.container.attr('data-gs-current-height', height);
+        if (!this.opts.cellHeight) {
+            return ;
+        }
+        if (!this.opts.verticalMargin) {
+            this.container.css('height', (height * (this.opts.cellHeight)) + this.opts.cellHeightUnit);
+        } else if (this.opts.cellHeightUnit === this.opts.verticalMarginUnit) {
+            this.container.css('height', (height * (this.opts.cellHeight + this.opts.verticalMargin) -
+                this.opts.verticalMargin) + this.opts.cellHeightUnit);
+        } else {
+            this.container.css('height', 'calc(' + ((height * (this.opts.cellHeight)) + this.opts.cellHeightUnit) +
+                ' + ' + ((height * (this.opts.verticalMargin - 1)) + this.opts.verticalMarginUnit) + ')');
+        }
+    };
+
+    GridStack.prototype._isOneColumnMode = function() {
+        return (window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth) <=
+            this.opts.minWidth;
+    };
+
+    GridStack.prototype._setupRemovingTimeout = function(el) {
+        var self = this;
+        var node = $(el).data('_gridstack_node');
+
+        if (node._removeTimeout || !self.opts.removable) {
+            return;
+        }
+        node._removeTimeout = setTimeout(function() {
+            el.addClass('grid-stack-item-removing');
+            node._isAboutToRemove = true;
+        }, self.opts.removeTimeout);
+    };
+
+    GridStack.prototype._clearRemovingTimeout = function(el) {
+        var node = $(el).data('_gridstack_node');
+
+        if (!node._removeTimeout) {
+            return;
+        }
+        clearTimeout(node._removeTimeout);
+        node._removeTimeout = null;
+        el.removeClass('grid-stack-item-removing');
+        node._isAboutToRemove = false;
+    };
+
+    GridStack.prototype._prepareElementsByNode = function(el, node) {
+        var self = this;
+
+        var cellWidth;
+        var cellHeight;
+
+        var dragOrResize = function(event, ui) {
+            var x = Math.round(ui.position.left / cellWidth);
+            var y = Math.floor((ui.position.top + cellHeight / 2) / cellHeight);
+            var width;
+            var height;
+
+            if (event.type != 'drag') {
+                width = Math.round(ui.size.width / cellWidth);
+                height = Math.round(ui.size.height / cellHeight);
+            }
+
+            if (event.type == 'drag') {
+                if (x < 0 || x >= self.grid.width || y < 0 || (!self.grid.float && y > self.grid.getGridHeight())) {
+                    if (!node._temporaryRemoved) {
+                        if (self.opts.removable === true) {
+                            self._setupRemovingTimeout(el);
+                        }
+
+                        x = node._beforeDragX;
+                        y = node._beforeDragY;
+
+                        self.placeholder.detach();
+                        self.placeholder.hide();
+                        self.grid.removeNode(node);
+                        self._updateContainerHeight();
+
+                        node._temporaryRemoved = true;
+                    }
+                } else {
+                    self._clearRemovingTimeout(el);
+
+                    if (node._temporaryRemoved) {
+                        self.grid.addNode(node);
+                        self.placeholder
+                            .attr('data-gs-x', x)
+                            .attr('data-gs-y', y)
+                            .attr('data-gs-width', width)
+                            .attr('data-gs-height', height)
+                            .show();
+                        self.container.append(self.placeholder);
+                        node.el = self.placeholder;
+                        node._temporaryRemoved = false;
+                    }
+                }
+            } else if (event.type == 'resize')  {
+                if (x < 0) {
+                    return;
+                }
+            }
+            // width and height are undefined if not resizing
+            var lastTriedWidth = typeof width !== 'undefined' ? width : node.lastTriedWidth;
+            var lastTriedHeight = typeof height !== 'undefined' ? height : node.lastTriedHeight;
+            if (!self.grid.canMoveNode(node, x, y, width, height) ||
+                (node.lastTriedX === x && node.lastTriedY === y &&
+                node.lastTriedWidth === lastTriedWidth && node.lastTriedHeight === lastTriedHeight)) {
+                return;
+            }
+            node.lastTriedX = x;
+            node.lastTriedY = y;
+            node.lastTriedWidth = width;
+            node.lastTriedHeight = height;
+            self.grid.moveNode(node, x, y, width, height);
+            self._updateContainerHeight();
+        };
+
+        var onStartMoving = function(event, ui) {
+            self.container.append(self.placeholder);
+            var o = $(this);
+            self.grid.cleanNodes();
+            self.grid.beginUpdate(node);
+            cellWidth = self.cellWidth();
+            var strictCellHeight = Math.ceil(o.outerHeight() / o.attr('data-gs-height'));
+            cellHeight = self.container.height() / parseInt(self.container.attr('data-gs-current-height'));
+            self.placeholder
+                .attr('data-gs-x', o.attr('data-gs-x'))
+                .attr('data-gs-y', o.attr('data-gs-y'))
+                .attr('data-gs-width', o.attr('data-gs-width'))
+                .attr('data-gs-height', o.attr('data-gs-height'))
+                .show();
+            node.el = self.placeholder;
+            node._beforeDragX = node.x;
+            node._beforeDragY = node.y;
+
+            self.dd.resizable(el, 'option', 'minWidth', cellWidth * (node.minWidth || 1));
+            self.dd.resizable(el, 'option', 'minHeight', strictCellHeight * (node.minHeight || 1));
+
+            if (event.type == 'resizestart') {
+                o.find('.grid-stack-item').trigger('resizestart');
+            }
+        };
+
+        var onEndMoving = function(event, ui) {
+            var o = $(this);
+            if (!o.data('_gridstack_node')) {
+                return;
+            }
+
+            var forceNotify = false;
+            self.placeholder.detach();
+            node.el = o;
+            self.placeholder.hide();
+
+            if (node._isAboutToRemove) {
+                forceNotify = true;
+                var gridToNotify = el.data('_gridstack_node')._grid;
+                gridToNotify._triggerRemoveEvent();
+                el.removeData('_gridstack_node');
+                el.remove();
+            } else {
+                self._clearRemovingTimeout(el);
+                if (!node._temporaryRemoved) {
+                    o
+                        .attr('data-gs-x', node.x)
+                        .attr('data-gs-y', node.y)
+                        .attr('data-gs-width', node.width)
+                        .attr('data-gs-height', node.height)
+                        .removeAttr('style');
+                } else {
+                    o
+                        .attr('data-gs-x', node._beforeDragX)
+                        .attr('data-gs-y', node._beforeDragY)
+                        .attr('data-gs-width', node.width)
+                        .attr('data-gs-height', node.height)
+                        .removeAttr('style');
+                    node.x = node._beforeDragX;
+                    node.y = node._beforeDragY;
+                    self.grid.addNode(node);
+                }
+            }
+            self._updateContainerHeight();
+            self._triggerChangeEvent(forceNotify);
+
+            self.grid.endUpdate();
+
+            var nestedGrids = o.find('.grid-stack');
+            if (nestedGrids.length && event.type == 'resizestop') {
+                nestedGrids.each(function(index, el) {
+                    $(el).data('gridstack').onResizeHandler();
+                });
+                o.find('.grid-stack-item').trigger('resizestop');
+                o.find('.grid-stack-item').trigger('gsresizestop');
+            }
+            if (event.type == 'resizestop') {
+                self.container.trigger('gsresizestop', o);
+            }
+        };
+
+        this.dd
+            .draggable(el, {
+                start: onStartMoving,
+                stop: onEndMoving,
+                drag: dragOrResize
+            })
+            .resizable(el, {
+                start: onStartMoving,
+                stop: onEndMoving,
+                resize: dragOrResize
+            });
+
+        if (node.noMove || (this._isOneColumnMode() && !self.opts.disableOneColumnMode) || this.opts.disableDrag) {
+            this.dd.draggable(el, 'disable');
+        }
+
+        if (node.noResize || (this._isOneColumnMode() && !self.opts.disableOneColumnMode) || this.opts.disableResize) {
+            this.dd.resizable(el, 'disable');
+        }
+
+        el.attr('data-gs-locked', node.locked ? 'yes' : null);
+    };
+
+    GridStack.prototype._prepareElement = function(el, triggerAddEvent) {
+        triggerAddEvent = typeof triggerAddEvent != 'undefined' ? triggerAddEvent : false;
+        var self = this;
+        el = $(el);
+
+        el.addClass(this.opts.itemClass);
+        var node = self.grid.addNode({
+            x: el.attr('data-gs-x'),
+            y: el.attr('data-gs-y'),
+            width: el.attr('data-gs-width'),
+            height: el.attr('data-gs-height'),
+            maxWidth: el.attr('data-gs-max-width'),
+            minWidth: el.attr('data-gs-min-width'),
+            maxHeight: el.attr('data-gs-max-height'),
+            minHeight: el.attr('data-gs-min-height'),
+            autoPosition: Utils.toBool(el.attr('data-gs-auto-position')),
+            noResize: Utils.toBool(el.attr('data-gs-no-resize')),
+            noMove: Utils.toBool(el.attr('data-gs-no-move')),
+            locked: Utils.toBool(el.attr('data-gs-locked')),
+            el: el,
+            id: el.attr('data-gs-id'),
+            _grid: self
+        }, triggerAddEvent);
+        el.data('_gridstack_node', node);
+
+        this._prepareElementsByNode(el, node);
+    };
+
+    GridStack.prototype.setAnimation = function(enable) {
+        if (enable) {
+            this.container.addClass('grid-stack-animate');
+        } else {
+            this.container.removeClass('grid-stack-animate');
+        }
+    };
+
+    GridStack.prototype.addWidget = function(el, x, y, width, height, autoPosition, minWidth, maxWidth,
+        minHeight, maxHeight, id) {
+        el = $(el);
+        if (typeof x != 'undefined') { el.attr('data-gs-x', x); }
+        if (typeof y != 'undefined') { el.attr('data-gs-y', y); }
+        if (typeof width != 'undefined') { el.attr('data-gs-width', width); }
+        if (typeof height != 'undefined') { el.attr('data-gs-height', height); }
+        if (typeof autoPosition != 'undefined') { el.attr('data-gs-auto-position', autoPosition ? 'yes' : null); }
+        if (typeof minWidth != 'undefined') { el.attr('data-gs-min-width', minWidth); }
+        if (typeof maxWidth != 'undefined') { el.attr('data-gs-max-width', maxWidth); }
+        if (typeof minHeight != 'undefined') { el.attr('data-gs-min-height', minHeight); }
+        if (typeof maxHeight != 'undefined') { el.attr('data-gs-max-height', maxHeight); }
+        if (typeof id != 'undefined') { el.attr('data-gs-id', id); }
+        this.container.append(el);
+        this._prepareElement(el, true);
+        this._triggerAddEvent();
+        this._updateContainerHeight();
+        this._triggerChangeEvent(true);
+
+        return el;
+    };
+
+    GridStack.prototype.makeWidget = function(el) {
+        el = $(el);
+        this._prepareElement(el, true);
+        this._triggerAddEvent();
+        this._updateContainerHeight();
+        this._triggerChangeEvent(true);
+
+        return el;
+    };
+
+    GridStack.prototype.willItFit = function(x, y, width, height, autoPosition) {
+        var node = {x: x, y: y, width: width, height: height, autoPosition: autoPosition};
+        return this.grid.canBePlacedWithRespectToHeight(node);
+    };
+
+    GridStack.prototype.removeWidget = function(el, detachNode) {
+        detachNode = typeof detachNode === 'undefined' ? true : detachNode;
+        el = $(el);
+        var node = el.data('_gridstack_node');
+
+        // For Meteor support: https://github.com/troolee/gridstack.js/pull/272
+        if (!node) {
+            node = this.grid.getNodeDataByDOMEl(el);
+        }
+
+        this.grid.removeNode(node, detachNode);
+        el.removeData('_gridstack_node');
+        this._updateContainerHeight();
+        if (detachNode) {
+            el.remove();
+        }
+        this._triggerChangeEvent(true);
+        this._triggerRemoveEvent();
+    };
+
+    GridStack.prototype.removeAll = function(detachNode) {
+        _.each(this.grid.nodes, _.bind(function(node) {
+            this.removeWidget(node.el, detachNode);
+        }, this));
+        this.grid.nodes = [];
+        this._updateContainerHeight();
+    };
+
+    GridStack.prototype.destroy = function(detachGrid) {
+        $(window).off('resize', this.onResizeHandler);
+        this.disable();
+        if (typeof detachGrid != 'undefined' && !detachGrid) {
+            this.removeAll(false);
+            this.container.removeData('gridstack');
+        } else {
+            this.container.remove();
+        }
+        Utils.removeStylesheet(this._stylesId);
+        if (this.grid) {
+            this.grid = null;
+        }
+    };
+
+    GridStack.prototype.resizable = function(el, val) {
+        var self = this;
+        el = $(el);
+        el.each(function(index, el) {
+            el = $(el);
+            var node = el.data('_gridstack_node');
+            if (typeof node == 'undefined' || node === null) {
+                return;
+            }
+
+            node.noResize = !(val || false);
+            if (node.noResize || (self._isOneColumnMode() && !self.opts.disableOneColumnMode)) {
+                self.dd.resizable(el, 'disable');
+            } else {
+                self.dd.resizable(el, 'enable');
+            }
+        });
+        return this;
+    };
+
+    GridStack.prototype.movable = function(el, val) {
+        var self = this;
+        el = $(el);
+        el.each(function(index, el) {
+            el = $(el);
+            var node = el.data('_gridstack_node');
+            if (typeof node == 'undefined' || node === null) {
+                return;
+            }
+
+            node.noMove = !(val || false);
+            if (node.noMove || (self._isOneColumnMode() && !self.opts.disableOneColumnMode)) {
+                self.dd.draggable(el, 'disable');
+                el.removeClass('ui-draggable-handle');
+            } else {
+                self.dd.draggable(el, 'enable');
+                el.addClass('ui-draggable-handle');
+            }
+        });
+        return this;
+    };
+
+    GridStack.prototype.enableMove = function(doEnable, includeNewWidgets) {
+        this.movable(this.container.children('.' + this.opts.itemClass), doEnable);
+        if (includeNewWidgets) {
+            this.opts.disableDrag = !doEnable;
+        }
+    };
+
+    GridStack.prototype.enableResize = function(doEnable, includeNewWidgets) {
+        this.resizable(this.container.children('.' + this.opts.itemClass), doEnable);
+        if (includeNewWidgets) {
+            this.opts.disableResize = !doEnable;
+        }
+    };
+
+    GridStack.prototype.disable = function() {
+        this.movable(this.container.children('.' + this.opts.itemClass), false);
+        this.resizable(this.container.children('.' + this.opts.itemClass), false);
+        this.container.trigger('disable');
+    };
+
+    GridStack.prototype.enable = function() {
+        this.movable(this.container.children('.' + this.opts.itemClass), true);
+        this.resizable(this.container.children('.' + this.opts.itemClass), true);
+        this.container.trigger('enable');
+    };
+
+    GridStack.prototype.locked = function(el, val) {
+        el = $(el);
+        el.each(function(index, el) {
+            el = $(el);
+            var node = el.data('_gridstack_node');
+            if (typeof node == 'undefined' || node === null) {
+                return;
+            }
+
+            node.locked = (val || false);
+            el.attr('data-gs-locked', node.locked ? 'yes' : null);
+        });
+        return this;
+    };
+
+    GridStack.prototype.maxHeight = function(el, val) {
+        el = $(el);
+        el.each(function(index, el) {
+            el = $(el);
+            var node = el.data('_gridstack_node');
+            if (typeof node === 'undefined' || node === null) {
+                return;
+            }
+
+            if (!isNaN(val)) {
+                node.maxHeight = (val || false);
+                el.attr('data-gs-max-height', val);
+            }
+        });
+        return this;
+    };
+
+    GridStack.prototype.minHeight = function(el, val) {
+        el = $(el);
+        el.each(function(index, el) {
+            el = $(el);
+            var node = el.data('_gridstack_node');
+            if (typeof node === 'undefined' || node === null) {
+                return;
+            }
+
+            if (!isNaN(val)) {
+                node.minHeight = (val || false);
+                el.attr('data-gs-min-height', val);
+            }
+        });
+        return this;
+    };
+
+    GridStack.prototype.maxWidth = function(el, val) {
+        el = $(el);
+        el.each(function(index, el) {
+            el = $(el);
+            var node = el.data('_gridstack_node');
+            if (typeof node === 'undefined' || node === null) {
+                return;
+            }
+
+            if (!isNaN(val)) {
+                node.maxWidth = (val || false);
+                el.attr('data-gs-max-width', val);
+            }
+        });
+        return this;
+    };
+
+    GridStack.prototype.minWidth = function(el, val) {
+        el = $(el);
+        el.each(function(index, el) {
+            el = $(el);
+            var node = el.data('_gridstack_node');
+            if (typeof node === 'undefined' || node === null) {
+                return;
+            }
+
+            if (!isNaN(val)) {
+                node.minWidth = (val || false);
+                el.attr('data-gs-min-width', val);
+            }
+        });
+        return this;
+    };
+
+    GridStack.prototype._updateElement = function(el, callback) {
+        el = $(el).first();
+        var node = el.data('_gridstack_node');
+        if (typeof node == 'undefined' || node === null) {
+            return;
+        }
+
+        var self = this;
+
+        self.grid.cleanNodes();
+        self.grid.beginUpdate(node);
+
+        callback.call(this, el, node);
+
+        self._updateContainerHeight();
+        self._triggerChangeEvent();
+
+        self.grid.endUpdate();
+    };
+
+    GridStack.prototype.resize = function(el, width, height) {
+        this._updateElement(el, function(el, node) {
+            width = (width !== null && typeof width != 'undefined') ? width : node.width;
+            height = (height !== null && typeof height != 'undefined') ? height : node.height;
+
+            this.grid.moveNode(node, node.x, node.y, width, height);
+        });
+    };
+
+    GridStack.prototype.move = function(el, x, y) {
+        this._updateElement(el, function(el, node) {
+            x = (x !== null && typeof x != 'undefined') ? x : node.x;
+            y = (y !== null && typeof y != 'undefined') ? y : node.y;
+
+            this.grid.moveNode(node, x, y, node.width, node.height);
+        });
+    };
+
+    GridStack.prototype.update = function(el, x, y, width, height) {
+        this._updateElement(el, function(el, node) {
+            x = (x !== null && typeof x != 'undefined') ? x : node.x;
+            y = (y !== null && typeof y != 'undefined') ? y : node.y;
+            width = (width !== null && typeof width != 'undefined') ? width : node.width;
+            height = (height !== null && typeof height != 'undefined') ? height : node.height;
+
+            this.grid.moveNode(node, x, y, width, height);
+        });
+    };
+
+    GridStack.prototype.verticalMargin = function(val, noUpdate) {
+        if (typeof val == 'undefined') {
+            return this.opts.verticalMargin;
+        }
+
+        var heightData = Utils.parseHeight(val);
+
+        if (this.opts.verticalMarginUnit === heightData.unit && this.opts.height === heightData.height) {
+            return ;
+        }
+        this.opts.verticalMarginUnit = heightData.unit;
+        this.opts.verticalMargin = heightData.height;
+
+        if (!noUpdate) {
+            this._updateStyles();
+        }
+    };
+
+    GridStack.prototype.cellHeight = function(val, noUpdate) {
+        if (typeof val == 'undefined') {
+            if (this.opts.cellHeight) {
+                return this.opts.cellHeight;
+            }
+            var o = this.container.children('.' + this.opts.itemClass).first();
+            return Math.ceil(o.outerHeight() / o.attr('data-gs-height'));
+        }
+        var heightData = Utils.parseHeight(val);
+
+        if (this.opts.cellHeightUnit === heightData.heightUnit && this.opts.height === heightData.height) {
+            return ;
+        }
+        this.opts.cellHeightUnit = heightData.unit;
+        this.opts.cellHeight = heightData.height;
+
+        if (!noUpdate) {
+            this._updateStyles();
+        }
+
+    };
+
+    GridStack.prototype.cellWidth = function() {
+        return Math.round(this.container.outerWidth() / this.opts.width);
+    };
+
+    GridStack.prototype.getCellFromPixel = function(position, useOffset) {
+        var containerPos = (typeof useOffset != 'undefined' && useOffset) ?
+            this.container.offset() : this.container.position();
+        var relativeLeft = position.left - containerPos.left;
+        var relativeTop = position.top - containerPos.top;
+
+        var columnWidth = Math.floor(this.container.width() / this.opts.width);
+        var rowHeight = Math.floor(this.container.height() / parseInt(this.container.attr('data-gs-current-height')));
+
+        return {x: Math.floor(relativeLeft / columnWidth), y: Math.floor(relativeTop / rowHeight)};
+    };
+
+    GridStack.prototype.batchUpdate = function() {
+        this.grid.batchUpdate();
+    };
+
+    GridStack.prototype.commit = function() {
+        this.grid.commit();
+        this._updateContainerHeight();
+    };
+
+    GridStack.prototype.isAreaEmpty = function(x, y, width, height) {
+        return this.grid.isAreaEmpty(x, y, width, height);
+    };
+
+    GridStack.prototype.setStatic = function(staticValue) {
+        this.opts.staticGrid = (staticValue === true);
+        this.enableMove(!staticValue);
+        this.enableResize(!staticValue);
+        this._setStaticClass();
+    };
+
+    GridStack.prototype._setStaticClass = function() {
+        var staticClassName = 'grid-stack-static';
+
+        if (this.opts.staticGrid === true) {
+            this.container.addClass(staticClassName);
+        } else {
+            this.container.removeClass(staticClassName);
+        }
+    };
+
+    GridStack.prototype._updateNodeWidths = function(oldWidth, newWidth) {
+        this.grid._sortNodes();
+        this.grid.batchUpdate();
+        var node = {};
+        for (var i = 0; i < this.grid.nodes.length; i++) {
+            node = this.grid.nodes[i];
+            this.update(node.el, Math.round(node.x * newWidth / oldWidth), undefined,
+                Math.round(node.width * newWidth / oldWidth), undefined);
+        }
+        this.grid.commit();
+    };
+
+    GridStack.prototype.setGridWidth = function(gridWidth,doNotPropagate) {
+        this.container.removeClass('grid-stack-' + this.opts.width);
+        if (doNotPropagate !== true) {
+            this._updateNodeWidths(this.opts.width, gridWidth);
+        }
+        this.opts.width = gridWidth;
+        this.grid.width = gridWidth;
+        this.container.addClass('grid-stack-' + gridWidth);
+    };
+
+    // jscs:disable requireCamelCaseOrUpperCaseIdentifiers
+    GridStackEngine.prototype.batch_update = obsolete(GridStackEngine.prototype.batchUpdate);
+    GridStackEngine.prototype._fix_collisions = obsolete(GridStackEngine.prototype._fixCollisions,
+        '_fix_collisions', '_fixCollisions');
+    GridStackEngine.prototype.is_area_empty = obsolete(GridStackEngine.prototype.isAreaEmpty,
+        'is_area_empty', 'isAreaEmpty');
+    GridStackEngine.prototype._sort_nodes = obsolete(GridStackEngine.prototype._sortNodes,
+        '_sort_nodes', '_sortNodes');
+    GridStackEngine.prototype._pack_nodes = obsolete(GridStackEngine.prototype._packNodes,
+        '_pack_nodes', '_packNodes');
+    GridStackEngine.prototype._prepare_node = obsolete(GridStackEngine.prototype._prepareNode,
+        '_prepare_node', '_prepareNode');
+    GridStackEngine.prototype.clean_nodes = obsolete(GridStackEngine.prototype.cleanNodes,
+        'clean_nodes', 'cleanNodes');
+    GridStackEngine.prototype.get_dirty_nodes = obsolete(GridStackEngine.prototype.getDirtyNodes,
+        'get_dirty_nodes', 'getDirtyNodes');
+    GridStackEngine.prototype.add_node = obsolete(GridStackEngine.prototype.addNode,
+        'add_node', 'addNode, ');
+    GridStackEngine.prototype.remove_node = obsolete(GridStackEngine.prototype.removeNode,
+        'remove_node', 'removeNode');
+    GridStackEngine.prototype.can_move_node = obsolete(GridStackEngine.prototype.canMoveNode,
+        'can_move_node', 'canMoveNode');
+    GridStackEngine.prototype.move_node = obsolete(GridStackEngine.prototype.moveNode,
+        'move_node', 'moveNode');
+    GridStackEngine.prototype.get_grid_height = obsolete(GridStackEngine.prototype.getGridHeight,
+        'get_grid_height', 'getGridHeight');
+    GridStackEngine.prototype.begin_update = obsolete(GridStackEngine.prototype.beginUpdate,
+        'begin_update', 'beginUpdate');
+    GridStackEngine.prototype.end_update = obsolete(GridStackEngine.prototype.endUpdate,
+        'end_update', 'endUpdate');
+    GridStackEngine.prototype.can_be_placed_with_respect_to_height =
+        obsolete(GridStackEngine.prototype.canBePlacedWithRespectToHeight,
+        'can_be_placed_with_respect_to_height', 'canBePlacedWithRespectToHeight');
+    GridStack.prototype._trigger_change_event = obsolete(GridStack.prototype._triggerChangeEvent,
+        '_trigger_change_event', '_triggerChangeEvent');
+    GridStack.prototype._init_styles = obsolete(GridStack.prototype._initStyles,
+        '_init_styles', '_initStyles');
+    GridStack.prototype._update_styles = obsolete(GridStack.prototype._updateStyles,
+        '_update_styles', '_updateStyles');
+    GridStack.prototype._update_container_height = obsolete(GridStack.prototype._updateContainerHeight,
+        '_update_container_height', '_updateContainerHeight');
+    GridStack.prototype._is_one_column_mode = obsolete(GridStack.prototype._isOneColumnMode,
+        '_is_one_column_mode','_isOneColumnMode');
+    GridStack.prototype._prepare_element = obsolete(GridStack.prototype._prepareElement,
+        '_prepare_element', '_prepareElement');
+    GridStack.prototype.set_animation = obsolete(GridStack.prototype.setAnimation,
+        'set_animation', 'setAnimation');
+    GridStack.prototype.add_widget = obsolete(GridStack.prototype.addWidget,
+        'add_widget', 'addWidget');
+    GridStack.prototype.make_widget = obsolete(GridStack.prototype.makeWidget,
+        'make_widget', 'makeWidget');
+    GridStack.prototype.will_it_fit = obsolete(GridStack.prototype.willItFit,
+        'will_it_fit', 'willItFit');
+    GridStack.prototype.remove_widget = obsolete(GridStack.prototype.removeWidget,
+        'remove_widget', 'removeWidget');
+    GridStack.prototype.remove_all = obsolete(GridStack.prototype.removeAll,
+        'remove_all', 'removeAll');
+    GridStack.prototype.min_height = obsolete(GridStack.prototype.minHeight,
+        'min_height', 'minHeight');
+    GridStack.prototype.min_width = obsolete(GridStack.prototype.minWidth,
+        'min_width', 'minWidth');
+    GridStack.prototype._update_element = obsolete(GridStack.prototype._updateElement,
+        '_update_element', '_updateElement');
+    GridStack.prototype.cell_height = obsolete(GridStack.prototype.cellHeight,
+        'cell_height', 'cellHeight');
+    GridStack.prototype.cell_width = obsolete(GridStack.prototype.cellWidth,
+        'cell_width', 'cellWidth');
+    GridStack.prototype.get_cell_from_pixel = obsolete(GridStack.prototype.getCellFromPixel,
+        'get_cell_from_pixel', 'getCellFromPixel');
+    GridStack.prototype.batch_update = obsolete(GridStack.prototype.batchUpdate,
+        'batch_update', 'batchUpdate');
+    GridStack.prototype.is_area_empty = obsolete(GridStack.prototype.isAreaEmpty,
+        'is_area_empty', 'isAreaEmpty');
+    GridStack.prototype.set_static = obsolete(GridStack.prototype.setStatic,
+        'set_static', 'setStatic');
+    GridStack.prototype._set_static_class = obsolete(GridStack.prototype._setStaticClass,
+        '_set_static_class', '_setStaticClass');
+    // jscs:enable requireCamelCaseOrUpperCaseIdentifiers
+
+    scope.GridStackUI = GridStack;
+
+    scope.GridStackUI.Utils = Utils;
+    scope.GridStackUI.Engine = GridStackEngine;
+    scope.GridStackUI.GridStackDragDropPlugin = GridStackDragDropPlugin;
+
+    $.fn.gridstack = function(opts) {
+        return this.each(function() {
+            var o = $(this);
+            if (!o.data('gridstack')) {
+                o
+                    .data('gridstack', new GridStack(this, opts));
+            }
+        });
+    };
+
+    return scope.GridStackUI;
+});

+ 190 - 0
static/lib/jquery/jquery.base64.js

@@ -0,0 +1,190 @@
+/*jslint adsafe: false, bitwise: true, browser: true, cap: false, css: false,
+  debug: false, devel: true, eqeqeq: true, es5: false, evil: false,
+  forin: false, fragment: false, immed: true, laxbreak: false, newcap: true,
+  nomen: false, on: false, onevar: true, passfail: false, plusplus: true,
+  regexp: false, rhino: true, safe: false, strict: false, sub: false,
+  undef: true, white: false, widget: false, windows: false */
+/*global jQuery: false, window: false */
+//"use strict";
+
+/*
+ * Original code (c) 2010 Nick Galbreath
+ * http://code.google.com/p/stringencoders/source/browse/#svn/trunk/javascript
+ *
+ * jQuery port (c) 2010 Carlo Zottmann
+ * http://github.com/carlo/jquery-base64
+ *
+ * Permission is hereby granted, free of charge, to any person
+ * obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without
+ * restriction, including without limitation the rights to use,
+ * copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following
+ * conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
+ * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+ * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+ * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+ * OTHER DEALINGS IN THE SOFTWARE.
+*/
+
+/* base64 encode/decode compatible with window.btoa/atob
+ *
+ * window.atob/btoa is a Firefox extension to convert binary data (the "b")
+ * to base64 (ascii, the "a").
+ *
+ * It is also found in Safari and Chrome.  It is not available in IE.
+ *
+ * if (!window.btoa) window.btoa = $.base64.encode
+ * if (!window.atob) window.atob = $.base64.decode
+ *
+ * The original spec's for atob/btoa are a bit lacking
+ * https://developer.mozilla.org/en/DOM/window.atob
+ * https://developer.mozilla.org/en/DOM/window.btoa
+ *
+ * window.btoa and $.base64.encode takes a string where charCodeAt is [0,255]
+ * If any character is not [0,255], then an exception is thrown.
+ *
+ * window.atob and $.base64.decode take a base64-encoded string
+ * If the input length is not a multiple of 4, or contains invalid characters
+ *   then an exception is thrown.
+ */
+ 
+jQuery.base64 = ( function( $ ) {
+  
+  var _PADCHAR = "=",
+    _ALPHA = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
+    _VERSION = "1.0";
+
+
+  function _getbyte64( s, i ) {
+    // This is oddly fast, except on Chrome/V8.
+    // Minimal or no improvement in performance by using a
+    // object with properties mapping chars to value (eg. 'A': 0)
+
+    var idx = _ALPHA.indexOf( s.charAt( i ) );
+
+    if ( idx === -1 ) {
+      throw "Cannot decode base64";
+    }
+
+    return idx;
+  }
+  
+  
+  function _decode( s ) {
+    var pads = 0,
+      i,
+      b10,
+      imax = s.length,
+      x = [];
+
+    s = String( s );
+    
+    if ( imax === 0 ) {
+      return s;
+    }
+
+    if ( imax % 4 !== 0 ) {
+      throw "Cannot decode base64";
+    }
+
+    if ( s.charAt( imax - 1 ) === _PADCHAR ) {
+      pads = 1;
+
+      if ( s.charAt( imax - 2 ) === _PADCHAR ) {
+        pads = 2;
+      }
+
+      // either way, we want to ignore this last block
+      imax -= 4;
+    }
+
+    for ( i = 0; i < imax; i += 4 ) {
+      b10 = ( _getbyte64( s, i ) << 18 ) | ( _getbyte64( s, i + 1 ) << 12 ) | ( _getbyte64( s, i + 2 ) << 6 ) | _getbyte64( s, i + 3 );
+      x.push( String.fromCharCode( b10 >> 16, ( b10 >> 8 ) & 0xff, b10 & 0xff ) );
+    }
+
+    switch ( pads ) {
+      case 1:
+        b10 = ( _getbyte64( s, i ) << 18 ) | ( _getbyte64( s, i + 1 ) << 12 ) | ( _getbyte64( s, i + 2 ) << 6 );
+        x.push( String.fromCharCode( b10 >> 16, ( b10 >> 8 ) & 0xff ) );
+        break;
+
+      case 2:
+        b10 = ( _getbyte64( s, i ) << 18) | ( _getbyte64( s, i + 1 ) << 12 );
+        x.push( String.fromCharCode( b10 >> 16 ) );
+        break;
+    }
+
+    return x.join( "" );
+  }
+  
+  
+  function _getbyte( s, i ) {
+    var x = s.charCodeAt( i );
+
+    if ( x > 255 ) {
+      throw "INVALID_CHARACTER_ERR: DOM Exception 5";
+    }
+    
+    return x;
+  }
+
+
+  function _encode( s ) {
+    if ( arguments.length !== 1 ) {
+      throw "SyntaxError: exactly one argument required";
+    }
+
+    s = String( s );
+
+    var i,
+      b10,
+      x = [],
+      imax = s.length - s.length % 3;
+
+    if ( s.length === 0 ) {
+      return s;
+    }
+
+    for ( i = 0; i < imax; i += 3 ) {
+      b10 = ( _getbyte( s, i ) << 16 ) | ( _getbyte( s, i + 1 ) << 8 ) | _getbyte( s, i + 2 );
+      x.push( _ALPHA.charAt( b10 >> 18 ) );
+      x.push( _ALPHA.charAt( ( b10 >> 12 ) & 0x3F ) );
+      x.push( _ALPHA.charAt( ( b10 >> 6 ) & 0x3f ) );
+      x.push( _ALPHA.charAt( b10 & 0x3f ) );
+    }
+
+    switch ( s.length - imax ) {
+      case 1:
+        b10 = _getbyte( s, i ) << 16;
+        x.push( _ALPHA.charAt( b10 >> 18 ) + _ALPHA.charAt( ( b10 >> 12 ) & 0x3F ) + _PADCHAR + _PADCHAR );
+        break;
+
+      case 2:
+        b10 = ( _getbyte( s, i ) << 16 ) | ( _getbyte( s, i + 1 ) << 8 );
+        x.push( _ALPHA.charAt( b10 >> 18 ) + _ALPHA.charAt( ( b10 >> 12 ) & 0x3F ) + _ALPHA.charAt( ( b10 >> 6 ) & 0x3f ) + _PADCHAR );
+        break;
+    }
+
+    return x.join( "" );
+  }
+
+
+  return {
+    decode: _decode,
+    encode: _encode,
+    VERSION: _VERSION
+  };
+      
+}( jQuery ) );
+

+ 40 - 0
static/lib/jquery/jquery.dragtable.css

@@ -0,0 +1,40 @@
+/* 
+ * dragtable
+ *
+ * @Version 2.0.15
+ *
+ * default css
+ *
+ */
+/*##### the dragtable stuff #####*/
+.dragtable-sortable { 
+    list-style-type: none; margin: 0; padding: 0; -moz-user-select: none;
+}
+.dragtable-sortable li {
+    margin: 0; padding: 0; float: left; font-size: 1em; background: white; 
+}
+
+.dragtable-sortable th, .dragtable-sortable td{
+    border-left: 0px;
+}
+
+.dragtable-sortable li:first-child th, .dragtable-sortable li:first-child td {
+    border-left: 1px solid #CCC; 
+}
+
+.ui-sortable-helper {
+    opacity: 0.7;filter: alpha(opacity=70);
+}
+.ui-sortable-placeholder { 
+    -moz-box-shadow: 4px 5px 4px #C6C6C6 inset;
+    -webkit-box-shadow: 4px 5px 4px #C6C6C6 inset;
+    box-shadow: 4px 5px 4px #C6C6C6 inset;
+    border-bottom: 1px solid #CCCCCC;
+    border-top: 1px solid #CCCCCC;
+    visibility: visible !important;
+    background: #EFEFEF !important; 
+    visibility: visible !important;
+}
+.ui-sortable-placeholder * { 
+    opacity: 0.0; visibility: hidden; 
+}

+ 403 - 0
static/lib/jquery/jquery.dragtable.js

@@ -0,0 +1,403 @@
+/*!
+ * dragtable
+ *
+ * @Version 2.0.15
+ *
+ * Copyright (c) 2010-2013, Andres akottr@gmail.com
+ * Dual licensed under the MIT (MIT-LICENSE.txt)
+ * and GPL (GPL-LICENSE.txt) licenses.
+ *
+ * Inspired by the the dragtable from Dan Vanderkam (danvk.org/dragtable/)
+ * Thanks to the jquery and jqueryui comitters
+ *
+ * Any comment, bug report, feature-request is welcome
+ * Feel free to contact me.
+ */
+
+/* TOKNOW:
+ * For IE7 you need this css rule:
+ * table {
+ *   border-collapse: collapse;
+ * }
+ * Or take a clean reset.css (see http://meyerweb.com/eric/tools/css/reset/)
+ */
+
+/* TODO: investigate
+ * Does not work properly with css rule:
+ * html {
+ *      overflow: -moz-scrollbars-vertical;
+ *  }
+ * Workaround:
+ * Fixing Firefox issues by scrolling down the page
+ * http://stackoverflow.com/questions/2451528/jquery-ui-sortable-scroll-helper-element-offset-firefox-issue
+ *
+ * var start = $.noop;
+ * var beforeStop = $.noop;
+ * if($.browser.mozilla) {
+ * var start = function (event, ui) {
+ *               if( ui.helper !== undefined )
+ *                 ui.helper.css('position','absolute').css('margin-top', $(window).scrollTop() );
+ *               }
+ * var beforeStop = function (event, ui) {
+ *              if( ui.offset !== undefined )
+ *                ui.helper.css('margin-top', 0);
+ *              }
+ * }
+ *
+ * and pass this as start and stop function to the sortable initialisation
+ * start: start,
+ * beforeStop: beforeStop
+ */
+/*
+ * Special thx to all pull requests comitters
+ */
+
+(function($) {
+  $.widget("akottr.dragtable", {
+    options: {
+      revert: false,               // smooth revert
+      dragHandle: '.table-handle', // handle for moving cols, if not exists the whole 'th' is the handle
+      maxMovingRows: 40,           // 1 -> only header. 40 row should be enough, the rest is usually not in the viewport
+      excludeFooter: false,        // excludes the footer row(s) while moving other columns. Make sense if there is a footer with a colspan. */
+      onlyHeaderThreshold: 100,    // TODO:  not implemented yet, switch automatically between entire col moving / only header moving
+      dragaccept: null,            // draggable cols -> default all
+      persistState: null,          // url or function -> plug in your custom persistState function right here. function call is persistState(originalTable)
+      restoreState: null,          // JSON-Object or function:  some kind of experimental aka Quick-Hack TODO: do it better
+      exact: true,                 // removes pixels, so that the overlay table width fits exactly the original table width
+      clickDelay: 10,              // ms to wait before rendering sortable list and delegating click event
+      containment: null,           // @see http://api.jqueryui.com/sortable/#option-containment, use it if you want to move in 2 dimesnions (together with axis: null)
+      cursor: 'move',              // @see http://api.jqueryui.com/sortable/#option-cursor
+      cursorAt: false,             // @see http://api.jqueryui.com/sortable/#option-cursorAt
+      distance: 0,                 // @see http://api.jqueryui.com/sortable/#option-distance, for immediate feedback use "0"
+      tolerance: 'pointer',        // @see http://api.jqueryui.com/sortable/#option-tolerance
+      axis: 'x',                   // @see http://api.jqueryui.com/sortable/#option-axis, Only vertical moving is allowed. Use 'x' or null. Use this in conjunction with the 'containment' setting
+      beforeStart: $.noop,         // returning FALSE will stop the execution chain.
+      beforeMoving: $.noop,
+      beforeReorganize: $.noop,
+      beforeStop: $.noop
+    },
+    originalTable: {
+      el: null,
+      selectedHandle: null,
+      sortOrder: null,
+      startIndex: 0,
+      endIndex: 0
+    },
+    sortableTable: {
+      el: $(),
+      selectedHandle: $(),
+      movingRow: $()
+    },
+    persistState: function() {
+      var _this = this;
+      this.originalTable.el.find('th').each(function(i) {
+        if (this.id !== '') {
+          _this.originalTable.sortOrder[this.id] = i;
+        }
+      });
+      $.ajax({
+        url: this.options.persistState,
+        data: this.originalTable.sortOrder
+      });
+    },
+    /*
+     * persistObj looks like
+     * {'id1':'2','id3':'3','id2':'1'}
+     * table looks like
+     * |   id2  |   id1   |   id3   |
+     */
+    _restoreState: function(persistObj) {
+      for (var n in persistObj) {
+        this.originalTable.startIndex = $('#' + n).closest('th').prevAll().length + 1;
+        this.originalTable.endIndex = parseInt(persistObj[n], 10) + 1;
+        this._bubbleCols();
+      }
+    },
+    // bubble the moved col left or right
+    _bubbleCols: function() {
+      var i, j, col1, col2;
+      var from = this.originalTable.startIndex;
+      var to = this.originalTable.endIndex;
+      /* Find children thead and tbody.
+       * Only to process the immediate tr-children. Bugfix for inner tables
+       */
+      var thtb = this.originalTable.el.children();
+      if (this.options.excludeFooter) {
+        thtb = thtb.not('tfoot');
+      }
+      if (from < to) {
+        for (i = from; i < to; i++) {
+          col1 = thtb.find('> tr > td:nth-child(' + i + ')')
+            .add(thtb.find('> tr > th:nth-child(' + i + ')'));
+          col2 = thtb.find('> tr > td:nth-child(' + (i + 1) + ')')
+            .add(thtb.find('> tr > th:nth-child(' + (i + 1) + ')'));
+          for (j = 0; j < col1.length; j++) {
+            swapNodes(col1[j], col2[j]);
+          }
+        }
+      } else {
+        for (i = from; i > to; i--) {
+          col1 = thtb.find('> tr > td:nth-child(' + i + ')')
+            .add(thtb.find('> tr > th:nth-child(' + i + ')'));
+          col2 = thtb.find('> tr > td:nth-child(' + (i - 1) + ')')
+            .add(thtb.find('> tr > th:nth-child(' + (i - 1) + ')'));
+          for (j = 0; j < col1.length; j++) {
+            swapNodes(col1[j], col2[j]);
+          }
+        }
+      }
+    },
+    _rearrangeTableBackroundProcessing: function() {
+      var _this = this;
+      return function() {
+        _this._bubbleCols();
+        _this.options.beforeStop(_this.originalTable);
+        _this.sortableTable.el.remove();
+        restoreTextSelection();
+        // persist state if necessary
+        if (_this.options.persistState !== null) {
+          $.isFunction(_this.options.persistState) ? _this.options.persistState(_this.originalTable) : _this.persistState();
+        }
+      };
+    },
+    _rearrangeTable: function() {
+      var _this = this;
+      return function() {
+        // remove handler-class -> handler is now finished
+        _this.originalTable.selectedHandle.removeClass('dragtable-handle-selected');
+        // add disabled class -> reorgorganisation starts soon
+        _this.sortableTable.el.sortable("disable");
+        _this.sortableTable.el.addClass('dragtable-disabled');
+        _this.options.beforeReorganize(_this.originalTable, _this.sortableTable);
+        // do reorganisation asynchronous
+        // for chrome a little bit more than 1 ms because we want to force a rerender
+        _this.originalTable.endIndex = _this.sortableTable.movingRow.prevAll().length + 1;
+        setTimeout(_this._rearrangeTableBackroundProcessing(), 50);
+      };
+    },
+    /*
+     * Disrupts the table. The original table stays the same.
+     * But on a layer above the original table we are constructing a list (ul > li)
+     * each li with a separate table representig a single col of the original table.
+     */
+    _generateSortable: function(e) {
+      !e.cancelBubble && (e.cancelBubble = true);
+      var _this = this;
+      // table attributes
+      var attrs = this.originalTable.el[0].attributes;
+      var attrsString = '';
+      for (var i = 0; i < attrs.length; i++) {
+        if (attrs[i].nodeValue && attrs[i].nodeName != 'id' && attrs[i].nodeName != 'width') {
+          attrsString += attrs[i].nodeName + '="' + attrs[i].nodeValue + '" ';
+        }
+      }
+
+      // row attributes
+      var rowAttrsArr = [];
+      //compute height, special handling for ie needed :-(
+      var heightArr = [];
+      this.originalTable.el.find('tr').slice(0, this.options.maxMovingRows).each(function(i, v) {
+        // row attributes
+        var attrs = this.attributes;
+        var attrsString = "";
+        for (var j = 0; j < attrs.length; j++) {
+          if (attrs[j].nodeValue && attrs[j].nodeName != 'id') {
+            attrsString += " " + attrs[j].nodeName + '="' + attrs[j].nodeValue + '"';
+          }
+        }
+        rowAttrsArr.push(attrsString);
+        heightArr.push($(this).height());
+      });
+
+      // compute width, no special handling for ie needed :-)
+      var widthArr = [];
+      // compute total width, needed for not wrapping around after the screen ends (floating)
+      var totalWidth = 0;
+      /* Find children thead and tbody.
+       * Only to process the immediate tr-children. Bugfix for inner tables
+       */
+      var thtb = _this.originalTable.el.children();
+      if (this.options.excludeFooter) {
+        thtb = thtb.not('tfoot');
+      }
+      thtb.find('> tr > th').each(function(i, v) {
+        var w = $(this).is(':visible') ? $(this).outerWidth() : 0;
+        widthArr.push(w);
+        totalWidth += w;
+      });
+      if(_this.options.exact) {
+          var difference = totalWidth - _this.originalTable.el.outerWidth();
+          widthArr[0] -= difference;
+      }
+      // one extra px on right and left side
+      totalWidth += 2
+
+      var sortableHtml = '<ul class="dragtable-sortable" style="position:absolute; width:' + totalWidth + 'px;">';
+      // assemble the needed html
+      thtb.find('> tr > th').each(function(i, v) {
+        var width_li = $(this).is(':visible') ? $(this).outerWidth() : 0;
+        sortableHtml += '<li style="width:' + width_li + 'px;">';
+        sortableHtml += '<table ' + attrsString + '>';
+        var row = thtb.find('> tr > th:nth-child(' + (i + 1) + ')');
+        if (_this.options.maxMovingRows > 1) {
+          row = row.add(thtb.find('> tr > td:nth-child(' + (i + 1) + ')').slice(0, _this.options.maxMovingRows - 1));
+        }
+        row.each(function(j) {
+          // TODO: May cause duplicate style-Attribute
+          var row_content = $(this).clone().wrap('<div></div>').parent().html();
+          if (row_content.toLowerCase().indexOf('<th') === 0) sortableHtml += "<thead>";
+          sortableHtml += '<tr ' + rowAttrsArr[j] + '" style="height:' + heightArr[j] + 'px;">';
+          sortableHtml += row_content;
+          if (row_content.toLowerCase().indexOf('<th') === 0) sortableHtml += "</thead>";
+          sortableHtml += '</tr>';
+        });
+        sortableHtml += '</table>';
+        sortableHtml += '</li>';
+      });
+      sortableHtml += '</ul>';
+      this.sortableTable.el = this.originalTable.el.before(sortableHtml).prev();
+      // set width if necessary
+      this.sortableTable.el.find('> li > table').each(function(i, v) {
+        $(this).css('width', widthArr[i] + 'px');
+      });
+
+      // assign this.sortableTable.selectedHandle
+      this.sortableTable.selectedHandle = this.sortableTable.el.find('th .dragtable-handle-selected');
+
+      var items = !this.options.dragaccept ? 'li' : 'li:has(' + this.options.dragaccept + ')';
+      this.sortableTable.el.sortable({
+        items: items,
+        stop: this._rearrangeTable(),
+        // pass thru options for sortable widget
+        revert: this.options.revert,
+        tolerance: this.options.tolerance,
+        containment: this.options.containment,
+        cursor: this.options.cursor,
+        cursorAt: this.options.cursorAt,
+        distance: this.options.distance,
+        axis: this.options.axis
+      });
+
+      // assign start index
+      this.originalTable.startIndex = $(e.target).closest('th').prevAll().length + 1;
+
+      this.options.beforeMoving(this.originalTable, this.sortableTable);
+      // Start moving by delegating the original event to the new sortable table
+      this.sortableTable.movingRow = this.sortableTable.el.find('> li:nth-child(' + this.originalTable.startIndex + ')');
+
+      // prevent the user from drag selecting "highlighting" surrounding page elements
+      disableTextSelection();
+      // clone the initial event and trigger the sort with it
+      this.sortableTable.movingRow.trigger($.extend($.Event(e.type), {
+        which: 1,
+        clientX: e.clientX,
+        clientY: e.clientY,
+        pageX: e.pageX,
+        pageY: e.pageY,
+        screenX: e.screenX,
+        screenY: e.screenY
+      }));
+
+      // Some inner divs to deliver the posibillity to style the placeholder more sophisticated
+      var placeholder = this.sortableTable.el.find('.ui-sortable-placeholder');
+      if(!placeholder.height()  <= 0) {
+        placeholder.css('height', this.sortableTable.el.find('.ui-sortable-helper').height());
+      }
+
+      placeholder.html('<div class="outer" style="height:100%;"><div class="inner" style="height:100%;"></div></div>');
+    },
+    bindTo: {},
+    _create: function() {
+      this.originalTable = {
+        el: this.element,
+        selectedHandle: $(),
+        sortOrder: {},
+        startIndex: 0,
+        endIndex: 0
+      };
+      // bind draggable to 'th' by default
+      this.bindTo = this.originalTable.el.find('th');
+      // filter only the cols that are accepted
+      if (this.options.dragaccept) {
+        this.bindTo = this.bindTo.filter(this.options.dragaccept);
+      }
+      // bind draggable to handle if exists
+      if (this.bindTo.find(this.options.dragHandle).length > 0) {
+        this.bindTo = this.bindTo.find(this.options.dragHandle);
+      }
+      // restore state if necessary
+      if (this.options.restoreState !== null) {
+        $.isFunction(this.options.restoreState) ? this.options.restoreState(this.originalTable) : this._restoreState(this.options.restoreState);
+      }
+      var _this = this;
+      this.bindTo.mousedown(function(evt) {
+        // listen only to left mouse click
+        if(evt.which!==1) return;
+        if (_this.options.beforeStart(_this.originalTable) === false) {
+          return;
+        }
+        clearTimeout(this.downTimer);
+        this.downTimer = setTimeout(function() {
+          _this.originalTable.selectedHandle = $(this);
+          _this.originalTable.selectedHandle.addClass('dragtable-handle-selected');
+          _this._generateSortable(evt);
+        }, _this.options.clickDelay);
+      }).mouseup(function(evt) {
+        clearTimeout(this.downTimer);
+      });
+    },
+    redraw: function(){
+      this.destroy();
+      this._create();
+    },
+    destroy: function() {
+      this.bindTo.unbind('mousedown');
+      $.Widget.prototype.destroy.apply(this, arguments); // default destroy
+      // now do other stuff particular to this widget
+    }
+  });
+
+  /** closure-scoped "private" functions **/
+
+  var body_onselectstart_save = $(document.body).attr('onselectstart'),
+    body_unselectable_save = $(document.body).attr('unselectable');
+
+  // css properties to disable user-select on the body tag by appending a <style> tag to the <head>
+  // remove any current document selections
+
+  function disableTextSelection() {
+    // jQuery doesn't support the element.text attribute in MSIE 8
+    // http://stackoverflow.com/questions/2692770/style-style-textcss-appendtohead-does-not-work-in-ie
+    var $style = $('<style id="__dragtable_disable_text_selection__" type="text/css">body { -ms-user-select:none;-moz-user-select:-moz-none;-khtml-user-select:none;-webkit-user-select:none;user-select:none; }</style>');
+    $(document.head).append($style);
+    $(document.body).attr('onselectstart', 'return false;').attr('unselectable', 'on');
+    if (window.getSelection) {
+      window.getSelection().removeAllRanges();
+    } else {
+      document.selection.empty(); // MSIE http://msdn.microsoft.com/en-us/library/ms535869%28v=VS.85%29.aspx
+    }
+  }
+
+  // remove the <style> tag, and restore the original <body> onselectstart attribute
+
+  function restoreTextSelection() {
+    $('#__dragtable_disable_text_selection__').remove();
+    if (body_onselectstart_save) {
+      $(document.body).attr('onselectstart', body_onselectstart_save);
+    } else {
+      $(document.body).removeAttr('onselectstart');
+    }
+    if (body_unselectable_save) {
+      $(document.body).attr('unselectable', body_unselectable_save);
+    } else {
+      $(document.body).removeAttr('unselectable');
+    }
+  }
+
+  function swapNodes(a, b) {
+    var aparent = a.parentNode;
+    var asibling = a.nextSibling === b ? a : a.nextSibling;
+    b.parentNode.insertBefore(a, b);
+    aparent.insertBefore(b, asibling);
+  }
+})(jQuery);

+ 340 - 0
static/lib/jquery/jquery.serializejson.js

@@ -0,0 +1,340 @@
+/*!
+  SerializeJSON jQuery plugin.
+  https://github.com/marioizquierdo/jquery.serializeJSON
+  version 2.8.1 (Dec, 2016)
+
+  Copyright (c) 2012, 2017 Mario Izquierdo
+  Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
+  and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
+*/
+(function (factory) {
+  if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module.
+    define(['jquery'], factory);
+  } else if (typeof exports === 'object') { // Node/CommonJS
+    var jQuery = require('jquery');
+    module.exports = factory(jQuery);
+  } else { // Browser globals (zepto supported)
+    factory(window.jQuery || window.Zepto || window.$); // Zepto supported on browsers as well
+  }
+
+}(function ($) {
+  "use strict";
+
+  // jQuery('form').serializeJSON()
+  $.fn.serializeJSON = function (options) {
+    var f, $form, opts, formAsArray, serializedObject, name, value, parsedValue, _obj, nameWithNoType, type, keys, skipFalsy;
+    f = $.serializeJSON;
+    $form = this; // NOTE: the set of matched elements is most likely a form, but it could also be a group of inputs
+    opts = f.setupOpts(options); // calculate values for options {parseNumbers, parseBoolens, parseNulls, ...} with defaults
+
+    // Use native `serializeArray` function to get an array of {name, value} objects.
+    formAsArray = $form.serializeArray();
+    f.readCheckboxUncheckedValues(formAsArray, opts, $form); // add objects to the array from unchecked checkboxes if needed
+
+    // Convert the formAsArray into a serializedObject with nested keys
+    serializedObject = {};
+    $.each(formAsArray, function (i, obj) {
+      name  = obj.name; // original input name
+      value = obj.value; // input value
+      _obj = f.extractTypeAndNameWithNoType(name);
+      nameWithNoType = _obj.nameWithNoType; // input name with no type (i.e. "foo:string" => "foo")
+      type = _obj.type; // type defined from the input name in :type colon notation
+      if (!type) type = f.attrFromInputWithName($form, name, 'data-value-type');
+      f.validateType(name, type, opts); // make sure that the type is one of the valid types if defined
+
+      if (type !== 'skip') { // ignore inputs with type 'skip'
+        keys = f.splitInputNameIntoKeysArray(nameWithNoType);
+        parsedValue = f.parseValue(value, name, type, opts); // convert to string, number, boolean, null or customType
+
+        skipFalsy = !parsedValue && f.shouldSkipFalsy($form, name, nameWithNoType, type, opts); // ignore falsy inputs if specified
+        if (!skipFalsy) {
+          f.deepSet(serializedObject, keys, parsedValue, opts);
+        }
+      }
+    });
+    return serializedObject;
+  };
+
+  // Use $.serializeJSON as namespace for the auxiliar functions
+  // and to define defaults
+  $.serializeJSON = {
+
+    defaultOptions: {
+      checkboxUncheckedValue: undefined, // to include that value for unchecked checkboxes (instead of ignoring them)
+
+      parseNumbers: false, // convert values like "1", "-2.33" to 1, -2.33
+      parseBooleans: false, // convert "true", "false" to true, false
+      parseNulls: false, // convert "null" to null
+      parseAll: false, // all of the above
+      parseWithFunction: null, // to use custom parser, a function like: function(val){ return parsed_val; }
+
+      skipFalsyValuesForTypes: [], // skip serialization of falsy values for listed value types
+      skipFalsyValuesForFields: [], // skip serialization of falsy values for listed field names
+
+      customTypes: {}, // override defaultTypes
+      defaultTypes: {
+        "string":  function(str) { return String(str); },
+        "number":  function(str) { return Number(str); },
+        "boolean": function(str) { var falses = ["false", "null", "undefined", "", "0"]; return falses.indexOf(str) === -1; },
+        "null":    function(str) { var falses = ["false", "null", "undefined", "", "0"]; return falses.indexOf(str) === -1 ? str : null; },
+        "array":   function(str) { return JSON.parse(str); },
+        "object":  function(str) { return JSON.parse(str); },
+        "auto":    function(str) { return $.serializeJSON.parseValue(str, null, null, {parseNumbers: true, parseBooleans: true, parseNulls: true}); }, // try again with something like "parseAll"
+        "skip":    null // skip is a special type that makes it easy to ignore elements
+      },
+
+      useIntKeysAsArrayIndex: false // name="foo[2]" value="v" => {foo: [null, null, "v"]}, instead of {foo: ["2": "v"]}
+    },
+
+    // Merge option defaults into the options
+    setupOpts: function(options) {
+      var opt, validOpts, defaultOptions, optWithDefault, parseAll, f;
+      f = $.serializeJSON;
+
+      if (options == null) { options = {}; }   // options ||= {}
+      defaultOptions = f.defaultOptions || {}; // defaultOptions
+
+      // Make sure that the user didn't misspell an option
+      validOpts = ['checkboxUncheckedValue', 'parseNumbers', 'parseBooleans', 'parseNulls', 'parseAll', 'parseWithFunction', 'skipFalsyValuesForTypes', 'skipFalsyValuesForFields', 'customTypes', 'defaultTypes', 'useIntKeysAsArrayIndex']; // re-define because the user may override the defaultOptions
+      for (opt in options) {
+        if (validOpts.indexOf(opt) === -1) {
+          throw new  Error("serializeJSON ERROR: invalid option '" + opt + "'. Please use one of " + validOpts.join(', '));
+        }
+      }
+
+      // Helper to get the default value for this option if none is specified by the user
+      optWithDefault = function(key) { return (options[key] !== false) && (options[key] !== '') && (options[key] || defaultOptions[key]); };
+
+      // Return computed options (opts to be used in the rest of the script)
+      parseAll = optWithDefault('parseAll');
+      return {
+        checkboxUncheckedValue:    optWithDefault('checkboxUncheckedValue'),
+
+        parseNumbers:  parseAll || optWithDefault('parseNumbers'),
+        parseBooleans: parseAll || optWithDefault('parseBooleans'),
+        parseNulls:    parseAll || optWithDefault('parseNulls'),
+        parseWithFunction:         optWithDefault('parseWithFunction'),
+
+        skipFalsyValuesForTypes:   optWithDefault('skipFalsyValuesForTypes'),
+        skipFalsyValuesForFields:  optWithDefault('skipFalsyValuesForFields'),
+        typeFunctions: $.extend({}, optWithDefault('defaultTypes'), optWithDefault('customTypes')),
+
+        useIntKeysAsArrayIndex: optWithDefault('useIntKeysAsArrayIndex')
+      };
+    },
+
+    // Given a string, apply the type or the relevant "parse" options, to return the parsed value
+    parseValue: function(valStr, inputName, type, opts) {
+      var f, parsedVal;
+      f = $.serializeJSON;
+      parsedVal = valStr; // if no parsing is needed, the returned value will be the same
+
+      if (opts.typeFunctions && type && opts.typeFunctions[type]) { // use a type if available
+        parsedVal = opts.typeFunctions[type](valStr);
+      } else if (opts.parseNumbers  && f.isNumeric(valStr)) { // auto: number
+        parsedVal = Number(valStr);
+      } else if (opts.parseBooleans && (valStr === "true" || valStr === "false")) { // auto: boolean
+        parsedVal = (valStr === "true");
+      } else if (opts.parseNulls    && valStr == "null") { // auto: null
+        parsedVal = null;
+      }
+      if (opts.parseWithFunction && !type) { // custom parse function (apply after previous parsing options, but not if there's a specific type)
+        parsedVal = opts.parseWithFunction(parsedVal, inputName);
+      }
+
+      return parsedVal;
+    },
+
+    isObject:          function(obj) { return obj === Object(obj); }, // is it an Object?
+    isUndefined:       function(obj) { return obj === void 0; }, // safe check for undefined values
+    isValidArrayIndex: function(val) { return /^[0-9]+$/.test(String(val)); }, // 1,2,3,4 ... are valid array indexes
+    isNumeric:         function(obj) { return obj - parseFloat(obj) >= 0; }, // taken from jQuery.isNumeric implementation. Not using jQuery.isNumeric to support old jQuery and Zepto versions
+
+    optionKeys: function(obj) { if (Object.keys) { return Object.keys(obj); } else { var key, keys = []; for(key in obj){ keys.push(key); } return keys;} }, // polyfill Object.keys to get option keys in IE<9
+
+
+    // Fill the formAsArray object with values for the unchecked checkbox inputs,
+    // using the same format as the jquery.serializeArray function.
+    // The value of the unchecked values is determined from the opts.checkboxUncheckedValue
+    // and/or the data-unchecked-value attribute of the inputs.
+    readCheckboxUncheckedValues: function (formAsArray, opts, $form) {
+      var selector, $uncheckedCheckboxes, $el, uncheckedValue, f, name;
+      if (opts == null) { opts = {}; }
+      f = $.serializeJSON;
+
+      selector = 'input[type=checkbox][name]:not(:checked):not([disabled])';
+      $uncheckedCheckboxes = $form.find(selector).add($form.filter(selector));
+      $uncheckedCheckboxes.each(function (i, el) {
+        // Check data attr first, then the option
+        $el = $(el);
+        uncheckedValue = $el.attr('data-unchecked-value');
+        if (uncheckedValue == null) {
+          uncheckedValue = opts.checkboxUncheckedValue;
+        }
+
+        // If there's an uncheckedValue, push it into the serialized formAsArray
+        if (uncheckedValue != null) {
+          if (el.name && el.name.indexOf("[][") !== -1) { // identify a non-supported
+            throw new Error("serializeJSON ERROR: checkbox unchecked values are not supported on nested arrays of objects like '"+el.name+"'. See https://github.com/marioizquierdo/jquery.serializeJSON/issues/67");
+          }
+          formAsArray.push({name: el.name, value: uncheckedValue});
+        }
+      });
+    },
+
+    // Returns and object with properties {name_without_type, type} from a given name.
+    // The type is null if none specified. Example:
+    //   "foo"           =>  {nameWithNoType: "foo",      type:  null}
+    //   "foo:boolean"   =>  {nameWithNoType: "foo",      type: "boolean"}
+    //   "foo[bar]:null" =>  {nameWithNoType: "foo[bar]", type: "null"}
+    extractTypeAndNameWithNoType: function(name) {
+      var match;
+      if (match = name.match(/(.*):([^:]+)$/)) {
+        return {nameWithNoType: match[1], type: match[2]};
+      } else {
+        return {nameWithNoType: name, type: null};
+      }
+    },
+
+
+    // Check if this input should be skipped when it has a falsy value,
+    // depending on the options to skip values by name or type, and the data-skip-falsy attribute.
+    shouldSkipFalsy: function($form, name, nameWithNoType, type, opts) {
+      var f = $.serializeJSON;
+      
+      var skipFromDataAttr = f.attrFromInputWithName($form, name, 'data-skip-falsy');
+      if (skipFromDataAttr != null) {
+        return skipFromDataAttr !== 'false'; // any value is true, except if explicitly using 'false' 
+      }
+
+      var optForFields = opts.skipFalsyValuesForFields;
+      if (optForFields && (optForFields.indexOf(nameWithNoType) !== -1 || optForFields.indexOf(name) !== -1)) {
+        return true;
+      }
+      
+      var optForTypes = opts.skipFalsyValuesForTypes;
+      if (type == null) type = 'string'; // assume fields with no type are targeted as string
+      if (optForTypes && optForTypes.indexOf(type) !== -1) {
+        return true
+      }
+
+      return false;
+    },
+
+    // Finds the first input in $form with this name, and get the given attr from it.
+    // Returns undefined if no input or no attribute was found.
+    attrFromInputWithName: function($form, name, attrName) {
+      var escapedName, selector, $input, attrValue;
+      escapedName = name.replace(/(:|\.|\[|\]|\s)/g,'\\$1'); // every non-standard character need to be escaped by \\
+      selector = '[name="' + escapedName + '"]';
+      $input = $form.find(selector).add($form.filter(selector)); // NOTE: this returns only the first $input element if multiple are matched with the same name (i.e. an "array[]"). So, arrays with different element types specified through the data-value-type attr is not supported.
+      return $input.attr(attrName);
+    },
+
+    // Raise an error if the type is not recognized.
+    validateType: function(name, type, opts) {
+      var validTypes, f;
+      f = $.serializeJSON;
+      validTypes = f.optionKeys(opts ? opts.typeFunctions : f.defaultOptions.defaultTypes);
+      if (!type || validTypes.indexOf(type) !== -1) {
+        return true;
+      } else {
+        throw new Error("serializeJSON ERROR: Invalid type " + type + " found in input name '" + name + "', please use one of " + validTypes.join(', '));
+      }
+    },
+
+
+    // Split the input name in programatically readable keys.
+    // Examples:
+    // "foo"              => ['foo']
+    // "[foo]"            => ['foo']
+    // "foo[inn][bar]"    => ['foo', 'inn', 'bar']
+    // "foo[inn[bar]]"    => ['foo', 'inn', 'bar']
+    // "foo[inn][arr][0]" => ['foo', 'inn', 'arr', '0']
+    // "arr[][val]"       => ['arr', '', 'val']
+    splitInputNameIntoKeysArray: function(nameWithNoType) {
+      var keys, f;
+      f = $.serializeJSON;
+      keys = nameWithNoType.split('['); // split string into array
+      keys = $.map(keys, function (key) { return key.replace(/\]/g, ''); }); // remove closing brackets
+      if (keys[0] === '') { keys.shift(); } // ensure no opening bracket ("[foo][inn]" should be same as "foo[inn]")
+      return keys;
+    },
+
+    // Set a value in an object or array, using multiple keys to set in a nested object or array:
+    //
+    // deepSet(obj, ['foo'], v)               // obj['foo'] = v
+    // deepSet(obj, ['foo', 'inn'], v)        // obj['foo']['inn'] = v // Create the inner obj['foo'] object, if needed
+    // deepSet(obj, ['foo', 'inn', '123'], v) // obj['foo']['arr']['123'] = v //
+    //
+    // deepSet(obj, ['0'], v)                                   // obj['0'] = v
+    // deepSet(arr, ['0'], v, {useIntKeysAsArrayIndex: true})   // arr[0] = v
+    // deepSet(arr, [''], v)                                    // arr.push(v)
+    // deepSet(obj, ['arr', ''], v)                             // obj['arr'].push(v)
+    //
+    // arr = [];
+    // deepSet(arr, ['', v]          // arr => [v]
+    // deepSet(arr, ['', 'foo'], v)  // arr => [v, {foo: v}]
+    // deepSet(arr, ['', 'bar'], v)  // arr => [v, {foo: v, bar: v}]
+    // deepSet(arr, ['', 'bar'], v)  // arr => [v, {foo: v, bar: v}, {bar: v}]
+    //
+    deepSet: function (o, keys, value, opts) {
+      var key, nextKey, tail, lastIdx, lastVal, f;
+      if (opts == null) { opts = {}; }
+      f = $.serializeJSON;
+      if (f.isUndefined(o)) { throw new Error("ArgumentError: param 'o' expected to be an object or array, found undefined"); }
+      if (!keys || keys.length === 0) { throw new Error("ArgumentError: param 'keys' expected to be an array with least one element"); }
+
+      key = keys[0];
+
+      // Only one key, then it's not a deepSet, just assign the value.
+      if (keys.length === 1) {
+        if (key === '') {
+          o.push(value); // '' is used to push values into the array (assume o is an array)
+        } else {
+          o[key] = value; // other keys can be used as object keys or array indexes
+        }
+
+      // With more keys is a deepSet. Apply recursively.
+      } else {
+        nextKey = keys[1];
+
+        // '' is used to push values into the array,
+        // with nextKey, set the value into the same object, in object[nextKey].
+        // Covers the case of ['', 'foo'] and ['', 'var'] to push the object {foo, var}, and the case of nested arrays.
+        if (key === '') {
+          lastIdx = o.length - 1; // asume o is array
+          lastVal = o[lastIdx];
+          if (f.isObject(lastVal) && (f.isUndefined(lastVal[nextKey]) || keys.length > 2)) { // if nextKey is not present in the last object element, or there are more keys to deep set
+            key = lastIdx; // then set the new value in the same object element
+          } else {
+            key = lastIdx + 1; // otherwise, point to set the next index in the array
+          }
+        }
+
+        // '' is used to push values into the array "array[]"
+        if (nextKey === '') {
+          if (f.isUndefined(o[key]) || !$.isArray(o[key])) {
+            o[key] = []; // define (or override) as array to push values
+          }
+        } else {
+          if (opts.useIntKeysAsArrayIndex && f.isValidArrayIndex(nextKey)) { // if 1, 2, 3 ... then use an array, where nextKey is the index
+            if (f.isUndefined(o[key]) || !$.isArray(o[key])) {
+              o[key] = []; // define (or override) as array, to insert values using int keys as array indexes
+            }
+          } else { // for anything else, use an object, where nextKey is going to be the attribute name
+            if (f.isUndefined(o[key]) || !f.isObject(o[key])) {
+              o[key] = {}; // define (or override) as object, to set nested properties
+            }
+          }
+        }
+
+        // Recursively set the inner object
+        tail = keys.slice(1);
+        f.deepSet(o[key], tail, value, opts);
+      }
+    }
+
+  };
+
+}));

+ 2343 - 0
static/lib/jspdf/jspdf.autotable.js

@@ -0,0 +1,2343 @@
+/*!
+ * jsPDF AutoTable plugin v2.3.0
+ * Copyright (c) 2014 Simon Bengtsson, https://github.com/simonbengtsson/jsPDF-AutoTable 
+ * 
+ * Licensed under the MIT License.
+ * http://opensource.org/licenses/mit-license
+ * 
+ * */if (typeof window === 'object') window.jspdfAutoTableVersion = '2.3.0';/*
+ */
+(function webpackUniversalModuleDefinition(root, factory) {
+	if(typeof exports === 'object' && typeof module === 'object')
+		module.exports = factory(require("jspdf"));
+	else if(typeof define === 'function' && define.amd)
+		define(["jspdf"], factory);
+	else {
+		var a = typeof exports === 'object' ? factory(require("jspdf")) : factory(root["jsPDF"]);
+		for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i];
+	}
+})(this, function(__WEBPACK_EXTERNAL_MODULE_18__) {
+return /******/ (function(modules) { // webpackBootstrap
+/******/ 	// The module cache
+/******/ 	var installedModules = {};
+
+/******/ 	// The require function
+/******/ 	function __webpack_require__(moduleId) {
+
+/******/ 		// Check if module is in cache
+/******/ 		if(installedModules[moduleId])
+/******/ 			return installedModules[moduleId].exports;
+
+/******/ 		// Create a new module (and put it into the cache)
+/******/ 		var module = installedModules[moduleId] = {
+/******/ 			i: moduleId,
+/******/ 			l: false,
+/******/ 			exports: {}
+/******/ 		};
+
+/******/ 		// Execute the module function
+/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
+
+/******/ 		// Flag the module as loaded
+/******/ 		module.l = true;
+
+/******/ 		// Return the exports of the module
+/******/ 		return module.exports;
+/******/ 	}
+
+
+/******/ 	// expose the modules object (__webpack_modules__)
+/******/ 	__webpack_require__.m = modules;
+
+/******/ 	// expose the module cache
+/******/ 	__webpack_require__.c = installedModules;
+
+/******/ 	// identity function for calling harmony imports with the correct context
+/******/ 	__webpack_require__.i = function(value) { return value; };
+
+/******/ 	// define getter function for harmony exports
+/******/ 	__webpack_require__.d = function(exports, name, getter) {
+/******/ 		if(!__webpack_require__.o(exports, name)) {
+/******/ 			Object.defineProperty(exports, name, {
+/******/ 				configurable: false,
+/******/ 				enumerable: true,
+/******/ 				get: getter
+/******/ 			});
+/******/ 		}
+/******/ 	};
+
+/******/ 	// getDefaultExport function for compatibility with non-harmony modules
+/******/ 	__webpack_require__.n = function(module) {
+/******/ 		var getter = module && module.__esModule ?
+/******/ 			function getDefault() { return module['default']; } :
+/******/ 			function getModuleExports() { return module; };
+/******/ 		__webpack_require__.d(getter, 'a', getter);
+/******/ 		return getter;
+/******/ 	};
+
+/******/ 	// Object.prototype.hasOwnProperty.call
+/******/ 	__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
+
+/******/ 	// __webpack_public_path__
+/******/ 	__webpack_require__.p = "";
+
+/******/ 	// Load entry module and return exports
+/******/ 	return __webpack_require__(__webpack_require__.s = 35);
+/******/ })
+/************************************************************************/
+/******/ ([
+/* 0 */
+/***/ function(module, exports, __webpack_require__) {
+
+"use strict";
+
+/**
+ * Ratio between font size and font height. The number comes from jspdf's source code
+ */
+exports.FONT_ROW_RATIO = 1.15;
+var models_1 = __webpack_require__(15);
+var table = null;
+var assign = __webpack_require__(12);
+var entries = __webpack_require__(33);
+/**
+ * Styles for the themes (overriding the default styles)
+ */
+exports.getTheme = function (name) {
+    var themes = {
+        'striped': {
+            table: { fillColor: 255, textColor: 80, fontStyle: 'normal' },
+            header: { textColor: 255, fillColor: [41, 128, 185], fontStyle: 'bold' },
+            body: {},
+            alternateRow: { fillColor: 245 }
+        },
+        'grid': {
+            table: { fillColor: 255, textColor: 80, fontStyle: 'normal', lineWidth: 0.1 },
+            header: { textColor: 255, fillColor: [26, 188, 156], fontStyle: 'bold', lineWidth: 0 },
+            body: {},
+            alternateRow: {}
+        },
+        'plain': {
+            header: { fontStyle: 'bold' }
+        }
+    };
+    return themes[name];
+};
+function getDefaults() {
+    var scaleFactor = Config.scaleFactor();
+    return {
+        // Styling
+        theme: 'striped',
+        styles: {},
+        headerStyles: {},
+        bodyStyles: {},
+        alternateRowStyles: {},
+        columnStyles: {},
+        // Properties
+        startY: false,
+        margin: 40 / scaleFactor,
+        pageBreak: 'auto',
+        tableWidth: 'auto',
+        showHeader: 'everyPage',
+        tableLineWidth: 0,
+        tableLineColor: 200,
+        // Hooks
+        createdHeaderCell: function (cell, data) { },
+        createdCell: function (cell, data) { },
+        drawHeaderRow: function (row, data) { },
+        drawRow: function (row, data) { },
+        drawHeaderCell: function (cell, data) { },
+        drawCell: function (cell, data) { },
+        addPageContent: function (data) { }
+    };
+}
+exports.getDefaults = getDefaults;
+// Base style for all themes
+function defaultStyles() {
+    var scaleFactor = Config.scaleFactor();
+    return {
+        font: "helvetica",
+        fontStyle: 'normal',
+        overflow: 'ellipsize',
+        fillColor: false,
+        textColor: 20,
+        halign: 'left',
+        valign: 'top',
+        fontSize: 10,
+        cellPadding: 5 / scaleFactor,
+        lineColor: 200,
+        lineWidth: 0 / scaleFactor,
+        columnWidth: 'auto'
+    };
+}
+var Config = (function () {
+    function Config() {
+    }
+    Config.pageSize = function () {
+        return table.doc.internal.pageSize;
+    };
+    Config.applyUserStyles = function () {
+        Config.applyStyles(table.userStyles);
+    };
+    Config.createTable = function (doc) {
+        table = new models_1.Table(doc);
+        return table;
+    };
+    Config.tableInstance = function () {
+        return table;
+    };
+    Config.scaleFactor = function () {
+        return table.doc.internal.scaleFactor;
+    };
+    Config.hooksData = function (additionalData) {
+        if (additionalData === void 0) { additionalData = {}; }
+        return assign({
+            pageCount: table.pageCount,
+            settings: table.settings,
+            table: table,
+            doc: table.doc,
+            cursor: table.cursor
+        }, additionalData || {});
+    };
+    Config.initSettings = function (table, allOptions) {
+        var _loop_1 = function (styleProp) {
+            var styles = allOptions.map(function (opts) { return opts[styleProp] || {}; });
+            table.styles[styleProp] = assign.apply(void 0, [{}].concat(styles));
+        };
+        // Merge styles one level deeper
+        for (var _i = 0, _a = Object.keys(table.styles); _i < _a.length; _i++) {
+            var styleProp = _a[_i];
+            _loop_1(styleProp);
+        }
+        // Append event handlers instead of replacing them
+        for (var _b = 0, _c = entries(table.hooks); _b < _c.length; _b++) {
+            var _d = _c[_b], hookName = _d[0], list = _d[1];
+            for (var _e = 0, allOptions_1 = allOptions; _e < allOptions_1.length; _e++) {
+                var opts = allOptions_1[_e];
+                if (opts && opts[hookName]) {
+                    list.push(opts[hookName]);
+                }
+            }
+        }
+        // Merge all other options one level
+        table.settings = assign.apply(void 0, [getDefaults()].concat(allOptions));
+    };
+    // This is messy, only keep array and number format the next major version
+    Config.marginOrPadding = function (value, defaultValue) {
+        var newValue = {};
+        if (Array.isArray(value)) {
+            if (value.length >= 4) {
+                newValue = { 'top': value[0], 'right': value[1], 'bottom': value[2], 'left': value[3] };
+            }
+            else if (value.length === 3) {
+                newValue = { 'top': value[0], 'right': value[1], 'bottom': value[2], 'left': value[1] };
+            }
+            else if (value.length === 2) {
+                newValue = { 'top': value[0], 'right': value[1], 'bottom': value[0], 'left': value[1] };
+            }
+            else if (value.length === 1) {
+                value = value[0];
+            }
+            else {
+                value = defaultValue;
+            }
+        }
+        else if (typeof value === 'object') {
+            if (value['vertical']) {
+                value['top'] = value['vertical'];
+                value['bottom'] = value['vertical'];
+            }
+            else if (value['horizontal']) {
+                value['right'] = value['horizontal'];
+                value['left'] = value['horizontal'];
+            }
+            for (var _i = 0, _a = ['top', 'right', 'bottom', 'left']; _i < _a.length; _i++) {
+                var side = _a[_i];
+                newValue[side] = value[side] || value[side] === 0 ? value[side] : defaultValue;
+            }
+        }
+        if (typeof value === 'number') {
+            newValue = { 'top': value, 'right': value, 'bottom': value, 'left': value };
+        }
+        return newValue;
+    };
+    Config.styles = function (styles) {
+        styles = Array.isArray(styles) ? styles : [styles];
+        return assign.apply(void 0, [defaultStyles()].concat(styles));
+    };
+    Config.applyStyles = function (styles) {
+        var doc = table.doc;
+        var styleModifiers = {
+            fillColor: doc.setFillColor,
+            textColor: doc.setTextColor,
+            fontStyle: doc.setFontStyle,
+            lineColor: doc.setDrawColor,
+            lineWidth: doc.setLineWidth,
+            font: doc.setFont,
+            fontSize: doc.setFontSize
+        };
+        Object.keys(styleModifiers).forEach(function (name) {
+            var style = styles[name];
+            var modifier = styleModifiers[name];
+            if (typeof style !== 'undefined') {
+                if (Array.isArray(style)) {
+                    modifier.apply(this, style);
+                }
+                else {
+                    modifier(style);
+                }
+            }
+        });
+    };
+    return Config;
+}());
+exports.Config = Config;
+
+
+/***/ },
+/* 1 */
+/***/ function(module, exports, __webpack_require__) {
+
+"use strict";
+
+var config_1 = __webpack_require__(0);
+var painter_1 = __webpack_require__(4);
+function getStringWidth(text, styles) {
+    var k = config_1.Config.scaleFactor();
+    var fontSize = styles.fontSize / k;
+    config_1.Config.applyStyles(styles);
+    text = Array.isArray(text) ? text : [text];
+    var maxWidth = 0;
+    text.forEach(function (line) {
+        var width = config_1.Config.tableInstance().doc.getStringUnitWidth(line);
+        if (width > maxWidth) {
+            maxWidth = width;
+        }
+    });
+    var precision = 10000 * k;
+    maxWidth = Math.floor(maxWidth * precision) / precision;
+    return maxWidth * fontSize;
+}
+exports.getStringWidth = getStringWidth;
+/**
+ * Ellipsize the text to fit in the width
+ */
+function ellipsize(text, width, styles, ellipsizeStr) {
+    if (ellipsizeStr === void 0) { ellipsizeStr = '...'; }
+    if (Array.isArray(text)) {
+        var value_1 = [];
+        text.forEach(function (str, i) {
+            value_1[i] = ellipsize(str, width, styles, ellipsizeStr);
+        });
+        return value_1;
+    }
+    var precision = 10000 * config_1.Config.scaleFactor();
+    width = Math.ceil(width * precision) / precision;
+    if (width >= getStringWidth(text, styles)) {
+        return text;
+    }
+    while (width < getStringWidth(text + ellipsizeStr, styles)) {
+        if (text.length <= 1) {
+            break;
+        }
+        text = text.substring(0, text.length - 1);
+    }
+    return text.trim() + ellipsizeStr;
+}
+exports.ellipsize = ellipsize;
+function addTableBorder() {
+    var table = config_1.Config.tableInstance();
+    var styles = { lineWidth: table.settings.tableLineWidth, lineColor: table.settings.tableLineColor };
+    config_1.Config.applyStyles(styles);
+    var fs = getFillStyle(styles);
+    if (fs) {
+        table.doc.rect(table.pageStartX, table.pageStartY, table.width, table.cursor.y - table.pageStartY, fs);
+    }
+}
+exports.addTableBorder = addTableBorder;
+function addPage() {
+    var table = config_1.Config.tableInstance();
+    table.finalY = table.cursor.y;
+    // Add user content just before adding new page ensure it will 
+    // be drawn above other things on the page
+    addContentHooks();
+    addTableBorder();
+    table.doc.addPage();
+    table.pageCount++;
+    table.cursor = { x: table.margin('left'), y: table.margin('top') };
+    table.pageStartX = table.cursor.x;
+    table.pageStartY = table.cursor.y;
+    if (table.settings.showHeader === true || table.settings.showHeader === 'everyPage') {
+        painter_1.printRow(table.headerRow, table.hooks.drawHeaderRow, table.hooks.drawHeaderCell);
+    }
+}
+exports.addPage = addPage;
+function addContentHooks() {
+    for (var _i = 0, _a = config_1.Config.tableInstance().hooks.addPageContent; _i < _a.length; _i++) {
+        var hook = _a[_i];
+        config_1.Config.applyUserStyles();
+        hook(config_1.Config.hooksData());
+    }
+    config_1.Config.applyUserStyles();
+}
+exports.addContentHooks = addContentHooks;
+function getFillStyle(styles) {
+    var drawLine = styles.lineWidth > 0;
+    var drawBackground = styles.fillColor || styles.fillColor === 0;
+    if (drawLine && drawBackground) {
+        return 'DF'; // Fill then stroke
+    }
+    else if (drawLine) {
+        return 'S'; // Only stroke (transparent background)
+    }
+    else if (drawBackground) {
+        return 'F'; // Only fill, no stroke
+    }
+    else {
+        return false;
+    }
+}
+exports.getFillStyle = getFillStyle;
+
+
+/***/ },
+/* 2 */
+/***/ function(module, exports, __webpack_require__) {
+
+var implementation = __webpack_require__(26);
+
+module.exports = Function.prototype.bind || implementation;
+
+
+/***/ },
+/* 3 */
+/***/ function(module, exports, __webpack_require__) {
+
+"use strict";
+
+
+var fnToStr = Function.prototype.toString;
+
+var constructorRegex = /^\s*class /;
+var isES6ClassFn = function isES6ClassFn(value) {
+	try {
+		var fnStr = fnToStr.call(value);
+		var singleStripped = fnStr.replace(/\/\/.*\n/g, '');
+		var multiStripped = singleStripped.replace(/\/\*[.\s\S]*\*\//g, '');
+		var spaceStripped = multiStripped.replace(/\n/mg, ' ').replace(/ {2}/g, ' ');
+		return constructorRegex.test(spaceStripped);
+	} catch (e) {
+		return false; // not a function
+	}
+};
+
+var tryFunctionObject = function tryFunctionObject(value) {
+	try {
+		if (isES6ClassFn(value)) { return false; }
+		fnToStr.call(value);
+		return true;
+	} catch (e) {
+		return false;
+	}
+};
+var toStr = Object.prototype.toString;
+var fnClass = '[object Function]';
+var genClass = '[object GeneratorFunction]';
+var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol';
+
+module.exports = function isCallable(value) {
+	if (!value) { return false; }
+	if (typeof value !== 'function' && typeof value !== 'object') { return false; }
+	if (hasToStringTag) { return tryFunctionObject(value); }
+	if (isES6ClassFn(value)) { return false; }
+	var strClass = toStr.call(value);
+	return strClass === fnClass || strClass === genClass;
+};
+
+
+/***/ },
+/* 4 */
+/***/ function(module, exports, __webpack_require__) {
+
+"use strict";
+
+var config_1 = __webpack_require__(0);
+var common_1 = __webpack_require__(1);
+function printFullRow(row, drawRowHooks, drawCellHooks) {
+    var remainingRowHeight = 0;
+    var remainingTexts = {};
+    var table = config_1.Config.tableInstance();
+    if (!canFitOnPage(row.height)) {
+        if (row.maxLineCount <= 1) {
+            common_1.addPage();
+        }
+        else {
+            // Modify the row to fit the current page and calculate text and height of partial row
+            row.spansMultiplePages = true;
+            var pageHeight = table.doc.internal.pageSize.height;
+            var maxCellHeight = 0;
+            for (var j = 0; j < table.columns.length; j++) {
+                var col = table.columns[j];
+                var cell = row.cells[col.dataKey];
+                var fontHeight = cell.styles.fontSize / config_1.Config.scaleFactor() * config_1.FONT_ROW_RATIO;
+                var vPadding = cell.padding('vertical');
+                var remainingPageSpace = pageHeight - table.cursor.y - table.margin('bottom');
+                var remainingLineCount = Math.floor((remainingPageSpace - vPadding) / fontHeight);
+                if (Array.isArray(cell.text) && cell.text.length > remainingLineCount) {
+                    var remainingLines = cell.text.splice(remainingLineCount, cell.text.length);
+                    remainingTexts[col.dataKey] = remainingLines;
+                    var cellHeight = cell.text.length * fontHeight + vPadding;
+                    if (cellHeight > maxCellHeight) {
+                        maxCellHeight = cellHeight;
+                    }
+                    var rCellHeight = remainingLines.length * fontHeight + vPadding;
+                    if (rCellHeight > remainingRowHeight) {
+                        remainingRowHeight = rCellHeight;
+                    }
+                }
+            }
+            // Reset row height since text are now removed
+            row.height = maxCellHeight;
+        }
+    }
+    printRow(row, drawRowHooks, drawCellHooks);
+    // Parts of the row is now printed. Time for adding a new page, prune 
+    // the text and start over
+    if (Object.keys(remainingTexts).length > 0) {
+        for (var j = 0; j < table.columns.length; j++) {
+            var col = table.columns[j];
+            var cell = row.cells[col.dataKey];
+            cell.text = remainingTexts[col.dataKey] || '';
+        }
+        common_1.addPage();
+        row.pageCount++;
+        row.height = remainingRowHeight;
+        printFullRow(row, drawRowHooks, drawCellHooks);
+    }
+}
+exports.printFullRow = printFullRow;
+function printRow(row, drawRowHooks, drawCellHooks) {
+    var table = config_1.Config.tableInstance();
+    row.y = table.cursor.y;
+    for (var _i = 0, drawRowHooks_1 = drawRowHooks; _i < drawRowHooks_1.length; _i++) {
+        var hook = drawRowHooks_1[_i];
+        if (hook(row, config_1.Config.hooksData({ row: row, addPage: common_1.addPage })) === false) {
+            return;
+        }
+    }
+    table.cursor.x = table.margin('left');
+    for (var i = 0; i < table.columns.length; i++) {
+        var column = table.columns[i];
+        var cell = row.cells[column.dataKey];
+        if (!cell) {
+            continue;
+        }
+        config_1.Config.applyStyles(cell.styles);
+        cell.x = table.cursor.x;
+        cell.y = table.cursor.y;
+        cell.height = row.height;
+        cell.width = column.width;
+        if (cell.styles.valign === 'top') {
+            cell.textPos.y = table.cursor.y + cell.padding('top');
+        }
+        else if (cell.styles.valign === 'bottom') {
+            cell.textPos.y = table.cursor.y + row.height - cell.padding('bottom');
+        }
+        else {
+            cell.textPos.y = table.cursor.y + row.height / 2;
+        }
+        if (cell.styles.halign === 'right') {
+            cell.textPos.x = cell.x + cell.width - cell.padding('right');
+        }
+        else if (cell.styles.halign === 'center') {
+            cell.textPos.x = cell.x + cell.width / 2;
+        }
+        else {
+            cell.textPos.x = cell.x + cell.padding('left');
+        }
+        var shouldDrawCell = true;
+        var data = config_1.Config.hooksData({ column: column, row: row, addPage: common_1.addPage });
+        for (var _a = 0, drawCellHooks_1 = drawCellHooks; _a < drawCellHooks_1.length; _a++) {
+            var hook = drawCellHooks_1[_a];
+            if (hook(cell, data) === false) {
+                shouldDrawCell = false;
+            }
+        }
+        if (shouldDrawCell) {
+            var fillStyle = common_1.getFillStyle(cell.styles);
+            if (fillStyle) {
+                table.doc.rect(cell.x, cell.y, cell.width, cell.height, fillStyle);
+            }
+            table.doc.autoTableText(cell.text, cell.textPos.x, cell.textPos.y, {
+                halign: cell.styles.halign,
+                valign: cell.styles.valign
+            });
+        }
+        table.cursor.x += cell.width;
+    }
+    table.cursor.y += row.height;
+}
+exports.printRow = printRow;
+function canFitOnPage(rowHeight) {
+    var table = config_1.Config.tableInstance();
+    var pos = rowHeight + table.cursor.y + table.margin('bottom');
+    return pos < config_1.Config.pageSize().height;
+}
+
+
+/***/ },
+/* 5 */
+/***/ function(module, exports, __webpack_require__) {
+
+"use strict";
+
+
+var keys = __webpack_require__(31);
+var foreach = __webpack_require__(25);
+var hasSymbols = typeof Symbol === 'function' && typeof Symbol() === 'symbol';
+
+var toStr = Object.prototype.toString;
+
+var isFunction = function (fn) {
+	return typeof fn === 'function' && toStr.call(fn) === '[object Function]';
+};
+
+var arePropertyDescriptorsSupported = function () {
+	var obj = {};
+	try {
+		Object.defineProperty(obj, 'x', { enumerable: false, value: obj });
+        /* eslint-disable no-unused-vars, no-restricted-syntax */
+        for (var _ in obj) { return false; }
+        /* eslint-enable no-unused-vars, no-restricted-syntax */
+		return obj.x === obj;
+	} catch (e) { /* this is IE 8. */
+		return false;
+	}
+};
+var supportsDescriptors = Object.defineProperty && arePropertyDescriptorsSupported();
+
+var defineProperty = function (object, name, value, predicate) {
+	if (name in object && (!isFunction(predicate) || !predicate())) {
+		return;
+	}
+	if (supportsDescriptors) {
+		Object.defineProperty(object, name, {
+			configurable: true,
+			enumerable: false,
+			value: value,
+			writable: true
+		});
+	} else {
+		object[name] = value;
+	}
+};
+
+var defineProperties = function (object, map) {
+	var predicates = arguments.length > 2 ? arguments[2] : {};
+	var props = keys(map);
+	if (hasSymbols) {
+		props = props.concat(Object.getOwnPropertySymbols(map));
+	}
+	foreach(props, function (name) {
+		defineProperty(object, name, map[name], predicates[name]);
+	});
+};
+
+defineProperties.supportsDescriptors = !!supportsDescriptors;
+
+module.exports = defineProperties;
+
+
+/***/ },
+/* 6 */
+/***/ function(module, exports) {
+
+var has = Object.prototype.hasOwnProperty;
+module.exports = Object.assign || function assign(target, source) {
+	for (var key in source) {
+		if (has.call(source, key)) {
+			target[key] = source[key];
+		}
+	}
+	return target;
+};
+
+
+/***/ },
+/* 7 */
+/***/ function(module, exports) {
+
+var $isNaN = Number.isNaN || function (a) { return a !== a; };
+
+module.exports = Number.isFinite || function (x) { return typeof x === 'number' && !$isNaN(x) && x !== Infinity && x !== -Infinity; };
+
+
+/***/ },
+/* 8 */
+/***/ function(module, exports) {
+
+module.exports = Number.isNaN || function isNaN(a) {
+	return a !== a;
+};
+
+
+/***/ },
+/* 9 */
+/***/ function(module, exports) {
+
+module.exports = function mod(number, modulo) {
+	var remain = number % modulo;
+	return Math.floor(remain >= 0 ? remain : remain + modulo);
+};
+
+
+/***/ },
+/* 10 */
+/***/ function(module, exports) {
+
+module.exports = function sign(number) {
+	return number >= 0 ? 1 : -1;
+};
+
+
+/***/ },
+/* 11 */
+/***/ function(module, exports) {
+
+module.exports = function isPrimitive(value) {
+	return value === null || (typeof value !== 'function' && typeof value !== 'object');
+};
+
+
+/***/ },
+/* 12 */
+/***/ function(module, exports, __webpack_require__) {
+
+"use strict";
+
+/* eslint-disable no-unused-vars */
+var hasOwnProperty = Object.prototype.hasOwnProperty;
+var propIsEnumerable = Object.prototype.propertyIsEnumerable;
+
+function toObject(val) {
+	if (val === null || val === undefined) {
+		throw new TypeError('Object.assign cannot be called with null or undefined');
+	}
+
+	return Object(val);
+}
+
+function shouldUseNative() {
+	try {
+		if (!Object.assign) {
+			return false;
+		}
+
+		// Detect buggy property enumeration order in older V8 versions.
+
+		// https://bugs.chromium.org/p/v8/issues/detail?id=4118
+		var test1 = new String('abc');  // eslint-disable-line
+		test1[5] = 'de';
+		if (Object.getOwnPropertyNames(test1)[0] === '5') {
+			return false;
+		}
+
+		// https://bugs.chromium.org/p/v8/issues/detail?id=3056
+		var test2 = {};
+		for (var i = 0; i < 10; i++) {
+			test2['_' + String.fromCharCode(i)] = i;
+		}
+		var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
+			return test2[n];
+		});
+		if (order2.join('') !== '0123456789') {
+			return false;
+		}
+
+		// https://bugs.chromium.org/p/v8/issues/detail?id=3056
+		var test3 = {};
+		'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
+			test3[letter] = letter;
+		});
+		if (Object.keys(Object.assign({}, test3)).join('') !==
+				'abcdefghijklmnopqrst') {
+			return false;
+		}
+
+		return true;
+	} catch (e) {
+		// We don't expect any of the above to throw, but better to be safe.
+		return false;
+	}
+}
+
+module.exports = shouldUseNative() ? Object.assign : function (target, source) {
+	var from;
+	var to = toObject(target);
+	var symbols;
+
+	for (var s = 1; s < arguments.length; s++) {
+		from = Object(arguments[s]);
+
+		for (var key in from) {
+			if (hasOwnProperty.call(from, key)) {
+				to[key] = from[key];
+			}
+		}
+
+		if (Object.getOwnPropertySymbols) {
+			symbols = Object.getOwnPropertySymbols(from);
+			for (var i = 0; i < symbols.length; i++) {
+				if (propIsEnumerable.call(from, symbols[i])) {
+					to[symbols[i]] = from[symbols[i]];
+				}
+			}
+		}
+	}
+
+	return to;
+};
+
+
+/***/ },
+/* 13 */
+/***/ function(module, exports, __webpack_require__) {
+
+"use strict";
+
+
+var ES = __webpack_require__(21);
+var has = __webpack_require__(27);
+var bind = __webpack_require__(2);
+var isEnumerable = bind.call(Function.call, Object.prototype.propertyIsEnumerable);
+
+module.exports = function entries(O) {
+	var obj = ES.RequireObjectCoercible(O);
+	var entrys = [];
+	for (var key in obj) {
+		if (has(obj, key) && isEnumerable(obj, key)) {
+			entrys.push([key, obj[key]]);
+		}
+	}
+	return entrys;
+};
+
+
+/***/ },
+/* 14 */
+/***/ function(module, exports, __webpack_require__) {
+
+"use strict";
+
+
+var implementation = __webpack_require__(13);
+
+module.exports = function getPolyfill() {
+	return typeof Object.entries === 'function' ? Object.entries : implementation;
+};
+
+
+/***/ },
+/* 15 */
+/***/ function(module, exports, __webpack_require__) {
+
+"use strict";
+
+var config_1 = __webpack_require__(0);
+exports.table = {};
+var Table = (function () {
+    function Table(doc) {
+        this.height = 0;
+        this.width = 0;
+        this.contentWidth = 0;
+        this.preferredWidth = 0;
+        this.rows = [];
+        this.columns = [];
+        this.headerRow = null;
+        this.pageCount = 1;
+        this.hooks = {
+            createdHeaderCell: [],
+            createdCell: [],
+            drawHeaderRow: [],
+            drawRow: [],
+            drawHeaderCell: [],
+            drawCell: [],
+            addPageContent: []
+        };
+        this.styles = {
+            styles: {},
+            headerStyles: {},
+            bodyStyles: {},
+            alternateRowStyles: {},
+            columnStyles: {}
+        };
+        this.doc = doc;
+        this.userStyles = {
+            textColor: 30,
+            fontSize: doc.internal.getFontSize(),
+            fontStyle: doc.internal.getFont().fontStyle
+        };
+    }
+    Table.prototype.margin = function (side) {
+        return config_1.Config.marginOrPadding(this.settings.margin, config_1.getDefaults().margin)[side];
+    };
+    return Table;
+}());
+exports.Table = Table;
+var Row = (function () {
+    function Row(raw, index) {
+        this.cells = {};
+        this.spansMultiplePages = false;
+        this.pageCount = 1;
+        this.height = 0;
+        this.y = 0;
+        this.maxLineCount = 1;
+        this.raw = raw;
+        this.index = index;
+    }
+    return Row;
+}());
+exports.Row = Row;
+var Cell = (function () {
+    function Cell(raw) {
+        this.styles = {};
+        this.text = '';
+        this.contentWidth = 0;
+        this.textPos = {};
+        this.height = 0;
+        this.width = 0;
+        this.x = 0;
+        this.y = 0;
+        this.raw = raw;
+    }
+    Cell.prototype.padding = function (name) {
+        var padding = config_1.Config.marginOrPadding(this.styles.cellPadding, config_1.Config.styles([]).cellPadding);
+        if (name === 'vertical') {
+            return padding.top + padding.bottom;
+        }
+        else if (name === 'horizontal') {
+            return padding.left + padding.right;
+        }
+        else {
+            return padding[name];
+        }
+    };
+    return Cell;
+}());
+exports.Cell = Cell;
+var Column = (function () {
+    function Column(dataKey, index) {
+        this.options = {};
+        this.contentWidth = 0;
+        this.preferredWidth = 0;
+        this.widthStyle = 'auto';
+        this.width = 0;
+        this.x = 0;
+        this.dataKey = dataKey;
+        this.index = index;
+    }
+    return Column;
+}());
+exports.Column = Column;
+
+
+/***/ },
+/* 16 */
+/***/ function(module, exports, __webpack_require__) {
+
+"use strict";
+
+var config_1 = __webpack_require__(0);
+var common_1 = __webpack_require__(1);
+/**
+ * Calculate the column widths
+ */
+function calculateWidths(doc, pageWidth) {
+    var table = config_1.Config.tableInstance();
+    // Column and table content width
+    var fixedWidth = 0;
+    var autoWidth = 0;
+    var dynamicColumns = [];
+    table.columns.forEach(function (column) {
+        column.contentWidth = 0;
+        table.rows.concat(table.headerRow).forEach(function (row) {
+            var cell = row.cells[column.dataKey];
+            cell.contentWidth = cell.padding('horizontal') + common_1.getStringWidth(cell.text, cell.styles);
+            if (cell.contentWidth > column.contentWidth) {
+                column.contentWidth = cell.contentWidth;
+            }
+        });
+        table.contentWidth += column.contentWidth;
+        if (typeof column.widthStyle === 'number') {
+            column.preferredWidth = column.widthStyle;
+            fixedWidth += column.preferredWidth;
+            column.width = column.preferredWidth;
+        }
+        else if (column.widthStyle === 'wrap') {
+            column.preferredWidth = column.contentWidth;
+            fixedWidth += column.preferredWidth;
+            column.width = column.preferredWidth;
+        }
+        else {
+            column.preferredWidth = column.contentWidth;
+            autoWidth += column.contentWidth;
+            dynamicColumns.push(column);
+        }
+        table.preferredWidth += column.preferredWidth;
+    });
+    if (typeof table.settings.tableWidth === 'number') {
+        table.width = table.settings.tableWidth;
+    }
+    else if (table.settings.tableWidth === 'wrap') {
+        table.width = table.preferredWidth;
+    }
+    else {
+        table.width = pageWidth - table.margin('left') - table.margin('right');
+    }
+    distributeWidth(dynamicColumns, fixedWidth, autoWidth, 0);
+    // Row height, table height and text overflow
+    var all = table.rows.concat(table.headerRow);
+    all.forEach(function (row) {
+        table.columns.forEach(function (col) {
+            var cell = row.cells[col.dataKey];
+            config_1.Config.applyStyles(cell.styles);
+            var textSpace = col.width - cell.padding('horizontal');
+            if (cell.styles.overflow === 'linebreak') {
+                // Add one pt to textSpace to fix rounding error
+                try {
+                    cell.text = doc.splitTextToSize(cell.text, textSpace + 1, { fontSize: cell.styles.fontSize });
+                }
+                catch (e) {
+                    if (e instanceof TypeError && Array.isArray(cell.text)) {
+                        cell.text = doc.splitTextToSize(cell.text.join(' '), textSpace + 1, { fontSize: cell.styles.fontSize });
+                    }
+                    else {
+                        throw e;
+                    }
+                }
+            }
+            else if (cell.styles.overflow === 'ellipsize') {
+                cell.text = common_1.ellipsize(cell.text, textSpace, cell.styles);
+            }
+            else if (cell.styles.overflow === 'visible') {
+            }
+            else if (cell.styles.overflow === 'hidden') {
+                cell.text = common_1.ellipsize(cell.text, textSpace, cell.styles, '');
+            }
+            else if (typeof cell.styles.overflow === 'function') {
+                cell.text = cell.styles.overflow(cell.text, textSpace);
+            }
+            else {
+                console.error("Unrecognized overflow type: " + cell.styles.overflow);
+            }
+            var k = config_1.Config.scaleFactor();
+            var lineCount = Array.isArray(cell.text) ? cell.text.length : 1;
+            var fontHeight = cell.styles.fontSize / k * config_1.FONT_ROW_RATIO;
+            cell.contentHeight = lineCount * fontHeight + cell.padding('vertical');
+            if (cell.contentHeight > row.height) {
+                row.height = cell.contentHeight;
+                row.maxLineCount = lineCount;
+            }
+        });
+        table.height += row.height;
+    });
+}
+exports.calculateWidths = calculateWidths;
+function distributeWidth(dynamicColumns, staticWidth, dynamicColumnsContentWidth, fairWidth) {
+    var table = config_1.Config.tableInstance();
+    var extraWidth = table.width - staticWidth - dynamicColumnsContentWidth;
+    for (var i = 0; i < dynamicColumns.length; i++) {
+        var col = dynamicColumns[i];
+        var ratio = col.contentWidth / dynamicColumnsContentWidth;
+        // A column turned out to be none dynamic, start over recursively
+        var isNoneDynamic = col.contentWidth + extraWidth * ratio < fairWidth;
+        if (extraWidth < 0 && isNoneDynamic) {
+            dynamicColumns.splice(i, 1);
+            dynamicColumnsContentWidth -= col.contentWidth;
+            col.width = fairWidth;
+            staticWidth += col.width;
+            distributeWidth(dynamicColumns, staticWidth, dynamicColumnsContentWidth, fairWidth);
+            break;
+        }
+        else {
+            col.width = col.contentWidth + extraWidth * ratio;
+        }
+    }
+}
+
+
+/***/ },
+/* 17 */
+/***/ function(module, exports, __webpack_require__) {
+
+"use strict";
+
+var models_1 = __webpack_require__(15);
+var config_1 = __webpack_require__(0);
+var assign = __webpack_require__(12);
+function validateInput(headers, data, allOptions) {
+    if (!headers || typeof headers !== 'object') {
+        console.error("The headers should be an object or array, is: " + typeof headers);
+    }
+    if (!data || typeof data !== 'object') {
+        console.error("The data should be an object or array, is: " + typeof data);
+    }
+    var _loop_1 = function (settings) {
+        if (settings && typeof settings !== 'object') {
+            console.error("The options parameter should be of type object, is: " + typeof settings);
+        }
+        if (typeof settings.extendWidth !== 'undefined') {
+            settings.tableWidth = settings.extendWidth ? 'auto' : 'wrap';
+            console.error("Use of deprecated option: extendWidth, use tableWidth instead.");
+        }
+        if (typeof settings.margins !== 'undefined') {
+            if (typeof settings.margin === 'undefined')
+                settings.margin = settings.margins;
+            console.error("Use of deprecated option: margins, use margin instead.");
+        }
+        if (typeof settings.afterPageContent !== 'undefined' || typeof settings.beforePageContent !== 'undefined' || typeof settings.afterPageAdd !== 'undefined') {
+            console.error("The afterPageContent, beforePageContent and afterPageAdd hooks are deprecated. Use addPageContent instead");
+            if (typeof settings.addPageContent === 'undefined') {
+                settings.addPageContent = function (data) {
+                    config_1.Config.applyUserStyles();
+                    if (settings.beforePageContent)
+                        settings.beforePageContent(data);
+                    config_1.Config.applyUserStyles();
+                    if (settings.afterPageContent)
+                        settings.afterPageContent(data);
+                    config_1.Config.applyUserStyles();
+                    if (settings.afterPageAdd && data.pageCount > 1) {
+                        data.afterPageAdd(data);
+                    }
+                    config_1.Config.applyUserStyles();
+                };
+            }
+        }
+        [['padding', 'cellPadding'], ['lineHeight', 'rowHeight'], 'fontSize', 'overflow'].forEach(function (o) {
+            var deprecatedOption = typeof o === 'string' ? o : o[0];
+            var style = typeof o === 'string' ? o : o[1];
+            if (typeof settings[deprecatedOption] !== 'undefined') {
+                if (typeof settings.styles[style] === 'undefined') {
+                    settings.styles[style] = settings[deprecatedOption];
+                }
+                console.error("Use of deprecated option: " + deprecatedOption + ", use the style " + style + " instead.");
+            }
+        });
+        for (var _i = 0, _a = ['styles', 'bodyStyles', 'headerStyles', 'columnStyles']; _i < _a.length; _i++) {
+            var styleProp = _a[_i];
+            if (settings[styleProp] && typeof settings[styleProp] !== 'object') {
+                console.error("The " + styleProp + " style should be of type object, is: " + typeof settings[styleProp]);
+            }
+            else if (settings[styleProp] && settings[styleProp].rowHeight) {
+                console.error("Use of deprecated style: rowHeight, use vertical cell padding instead");
+            }
+        }
+    };
+    for (var _i = 0, allOptions_1 = allOptions; _i < allOptions_1.length; _i++) {
+        var settings = allOptions_1[_i];
+        _loop_1(settings);
+    }
+}
+exports.validateInput = validateInput;
+/**
+ * Create models from the user input
+ *
+ * @param inputHeaders
+ * @param inputData
+ */
+function createModels(inputHeaders, inputData) {
+    var splitRegex = /\r\n|\r|\n/g;
+    var table = config_1.Config.tableInstance();
+    var settings = table.settings;
+    var theme = config_1.getTheme(settings.theme);
+    // Header row and columns
+    var headerRow = new models_1.Row(inputHeaders, -1);
+    headerRow.index = -1;
+    // Columns and header row
+    inputHeaders.forEach(function (rawColumn, index) {
+        var dataKey = index;
+        if (typeof rawColumn.dataKey !== 'undefined') {
+            dataKey = rawColumn.dataKey;
+        }
+        else if (typeof rawColumn.key !== 'undefined') {
+            console.error("Deprecation warning: Use dataKey instead of key");
+            dataKey = rawColumn.key; // deprecated since 2.x
+        }
+        var col = new models_1.Column(dataKey, index);
+        col.widthStyle = config_1.Config.styles([theme.table, theme.header, table.styles.styles, table.styles.columnStyles[col.dataKey] || {}]).columnWidth;
+        table.columns.push(col);
+        var cell = new models_1.Cell(rawColumn);
+        cell.styles = config_1.Config.styles([theme.table, theme.header, table.styles.styles, table.styles.headerStyles]);
+        if (cell.raw instanceof HTMLElement) {
+            cell.text = (cell.raw.innerText || '').trim();
+        }
+        else {
+            var text = typeof cell.raw === 'object' ? cell.raw.title : cell.raw;
+            // Stringify 0 and false, but not undefined
+            cell.text = typeof cell.raw !== 'undefined' ? '' + text : '';
+        }
+        cell.text = cell.text.split(splitRegex);
+        headerRow.cells[dataKey] = cell;
+        for (var _i = 0, _a = table.hooks.createdHeaderCell; _i < _a.length; _i++) {
+            var hook = _a[_i];
+            hook(cell, { cell: cell, column: col, row: headerRow, settings: settings });
+        }
+    });
+    table.headerRow = headerRow;
+    // Rows och cells
+    inputData.forEach(function (rawRow, i) {
+        var row = new models_1.Row(rawRow, i);
+        var rowStyles = i % 2 === 0 ? assign({}, theme.alternateRow, table.styles.alternateRowStyles) : {};
+        table.columns.forEach(function (column) {
+            var cell = new models_1.Cell(rawRow[column.dataKey]);
+            var colStyles = table.styles.columnStyles[column.dataKey] || {};
+            cell.styles = config_1.Config.styles([theme.table, theme.body, table.styles.styles, table.styles.bodyStyles, rowStyles, colStyles]);
+            if (cell.raw && cell.raw instanceof HTMLElement) {
+                cell.text = (cell.raw.innerText || '').trim();
+            }
+            else {
+                // Stringify 0 and false, but not undefined
+                cell.text = typeof cell.raw !== 'undefined' ? '' + cell.raw : '';
+            }
+            cell.text = cell.text.split(splitRegex);
+            row.cells[column.dataKey] = cell;
+            for (var _i = 0, _a = table.hooks.createdCell; _i < _a.length; _i++) {
+                var hook = _a[_i];
+                hook(cell, config_1.Config.hooksData({ cell: cell, column: column, row: row }));
+            }
+        });
+        table.rows.push(row);
+    });
+}
+exports.createModels = createModels;
+
+
+/***/ },
+/* 18 */
+/***/ function(module, exports) {
+
+module.exports = __WEBPACK_EXTERNAL_MODULE_18__;
+
+/***/ },
+/* 19 */
+/***/ function(module, exports, __webpack_require__) {
+
+"use strict";
+
+
+var $isNaN = __webpack_require__(8);
+var $isFinite = __webpack_require__(7);
+
+var sign = __webpack_require__(10);
+var mod = __webpack_require__(9);
+
+var IsCallable = __webpack_require__(3);
+var toPrimitive = __webpack_require__(23);
+
+// https://es5.github.io/#x9
+var ES5 = {
+	ToPrimitive: toPrimitive,
+
+	ToBoolean: function ToBoolean(value) {
+		return Boolean(value);
+	},
+	ToNumber: function ToNumber(value) {
+		return Number(value);
+	},
+	ToInteger: function ToInteger(value) {
+		var number = this.ToNumber(value);
+		if ($isNaN(number)) { return 0; }
+		if (number === 0 || !$isFinite(number)) { return number; }
+		return sign(number) * Math.floor(Math.abs(number));
+	},
+	ToInt32: function ToInt32(x) {
+		return this.ToNumber(x) >> 0;
+	},
+	ToUint32: function ToUint32(x) {
+		return this.ToNumber(x) >>> 0;
+	},
+	ToUint16: function ToUint16(value) {
+		var number = this.ToNumber(value);
+		if ($isNaN(number) || number === 0 || !$isFinite(number)) { return 0; }
+		var posInt = sign(number) * Math.floor(Math.abs(number));
+		return mod(posInt, 0x10000);
+	},
+	ToString: function ToString(value) {
+		return String(value);
+	},
+	ToObject: function ToObject(value) {
+		this.CheckObjectCoercible(value);
+		return Object(value);
+	},
+	CheckObjectCoercible: function CheckObjectCoercible(value, optMessage) {
+		/* jshint eqnull:true */
+		if (value == null) {
+			throw new TypeError(optMessage || 'Cannot call method on ' + value);
+		}
+		return value;
+	},
+	IsCallable: IsCallable,
+	SameValue: function SameValue(x, y) {
+		if (x === y) { // 0 === -0, but they are not identical.
+			if (x === 0) { return 1 / x === 1 / y; }
+			return true;
+		}
+		return $isNaN(x) && $isNaN(y);
+	},
+
+	// http://www.ecma-international.org/ecma-262/5.1/#sec-8
+	Type: function Type(x) {
+		if (x === null) {
+			return 'Null';
+		}
+		if (typeof x === 'undefined') {
+			return 'Undefined';
+		}
+		if (typeof x === 'function' || typeof x === 'object') {
+			return 'Object';
+		}
+		if (typeof x === 'number') {
+			return 'Number';
+		}
+		if (typeof x === 'boolean') {
+			return 'Boolean';
+		}
+		if (typeof x === 'string') {
+			return 'String';
+		}
+	}
+};
+
+module.exports = ES5;
+
+
+/***/ },
+/* 20 */
+/***/ function(module, exports, __webpack_require__) {
+
+"use strict";
+
+
+var toStr = Object.prototype.toString;
+var hasSymbols = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol';
+var symbolToStr = hasSymbols ? Symbol.prototype.toString : toStr;
+
+var $isNaN = __webpack_require__(8);
+var $isFinite = __webpack_require__(7);
+var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || Math.pow(2, 53) - 1;
+
+var assign = __webpack_require__(6);
+var sign = __webpack_require__(10);
+var mod = __webpack_require__(9);
+var isPrimitive = __webpack_require__(22);
+var toPrimitive = __webpack_require__(24);
+var parseInteger = parseInt;
+var bind = __webpack_require__(2);
+var strSlice = bind.call(Function.call, String.prototype.slice);
+var isBinary = bind.call(Function.call, RegExp.prototype.test, /^0b[01]+$/i);
+var isOctal = bind.call(Function.call, RegExp.prototype.test, /^0o[0-7]+$/i);
+var nonWS = ['\u0085', '\u200b', '\ufffe'].join('');
+var nonWSregex = new RegExp('[' + nonWS + ']', 'g');
+var hasNonWS = bind.call(Function.call, RegExp.prototype.test, nonWSregex);
+var invalidHexLiteral = /^[\-\+]0x[0-9a-f]+$/i;
+var isInvalidHexLiteral = bind.call(Function.call, RegExp.prototype.test, invalidHexLiteral);
+
+// whitespace from: http://es5.github.io/#x15.5.4.20
+// implementation from https://github.com/es-shims/es5-shim/blob/v3.4.0/es5-shim.js#L1304-L1324
+var ws = [
+	'\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003',
+	'\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028',
+	'\u2029\uFEFF'
+].join('');
+var trimRegex = new RegExp('(^[' + ws + ']+)|([' + ws + ']+$)', 'g');
+var replace = bind.call(Function.call, String.prototype.replace);
+var trim = function (value) {
+	return replace(value, trimRegex, '');
+};
+
+var ES5 = __webpack_require__(19);
+
+var hasRegExpMatcher = __webpack_require__(29);
+
+// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-abstract-operations
+var ES6 = assign(assign({}, ES5), {
+
+	// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-call-f-v-args
+	Call: function Call(F, V) {
+		var args = arguments.length > 2 ? arguments[2] : [];
+		if (!this.IsCallable(F)) {
+			throw new TypeError(F + ' is not a function');
+		}
+		return F.apply(V, args);
+	},
+
+	// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-toprimitive
+	ToPrimitive: toPrimitive,
+
+	// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-toboolean
+	// ToBoolean: ES5.ToBoolean,
+
+	// http://www.ecma-international.org/ecma-262/6.0/#sec-tonumber
+	ToNumber: function ToNumber(argument) {
+		var value = isPrimitive(argument) ? argument : toPrimitive(argument, 'number');
+		if (typeof value === 'symbol') {
+			throw new TypeError('Cannot convert a Symbol value to a number');
+		}
+		if (typeof value === 'string') {
+			if (isBinary(value)) {
+				return this.ToNumber(parseInteger(strSlice(value, 2), 2));
+			} else if (isOctal(value)) {
+				return this.ToNumber(parseInteger(strSlice(value, 2), 8));
+			} else if (hasNonWS(value) || isInvalidHexLiteral(value)) {
+				return NaN;
+			} else {
+				var trimmed = trim(value);
+				if (trimmed !== value) {
+					return this.ToNumber(trimmed);
+				}
+			}
+		}
+		return Number(value);
+	},
+
+	// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tointeger
+	// ToInteger: ES5.ToNumber,
+
+	// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-toint32
+	// ToInt32: ES5.ToInt32,
+
+	// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-touint32
+	// ToUint32: ES5.ToUint32,
+
+	// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-toint16
+	ToInt16: function ToInt16(argument) {
+		var int16bit = this.ToUint16(argument);
+		return int16bit >= 0x8000 ? int16bit - 0x10000 : int16bit;
+	},
+
+	// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-touint16
+	// ToUint16: ES5.ToUint16,
+
+	// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-toint8
+	ToInt8: function ToInt8(argument) {
+		var int8bit = this.ToUint8(argument);
+		return int8bit >= 0x80 ? int8bit - 0x100 : int8bit;
+	},
+
+	// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-touint8
+	ToUint8: function ToUint8(argument) {
+		var number = this.ToNumber(argument);
+		if ($isNaN(number) || number === 0 || !$isFinite(number)) { return 0; }
+		var posInt = sign(number) * Math.floor(Math.abs(number));
+		return mod(posInt, 0x100);
+	},
+
+	// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-touint8clamp
+	ToUint8Clamp: function ToUint8Clamp(argument) {
+		var number = this.ToNumber(argument);
+		if ($isNaN(number) || number <= 0) { return 0; }
+		if (number >= 0xFF) { return 0xFF; }
+		var f = Math.floor(argument);
+		if (f + 0.5 < number) { return f + 1; }
+		if (number < f + 0.5) { return f; }
+		if (f % 2 !== 0) { return f + 1; }
+		return f;
+	},
+
+	// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tostring
+	ToString: function ToString(argument) {
+		if (typeof argument === 'symbol') {
+			throw new TypeError('Cannot convert a Symbol value to a string');
+		}
+		return String(argument);
+	},
+
+	// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-toobject
+	ToObject: function ToObject(value) {
+		this.RequireObjectCoercible(value);
+		return Object(value);
+	},
+
+	// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-topropertykey
+	ToPropertyKey: function ToPropertyKey(argument) {
+		var key = this.ToPrimitive(argument, String);
+		return typeof key === 'symbol' ? symbolToStr.call(key) : this.ToString(key);
+	},
+
+	// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength
+	ToLength: function ToLength(argument) {
+		var len = this.ToInteger(argument);
+		if (len <= 0) { return 0; } // includes converting -0 to +0
+		if (len > MAX_SAFE_INTEGER) { return MAX_SAFE_INTEGER; }
+		return len;
+	},
+
+	// http://www.ecma-international.org/ecma-262/6.0/#sec-canonicalnumericindexstring
+	CanonicalNumericIndexString: function CanonicalNumericIndexString(argument) {
+		if (toStr.call(argument) !== '[object String]') {
+			throw new TypeError('must be a string');
+		}
+		if (argument === '-0') { return -0; }
+		var n = this.ToNumber(argument);
+		if (this.SameValue(this.ToString(n), argument)) { return n; }
+		return void 0;
+	},
+
+	// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-requireobjectcoercible
+	RequireObjectCoercible: ES5.CheckObjectCoercible,
+
+	// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-isarray
+	IsArray: Array.isArray || function IsArray(argument) {
+		return toStr.call(argument) === '[object Array]';
+	},
+
+	// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-iscallable
+	// IsCallable: ES5.IsCallable,
+
+	// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-isconstructor
+	IsConstructor: function IsConstructor(argument) {
+		return typeof argument === 'function' && !!argument.prototype; // unfortunately there's no way to truly check this without try/catch `new argument`
+	},
+
+	// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-isextensible-o
+	IsExtensible: function IsExtensible(obj) {
+		if (!Object.preventExtensions) { return true; }
+		if (isPrimitive(obj)) {
+			return false;
+		}
+		return Object.isExtensible(obj);
+	},
+
+	// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-isinteger
+	IsInteger: function IsInteger(argument) {
+		if (typeof argument !== 'number' || $isNaN(argument) || !$isFinite(argument)) {
+			return false;
+		}
+		var abs = Math.abs(argument);
+		return Math.floor(abs) === abs;
+	},
+
+	// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-ispropertykey
+	IsPropertyKey: function IsPropertyKey(argument) {
+		return typeof argument === 'string' || typeof argument === 'symbol';
+	},
+
+	// http://www.ecma-international.org/ecma-262/6.0/#sec-isregexp
+	IsRegExp: function IsRegExp(argument) {
+		if (!argument || typeof argument !== 'object') {
+			return false;
+		}
+		if (hasSymbols) {
+			var isRegExp = argument[Symbol.match];
+			if (typeof isRegExp !== 'undefined') {
+				return ES5.ToBoolean(isRegExp);
+			}
+		}
+		return hasRegExpMatcher(argument);
+	},
+
+	// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevalue
+	// SameValue: ES5.SameValue,
+
+	// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero
+	SameValueZero: function SameValueZero(x, y) {
+		return (x === y) || ($isNaN(x) && $isNaN(y));
+	},
+
+	Type: function Type(x) {
+		if (typeof x === 'symbol') {
+			return 'Symbol';
+		}
+		return ES5.Type(x);
+	},
+
+	// http://www.ecma-international.org/ecma-262/6.0/#sec-speciesconstructor
+	SpeciesConstructor: function SpeciesConstructor(O, defaultConstructor) {
+		if (this.Type(O) !== 'Object') {
+			throw new TypeError('Assertion failed: Type(O) is not Object');
+		}
+		var C = O.constructor;
+		if (typeof C === 'undefined') {
+			return defaultConstructor;
+		}
+		if (this.Type(C) !== 'Object') {
+			throw new TypeError('O.constructor is not an Object');
+		}
+		var S = hasSymbols && Symbol.species ? C[Symbol.species] : undefined;
+		if (S == null) {
+			return defaultConstructor;
+		}
+		if (this.IsConstructor(S)) {
+			return S;
+		}
+		throw new TypeError('no constructor found');
+	}
+});
+
+delete ES6.CheckObjectCoercible; // renamed in ES6 to RequireObjectCoercible
+
+module.exports = ES6;
+
+
+/***/ },
+/* 21 */
+/***/ function(module, exports, __webpack_require__) {
+
+"use strict";
+
+
+var ES6 = __webpack_require__(20);
+var assign = __webpack_require__(6);
+
+var ES7 = assign(ES6, {
+	// https://github.com/tc39/ecma262/pull/60
+	SameValueNonNumber: function SameValueNonNumber(x, y) {
+		if (typeof x === 'number' || typeof x !== typeof y) {
+			throw new TypeError('SameValueNonNumber requires two non-number values of the same type.');
+		}
+		return this.SameValue(x, y);
+	}
+});
+
+module.exports = ES7;
+
+
+/***/ },
+/* 22 */
+/***/ function(module, exports) {
+
+module.exports = function isPrimitive(value) {
+	return value === null || (typeof value !== 'function' && typeof value !== 'object');
+};
+
+
+/***/ },
+/* 23 */
+/***/ function(module, exports, __webpack_require__) {
+
+"use strict";
+
+
+var toStr = Object.prototype.toString;
+
+var isPrimitive = __webpack_require__(11);
+
+var isCallable = __webpack_require__(3);
+
+// https://es5.github.io/#x8.12
+var ES5internalSlots = {
+	'[[DefaultValue]]': function (O, hint) {
+		var actualHint = hint || (toStr.call(O) === '[object Date]' ? String : Number);
+
+		if (actualHint === String || actualHint === Number) {
+			var methods = actualHint === String ? ['toString', 'valueOf'] : ['valueOf', 'toString'];
+			var value, i;
+			for (i = 0; i < methods.length; ++i) {
+				if (isCallable(O[methods[i]])) {
+					value = O[methods[i]]();
+					if (isPrimitive(value)) {
+						return value;
+					}
+				}
+			}
+			throw new TypeError('No default value');
+		}
+		throw new TypeError('invalid [[DefaultValue]] hint supplied');
+	}
+};
+
+// https://es5.github.io/#x9
+module.exports = function ToPrimitive(input, PreferredType) {
+	if (isPrimitive(input)) {
+		return input;
+	}
+	return ES5internalSlots['[[DefaultValue]]'](input, PreferredType);
+};
+
+
+/***/ },
+/* 24 */
+/***/ function(module, exports, __webpack_require__) {
+
+"use strict";
+
+
+var hasSymbols = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol';
+
+var isPrimitive = __webpack_require__(11);
+var isCallable = __webpack_require__(3);
+var isDate = __webpack_require__(28);
+var isSymbol = __webpack_require__(30);
+
+var ordinaryToPrimitive = function OrdinaryToPrimitive(O, hint) {
+	if (typeof O === 'undefined' || O === null) {
+		throw new TypeError('Cannot call method on ' + O);
+	}
+	if (typeof hint !== 'string' || (hint !== 'number' && hint !== 'string')) {
+		throw new TypeError('hint must be "string" or "number"');
+	}
+	var methodNames = hint === 'string' ? ['toString', 'valueOf'] : ['valueOf', 'toString'];
+	var method, result, i;
+	for (i = 0; i < methodNames.length; ++i) {
+		method = O[methodNames[i]];
+		if (isCallable(method)) {
+			result = method.call(O);
+			if (isPrimitive(result)) {
+				return result;
+			}
+		}
+	}
+	throw new TypeError('No default value');
+};
+
+var GetMethod = function GetMethod(O, P) {
+	var func = O[P];
+	if (func !== null && typeof func !== 'undefined') {
+		if (!isCallable(func)) {
+			throw new TypeError(func + ' returned for property ' + P + ' of object ' + O + ' is not a function');
+		}
+		return func;
+	}
+};
+
+// http://www.ecma-international.org/ecma-262/6.0/#sec-toprimitive
+module.exports = function ToPrimitive(input, PreferredType) {
+	if (isPrimitive(input)) {
+		return input;
+	}
+	var hint = 'default';
+	if (arguments.length > 1) {
+		if (PreferredType === String) {
+			hint = 'string';
+		} else if (PreferredType === Number) {
+			hint = 'number';
+		}
+	}
+
+	var exoticToPrim;
+	if (hasSymbols) {
+		if (Symbol.toPrimitive) {
+			exoticToPrim = GetMethod(input, Symbol.toPrimitive);
+		} else if (isSymbol(input)) {
+			exoticToPrim = Symbol.prototype.valueOf;
+		}
+	}
+	if (typeof exoticToPrim !== 'undefined') {
+		var result = exoticToPrim.call(input, hint);
+		if (isPrimitive(result)) {
+			return result;
+		}
+		throw new TypeError('unable to convert exotic object to primitive');
+	}
+	if (hint === 'default' && (isDate(input) || isSymbol(input))) {
+		hint = 'string';
+	}
+	return ordinaryToPrimitive(input, hint === 'default' ? 'number' : hint);
+};
+
+
+/***/ },
+/* 25 */
+/***/ function(module, exports) {
+
+
+var hasOwn = Object.prototype.hasOwnProperty;
+var toString = Object.prototype.toString;
+
+module.exports = function forEach (obj, fn, ctx) {
+    if (toString.call(fn) !== '[object Function]') {
+        throw new TypeError('iterator must be a function');
+    }
+    var l = obj.length;
+    if (l === +l) {
+        for (var i = 0; i < l; i++) {
+            fn.call(ctx, obj[i], i, obj);
+        }
+    } else {
+        for (var k in obj) {
+            if (hasOwn.call(obj, k)) {
+                fn.call(ctx, obj[k], k, obj);
+            }
+        }
+    }
+};
+
+
+
+/***/ },
+/* 26 */
+/***/ function(module, exports) {
+
+var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible ';
+var slice = Array.prototype.slice;
+var toStr = Object.prototype.toString;
+var funcType = '[object Function]';
+
+module.exports = function bind(that) {
+    var target = this;
+    if (typeof target !== 'function' || toStr.call(target) !== funcType) {
+        throw new TypeError(ERROR_MESSAGE + target);
+    }
+    var args = slice.call(arguments, 1);
+
+    var bound;
+    var binder = function () {
+        if (this instanceof bound) {
+            var result = target.apply(
+                this,
+                args.concat(slice.call(arguments))
+            );
+            if (Object(result) === result) {
+                return result;
+            }
+            return this;
+        } else {
+            return target.apply(
+                that,
+                args.concat(slice.call(arguments))
+            );
+        }
+    };
+
+    var boundLength = Math.max(0, target.length - args.length);
+    var boundArgs = [];
+    for (var i = 0; i < boundLength; i++) {
+        boundArgs.push('$' + i);
+    }
+
+    bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder);
+
+    if (target.prototype) {
+        var Empty = function Empty() {};
+        Empty.prototype = target.prototype;
+        bound.prototype = new Empty();
+        Empty.prototype = null;
+    }
+
+    return bound;
+};
+
+
+/***/ },
+/* 27 */
+/***/ function(module, exports, __webpack_require__) {
+
+var bind = __webpack_require__(2);
+
+module.exports = bind.call(Function.call, Object.prototype.hasOwnProperty);
+
+
+/***/ },
+/* 28 */
+/***/ function(module, exports, __webpack_require__) {
+
+"use strict";
+
+
+var getDay = Date.prototype.getDay;
+var tryDateObject = function tryDateObject(value) {
+	try {
+		getDay.call(value);
+		return true;
+	} catch (e) {
+		return false;
+	}
+};
+
+var toStr = Object.prototype.toString;
+var dateClass = '[object Date]';
+var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol';
+
+module.exports = function isDateObject(value) {
+	if (typeof value !== 'object' || value === null) { return false; }
+	return hasToStringTag ? tryDateObject(value) : toStr.call(value) === dateClass;
+};
+
+
+/***/ },
+/* 29 */
+/***/ function(module, exports, __webpack_require__) {
+
+"use strict";
+
+
+var regexExec = RegExp.prototype.exec;
+var tryRegexExec = function tryRegexExec(value) {
+	try {
+		regexExec.call(value);
+		return true;
+	} catch (e) {
+		return false;
+	}
+};
+var toStr = Object.prototype.toString;
+var regexClass = '[object RegExp]';
+var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol';
+
+module.exports = function isRegex(value) {
+	if (typeof value !== 'object') { return false; }
+	return hasToStringTag ? tryRegexExec(value) : toStr.call(value) === regexClass;
+};
+
+
+/***/ },
+/* 30 */
+/***/ function(module, exports, __webpack_require__) {
+
+"use strict";
+
+
+var toStr = Object.prototype.toString;
+var hasSymbols = typeof Symbol === 'function' && typeof Symbol() === 'symbol';
+
+if (hasSymbols) {
+	var symToStr = Symbol.prototype.toString;
+	var symStringRegex = /^Symbol\(.*\)$/;
+	var isSymbolObject = function isSymbolObject(value) {
+		if (typeof value.valueOf() !== 'symbol') { return false; }
+		return symStringRegex.test(symToStr.call(value));
+	};
+	module.exports = function isSymbol(value) {
+		if (typeof value === 'symbol') { return true; }
+		if (toStr.call(value) !== '[object Symbol]') { return false; }
+		try {
+			return isSymbolObject(value);
+		} catch (e) {
+			return false;
+		}
+	};
+} else {
+	module.exports = function isSymbol(value) {
+		// this environment does not support Symbols.
+		return false;
+	};
+}
+
+
+/***/ },
+/* 31 */
+/***/ function(module, exports, __webpack_require__) {
+
+"use strict";
+
+
+// modified from https://github.com/es-shims/es5-shim
+var has = Object.prototype.hasOwnProperty;
+var toStr = Object.prototype.toString;
+var slice = Array.prototype.slice;
+var isArgs = __webpack_require__(32);
+var isEnumerable = Object.prototype.propertyIsEnumerable;
+var hasDontEnumBug = !isEnumerable.call({ toString: null }, 'toString');
+var hasProtoEnumBug = isEnumerable.call(function () {}, 'prototype');
+var dontEnums = [
+	'toString',
+	'toLocaleString',
+	'valueOf',
+	'hasOwnProperty',
+	'isPrototypeOf',
+	'propertyIsEnumerable',
+	'constructor'
+];
+var equalsConstructorPrototype = function (o) {
+	var ctor = o.constructor;
+	return ctor && ctor.prototype === o;
+};
+var excludedKeys = {
+	$console: true,
+	$external: true,
+	$frame: true,
+	$frameElement: true,
+	$frames: true,
+	$innerHeight: true,
+	$innerWidth: true,
+	$outerHeight: true,
+	$outerWidth: true,
+	$pageXOffset: true,
+	$pageYOffset: true,
+	$parent: true,
+	$scrollLeft: true,
+	$scrollTop: true,
+	$scrollX: true,
+	$scrollY: true,
+	$self: true,
+	$webkitIndexedDB: true,
+	$webkitStorageInfo: true,
+	$window: true
+};
+var hasAutomationEqualityBug = (function () {
+	/* global window */
+	if (typeof window === 'undefined') { return false; }
+	for (var k in window) {
+		try {
+			if (!excludedKeys['$' + k] && has.call(window, k) && window[k] !== null && typeof window[k] === 'object') {
+				try {
+					equalsConstructorPrototype(window[k]);
+				} catch (e) {
+					return true;
+				}
+			}
+		} catch (e) {
+			return true;
+		}
+	}
+	return false;
+}());
+var equalsConstructorPrototypeIfNotBuggy = function (o) {
+	/* global window */
+	if (typeof window === 'undefined' || !hasAutomationEqualityBug) {
+		return equalsConstructorPrototype(o);
+	}
+	try {
+		return equalsConstructorPrototype(o);
+	} catch (e) {
+		return false;
+	}
+};
+
+var keysShim = function keys(object) {
+	var isObject = object !== null && typeof object === 'object';
+	var isFunction = toStr.call(object) === '[object Function]';
+	var isArguments = isArgs(object);
+	var isString = isObject && toStr.call(object) === '[object String]';
+	var theKeys = [];
+
+	if (!isObject && !isFunction && !isArguments) {
+		throw new TypeError('Object.keys called on a non-object');
+	}
+
+	var skipProto = hasProtoEnumBug && isFunction;
+	if (isString && object.length > 0 && !has.call(object, 0)) {
+		for (var i = 0; i < object.length; ++i) {
+			theKeys.push(String(i));
+		}
+	}
+
+	if (isArguments && object.length > 0) {
+		for (var j = 0; j < object.length; ++j) {
+			theKeys.push(String(j));
+		}
+	} else {
+		for (var name in object) {
+			if (!(skipProto && name === 'prototype') && has.call(object, name)) {
+				theKeys.push(String(name));
+			}
+		}
+	}
+
+	if (hasDontEnumBug) {
+		var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object);
+
+		for (var k = 0; k < dontEnums.length; ++k) {
+			if (!(skipConstructor && dontEnums[k] === 'constructor') && has.call(object, dontEnums[k])) {
+				theKeys.push(dontEnums[k]);
+			}
+		}
+	}
+	return theKeys;
+};
+
+keysShim.shim = function shimObjectKeys() {
+	if (Object.keys) {
+		var keysWorksWithArguments = (function () {
+			// Safari 5.0 bug
+			return (Object.keys(arguments) || '').length === 2;
+		}(1, 2));
+		if (!keysWorksWithArguments) {
+			var originalKeys = Object.keys;
+			Object.keys = function keys(object) {
+				if (isArgs(object)) {
+					return originalKeys(slice.call(object));
+				} else {
+					return originalKeys(object);
+				}
+			};
+		}
+	} else {
+		Object.keys = keysShim;
+	}
+	return Object.keys || keysShim;
+};
+
+module.exports = keysShim;
+
+
+/***/ },
+/* 32 */
+/***/ function(module, exports, __webpack_require__) {
+
+"use strict";
+
+
+var toStr = Object.prototype.toString;
+
+module.exports = function isArguments(value) {
+	var str = toStr.call(value);
+	var isArgs = str === '[object Arguments]';
+	if (!isArgs) {
+		isArgs = str !== '[object Array]' &&
+			value !== null &&
+			typeof value === 'object' &&
+			typeof value.length === 'number' &&
+			value.length >= 0 &&
+			toStr.call(value.callee) === '[object Function]';
+	}
+	return isArgs;
+};
+
+
+/***/ },
+/* 33 */
+/***/ function(module, exports, __webpack_require__) {
+
+"use strict";
+
+
+var define = __webpack_require__(5);
+
+var implementation = __webpack_require__(13);
+var getPolyfill = __webpack_require__(14);
+var shim = __webpack_require__(34);
+
+var polyfill = getPolyfill();
+
+define(polyfill, {
+	getPolyfill: getPolyfill,
+	implementation: implementation,
+	shim: shim
+});
+
+module.exports = polyfill;
+
+
+/***/ },
+/* 34 */
+/***/ function(module, exports, __webpack_require__) {
+
+"use strict";
+
+
+var getPolyfill = __webpack_require__(14);
+var define = __webpack_require__(5);
+
+module.exports = function shimEntries() {
+	var polyfill = getPolyfill();
+	define(Object, { entries: polyfill }, {
+		entries: function testEntries() {
+			return Object.entries !== polyfill;
+		}
+	});
+	return polyfill;
+};
+
+
+/***/ },
+/* 35 */
+/***/ function(module, exports, __webpack_require__) {
+
+"use strict";
+
+var jsPDF = __webpack_require__(18);
+var config_1 = __webpack_require__(0);
+var common_1 = __webpack_require__(1);
+var painter_1 = __webpack_require__(4);
+var calculator_1 = __webpack_require__(16);
+var creator_1 = __webpack_require__(17);
+/**
+ * Create a table from a set of rows and columns.
+ *
+ * @param {Object[]|String[]} headers Either as an array of objects or array of strings
+ * @param {Object[][]|String[][]} data Either as an array of objects or array of strings
+ * @param {Object} [userOptions={}] Options that will override the default ones
+ */
+jsPDF.API.autoTable = function (headers, data, tableOptions) {
+    if (tableOptions === void 0) { tableOptions = {}; }
+    this.autoTableState = this.autoTableState || {};
+    jsPDF.autoTableState = jsPDF.autoTableState || {};
+    var allOptions = [jsPDF.autoTableState.defaults || {}, this.autoTableState.defaults || {}, tableOptions || {}];
+    creator_1.validateInput(headers, data, allOptions);
+    var table = config_1.Config.createTable(this);
+    config_1.Config.initSettings(table, allOptions);
+    var settings = table.settings;
+    // Create the table model with its columns, rows and cells
+    creator_1.createModels(headers, data);
+    settings.margin = config_1.Config.marginOrPadding(settings.margin, config_1.getDefaults().margin);
+    calculator_1.calculateWidths(this, config_1.Config.pageSize().width);
+    table.cursor = {
+        x: table.margin('left'),
+        y: settings.startY === false ? table.margin('top') : settings.startY
+    };
+    var minTableBottomPos = settings.startY + table.margin('bottom') + table.headerRow.height;
+    if (settings.pageBreak === 'avoid') {
+        minTableBottomPos += table.height;
+    }
+    var pageHeight = config_1.Config.pageSize().height;
+    if ((settings.pageBreak === 'always' && settings.startY !== false) ||
+        (settings.startY !== false && minTableBottomPos > pageHeight)) {
+        table.doc.addPage();
+        table.cursor.y = table.margin('top');
+    }
+    table.pageStartX = table.cursor.x;
+    table.pageStartY = table.cursor.y;
+    config_1.Config.applyUserStyles();
+    if (settings.showHeader === true || settings.showHeader === 'firstPage' || settings.showHeader === 'everyPage') {
+        painter_1.printRow(table.headerRow, table.hooks.drawHeaderRow, table.hooks.drawHeaderCell);
+    }
+    config_1.Config.applyUserStyles();
+    table.rows.forEach(function (row) {
+        painter_1.printFullRow(row, table.hooks.drawRow, table.hooks.drawCell);
+    });
+    common_1.addTableBorder();
+    // Don't call global and document addPageContent more than once for each page
+    var pageNumber = this.internal.getCurrentPageInfo().pageNumber;
+    if (this.autoTableState.addPageHookPages && this.autoTableState.addPageHookPages[pageNumber]) {
+        if (typeof tableOptions['addPageContent'] === 'function') {
+            tableOptions['addPageContent'](config_1.Config.hooksData());
+        }
+    }
+    else {
+        if (!this.autoTableState.addPageHookPages)
+            this.autoTableState.addPageHookPages = {};
+        this.autoTableState.addPageHookPages[pageNumber] = true;
+        common_1.addContentHooks();
+    }
+    table.finalY = table.cursor.y;
+    this.autoTable.previous = table;
+    config_1.Config.applyUserStyles();
+    return this;
+};
+// Enables doc.autoTable.previous.finalY || 40;
+jsPDF.API.autoTable.previous = false;
+jsPDF.API.autoTableSetDefaults = function (defaults) {
+    if (!this.autoTableState)
+        this.autoTableState = {};
+    if (defaults && typeof defaults === 'object') {
+        this.autoTableState.defaults = defaults;
+    }
+    else {
+        delete this.autoTableState.defaults;
+    }
+    return this;
+};
+jsPDF.autoTableSetDefaults = function (defaults) {
+    if (!jsPDF.autoTableState)
+        jsPDF.autoTableState = {};
+    if (defaults && typeof defaults === 'object') {
+        this.autoTableState.defaults = defaults;
+    }
+    else {
+        delete this.autoTableState.defaults;
+    }
+    jsPDF.autoTableState.defaults = defaults;
+};
+/**
+ * Parses an html table
+ *
+ * @param tableElem Html table element
+ * @param includeHiddenElements If to include hidden rows and columns (defaults to false)
+ * @returns Object Object with two properties, columns and rows
+ */
+jsPDF.API.autoTableHtmlToJson = function (tableElem, includeHiddenElements) {
+    includeHiddenElements = includeHiddenElements || false;
+    if (!tableElem || !(tableElem instanceof HTMLTableElement)) {
+        console.error("A HTMLTableElement has to be sent to autoTableHtmlToJson");
+        return null;
+    }
+    var columns = {}, rows = [];
+    var header = tableElem.rows[0];
+    for (var i = 0; i < header.cells.length; i++) {
+        var cell = header.cells[i];
+        var style = window.getComputedStyle(cell);
+        if (includeHiddenElements || style.display !== 'none') {
+            columns[i] = cell;
+        }
+    }
+    var _loop_1 = function (i) {
+        var tableRow = tableElem.rows[i];
+        var style = window.getComputedStyle(tableRow);
+        if (includeHiddenElements || style.display !== 'none') {
+            var rowData_1 = [];
+            Object.keys(columns).forEach(function (key) {
+                var cell = tableRow.cells[key];
+                rowData_1.push(cell);
+            });
+            rows.push(rowData_1);
+        }
+    };
+    for (var i = 1; i < tableElem.rows.length; i++) {
+        _loop_1(i);
+    }
+    var values = Object.keys(columns).map(function (key) { return columns[key]; });
+    return { columns: values, rows: rows, data: rows };
+};
+/**
+ * Improved text function with halign and valign support
+ * Inspiration from: http://stackoverflow.com/questions/28327510/align-text-right-using-jspdf/28433113#28433113
+ */
+jsPDF.API.autoTableText = function (text, x, y, styles) {
+    if (typeof x !== 'number' || typeof y !== 'number') {
+        console.error('The x and y parameters are required. Missing for the text: ', text);
+    }
+    var k = this.internal.scaleFactor;
+    var fontSize = this.internal.getFontSize() / k;
+    var splitRegex = /\r\n|\r|\n/g;
+    var splitText = null;
+    var lineCount = 1;
+    if (styles.valign === 'middle' || styles.valign === 'bottom' || styles.halign === 'center' || styles.halign === 'right') {
+        splitText = typeof text === 'string' ? text.split(splitRegex) : text;
+        lineCount = splitText.length || 1;
+    }
+    // Align the top
+    y += fontSize * (2 - config_1.FONT_ROW_RATIO);
+    if (styles.valign === 'middle')
+        y -= (lineCount / 2) * fontSize * config_1.FONT_ROW_RATIO;
+    else if (styles.valign === 'bottom')
+        y -= lineCount * fontSize * config_1.FONT_ROW_RATIO;
+    if (styles.halign === 'center' || styles.halign === 'right') {
+        var alignSize = fontSize;
+        if (styles.halign === 'center')
+            alignSize *= 0.5;
+        if (lineCount >= 1) {
+            for (var iLine = 0; iLine < splitText.length; iLine++) {
+                this.text(splitText[iLine], x - this.getStringUnitWidth(splitText[iLine]) * alignSize, y);
+                y += fontSize;
+            }
+            return this;
+        }
+        x -= this.getStringUnitWidth(text) * alignSize;
+    }
+    this.text(text, x, y);
+    return this;
+};
+/**
+ * @deprecated Use doc.autoTable.previous.finalY instead
+ */
+jsPDF.API.autoTableEndPosY = function () {
+    var prev = this.autoTable.previous;
+    if (prev.cursor && typeof prev.cursor.y === 'number') {
+        return prev.cursor.y;
+    }
+    else {
+        return 0;
+    }
+};
+/**
+ * @deprecated Use jsPDF.autoTableSetDefaults({addPageContent: function() {}}) instead
+ */
+jsPDF.API.autoTableAddPageContent = function (hook) {
+    if (!jsPDF.API.autoTable.globalDefaults) {
+        jsPDF.API.autoTable.globalDefaults = {};
+    }
+    jsPDF.API.autoTable.globalDefaults.addPageContent = hook;
+    return this;
+};
+/**
+ * @deprecated Use data.addPage in hooks instead
+ */
+jsPDF.API.autoTableAddPage = function () {
+    common_1.addPage();
+    return this;
+};
+
+
+/***/ }
+/******/ ]);
+});

+ 17368 - 0
static/lib/jspdf/jspdf.js

@@ -0,0 +1,17368 @@
+(function (global, factory) {
+    typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
+    typeof define === 'function' && define.amd ? define(factory) :
+    (global.jspdf = factory());
+}(this, (function () { 'use strict';
+
+var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
+  return typeof obj;
+} : function (obj) {
+  return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
+};
+
+
+
+
+
+var asyncGenerator = function () {
+  function AwaitValue(value) {
+    this.value = value;
+  }
+
+  function AsyncGenerator(gen) {
+    var front, back;
+
+    function send(key, arg) {
+      return new Promise(function (resolve, reject) {
+        var request = {
+          key: key,
+          arg: arg,
+          resolve: resolve,
+          reject: reject,
+          next: null
+        };
+
+        if (back) {
+          back = back.next = request;
+        } else {
+          front = back = request;
+          resume(key, arg);
+        }
+      });
+    }
+
+    function resume(key, arg) {
+      try {
+        var result = gen[key](arg);
+        var value = result.value;
+
+        if (value instanceof AwaitValue) {
+          Promise.resolve(value.value).then(function (arg) {
+            resume("next", arg);
+          }, function (arg) {
+            resume("throw", arg);
+          });
+        } else {
+          settle(result.done ? "return" : "normal", result.value);
+        }
+      } catch (err) {
+        settle("throw", err);
+      }
+    }
+
+    function settle(type, value) {
+      switch (type) {
+        case "return":
+          front.resolve({
+            value: value,
+            done: true
+          });
+          break;
+
+        case "throw":
+          front.reject(value);
+          break;
+
+        default:
+          front.resolve({
+            value: value,
+            done: false
+          });
+          break;
+      }
+
+      front = front.next;
+
+      if (front) {
+        resume(front.key, front.arg);
+      } else {
+        back = null;
+      }
+    }
+
+    this._invoke = send;
+
+    if (typeof gen.return !== "function") {
+      this.return = undefined;
+    }
+  }
+
+  if (typeof Symbol === "function" && Symbol.asyncIterator) {
+    AsyncGenerator.prototype[Symbol.asyncIterator] = function () {
+      return this;
+    };
+  }
+
+  AsyncGenerator.prototype.next = function (arg) {
+    return this._invoke("next", arg);
+  };
+
+  AsyncGenerator.prototype.throw = function (arg) {
+    return this._invoke("throw", arg);
+  };
+
+  AsyncGenerator.prototype.return = function (arg) {
+    return this._invoke("return", arg);
+  };
+
+  return {
+    wrap: function (fn) {
+      return function () {
+        return new AsyncGenerator(fn.apply(this, arguments));
+      };
+    },
+    await: function (value) {
+      return new AwaitValue(value);
+    }
+  };
+}();
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+var get$1 = function get$1(object, property, receiver) {
+  if (object === null) object = Function.prototype;
+  var desc = Object.getOwnPropertyDescriptor(object, property);
+
+  if (desc === undefined) {
+    var parent = Object.getPrototypeOf(object);
+
+    if (parent === null) {
+      return undefined;
+    } else {
+      return get$1(parent, property, receiver);
+    }
+  } else if ("value" in desc) {
+    return desc.value;
+  } else {
+    var getter = desc.get;
+
+    if (getter === undefined) {
+      return undefined;
+    }
+
+    return getter.call(receiver);
+  }
+};
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+var set$1 = function set$1(object, property, value, receiver) {
+  var desc = Object.getOwnPropertyDescriptor(object, property);
+
+  if (desc === undefined) {
+    var parent = Object.getPrototypeOf(object);
+
+    if (parent !== null) {
+      set$1(parent, property, value, receiver);
+    }
+  } else if ("value" in desc && desc.writable) {
+    desc.value = value;
+  } else {
+    var setter = desc.set;
+
+    if (setter !== undefined) {
+      setter.call(receiver, value);
+    }
+  }
+
+  return value;
+};
+
+/** @preserve
+ * jsPDF - PDF Document creation from JavaScript
+ * Version 1.3.4 Built on 2017-04-10T14:14:44.483Z
+ *                           CommitID cf4827d221
+ *
+ * Copyright (c) 2010-2016 James Hall <james@parall.ax>, https://github.com/MrRio/jsPDF
+ *               2010 Aaron Spike, https://github.com/acspike
+ *               2012 Willow Systems Corporation, willow-systems.com
+ *               2012 Pablo Hess, https://github.com/pablohess
+ *               2012 Florian Jenett, https://github.com/fjenett
+ *               2013 Warren Weckesser, https://github.com/warrenweckesser
+ *               2013 Youssef Beddad, https://github.com/lifof
+ *               2013 Lee Driscoll, https://github.com/lsdriscoll
+ *               2013 Stefan Slonevskiy, https://github.com/stefslon
+ *               2013 Jeremy Morel, https://github.com/jmorel
+ *               2013 Christoph Hartmann, https://github.com/chris-rock
+ *               2014 Juan Pablo Gaviria, https://github.com/juanpgaviria
+ *               2014 James Makes, https://github.com/dollaruw
+ *               2014 Diego Casorran, https://github.com/diegocr
+ *               2014 Steven Spungin, https://github.com/Flamenco
+ *               2014 Kenneth Glassey, https://github.com/Gavvers
+ *
+ * Licensed under the MIT License
+ *
+ * Contributor(s):
+ *    siefkenj, ahwolf, rickygu, Midnith, saintclair, eaparango,
+ *    kim3er, mfo, alnorth, Flamenco
+ */
+
+/**
+ * Creates new jsPDF document object instance.
+ *
+ * @class
+ * @param orientation One of "portrait" or "landscape" (or shortcuts "p" (Default), "l")
+ * @param unit        Measurement unit to be used when coordinates are specified.
+ *                    One of "pt" (points), "mm" (Default), "cm", "in"
+ * @param format      One of 'pageFormats' as shown below, default: a4
+ * @returns {jsPDF}
+ * @name jsPDF
+ */
+var jsPDF = function (global) {
+  'use strict';
+
+  var pdfVersion = '1.3',
+      pageFormats = { // Size in pt of various paper formats
+    '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.40, 209.76],
+    'a9': [104.88, 147.40],
+    'a10': [73.70, 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.90, 708.66],
+    'b6': [354.33, 498.90],
+    '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]
+  };
+
+  /**
+   * jsPDF's Internal PubSub Implementation.
+   * See mrrio.github.io/jsPDF/doc/symbols/PubSub.html
+   * Backward compatible rewritten on 2014 by
+   * Diego Casorran, https://github.com/diegocr
+   *
+   * @class
+   * @name PubSub
+   * @ignore This should not be in the public docs.
+   */
+  function PubSub(context) {
+    var topics = {};
+
+    this.subscribe = function (topic, callback, once) {
+      if (typeof callback !== 'function') {
+        return false;
+      }
+
+      if (!topics.hasOwnProperty(topic)) {
+        topics[topic] = {};
+      }
+
+      var id = Math.random().toString(35);
+      topics[topic][id] = [callback, !!once];
+
+      return id;
+    };
+
+    this.unsubscribe = function (token) {
+      for (var topic in topics) {
+        if (topics[topic][token]) {
+          delete topics[topic][token];
+          return true;
+        }
+      }
+      return false;
+    };
+
+    this.publish = function (topic) {
+      if (topics.hasOwnProperty(topic)) {
+        var args = Array.prototype.slice.call(arguments, 1),
+            idr = [];
+
+        for (var id in topics[topic]) {
+          var sub = topics[topic][id];
+          try {
+            sub[0].apply(context, args);
+          } catch (ex) {
+            if (global.console) {
+              console.error('jsPDF PubSub Error', ex.message, ex);
+            }
+          }
+          if (sub[1]) idr.push(id);
+        }
+        if (idr.length) idr.forEach(this.unsubscribe);
+      }
+    };
+  }
+
+  /**
+   * @constructor
+   * @private
+   */
+  function jsPDF(orientation, unit, format, compressPdf) {
+    var options = {};
+
+    if ((typeof orientation === 'undefined' ? 'undefined' : _typeof(orientation)) === 'object') {
+      options = orientation;
+
+      orientation = options.orientation;
+      unit = options.unit || unit;
+      format = options.format || format;
+      compressPdf = options.compress || options.compressPdf || compressPdf;
+    }
+
+    // Default options
+    unit = unit || 'mm';
+    format = format || 'a4';
+    orientation = ('' + (orientation || 'P')).toLowerCase();
+
+    var format_as_string = ('' + format).toLowerCase(),
+        compress = !!compressPdf && typeof Uint8Array === 'function',
+        textColor = options.textColor || '0 g',
+        drawColor = options.drawColor || '0 G',
+        activeFontSize = options.fontSize || 16,
+        lineHeightProportion = options.lineHeight || 1.15,
+        lineWidth = options.lineWidth || 0.200025,
+        // 2mm
+    objectNumber = 2,
+        // 'n' Current object number
+    outToPages = !1,
+        // switches where out() prints. outToPages true = push to pages obj. outToPages false = doc builder content
+    offsets = [],
+        // List of offsets. Activated and reset by buildDocument(). Pupulated by various calls buildDocument makes.
+    fonts = {},
+        // collection of font objects, where key is fontKey - a dynamically created label for a given font.
+    fontmap = {},
+        // mapping structure fontName > fontStyle > font key - performance layer. See addFont()
+    activeFontKey,
+        // will be string representing the KEY of the font as combination of fontName + fontStyle
+    k,
+        // Scale factor
+    tmp,
+        page = 0,
+        currentPage,
+        pages = [],
+        pagesContext = [],
+        // same index as pages and pagedim
+    pagedim = [],
+        content = [],
+        additionalObjects = [],
+        lineCapID = 0,
+        lineJoinID = 0,
+        content_length = 0,
+        pageWidth,
+        pageHeight,
+        pageMode,
+        zoomMode,
+        layoutMode,
+        documentProperties = {
+      'title': '',
+      'subject': '',
+      'author': '',
+      'keywords': '',
+      'creator': ''
+    },
+        API = {},
+        events = new PubSub(API),
+
+
+    /////////////////////
+    // Private functions
+    /////////////////////
+    f2 = function f2(number) {
+      return number.toFixed(2); // Ie, %.2f
+    },
+        f3 = function f3(number) {
+      return number.toFixed(3); // Ie, %.3f
+    },
+        padd2 = function padd2(number) {
+      return ('0' + parseInt(number)).slice(-2);
+    },
+        out = function out(string) {
+      if (outToPages) {
+        /* set by beginPage */
+        pages[currentPage].push(string);
+      } else {
+        // +1 for '\n' that will be used to join 'content'
+        content_length += string.length + 1;
+        content.push(string);
+      }
+    },
+        newObject = function newObject() {
+      // Begin a new object
+      objectNumber++;
+      offsets[objectNumber] = content_length;
+      out(objectNumber + ' 0 obj');
+      return objectNumber;
+    },
+
+    // Does not output the object until after the pages have been output.
+    // Returns an object containing the objectId and content.
+    // All pages have been added so the object ID can be estimated to start right after.
+    // This does not modify the current objectNumber;  It must be updated after the newObjects are output.
+    newAdditionalObject = function newAdditionalObject() {
+      var objId = pages.length * 2 + 1;
+      objId += additionalObjects.length;
+      var obj = {
+        objId: objId,
+        content: ''
+      };
+      additionalObjects.push(obj);
+      return obj;
+    },
+
+    // Does not output the object.  The caller must call newObjectDeferredBegin(oid) before outputing any data
+    newObjectDeferred = function newObjectDeferred() {
+      objectNumber++;
+      offsets[objectNumber] = function () {
+        return content_length;
+      };
+      return objectNumber;
+    },
+        newObjectDeferredBegin = function newObjectDeferredBegin(oid) {
+      offsets[oid] = content_length;
+    },
+        putStream = function putStream(str) {
+      out('stream');
+      out(str);
+      out('endstream');
+    },
+        putPages = function putPages() {
+      var n,
+          p,
+          arr,
+          i,
+          deflater,
+          adler32,
+          adler32cs,
+          wPt,
+          hPt,
+          pageObjectNumbers = [];
+
+      adler32cs = global.adler32cs || jsPDF.adler32cs;
+      if (compress && typeof adler32cs === 'undefined') {
+        compress = false;
+      }
+
+      // outToPages = false as set in endDocument(). out() writes to content.
+
+      for (n = 1; n <= page; n++) {
+        pageObjectNumbers.push(newObject());
+        wPt = (pageWidth = pagedim[n].width) * k;
+        hPt = (pageHeight = pagedim[n].height) * k;
+        out('<</Type /Page');
+        out('/Parent 1 0 R');
+        out('/Resources 2 0 R');
+        out('/MediaBox [0 0 ' + f2(wPt) + ' ' + f2(hPt) + ']');
+        // Added for annotation plugin
+        events.publish('putPage', {
+          pageNumber: n,
+          page: pages[n]
+        });
+        out('/Contents ' + (objectNumber + 1) + ' 0 R');
+        out('>>');
+        out('endobj');
+
+        // Page content
+        p = pages[n].join('\n');
+        newObject();
+        if (compress) {
+          arr = [];
+          i = p.length;
+          while (i--) {
+            arr[i] = p.charCodeAt(i);
+          }
+          adler32 = adler32cs.from(p);
+          deflater = new Deflater(6);
+          deflater.append(new Uint8Array(arr));
+          p = deflater.flush();
+          arr = new Uint8Array(p.length + 6);
+          arr.set(new Uint8Array([120, 156])), arr.set(p, 2);
+          arr.set(new Uint8Array([adler32 & 0xFF, adler32 >> 8 & 0xFF, adler32 >> 16 & 0xFF, adler32 >> 24 & 0xFF]), p.length + 2);
+          p = String.fromCharCode.apply(null, arr);
+          out('<</Length ' + p.length + ' /Filter [/FlateDecode]>>');
+        } else {
+          out('<</Length ' + p.length + '>>');
+        }
+        putStream(p);
+        out('endobj');
+      }
+      offsets[1] = content_length;
+      out('1 0 obj');
+      out('<</Type /Pages');
+      var kids = '/Kids [';
+      for (i = 0; i < page; i++) {
+        kids += pageObjectNumbers[i] + ' 0 R ';
+      }
+      out(kids + ']');
+      out('/Count ' + page);
+      out('>>');
+      out('endobj');
+      events.publish('postPutPages');
+    },
+        putFont = function putFont(font) {
+      font.objectNumber = newObject();
+      out('<</BaseFont/' + font.PostScriptName + '/Type/Font');
+      if (typeof font.encoding === 'string') {
+        out('/Encoding/' + font.encoding);
+      }
+      out('/Subtype/Type1>>');
+      out('endobj');
+    },
+        putFonts = function putFonts() {
+      for (var fontKey in fonts) {
+        if (fonts.hasOwnProperty(fontKey)) {
+          putFont(fonts[fontKey]);
+        }
+      }
+    },
+        putXobjectDict = function putXobjectDict() {
+      // Loop through images, or other data objects
+      events.publish('putXobjectDict');
+    },
+        putResourceDictionary = function putResourceDictionary() {
+      out('/ProcSet [/PDF /Text /ImageB /ImageC /ImageI]');
+      out('/Font <<');
+
+      // Do this for each font, the '1' bit is the index of the font
+      for (var fontKey in fonts) {
+        if (fonts.hasOwnProperty(fontKey)) {
+          out('/' + fontKey + ' ' + fonts[fontKey].objectNumber + ' 0 R');
+        }
+      }
+      out('>>');
+      out('/XObject <<');
+      putXobjectDict();
+      out('>>');
+    },
+        putResources = function putResources() {
+      putFonts();
+      events.publish('putResources');
+      // Resource dictionary
+      offsets[2] = content_length;
+      out('2 0 obj');
+      out('<<');
+      putResourceDictionary();
+      out('>>');
+      out('endobj');
+      events.publish('postPutResources');
+    },
+        putAdditionalObjects = function putAdditionalObjects() {
+      events.publish('putAdditionalObjects');
+      for (var i = 0; i < additionalObjects.length; i++) {
+        var obj = additionalObjects[i];
+        offsets[obj.objId] = content_length;
+        out(obj.objId + ' 0 obj');
+        out(obj.content);
+        out('endobj');
+      }
+      objectNumber += additionalObjects.length;
+      events.publish('postPutAdditionalObjects');
+    },
+        addToFontDictionary = function addToFontDictionary(fontKey, fontName, fontStyle) {
+      // this is mapping structure for quick font key lookup.
+      // returns the KEY of the font (ex: "F1") for a given
+      // pair of font name and type (ex: "Arial". "Italic")
+      if (!fontmap.hasOwnProperty(fontName)) {
+        fontmap[fontName] = {};
+      }
+      fontmap[fontName][fontStyle] = fontKey;
+    },
+
+    /**
+     * FontObject describes a particular font as member of an instnace of jsPDF
+     *
+     * It's a collection of properties like 'id' (to be used in PDF stream),
+     * 'fontName' (font's family name), 'fontStyle' (font's style variant label)
+     *
+     * @class
+     * @public
+     * @property id {String} PDF-document-instance-specific label assinged to the font.
+     * @property PostScriptName {String} PDF specification full name for the font
+     * @property encoding {Object} Encoding_name-to-Font_metrics_object mapping.
+     * @name FontObject
+     * @ignore This should not be in the public docs.
+     */
+    addFont = function addFont(PostScriptName, fontName, fontStyle, encoding) {
+      var fontKey = 'F' + (Object.keys(fonts).length + 1).toString(10),
+
+      // This is FontObject
+      font = fonts[fontKey] = {
+        'id': fontKey,
+        'PostScriptName': PostScriptName,
+        'fontName': fontName,
+        'fontStyle': fontStyle,
+        'encoding': encoding,
+        'metadata': {}
+      };
+      addToFontDictionary(fontKey, fontName, fontStyle);
+      events.publish('addFont', font);
+
+      return fontKey;
+    },
+        addFonts = function addFonts() {
+
+      var HELVETICA = "helvetica",
+          TIMES = "times",
+          COURIER = "courier",
+          NORMAL = "normal",
+          BOLD = "bold",
+          ITALIC = "italic",
+          BOLD_ITALIC = "bolditalic",
+          encoding = 'StandardEncoding',
+          ZAPF = "zapfdingbats",
+          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]];
+
+      for (var i = 0, l = standardFonts.length; i < l; i++) {
+        var fontKey = addFont(standardFonts[i][0], standardFonts[i][1], standardFonts[i][2], encoding);
+
+        // adding aliases for standard fonts, this time matching the capitalization
+        var parts = standardFonts[i][0].split('-');
+        addToFontDictionary(fontKey, parts[0], parts[1] || '');
+      }
+      events.publish('addFonts', {
+        fonts: fonts,
+        dictionary: fontmap
+      });
+    },
+        SAFE = function __safeCall(fn) {
+      fn.foo = function __safeCallWrapper() {
+        try {
+          return fn.apply(this, arguments);
+        } catch (e) {
+          var stack = e.stack || '';
+          if (~stack.indexOf(' at ')) stack = stack.split(" at ")[1];
+          var m = "Error in function " + stack.split("\n")[0].split('<')[0] + ": " + e.message;
+          if (global.console) {
+            global.console.error(m, e);
+            if (global.alert) alert(m);
+          } else {
+            throw new Error(m);
+          }
+        }
+      };
+      fn.foo.bar = fn;
+      return fn.foo;
+    },
+        to8bitStream = function to8bitStream(text, flags) {
+      /**
+       * PDF 1.3 spec:
+       * "For text strings encoded in Unicode, the first two bytes must be 254 followed by
+       * 255, representing the Unicode byte order marker, U+FEFF. (This sequence conflicts
+       * with the PDFDocEncoding character sequence thorn ydieresis, which is unlikely
+       * to be a meaningful beginning of a word or phrase.) The remainder of the
+       * string consists of Unicode character codes, according to the UTF-16 encoding
+       * specified in the Unicode standard, version 2.0. Commonly used Unicode values
+       * are represented as 2 bytes per character, with the high-order byte appearing first
+       * in the string."
+       *
+       * In other words, if there are chars in a string with char code above 255, we
+       * recode the string to UCS2 BE - string doubles in length and BOM is prepended.
+       *
+       * HOWEVER!
+       * Actual *content* (body) text (as opposed to strings used in document properties etc)
+       * does NOT expect BOM. There, it is treated as a literal GID (Glyph ID)
+       *
+       * Because of Adobe's focus on "you subset your fonts!" you are not supposed to have
+       * a font that maps directly Unicode (UCS2 / UTF16BE) code to font GID, but you could
+       * fudge it with "Identity-H" encoding and custom CIDtoGID map that mimics Unicode
+       * code page. There, however, all characters in the stream are treated as GIDs,
+       * including BOM, which is the reason we need to skip BOM in content text (i.e. that
+       * that is tied to a font).
+       *
+       * To signal this "special" PDFEscape / to8bitStream handling mode,
+       * API.text() function sets (unless you overwrite it with manual values
+       * given to API.text(.., flags) )
+       * flags.autoencode = true
+       * flags.noBOM = true
+       *
+       * ===================================================================================
+       * `flags` properties relied upon:
+       *   .sourceEncoding = string with encoding label.
+       *                     "Unicode" by default. = encoding of the incoming text.
+       *                     pass some non-existing encoding name
+       *                     (ex: 'Do not touch my strings! I know what I am doing.')
+       *                     to make encoding code skip the encoding step.
+       *   .outputEncoding = Either valid PDF encoding name
+       *                     (must be supported by jsPDF font metrics, otherwise no encoding)
+       *                     or a JS object, where key = sourceCharCode, value = outputCharCode
+       *                     missing keys will be treated as: sourceCharCode === outputCharCode
+       *   .noBOM
+       *       See comment higher above for explanation for why this is important
+       *   .autoencode
+       *       See comment higher above for explanation for why this is important
+       */
+
+      var i, l, sourceEncoding, encodingBlock, outputEncoding, newtext, isUnicode, ch, bch;
+
+      flags = flags || {};
+      sourceEncoding = flags.sourceEncoding || 'Unicode';
+      outputEncoding = flags.outputEncoding;
+
+      // This 'encoding' section relies on font metrics format
+      // attached to font objects by, among others,
+      // "Willow Systems' standard_font_metrics plugin"
+      // see jspdf.plugin.standard_font_metrics.js for format
+      // of the font.metadata.encoding Object.
+      // It should be something like
+      //   .encoding = {'codePages':['WinANSI....'], 'WinANSI...':{code:code, ...}}
+      //   .widths = {0:width, code:width, ..., 'fof':divisor}
+      //   .kerning = {code:{previous_char_code:shift, ..., 'fof':-divisor},...}
+      if ((flags.autoencode || outputEncoding) && fonts[activeFontKey].metadata && fonts[activeFontKey].metadata[sourceEncoding] && fonts[activeFontKey].metadata[sourceEncoding].encoding) {
+        encodingBlock = fonts[activeFontKey].metadata[sourceEncoding].encoding;
+
+        // each font has default encoding. Some have it clearly defined.
+        if (!outputEncoding && fonts[activeFontKey].encoding) {
+          outputEncoding = fonts[activeFontKey].encoding;
+        }
+
+        // Hmmm, the above did not work? Let's try again, in different place.
+        if (!outputEncoding && encodingBlock.codePages) {
+          outputEncoding = encodingBlock.codePages[0]; // let's say, first one is the default
+        }
+
+        if (typeof outputEncoding === 'string') {
+          outputEncoding = encodingBlock[outputEncoding];
+        }
+        // we want output encoding to be a JS Object, where
+        // key = sourceEncoding's character code and
+        // value = outputEncoding's character code.
+        if (outputEncoding) {
+          isUnicode = false;
+          newtext = [];
+          for (i = 0, l = text.length; i < l; i++) {
+            ch = outputEncoding[text.charCodeAt(i)];
+            if (ch) {
+              newtext.push(String.fromCharCode(ch));
+            } else {
+              newtext.push(text[i]);
+            }
+
+            // since we are looping over chars anyway, might as well
+            // check for residual unicodeness
+            if (newtext[i].charCodeAt(0) >> 8) {
+              /* more than 255 */
+              isUnicode = true;
+            }
+          }
+          text = newtext.join('');
+        }
+      }
+
+      i = text.length;
+      // isUnicode may be set to false above. Hence the triple-equal to undefined
+      while (isUnicode === undefined && i !== 0) {
+        if (text.charCodeAt(i - 1) >> 8) {
+          /* more than 255 */
+          isUnicode = true;
+        }
+        i--;
+      }
+      if (!isUnicode) {
+        return text;
+      }
+
+      newtext = flags.noBOM ? [] : [254, 255];
+      for (i = 0, l = text.length; i < l; i++) {
+        ch = text.charCodeAt(i);
+        bch = ch >> 8; // divide by 256
+        if (bch >> 8) {
+          /* something left after dividing by 256 second time */
+          throw new Error("Character at position " + i + " of string '" + text + "' exceeds 16bits. Cannot be encoded into UCS-2 BE");
+        }
+        newtext.push(bch);
+        newtext.push(ch - (bch << 8));
+      }
+      return String.fromCharCode.apply(undefined, newtext);
+    },
+        pdfEscape = function pdfEscape(text, flags) {
+      /**
+       * Replace '/', '(', and ')' with pdf-safe versions
+       *
+       * Doing to8bitStream does NOT make this PDF display unicode text. For that
+       * we also need to reference a unicode font and embed it - royal pain in the rear.
+       *
+       * There is still a benefit to to8bitStream - PDF simply cannot handle 16bit chars,
+       * which JavaScript Strings are happy to provide. So, while we still cannot display
+       * 2-byte characters property, at least CONDITIONALLY converting (entire string containing)
+       * 16bit chars to (USC-2-BE) 2-bytes per char + BOM streams we ensure that entire PDF
+       * is still parseable.
+       * This will allow immediate support for unicode in document properties strings.
+       */
+      return to8bitStream(text, flags).replace(/\\/g, '\\\\').replace(/\(/g, '\\(').replace(/\)/g, '\\)');
+    },
+        putInfo = function putInfo() {
+      out('/Producer (jsPDF ' + jsPDF.version + ')');
+      for (var key in documentProperties) {
+        if (documentProperties.hasOwnProperty(key) && documentProperties[key]) {
+          out('/' + key.substr(0, 1).toUpperCase() + key.substr(1) + ' (' + pdfEscape(documentProperties[key]) + ')');
+        }
+      }
+      var created = new Date(),
+          tzoffset = created.getTimezoneOffset(),
+          tzsign = tzoffset < 0 ? '+' : '-',
+          tzhour = Math.floor(Math.abs(tzoffset / 60)),
+          tzmin = Math.abs(tzoffset % 60),
+          tzstr = [tzsign, padd2(tzhour), "'", padd2(tzmin), "'"].join('');
+      out(['/CreationDate (D:', created.getFullYear(), padd2(created.getMonth() + 1), padd2(created.getDate()), padd2(created.getHours()), padd2(created.getMinutes()), padd2(created.getSeconds()), tzstr, ')'].join(''));
+    },
+        putCatalog = function putCatalog() {
+      out('/Type /Catalog');
+      out('/Pages 1 0 R');
+      // PDF13ref Section 7.2.1
+      if (!zoomMode) zoomMode = 'fullwidth';
+      switch (zoomMode) {
+        case 'fullwidth':
+          out('/OpenAction [3 0 R /FitH null]');
+          break;
+        case 'fullheight':
+          out('/OpenAction [3 0 R /FitV null]');
+          break;
+        case 'fullpage':
+          out('/OpenAction [3 0 R /Fit]');
+          break;
+        case 'original':
+          out('/OpenAction [3 0 R /XYZ null null 1]');
+          break;
+        default:
+          var pcn = '' + zoomMode;
+          if (pcn.substr(pcn.length - 1) === '%') zoomMode = parseInt(zoomMode) / 100;
+          if (typeof zoomMode === 'number') {
+            out('/OpenAction [3 0 R /XYZ null null ' + f2(zoomMode) + ']');
+          }
+      }
+      if (!layoutMode) layoutMode = 'continuous';
+      switch (layoutMode) {
+        case 'continuous':
+          out('/PageLayout /OneColumn');
+          break;
+        case 'single':
+          out('/PageLayout /SinglePage');
+          break;
+        case 'two':
+        case 'twoleft':
+          out('/PageLayout /TwoColumnLeft');
+          break;
+        case 'tworight':
+          out('/PageLayout /TwoColumnRight');
+          break;
+      }
+      if (pageMode) {
+        /**
+         * A name object specifying how the document should be displayed when opened:
+         * UseNone      : Neither document outline nor thumbnail images visible -- DEFAULT
+         * UseOutlines  : Document outline visible
+         * UseThumbs    : Thumbnail images visible
+         * FullScreen   : Full-screen mode, with no menu bar, window controls, or any other window visible
+         */
+        out('/PageMode /' + pageMode);
+      }
+      events.publish('putCatalog');
+    },
+        putTrailer = function putTrailer() {
+      out('/Size ' + (objectNumber + 1));
+      out('/Root ' + objectNumber + ' 0 R');
+      out('/Info ' + (objectNumber - 1) + ' 0 R');
+    },
+        beginPage = function beginPage(width, height) {
+      // Dimensions are stored as user units and converted to points on output
+      var orientation = typeof height === 'string' && height.toLowerCase();
+      if (typeof width === 'string') {
+        var format = width.toLowerCase();
+        if (pageFormats.hasOwnProperty(format)) {
+          width = pageFormats[format][0] / k;
+          height = pageFormats[format][1] / k;
+        }
+      }
+      if (Array.isArray(width)) {
+        height = width[1];
+        width = width[0];
+      }
+      if (orientation) {
+        switch (orientation.substr(0, 1)) {
+          case 'l':
+            if (height > width) orientation = 's';
+            break;
+          case 'p':
+            if (width > height) orientation = 's';
+            break;
+        }
+        if (orientation === 's') {
+          tmp = width;
+          width = height;
+          height = tmp;
+        }
+      }
+      outToPages = true;
+      pages[++page] = [];
+      pagedim[page] = {
+        width: Number(width) || pageWidth,
+        height: Number(height) || pageHeight
+      };
+      pagesContext[page] = {};
+      _setPage(page);
+    },
+        _addPage = function _addPage() {
+      beginPage.apply(this, arguments);
+      // Set line width
+      out(f2(lineWidth * k) + ' w');
+      // Set draw color
+      out(drawColor);
+      // resurrecting non-default line caps, joins
+      if (lineCapID !== 0) {
+        out(lineCapID + ' J');
+      }
+      if (lineJoinID !== 0) {
+        out(lineJoinID + ' j');
+      }
+      events.publish('addPage', {
+        pageNumber: page
+      });
+    },
+        _deletePage = function _deletePage(n) {
+      if (n > 0 && n <= page) {
+        pages.splice(n, 1);
+        pagedim.splice(n, 1);
+        page--;
+        if (currentPage > page) {
+          currentPage = page;
+        }
+        this.setPage(currentPage);
+      }
+    },
+        _setPage = function _setPage(n) {
+      if (n > 0 && n <= page) {
+        currentPage = n;
+        pageWidth = pagedim[n].width;
+        pageHeight = pagedim[n].height;
+      }
+    },
+
+    /**
+     * Returns a document-specific font key - a label assigned to a
+     * font name + font type combination at the time the font was added
+     * to the font inventory.
+     *
+     * Font key is used as label for the desired font for a block of text
+     * to be added to the PDF document stream.
+     * @private
+     * @function
+     * @param fontName {String} can be undefined on "falthy" to indicate "use current"
+     * @param fontStyle {String} can be undefined on "falthy" to indicate "use current"
+     * @returns {String} Font key.
+     */
+    _getFont = function _getFont(fontName, fontStyle) {
+      var key;
+
+      fontName = fontName !== undefined ? fontName : fonts[activeFontKey].fontName;
+      fontStyle = fontStyle !== undefined ? fontStyle : fonts[activeFontKey].fontStyle;
+
+      if (fontName !== undefined) {
+        fontName = fontName.toLowerCase();
+      }
+      switch (fontName) {
+        case 'sans-serif':
+        case 'verdana':
+        case 'arial':
+        case 'helvetica':
+          fontName = 'helvetica';
+          break;
+        case 'fixed':
+        case 'monospace':
+        case 'terminal':
+        case 'courier':
+          fontName = 'courier';
+          break;
+        case 'serif':
+        case 'cursive':
+        case 'fantasy':
+        default:
+          fontName = 'times';
+          break;
+      }
+
+      try {
+        // get a string like 'F3' - the KEY corresponding tot he font + type combination.
+        key = fontmap[fontName][fontStyle];
+      } catch (e) {}
+
+      if (!key) {
+        //throw new Error("Unable to look up font label for font '" + fontName + "', '"
+        //+ fontStyle + "'. Refer to getFontList() for available fonts.");
+        key = fontmap['times'][fontStyle];
+        if (key == null) {
+          key = fontmap['times']['normal'];
+        }
+      }
+      return key;
+    },
+        buildDocument = function buildDocument() {
+      outToPages = false; // switches out() to content
+
+      objectNumber = 2;
+      content_length = 0;
+      content = [];
+      offsets = [];
+      additionalObjects = [];
+      // Added for AcroForm
+      events.publish('buildDocument');
+
+      // putHeader()
+      out('%PDF-' + pdfVersion);
+
+      putPages();
+
+      // Must happen after putPages
+      // Modifies current object Id
+      putAdditionalObjects();
+
+      putResources();
+
+      // Info
+      newObject();
+      out('<<');
+      putInfo();
+      out('>>');
+      out('endobj');
+
+      // Catalog
+      newObject();
+      out('<<');
+      putCatalog();
+      out('>>');
+      out('endobj');
+
+      // Cross-ref
+      var o = content_length,
+          i,
+          p = "0000000000";
+      out('xref');
+      out('0 ' + (objectNumber + 1));
+      out(p + ' 65535 f ');
+      for (i = 1; i <= objectNumber; i++) {
+        var offset = offsets[i];
+        if (typeof offset === 'function') {
+          out((p + offsets[i]()).slice(-10) + ' 00000 n ');
+        } else {
+          out((p + offsets[i]).slice(-10) + ' 00000 n ');
+        }
+      }
+      // Trailer
+      out('trailer');
+      out('<<');
+      putTrailer();
+      out('>>');
+      out('startxref');
+      out('' + o);
+      out('%%EOF');
+
+      outToPages = true;
+
+      return content.join('\n');
+    },
+        getStyle = function getStyle(style) {
+      // see path-painting operators in PDF spec
+      var op = 'S'; // stroke
+      if (style === 'F') {
+        op = 'f'; // fill
+      } else if (style === 'FD' || style === 'DF') {
+        op = 'B'; // both
+      } else if (style === 'f' || style === 'f*' || style === 'B' || style === 'B*') {
+        /*
+         Allow direct use of these PDF path-painting operators:
+         - f	fill using nonzero winding number rule
+         - f*	fill using even-odd rule
+         - B	fill then stroke with fill using non-zero winding number rule
+         - B*	fill then stroke with fill using even-odd rule
+         */
+        op = style;
+      }
+      return op;
+    },
+        getArrayBuffer = function getArrayBuffer() {
+      var data = buildDocument(),
+          len = data.length,
+          ab = new ArrayBuffer(len),
+          u8 = new Uint8Array(ab);
+
+      while (len--) {
+        u8[len] = data.charCodeAt(len);
+      }return ab;
+    },
+        getBlob = function getBlob() {
+      return new Blob([getArrayBuffer()], {
+        type: "application/pdf"
+      });
+    },
+
+    /**
+     * Generates the PDF document.
+     *
+     * If `type` argument is undefined, output is raw body of resulting PDF returned as a string.
+     *
+     * @param {String} type A string identifying one of the possible output types.
+     * @param {Object} options An object providing some additional signalling to PDF generator.
+     * @function
+     * @returns {jsPDF}
+     * @methodOf jsPDF#
+     * @name output
+     */
+    _output = SAFE(function (type, options) {
+      var datauri = ('' + type).substr(0, 6) === 'dataur' ? 'data:application/pdf;base64,' + btoa(buildDocument()) : 0;
+
+      switch (type) {
+        case undefined:
+          return buildDocument();
+        case 'save':
+          if (navigator.getUserMedia) {
+            if (global.URL === undefined || global.URL.createObjectURL === undefined) {
+              return API.output('dataurlnewwindow');
+            }
+          }
+          saveAs(getBlob(), options);
+          if (typeof saveAs.unload === 'function') {
+            if (global.setTimeout) {
+              setTimeout(saveAs.unload, 911);
+            }
+          }
+          break;
+        case 'arraybuffer':
+          return getArrayBuffer();
+        case 'blob':
+          return getBlob();
+        case 'bloburi':
+        case 'bloburl':
+          // User is responsible of calling revokeObjectURL
+          return global.URL && global.URL.createObjectURL(getBlob()) || void 0;
+        case 'datauristring':
+        case 'dataurlstring':
+          return datauri;
+        case 'dataurlnewwindow':
+          var nW = global.open(datauri);
+          if (nW || typeof safari === "undefined") return nW;
+        /* pass through */
+        case 'datauri':
+        case 'dataurl':
+          return global.document.location.href = datauri;
+        default:
+          throw new Error('Output type "' + type + '" is not supported.');
+      }
+      // @TODO: Add different output options
+    });
+
+    switch (unit) {
+      case 'pt':
+        k = 1;
+        break;
+      case 'mm':
+        k = 72 / 25.4000508;
+        break;
+      case 'cm':
+        k = 72 / 2.54000508;
+        break;
+      case 'in':
+        k = 72;
+        break;
+      case 'px':
+        k = 96 / 72;
+        break;
+      case 'pc':
+        k = 12;
+        break;
+      case 'em':
+        k = 12;
+        break;
+      case 'ex':
+        k = 6;
+        break;
+      default:
+        throw 'Invalid unit: ' + unit;
+    }
+
+    //---------------------------------------
+    // Public API
+
+    /**
+     * Object exposing internal API to plugins
+     * @public
+     */
+    API.internal = {
+      'pdfEscape': pdfEscape,
+      'getStyle': getStyle,
+      /**
+       * Returns {FontObject} describing a particular font.
+       * @public
+       * @function
+       * @param fontName {String} (Optional) Font's family name
+       * @param fontStyle {String} (Optional) Font's style variation name (Example:"Italic")
+       * @returns {FontObject}
+       */
+      'getFont': function getFont() {
+        return fonts[_getFont.apply(API, arguments)];
+      },
+      'getFontSize': function getFontSize() {
+        return activeFontSize;
+      },
+      'getLineHeight': function getLineHeight() {
+        return activeFontSize * lineHeightProportion;
+      },
+      'write': function write(string1 /*, string2, string3, etc */) {
+        out(arguments.length === 1 ? string1 : Array.prototype.join.call(arguments, ' '));
+      },
+      'getCoordinateString': function getCoordinateString(value) {
+        return f2(value * k);
+      },
+      'getVerticalCoordinateString': function getVerticalCoordinateString(value) {
+        return f2((pageHeight - value) * k);
+      },
+      'collections': {},
+      'newObject': newObject,
+      'newAdditionalObject': newAdditionalObject,
+      'newObjectDeferred': newObjectDeferred,
+      'newObjectDeferredBegin': newObjectDeferredBegin,
+      'putStream': putStream,
+      'events': events,
+      // ratio that you use in multiplication of a given "size" number to arrive to 'point'
+      // units of measurement.
+      // scaleFactor is set at initialization of the document and calculated against the stated
+      // default measurement units for the document.
+      // If default is "mm", k is the number that will turn number in 'mm' into 'points' number.
+      // through multiplication.
+      'scaleFactor': k,
+      'pageSize': {
+        get width() {
+          return pageWidth;
+        },
+        get height() {
+          return pageHeight;
+        }
+      },
+      'output': function output(type, options) {
+        return _output(type, options);
+      },
+      'getNumberOfPages': function getNumberOfPages() {
+        return pages.length - 1;
+      },
+      'pages': pages,
+      'out': out,
+      'f2': f2,
+      'getPageInfo': function getPageInfo(pageNumberOneBased) {
+        var objId = (pageNumberOneBased - 1) * 2 + 3;
+        return {
+          objId: objId,
+          pageNumber: pageNumberOneBased,
+          pageContext: pagesContext[pageNumberOneBased]
+        };
+      },
+      'getCurrentPageInfo': function getCurrentPageInfo() {
+        var objId = (currentPage - 1) * 2 + 3;
+        return {
+          objId: objId,
+          pageNumber: currentPage,
+          pageContext: pagesContext[currentPage]
+        };
+      },
+      'getPDFVersion': function getPDFVersion() {
+        return pdfVersion;
+      }
+    };
+
+    /**
+     * Adds (and transfers the focus to) new page to the PDF document.
+     * @function
+     * @returns {jsPDF}
+     *
+     * @methodOf jsPDF#
+     * @name addPage
+     */
+    API.addPage = function () {
+      _addPage.apply(this, arguments);
+      return this;
+    };
+    /**
+     * Adds (and transfers the focus to) new page to the PDF document.
+     * @function
+     * @returns {jsPDF}
+     *
+     * @methodOf jsPDF#
+     * @name setPage
+     * @param {Number} page Switch the active page to the page number specified
+     * @example
+     * doc = jsPDF()
+     * doc.addPage()
+     * doc.addPage()
+     * doc.text('I am on page 3', 10, 10)
+     * doc.setPage(1)
+     * doc.text('I am on page 1', 10, 10)
+     */
+    API.setPage = function () {
+      _setPage.apply(this, arguments);
+      return this;
+    };
+    API.insertPage = function (beforePage) {
+      this.addPage();
+      this.movePage(currentPage, beforePage);
+      return this;
+    };
+    API.movePage = function (targetPage, beforePage) {
+      if (targetPage > beforePage) {
+        var tmpPages = pages[targetPage];
+        var tmpPagedim = pagedim[targetPage];
+        var tmpPagesContext = pagesContext[targetPage];
+        for (var i = targetPage; i > beforePage; i--) {
+          pages[i] = pages[i - 1];
+          pagedim[i] = pagedim[i - 1];
+          pagesContext[i] = pagesContext[i - 1];
+        }
+        pages[beforePage] = tmpPages;
+        pagedim[beforePage] = tmpPagedim;
+        pagesContext[beforePage] = tmpPagesContext;
+        this.setPage(beforePage);
+      } else if (targetPage < beforePage) {
+        var tmpPages = pages[targetPage];
+        var tmpPagedim = pagedim[targetPage];
+        var tmpPagesContext = pagesContext[targetPage];
+        for (var i = targetPage; i < beforePage; i++) {
+          pages[i] = pages[i + 1];
+          pagedim[i] = pagedim[i + 1];
+          pagesContext[i] = pagesContext[i + 1];
+        }
+        pages[beforePage] = tmpPages;
+        pagedim[beforePage] = tmpPagedim;
+        pagesContext[beforePage] = tmpPagesContext;
+        this.setPage(beforePage);
+      }
+      return this;
+    };
+
+    API.deletePage = function () {
+      _deletePage.apply(this, arguments);
+      return this;
+    };
+
+    /**
+     * Set the display mode options of the page like zoom and layout.
+     *
+     * @param {integer|String} zoom   You can pass an integer or percentage as
+     * a string. 2 will scale the document up 2x, '200%' will scale up by the
+     * same amount. You can also set it to 'fullwidth', 'fullheight',
+     * 'fullpage', or 'original'.
+     *
+     * Only certain PDF readers support this, such as Adobe Acrobat
+     *
+     * @param {String} layout Layout mode can be: 'continuous' - this is the
+     * default continuous scroll. 'single' - the single page mode only shows one
+     * page at a time. 'twoleft' - two column left mode, first page starts on
+     * the left, and 'tworight' - pages are laid out in two columns, with the
+     * first page on the right. This would be used for books.
+     * @param {String} pmode 'UseOutlines' - it shows the
+     * outline of the document on the left. 'UseThumbs' - shows thumbnails along
+     * the left. 'FullScreen' - prompts the user to enter fullscreen mode.
+     *
+     * @function
+     * @returns {jsPDF}
+     * @name setDisplayMode
+     */
+    API.setDisplayMode = function (zoom, layout, pmode) {
+      zoomMode = zoom;
+      layoutMode = layout;
+      pageMode = pmode;
+
+      var validPageModes = [undefined, null, 'UseNone', 'UseOutlines', 'UseThumbs', 'FullScreen'];
+      if (validPageModes.indexOf(pmode) == -1) {
+        throw new Error('Page mode must be one of UseNone, UseOutlines, UseThumbs, or FullScreen. "' + pmode + '" is not recognized.');
+      }
+      return this;
+    },
+
+    /**
+     * Adds text to page. Supports adding multiline text when 'text' argument is an Array of Strings.
+     *
+     * @function
+     * @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.
+     * @param {Number} x Coordinate (in units declared at inception of PDF document) against left edge of the page
+     * @param {Number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page
+     * @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.
+     * @returns {jsPDF}
+     * @methodOf jsPDF#
+     * @name text
+     */
+    API.text = function (text, x, y, flags, angle, align) {
+      /**
+       * Inserts something like this into PDF
+       *   BT
+       *    /F1 16 Tf  % Font name + size
+       *    16 TL % How many units down for next line in multiline text
+       *    0 g % color
+       *    28.35 813.54 Td % position
+       *    (line one) Tj
+       *    T* (line two) Tj
+       *    T* (line three) Tj
+       *   ET
+       */
+      function ESC(s) {
+        s = s.split("\t").join(Array(options.TabLen || 9).join(" "));
+        return pdfEscape(s, flags);
+      }
+
+      // Pre-August-2012 the order of arguments was function(x, y, text, flags)
+      // in effort to make all calls have similar signature like
+      //   function(data, coordinates... , miscellaneous)
+      // this method had its args flipped.
+      // code below allows backward compatibility with old arg order.
+      if (typeof text === 'number') {
+        tmp = y;
+        y = x;
+        x = text;
+        text = tmp;
+      }
+
+      // If there are any newlines in text, we assume
+      // the user wanted to print multiple lines, so break the
+      // text up into an array.  If the text is already an array,
+      // we assume the user knows what they are doing.
+      // Convert text into an array anyway to simplify
+      // later code.
+      if (typeof text === 'string') {
+        if (text.match(/[\n\r]/)) {
+          text = text.split(/\r\n|\r|\n/g);
+        } else {
+          text = [text];
+        }
+      }
+      if (typeof angle === 'string') {
+        align = angle;
+        angle = null;
+      }
+      if (typeof flags === 'string') {
+        align = flags;
+        flags = null;
+      }
+      if (typeof flags === 'number') {
+        angle = flags;
+        flags = null;
+      }
+      var xtra = '',
+          mode = 'Td',
+          todo;
+      if (angle) {
+        angle *= Math.PI / 180;
+        var c = Math.cos(angle),
+            s = Math.sin(angle);
+        xtra = [f2(c), f2(s), f2(s * -1), f2(c), ''].join(" ");
+        mode = 'Tm';
+      }
+      flags = flags || {};
+      if (!('noBOM' in flags)) flags.noBOM = true;
+      if (!('autoencode' in flags)) flags.autoencode = true;
+
+      var strokeOption = '';
+      var pageContext = this.internal.getCurrentPageInfo().pageContext;
+      if (true === flags.stroke) {
+        if (pageContext.lastTextWasStroke !== true) {
+          strokeOption = '1 Tr\n';
+          pageContext.lastTextWasStroke = true;
+        }
+      } else {
+        if (pageContext.lastTextWasStroke) {
+          strokeOption = '0 Tr\n';
+        }
+        pageContext.lastTextWasStroke = false;
+      }
+
+      if (typeof this._runningPageHeight === 'undefined') {
+        this._runningPageHeight = 0;
+      }
+
+      if (typeof text === 'string') {
+        text = ESC(text);
+      } else if (Object.prototype.toString.call(text) === '[object Array]') {
+        // we don't want to destroy  original text array, so cloning it
+        var sa = text.concat(),
+            da = [],
+            len = sa.length;
+        // we do array.join('text that must not be PDFescaped")
+        // thus, pdfEscape each component separately
+        while (len--) {
+          da.push(ESC(sa.shift()));
+        }
+        var linesLeft = Math.ceil((pageHeight - y - this._runningPageHeight) * k / (activeFontSize * lineHeightProportion));
+        if (0 <= linesLeft && linesLeft < da.length + 1) {
+          //todo = da.splice(linesLeft-1);
+        }
+
+        if (align) {
+          var left,
+              prevX,
+              maxLineLength,
+              leading = activeFontSize * lineHeightProportion,
+              lineWidths = text.map(function (v) {
+            return this.getStringUnitWidth(v) * activeFontSize / k;
+          }, this);
+          maxLineLength = Math.max.apply(Math, lineWidths);
+          // The first line uses the "main" Td setting,
+          // and the subsequent lines are offset by the
+          // previous line's x coordinate.
+          if (align === "center") {
+            // The passed in x coordinate defines
+            // the center point.
+            left = x - maxLineLength / 2;
+            x -= lineWidths[0] / 2;
+          } else if (align === "right") {
+            // The passed in x coordinate defines the
+            // rightmost point of the text.
+            left = x - maxLineLength;
+            x -= lineWidths[0];
+          } else {
+            throw new Error('Unrecognized alignment option, use "center" or "right".');
+          }
+          prevX = x;
+          text = da[0];
+          for (var i = 1, len = da.length; i < len; i++) {
+            var delta = maxLineLength - lineWidths[i];
+            if (align === "center") delta /= 2;
+            // T* = x-offset leading Td ( text )
+            text += ") Tj\n" + (left - prevX + delta) + " -" + leading + " Td (" + da[i];
+            prevX = left + delta;
+          }
+        } else {
+          text = da.join(") Tj\nT* (");
+        }
+      } else {
+        throw new Error('Type of text must be string or Array. "' + text + '" is not recognized.');
+      }
+      // Using "'" ("go next line and render text" mark) would save space but would complicate our rendering code, templates
+
+      // BT .. ET does NOT have default settings for Tf. You must state that explicitely every time for BT .. ET
+      // if you want text transformation matrix (+ multiline) to work reliably (which reads sizes of things from font declarations)
+      // Thus, there is NO useful, *reliable* concept of "default" font for a page.
+      // The fact that "default" (reuse font used before) font worked before in basic cases is an accident
+      // - readers dealing smartly with brokenness of jsPDF's markup.
+
+      var curY;
+
+      if (todo) {
+        //this.addPage();
+        //this._runningPageHeight += y -  (activeFontSize * 1.7 / k);
+        //curY = f2(pageHeight - activeFontSize * 1.7 /k);
+      } else {
+        curY = f2((pageHeight - y) * k);
+      }
+      //curY = f2((pageHeight - (y - this._runningPageHeight)) * k);
+
+      //			if (curY < 0){
+      //				console.log('auto page break');
+      //				this.addPage();
+      //				this._runningPageHeight = y -  (activeFontSize * 1.7 / k);
+      //				curY = f2(pageHeight - activeFontSize * 1.7 /k);
+      //			}
+
+      out('BT\n/' + activeFontKey + ' ' + activeFontSize + ' Tf\n' + // font face, style, size
+      activeFontSize * lineHeightProportion + ' TL\n' + // line spacing
+      strokeOption + // stroke option
+      textColor + '\n' + xtra + f2(x * k) + ' ' + curY + ' ' + mode + '\n(' + text + ') Tj\nET');
+
+      if (todo) {
+        //this.text( todo, x, activeFontSize * 1.7 / k);
+        //this.text( todo, x, this._runningPageHeight + (activeFontSize * 1.7 / k));
+        this.text(todo, x, y); // + (activeFontSize * 1.7 / k));
+      }
+
+      return this;
+    };
+
+    /**
+     * Letter spacing method to print text with gaps
+     *
+     * @function
+     * @param {String|Array} text String to be added to the page.
+     * @param {Number} x Coordinate (in units declared at inception of PDF document) against left edge of the page
+     * @param {Number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page
+     * @param {Number} spacing Spacing (in units declared at inception)
+     * @returns {jsPDF}
+     * @methodOf jsPDF#
+     * @name lstext
+     * @deprecated We'll be removing this function. It doesn't take character width into account.
+     */
+    API.lstext = function (text, x, y, spacing) {
+      console.warn('jsPDF.lstext is deprecated');
+      for (var i = 0, len = text.length; i < len; i++, x += spacing) {
+        this.text(text[i], x, y);
+      }return this;
+    };
+
+    API.line = function (x1, y1, x2, y2) {
+      return this.lines([[x2 - x1, y2 - y1]], x1, y1);
+    };
+
+    API.clip = function () {
+      // By patrick-roberts, github.com/MrRio/jsPDF/issues/328
+      // Call .clip() after calling .rect() with a style argument of null
+      out('W'); // clip
+      out('S'); // stroke path; necessary for clip to work
+    };
+
+    /**
+     * This fixes the previous function clip(). Perhaps the 'stroke path' hack was due to the missing 'n' instruction?
+     * We introduce the fixed version so as to not break API.
+     * @param fillRule
+     */
+    API.clip_fixed = function (fillRule) {
+      // Call .clip() after calling drawing ops with a style argument of null
+      // W is the PDF clipping op
+      if ('evenodd' === fillRule) {
+        out('W*');
+      } else {
+        out('W');
+      }
+      // End the path object without filling or stroking it.
+      // This operator is a path-painting no-op, used primarily for the side effect of changing the current clipping path
+      // (see Section 4.4.3, “Clipping Path Operators”)
+      out('n');
+    };
+
+    /**
+     * Adds series of curves (straight lines or cubic bezier curves) to canvas, starting at `x`, `y` coordinates.
+     * All data points in `lines` are relative to last line origin.
+     * `x`, `y` become x1,y1 for first line / curve in the set.
+     * For lines you only need to specify [x2, y2] - (ending point) vector against x1, y1 starting point.
+     * 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.
+     *
+     * @example .lines([[2,2],[-2,2],[1,1,2,2,3,3],[2,1]], 212,110, 10) // line, line, bezier curve, line
+     * @param {Array} lines Array of *vector* shifts as pairs (lines) or sextets (cubic bezier curves).
+     * @param {Number} x Coordinate (in units declared at inception of PDF document) against left edge of the page
+     * @param {Number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page
+     * @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.
+     * @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.
+     * @param {Boolean} closed If true, the path is closed with a straight line from the end of the last curve to the starting point.
+     * @function
+     * @returns {jsPDF}
+     * @methodOf jsPDF#
+     * @name lines
+     */
+    API.lines = function (lines, x, y, scale, style, closed) {
+      var scalex, scaley, i, l, leg, x2, y2, x3, y3, x4, y4;
+
+      // Pre-August-2012 the order of arguments was function(x, y, lines, scale, style)
+      // in effort to make all calls have similar signature like
+      //   function(content, coordinateX, coordinateY , miscellaneous)
+      // this method had its args flipped.
+      // code below allows backward compatibility with old arg order.
+      if (typeof lines === 'number') {
+        tmp = y;
+        y = x;
+        x = lines;
+        lines = tmp;
+      }
+
+      scale = scale || [1, 1];
+
+      // starting point
+      out(f3(x * k) + ' ' + f3((pageHeight - y) * k) + ' m ');
+
+      scalex = scale[0];
+      scaley = scale[1];
+      l = lines.length;
+      //, x2, y2 // bezier only. In page default measurement "units", *after* scaling
+      //, x3, y3 // bezier only. In page default measurement "units", *after* scaling
+      // ending point for all, lines and bezier. . In page default measurement "units", *after* scaling
+      x4 = x; // last / ending point = starting point for first item.
+      y4 = y; // last / ending point = starting point for first item.
+
+      for (i = 0; i < l; i++) {
+        leg = lines[i];
+        if (leg.length === 2) {
+          // simple line
+          x4 = leg[0] * scalex + x4; // here last x4 was prior ending point
+          y4 = leg[1] * scaley + y4; // here last y4 was prior ending point
+          out(f3(x4 * k) + ' ' + f3((pageHeight - y4) * k) + ' l');
+        } else {
+          // bezier curve
+          x2 = leg[0] * scalex + x4; // here last x4 is prior ending point
+          y2 = leg[1] * scaley + y4; // here last y4 is prior ending point
+          x3 = leg[2] * scalex + x4; // here last x4 is prior ending point
+          y3 = leg[3] * scaley + y4; // here last y4 is prior ending point
+          x4 = leg[4] * scalex + x4; // here last x4 was prior ending point
+          y4 = leg[5] * scaley + y4; // here last y4 was prior ending point
+          out(f3(x2 * k) + ' ' + f3((pageHeight - y2) * k) + ' ' + f3(x3 * k) + ' ' + f3((pageHeight - y3) * k) + ' ' + f3(x4 * k) + ' ' + f3((pageHeight - y4) * k) + ' c');
+        }
+      }
+
+      if (closed) {
+        out(' h');
+      }
+
+      // stroking / filling / both the path
+      if (style !== null) {
+        out(getStyle(style));
+      }
+      return this;
+    };
+
+    /**
+     * Adds a rectangle to PDF
+     *
+     * @param {Number} x Coordinate (in units declared at inception of PDF document) against left edge of the page
+     * @param {Number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page
+     * @param {Number} w Width (in units declared at inception of PDF document)
+     * @param {Number} h Height (in units declared at inception of PDF document)
+     * @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.
+     * @function
+     * @returns {jsPDF}
+     * @methodOf jsPDF#
+     * @name rect
+     */
+    API.rect = function (x, y, w, h, style) {
+      var op = getStyle(style);
+      out([f2(x * k), f2((pageHeight - y) * k), f2(w * k), f2(-h * k), 're'].join(' '));
+
+      if (style !== null) {
+        out(getStyle(style));
+      }
+
+      return this;
+    };
+
+    /**
+     * Adds a triangle to PDF
+     *
+     * @param {Number} x1 Coordinate (in units declared at inception of PDF document) against left edge of the page
+     * @param {Number} y1 Coordinate (in units declared at inception of PDF document) against upper edge of the page
+     * @param {Number} x2 Coordinate (in units declared at inception of PDF document) against left edge of the page
+     * @param {Number} y2 Coordinate (in units declared at inception of PDF document) against upper edge of the page
+     * @param {Number} x3 Coordinate (in units declared at inception of PDF document) against left edge of the page
+     * @param {Number} y3 Coordinate (in units declared at inception of PDF document) against upper edge of the page
+     * @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.
+     * @function
+     * @returns {jsPDF}
+     * @methodOf jsPDF#
+     * @name triangle
+     */
+    API.triangle = function (x1, y1, x2, y2, x3, y3, style) {
+      this.lines([[x2 - x1, y2 - y1], // vector to point 2
+      [x3 - x2, y3 - y2], // vector to point 3
+      [x1 - x3, y1 - y3] // closing vector back to point 1
+      ], x1, y1, // start of path
+      [1, 1], style, true);
+      return this;
+    };
+
+    /**
+     * Adds a rectangle with rounded corners to PDF
+     *
+     * @param {Number} x Coordinate (in units declared at inception of PDF document) against left edge of the page
+     * @param {Number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page
+     * @param {Number} w Width (in units declared at inception of PDF document)
+     * @param {Number} h Height (in units declared at inception of PDF document)
+     * @param {Number} rx Radius along x axis (in units declared at inception of PDF document)
+     * @param {Number} rx Radius along y axis (in units declared at inception of PDF document)
+     * @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.
+     * @function
+     * @returns {jsPDF}
+     * @methodOf jsPDF#
+     * @name roundedRect
+     */
+    API.roundedRect = function (x, y, w, h, rx, ry, style) {
+      var MyArc = 4 / 3 * (Math.SQRT2 - 1);
+      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
+      [1, 1], style);
+      return this;
+    };
+
+    /**
+     * Adds an ellipse to PDF
+     *
+     * @param {Number} x Coordinate (in units declared at inception of PDF document) against left edge of the page
+     * @param {Number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page
+     * @param {Number} rx Radius along x axis (in units declared at inception of PDF document)
+     * @param {Number} rx Radius along y axis (in units declared at inception of PDF document)
+     * @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.
+     * @function
+     * @returns {jsPDF}
+     * @methodOf jsPDF#
+     * @name ellipse
+     */
+    API.ellipse = function (x, y, rx, ry, style) {
+      var lx = 4 / 3 * (Math.SQRT2 - 1) * rx,
+          ly = 4 / 3 * (Math.SQRT2 - 1) * ry;
+
+      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(' '));
+      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(' '));
+      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(' '));
+      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(' '));
+
+      if (style !== null) {
+        out(getStyle(style));
+      }
+
+      return this;
+    };
+
+    /**
+     * Adds an circle to PDF
+     *
+     * @param {Number} x Coordinate (in units declared at inception of PDF document) against left edge of the page
+     * @param {Number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page
+     * @param {Number} r Radius (in units declared at inception of PDF document)
+     * @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.
+     * @function
+     * @returns {jsPDF}
+     * @methodOf jsPDF#
+     * @name circle
+     */
+    API.circle = function (x, y, r, style) {
+      return this.ellipse(x, y, r, r, style);
+    };
+
+    /**
+     * Adds a properties to the PDF document
+     *
+     * @param {Object} A property_name-to-property_value object structure.
+     * @function
+     * @returns {jsPDF}
+     * @methodOf jsPDF#
+     * @name setProperties
+     */
+    API.setProperties = function (properties) {
+      // copying only those properties we can render.
+      for (var property in documentProperties) {
+        if (documentProperties.hasOwnProperty(property) && properties[property]) {
+          documentProperties[property] = properties[property];
+        }
+      }
+      return this;
+    };
+
+    /**
+     * Sets font size for upcoming text elements.
+     *
+     * @param {Number} size Font size in points.
+     * @function
+     * @returns {jsPDF}
+     * @methodOf jsPDF#
+     * @name setFontSize
+     */
+    API.setFontSize = function (size) {
+      activeFontSize = size;
+      return this;
+    };
+
+    /**
+     * Sets text font face, variant for upcoming text elements.
+     * See output of jsPDF.getFontList() for possible font names, styles.
+     *
+     * @param {String} fontName Font name or family. Example: "times"
+     * @param {String} fontStyle Font style or variant. Example: "italic"
+     * @function
+     * @returns {jsPDF}
+     * @methodOf jsPDF#
+     * @name setFont
+     */
+    API.setFont = function (fontName, fontStyle) {
+      activeFontKey = _getFont(fontName, fontStyle);
+      // if font is not found, the above line blows up and we never go further
+      return this;
+    };
+
+    /**
+     * Switches font style or variant for upcoming text elements,
+     * while keeping the font face or family same.
+     * See output of jsPDF.getFontList() for possible font names, styles.
+     *
+     * @param {String} style Font style or variant. Example: "italic"
+     * @function
+     * @returns {jsPDF}
+     * @methodOf jsPDF#
+     * @name setFontStyle
+     */
+    API.setFontStyle = API.setFontType = function (style) {
+      activeFontKey = _getFont(undefined, style);
+      // if font is not found, the above line blows up and we never go further
+      return this;
+    };
+
+    /**
+     * Returns an object - a tree of fontName to fontStyle relationships available to
+     * active PDF document.
+     *
+     * @public
+     * @function
+     * @returns {Object} Like {'times':['normal', 'italic', ... ], 'arial':['normal', 'bold', ... ], ... }
+     * @methodOf jsPDF#
+     * @name getFontList
+     */
+    API.getFontList = function () {
+      // TODO: iterate over fonts array or return copy of fontmap instead in case more are ever added.
+      var list = {},
+          fontName,
+          fontStyle,
+          tmp;
+
+      for (fontName in fontmap) {
+        if (fontmap.hasOwnProperty(fontName)) {
+          list[fontName] = tmp = [];
+          for (fontStyle in fontmap[fontName]) {
+            if (fontmap[fontName].hasOwnProperty(fontStyle)) {
+              tmp.push(fontStyle);
+            }
+          }
+        }
+      }
+
+      return list;
+    };
+
+    /**
+     * Add a custom font.
+     *
+     * @param {String} Postscript name of the Font.  Example: "Menlo-Regular"
+     * @param {String} Name of font-family from @font-face definition.  Example: "Menlo Regular"
+     * @param {String} Font style.  Example: "normal"
+     * @function
+     * @returns the {fontKey} (same as the internal method)
+     * @methodOf jsPDF#
+     * @name addFont
+     */
+    API.addFont = function (postScriptName, fontName, fontStyle) {
+      addFont(postScriptName, fontName, fontStyle, 'StandardEncoding');
+    };
+
+    /**
+     * Sets line width for upcoming lines.
+     *
+     * @param {Number} width Line width (in units declared at inception of PDF document)
+     * @function
+     * @returns {jsPDF}
+     * @methodOf jsPDF#
+     * @name setLineWidth
+     */
+    API.setLineWidth = function (width) {
+      out((width * k).toFixed(2) + ' w');
+      return this;
+    };
+
+    /**
+     * Sets the stroke color for upcoming elements.
+     *
+     * Depending on the number of arguments given, Gray, RGB, or CMYK
+     * color space is implied.
+     *
+     * When only ch1 is given, "Gray" color space is implied and it
+     * must be a value in the range from 0.00 (solid black) to to 1.00 (white)
+     * if values are communicated as String types, or in range from 0 (black)
+     * to 255 (white) if communicated as Number type.
+     * The RGB-like 0-255 range is provided for backward compatibility.
+     *
+     * When only ch1,ch2,ch3 are given, "RGB" color space is implied and each
+     * value must be in the range from 0.00 (minimum intensity) to to 1.00
+     * (max intensity) if values are communicated as String types, or
+     * from 0 (min intensity) to to 255 (max intensity) if values are communicated
+     * as Number types.
+     * The RGB-like 0-255 range is provided for backward compatibility.
+     *
+     * When ch1,ch2,ch3,ch4 are given, "CMYK" color space is implied and each
+     * value must be a in the range from 0.00 (0% concentration) to to
+     * 1.00 (100% concentration)
+     *
+     * Because JavaScript treats fixed point numbers badly (rounds to
+     * floating point nearest to binary representation) it is highly advised to
+     * communicate the fractional numbers as String types, not JavaScript Number type.
+     *
+     * @param {Number|String} ch1 Color channel value
+     * @param {Number|String} ch2 Color channel value
+     * @param {Number|String} ch3 Color channel value
+     * @param {Number|String} ch4 Color channel value
+     *
+     * @function
+     * @returns {jsPDF}
+     * @methodOf jsPDF#
+     * @name setDrawColor
+     */
+    API.setDrawColor = function (ch1, ch2, ch3, ch4) {
+      var color;
+      if (ch2 === undefined || ch4 === undefined && ch1 === ch2 === ch3) {
+        // Gray color space.
+        if (typeof ch1 === 'string') {
+          color = ch1 + ' G';
+        } else {
+          color = f2(ch1 / 255) + ' G';
+        }
+      } else if (ch4 === undefined) {
+        // RGB
+        if (typeof ch1 === 'string') {
+          color = [ch1, ch2, ch3, 'RG'].join(' ');
+        } else {
+          color = [f2(ch1 / 255), f2(ch2 / 255), f2(ch3 / 255), 'RG'].join(' ');
+        }
+      } else {
+        // CMYK
+        if (typeof ch1 === 'string') {
+          color = [ch1, ch2, ch3, ch4, 'K'].join(' ');
+        } else {
+          color = [f2(ch1), f2(ch2), f2(ch3), f2(ch4), 'K'].join(' ');
+        }
+      }
+
+      out(color);
+      return this;
+    };
+
+    /**
+     * Sets the fill color for upcoming elements.
+     *
+     * Depending on the number of arguments given, Gray, RGB, or CMYK
+     * color space is implied.
+     *
+     * When only ch1 is given, "Gray" color space is implied and it
+     * must be a value in the range from 0.00 (solid black) to to 1.00 (white)
+     * if values are communicated as String types, or in range from 0 (black)
+     * to 255 (white) if communicated as Number type.
+     * The RGB-like 0-255 range is provided for backward compatibility.
+     *
+     * When only ch1,ch2,ch3 are given, "RGB" color space is implied and each
+     * value must be in the range from 0.00 (minimum intensity) to to 1.00
+     * (max intensity) if values are communicated as String types, or
+     * from 0 (min intensity) to to 255 (max intensity) if values are communicated
+     * as Number types.
+     * The RGB-like 0-255 range is provided for backward compatibility.
+     *
+     * When ch1,ch2,ch3,ch4 are given, "CMYK" color space is implied and each
+     * value must be a in the range from 0.00 (0% concentration) to to
+     * 1.00 (100% concentration)
+     *
+     * Because JavaScript treats fixed point numbers badly (rounds to
+     * floating point nearest to binary representation) it is highly advised to
+     * communicate the fractional numbers as String types, not JavaScript Number type.
+     *
+     * @param {Number|String} ch1 Color channel value
+     * @param {Number|String} ch2 Color channel value
+     * @param {Number|String} ch3 Color channel value
+     * @param {Number|String} ch4 Color channel value
+     *
+     * @function
+     * @returns {jsPDF}
+     * @methodOf jsPDF#
+     * @name setFillColor
+     */
+    API.setFillColor = function (ch1, ch2, ch3, ch4) {
+      var color;
+
+      if (ch2 === undefined || ch4 === undefined && ch1 === ch2 === ch3) {
+        // Gray color space.
+        if (typeof ch1 === 'string') {
+          color = ch1 + ' g';
+        } else {
+          color = f2(ch1 / 255) + ' g';
+        }
+      } else if (ch4 === undefined || (typeof ch4 === 'undefined' ? 'undefined' : _typeof(ch4)) === 'object') {
+        // RGB
+        if (typeof ch1 === 'string') {
+          color = [ch1, ch2, ch3, 'rg'].join(' ');
+        } else {
+          color = [f2(ch1 / 255), f2(ch2 / 255), f2(ch3 / 255), 'rg'].join(' ');
+        }
+        if (ch4 && ch4.a === 0) {
+          //TODO Implement transparency.
+          //WORKAROUND use white for now
+          color = ['255', '255', '255', 'rg'].join(' ');
+        }
+      } else {
+        // CMYK
+        if (typeof ch1 === 'string') {
+          color = [ch1, ch2, ch3, ch4, 'k'].join(' ');
+        } else {
+          color = [f2(ch1), f2(ch2), f2(ch3), f2(ch4), 'k'].join(' ');
+        }
+      }
+
+      out(color);
+      return this;
+    };
+
+    /**
+     * Sets the text color for upcoming elements.
+     * If only one, first argument is given,
+     * treats the value as gray-scale color value.
+     *
+     * @param {Number} r Red channel color value in range 0-255 or {String} r color value in hexadecimal, example: '#FFFFFF'
+     * @param {Number} g Green channel color value in range 0-255
+     * @param {Number} b Blue channel color value in range 0-255
+     * @function
+     * @returns {jsPDF}
+     * @methodOf jsPDF#
+     * @name setTextColor
+     */
+    API.setTextColor = function (r, g, b) {
+      if (typeof r === 'string' && /^#[0-9A-Fa-f]{6}$/.test(r)) {
+        var hex = parseInt(r.substr(1), 16);
+        r = hex >> 16 & 255;
+        g = hex >> 8 & 255;
+        b = hex & 255;
+      }
+
+      if (r === 0 && g === 0 && b === 0 || typeof g === 'undefined') {
+        textColor = f3(r / 255) + ' g';
+      } else {
+        textColor = [f3(r / 255), f3(g / 255), f3(b / 255), 'rg'].join(' ');
+      }
+      return this;
+    };
+
+    /**
+     * Is an Object providing a mapping from human-readable to
+     * integer flag values designating the varieties of line cap
+     * and join styles.
+     *
+     * @returns {Object}
+     * @fieldOf jsPDF#
+     * @name CapJoinStyles
+     */
+    API.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
+    };
+
+    /**
+     * Sets the line cap styles
+     * See {jsPDF.CapJoinStyles} for variants
+     *
+     * @param {String|Number} style A string or number identifying the type of line cap
+     * @function
+     * @returns {jsPDF}
+     * @methodOf jsPDF#
+     * @name setLineCap
+     */
+    API.setLineCap = function (style) {
+      var id = this.CapJoinStyles[style];
+      if (id === undefined) {
+        throw new Error("Line cap style of '" + style + "' is not recognized. See or extend .CapJoinStyles property for valid styles");
+      }
+      lineCapID = id;
+      out(id + ' J');
+
+      return this;
+    };
+
+    /**
+     * Sets the line join styles
+     * See {jsPDF.CapJoinStyles} for variants
+     *
+     * @param {String|Number} style A string or number identifying the type of line join
+     * @function
+     * @returns {jsPDF}
+     * @methodOf jsPDF#
+     * @name setLineJoin
+     */
+    API.setLineJoin = function (style) {
+      var id = this.CapJoinStyles[style];
+      if (id === undefined) {
+        throw new Error("Line join style of '" + style + "' is not recognized. See or extend .CapJoinStyles property for valid styles");
+      }
+      lineJoinID = id;
+      out(id + ' j');
+
+      return this;
+    };
+
+    // Output is both an internal (for plugins) and external function
+    API.output = _output;
+
+    /**
+     * Saves as PDF document. An alias of jsPDF.output('save', 'filename.pdf')
+     * @param  {String} filename The filename including extension.
+     *
+     * @function
+     * @returns {jsPDF}
+     * @methodOf jsPDF#
+     * @name save
+     */
+    API.save = function (filename) {
+      API.output('save', filename);
+    };
+
+    // applying plugins (more methods) ON TOP of built-in API.
+    // this is intentional as we allow plugins to override
+    // built-ins
+    for (var plugin in jsPDF.API) {
+      if (jsPDF.API.hasOwnProperty(plugin)) {
+        if (plugin === 'events' && jsPDF.API.events.length) {
+          (function (events, newEvents) {
+
+            // jsPDF.API.events is a JS Array of Arrays
+            // where each Array is a pair of event name, handler
+            // Events were added by plugins to the jsPDF instantiator.
+            // These are always added to the new instance and some ran
+            // during instantiation.
+            var eventname, handler_and_args, i;
+
+            for (i = newEvents.length - 1; i !== -1; i--) {
+              // subscribe takes 3 args: 'topic', function, runonce_flag
+              // if undefined, runonce is false.
+              // users can attach callback directly,
+              // or they can attach an array with [callback, runonce_flag]
+              // that's what the "apply" magic is for below.
+              eventname = newEvents[i][0];
+              handler_and_args = newEvents[i][1];
+              events.subscribe.apply(events, [eventname].concat(typeof handler_and_args === 'function' ? [handler_and_args] : handler_and_args));
+            }
+          })(events, jsPDF.API.events);
+        } else {
+          API[plugin] = jsPDF.API[plugin];
+        }
+      }
+    }
+
+    //////////////////////////////////////////////////////
+    // continuing initialization of jsPDF Document object
+    //////////////////////////////////////////////////////
+    // Add the first page automatically
+    addFonts();
+    activeFontKey = 'F1';
+    _addPage(format, orientation);
+
+    events.publish('initialized');
+    return API;
+  }
+
+  /**
+   * jsPDF.API is a STATIC property of jsPDF class.
+   * jsPDF.API is an object you can add methods and properties to.
+   * The methods / properties you add will show up in new jsPDF objects.
+   *
+   * One property is prepopulated. It is the 'events' Object. Plugin authors can add topics,
+   * callbacks to this object. These will be reassigned to all new instances of jsPDF.
+   * Examples:
+   * jsPDF.API.events['initialized'] = function(){ 'this' is API object }
+   * jsPDF.API.events['addFont'] = function(added_font_object){ 'this' is API object }
+   *
+   * @static
+   * @public
+   * @memberOf jsPDF
+   * @name API
+   *
+   * @example
+   * jsPDF.API.mymethod = function(){
+   *   // 'this' will be ref to internal API object. see jsPDF source
+   *   // , so you can refer to built-in methods like so:
+   *   //     this.line(....)
+   *   //     this.text(....)
+   * }
+   * var pdfdoc = new jsPDF()
+   * pdfdoc.mymethod() // <- !!!!!!
+   */
+  jsPDF.API = {
+    events: []
+  };
+  jsPDF.version = "1.x-master";
+
+  if (typeof define === 'function' && define.amd) {
+    define('jsPDF', function () {
+      return jsPDF;
+    });
+  } else if (typeof module !== 'undefined' && module.exports) {
+    module.exports = jsPDF;
+  } else {
+    global.jsPDF = jsPDF;
+  }
+  return jsPDF;
+}(typeof self !== "undefined" && self || typeof window !== "undefined" && window || undefined);
+
+
+/**
+ * jsPDF AcroForm Plugin
+ * Copyright (c) 2016 Alexander Weidt, https://github.com/BiggA94
+ *
+ * Licensed under the MIT License.
+ * http://opensource.org/licenses/mit-license
+ */
+
+(window.AcroForm = function (jsPDFAPI) {
+    'use strict';
+
+    var AcroForm = window.AcroForm;
+
+    AcroForm.scale = function (x) {
+        return x * (acroformPlugin.internal.scaleFactor / 1); // 1 = (96 / 72)
+    };
+    AcroForm.antiScale = function (x) {
+        return 1 / acroformPlugin.internal.scaleFactor * x;
+    };
+
+    var acroformPlugin = {
+        fields: [],
+        xForms: [],
+        /**
+         * acroFormDictionaryRoot contains information about the AcroForm Dictionary
+         * 0: The Event-Token, the AcroFormDictionaryCallback has
+         * 1: The Object ID of the Root
+         */
+        acroFormDictionaryRoot: null,
+        /**
+         * After the PDF gets evaluated, the reference to the root has to be reset,
+         * this indicates, whether the root has already been printed out
+         */
+        printedOut: false,
+        internal: null
+    };
+
+    jsPDF.API.acroformPlugin = acroformPlugin;
+
+    var annotReferenceCallback = function annotReferenceCallback() {
+        for (var i in this.acroformPlugin.acroFormDictionaryRoot.Fields) {
+            var formObject = this.acroformPlugin.acroFormDictionaryRoot.Fields[i];
+            // add Annot Reference!
+            if (formObject.hasAnnotation) {
+                // If theres an Annotation Widget in the Form Object, put the Reference in the /Annot array
+                createAnnotationReference.call(this, formObject);
+            }
+        }
+    };
+
+    var createAcroForm = function createAcroForm() {
+        if (this.acroformPlugin.acroFormDictionaryRoot) {
+            //return;
+            throw new Error("Exception while creating AcroformDictionary");
+        }
+
+        // The Object Number of the AcroForm Dictionary
+        this.acroformPlugin.acroFormDictionaryRoot = new AcroForm.AcroFormDictionary();
+
+        this.acroformPlugin.internal = this.internal;
+
+        // add Callback for creating the AcroForm Dictionary
+        this.acroformPlugin.acroFormDictionaryRoot._eventID = this.internal.events.subscribe('postPutResources', AcroFormDictionaryCallback);
+
+        this.internal.events.subscribe('buildDocument', annotReferenceCallback); //buildDocument
+
+        // Register event, that is triggered when the DocumentCatalog is written, in order to add /AcroForm
+        this.internal.events.subscribe('putCatalog', putCatalogCallback);
+
+        // Register event, that creates all Fields
+        this.internal.events.subscribe('postPutPages', createFieldCallback);
+    };
+
+    /**
+     * Create the Reference to the widgetAnnotation, so that it gets referenced in the Annot[] int the+
+     * (Requires the Annotation Plugin)
+     */
+    var createAnnotationReference = function createAnnotationReference(object) {
+        var options = {
+            type: 'reference',
+            object: object
+        };
+        jsPDF.API.annotationPlugin.annotations[this.internal.getPageInfo(object.page).pageNumber].push(options);
+    };
+
+    var putForm = function putForm(formObject) {
+        if (this.acroformPlugin.printedOut) {
+            this.acroformPlugin.printedOut = false;
+            this.acroformPlugin.acroFormDictionaryRoot = null;
+        }
+        if (!this.acroformPlugin.acroFormDictionaryRoot) {
+            createAcroForm.call(this);
+        }
+        this.acroformPlugin.acroFormDictionaryRoot.Fields.push(formObject);
+    };
+
+    // Callbacks
+
+    var putCatalogCallback = function putCatalogCallback() {
+        //Put reference to AcroForm to DocumentCatalog
+        if (typeof this.acroformPlugin.acroFormDictionaryRoot != 'undefined') {
+            // for safety, shouldn't normally be the case
+            this.internal.write('/AcroForm ' + this.acroformPlugin.acroFormDictionaryRoot.objId + ' ' + 0 + ' R');
+        } else {
+            console.log('Root missing...');
+        }
+    };
+
+    /**
+     * Adds /Acroform X 0 R to Document Catalog,
+     * and creates the AcroForm Dictionary
+     */
+    var AcroFormDictionaryCallback = function AcroFormDictionaryCallback() {
+        // Remove event
+        this.internal.events.unsubscribe(this.acroformPlugin.acroFormDictionaryRoot._eventID);
+
+        delete this.acroformPlugin.acroFormDictionaryRoot._eventID;
+
+        this.acroformPlugin.printedOut = true;
+    };
+
+    /**
+     * Creates the single Fields and writes them into the Document
+     *
+     * If fieldArray is set, use the fields that are inside it instead of the fields from the AcroRoot
+     * (for the FormXObjects...)
+     */
+    var createFieldCallback = function createFieldCallback(fieldArray) {
+        var standardFields = !fieldArray;
+
+        if (!fieldArray) {
+            // in case there is no fieldArray specified, we want to print out the Fields of the AcroForm
+            // Print out Root
+            this.internal.newObjectDeferredBegin(this.acroformPlugin.acroFormDictionaryRoot.objId);
+            this.internal.out(this.acroformPlugin.acroFormDictionaryRoot.getString());
+        }
+
+        var fieldArray = fieldArray || this.acroformPlugin.acroFormDictionaryRoot.Kids;
+
+        for (var i in fieldArray) {
+            var key = i;
+            var form = fieldArray[i];
+
+            var oldRect = form.Rect;
+
+            if (form.Rect) {
+                form.Rect = AcroForm.internal.calculateCoordinates.call(this, form.Rect);
+            }
+
+            // Start Writing the Object
+            this.internal.newObjectDeferredBegin(form.objId);
+
+            var content = "";
+            content += form.objId + " 0 obj\n";
+
+            content += "<<\n" + form.getContent();
+
+            form.Rect = oldRect;
+
+            if (form.hasAppearanceStream && !form.appearanceStreamContent) {
+                // Calculate Appearance
+                var appearance = AcroForm.internal.calculateAppearanceStream.call(this, form);
+                content += "/AP << /N " + appearance + " >>\n";
+
+                this.acroformPlugin.xForms.push(appearance);
+            }
+
+            // Assume AppearanceStreamContent is a Array with N,R,D (at least one of them!)
+            if (form.appearanceStreamContent) {
+                content += "/AP << ";
+                // Iterate over N,R and D
+                for (var k in form.appearanceStreamContent) {
+                    var value = form.appearanceStreamContent[k];
+                    content += "/" + k + " ";
+                    content += "<< ";
+                    if (Object.keys(value).length >= 1 || Array.isArray(value)) {
+                        // appearanceStream is an Array or Object!
+                        for (var i in value) {
+                            var obj = value[i];
+                            if (typeof obj === 'function') {
+                                // if Function is referenced, call it in order to get the FormXObject
+                                obj = obj.call(this, form);
+                            }
+                            content += "/" + i + " " + obj + " ";
+
+                            // In case the XForm is already used, e.g. OffState of CheckBoxes, don't add it
+                            if (!(this.acroformPlugin.xForms.indexOf(obj) >= 0)) this.acroformPlugin.xForms.push(obj);
+                        }
+                    } else {
+                        var obj = value;
+                        if (typeof obj === 'function') {
+                            // if Function is referenced, call it in order to get the FormXObject
+                            obj = obj.call(this, form);
+                        }
+                        content += "/" + i + " " + obj + " \n";
+                        if (!(this.acroformPlugin.xForms.indexOf(obj) >= 0)) this.acroformPlugin.xForms.push(obj);
+                    }
+                    content += " >>\n";
+                }
+
+                // appearance stream is a normal Object..
+                content += ">>\n";
+            }
+
+            content += ">>\nendobj\n";
+
+            this.internal.out(content);
+        }
+        if (standardFields) {
+            createXFormObjectCallback.call(this, this.acroformPlugin.xForms);
+        }
+    };
+
+    var createXFormObjectCallback = function createXFormObjectCallback(fieldArray) {
+        for (var i in fieldArray) {
+            var key = i;
+            var form = fieldArray[i];
+            // Start Writing the Object
+            this.internal.newObjectDeferredBegin(form && form.objId);
+
+            var content = "";
+            content += form ? form.getString() : '';
+            this.internal.out(content);
+
+            delete fieldArray[key];
+        }
+    };
+
+    // Public:
+
+    jsPDFAPI.addField = function (fieldObject) {
+        //var opt = parseOptions(fieldObject);
+        if (fieldObject instanceof AcroForm.TextField) {
+            addTextField.call(this, fieldObject);
+        } else if (fieldObject instanceof AcroForm.ChoiceField) {
+            addChoiceField.call(this, fieldObject);
+        } else if (fieldObject instanceof AcroForm.Button) {
+            addButton.call(this, fieldObject);
+        } else if (fieldObject instanceof AcroForm.ChildClass) {
+            putForm.call(this, fieldObject);
+        } else if (fieldObject) {
+            // try to put..
+            putForm.call(this, fieldObject);
+        }
+        fieldObject.page = this.acroformPlugin.internal.getCurrentPageInfo().pageNumber;
+        return this;
+    };
+
+    // ############### sort in:
+
+    /**
+     * Button
+     * FT = Btn
+     */
+    var addButton = function addButton(options) {
+        var options = options || new AcroForm.Field();
+
+        options.FT = '/Btn';
+
+        /**
+         * Calculating the Ff entry:
+         *
+         * The Ff entry contains flags, that have to be set bitwise
+         * In the Following the number in the Comment is the BitPosition
+         */
+        var flags = options.Ff || 0;
+
+        // 17, Pushbutton
+        if (options.pushbutton) {
+            // Options.pushbutton should be 1 or 0
+            flags = AcroForm.internal.setBitPosition(flags, 17);
+            delete options.pushbutton;
+        }
+
+        //16, Radio
+        if (options.radio) {
+            //flags = options.Ff | options.radio << 15;
+            flags = AcroForm.internal.setBitPosition(flags, 16);
+            delete options.radio;
+        }
+
+        // 15, NoToggleToOff (Radio buttons only
+        if (options.noToggleToOff) {
+            //flags = options.Ff | options.noToggleToOff << 14;
+            flags = AcroForm.internal.setBitPosition(flags, 15);
+            //delete options.noToggleToOff;
+        }
+
+        // In case, there is no Flag set, it is a check-box
+        options.Ff = flags;
+
+        putForm.call(this, options);
+    };
+
+    var addTextField = function addTextField(options) {
+        var options = options || new AcroForm.Field();
+
+        options.FT = '/Tx';
+
+        /**
+         * Calculating the Ff entry:
+         *
+         * The Ff entry contains flags, that have to be set bitwise
+         * In the Following the number in the Comment is the BitPosition
+         */
+
+        var flags = options.Ff || 0;
+
+        // 13, multiline
+        if (options.multiline) {
+            // Set Flag
+            flags = flags | 1 << 12;
+            // Remove multiline from FieldObject
+            //delete options.multiline;
+        }
+
+        // 14, Password
+        if (options.password) {
+            flags = flags | 1 << 13;
+            //delete options.password;
+        }
+
+        // 21, FileSelect, PDF 1.4...
+        if (options.fileSelect) {
+            flags = flags | 1 << 20;
+            //delete options.fileSelect;
+        }
+
+        // 23, DoNotSpellCheck, PDF 1.4...
+        if (options.doNotSpellCheck) {
+            flags = flags | 1 << 22;
+            //delete options.doNotSpellCheck;
+        }
+
+        // 24, DoNotScroll, PDF 1.4...
+        if (options.doNotScroll) {
+            flags = flags | 1 << 23;
+            //delete options.doNotScroll;
+        }
+
+        options.Ff = options.Ff || flags;
+
+        // Add field
+        putForm.call(this, options);
+    };
+
+    var addChoiceField = function addChoiceField(opt) {
+        var options = opt || new AcroForm.Field();
+
+        options.FT = '/Ch';
+
+        /**
+         * Calculating the Ff entry:
+         *
+         * The Ff entry contains flags, that have to be set bitwise
+         * In the Following the number in the Comment is the BitPosition
+         */
+
+        var flags = options.Ff || 0;
+
+        // 18, Combo (If not set, the choiceField is a listBox!!)
+        if (options.combo) {
+            // Set Flag
+            flags = AcroForm.internal.setBitPosition(flags, 18);
+            // Remove combo from FieldObject
+            delete options.combo;
+        }
+
+        // 19, Edit
+        if (options.edit) {
+            flags = AcroForm.internal.setBitPosition(flags, 19);
+            delete options.edit;
+        }
+
+        // 20, Sort
+        if (options.sort) {
+            flags = AcroForm.internal.setBitPosition(flags, 20);
+            delete options.sort;
+        }
+
+        // 22, MultiSelect (PDF 1.4)
+        if (options.multiSelect && this.internal.getPDFVersion() >= 1.4) {
+            flags = AcroForm.internal.setBitPosition(flags, 22);
+            delete options.multiSelect;
+        }
+
+        // 23, DoNotSpellCheck (PDF 1.4)
+        if (options.doNotSpellCheck && this.internal.getPDFVersion() >= 1.4) {
+            flags = AcroForm.internal.setBitPosition(flags, 23);
+            delete options.doNotSpellCheck;
+        }
+
+        options.Ff = flags;
+
+        //options.hasAnnotation = true;
+
+        // Add field
+        putForm.call(this, options);
+    };
+})(jsPDF.API);
+
+var AcroForm = window.AcroForm;
+
+AcroForm.internal = {};
+
+AcroForm.createFormXObject = function (formObject) {
+    var xobj = new AcroForm.FormXObject();
+    var height = AcroForm.Appearance.internal.getHeight(formObject) || 0;
+    var width = AcroForm.Appearance.internal.getWidth(formObject) || 0;
+    xobj.BBox = [0, 0, width, height];
+    return xobj;
+};
+
+// Contains Methods for creating standard appearances
+AcroForm.Appearance = {
+    CheckBox: {
+        createAppearanceStream: function createAppearanceStream() {
+            var appearance = {
+                N: {
+                    On: AcroForm.Appearance.CheckBox.YesNormal
+                },
+                D: {
+                    On: AcroForm.Appearance.CheckBox.YesPushDown,
+                    Off: AcroForm.Appearance.CheckBox.OffPushDown
+                }
+            };
+
+            return appearance;
+        },
+        /**
+         * If any other icons are needed, the number between the brackets can be changed
+         * @returns {string}
+         */
+        createMK: function createMK() {
+            // 3-> Hook
+            return "<< /CA (3)>>";
+        },
+        /**
+         * Returns the standard On Appearance for a CheckBox
+         * @returns {AcroForm.FormXObject}
+         */
+        YesPushDown: function YesPushDown(formObject) {
+            var xobj = AcroForm.createFormXObject(formObject);
+            var stream = "";
+            // F13 is ZapfDingbats (Symbolic)
+            formObject.Q = 1; // set text-alignment as centered
+            var calcRes = AcroForm.internal.calculateX(formObject, "3", "ZapfDingbats", 50);
+            stream += "0.749023 g\n\
+             0 0 " + AcroForm.Appearance.internal.getWidth(formObject) + " " + AcroForm.Appearance.internal.getHeight(formObject) + " re\n\
+             f\n\
+             BMC\n\
+             q\n\
+             0 0 1 rg\n\
+             /F13 " + calcRes.fontSize + " Tf 0 g\n\
+             BT\n";
+            stream += calcRes.text;
+            stream += "ET\n\
+             Q\n\
+             EMC\n";
+            xobj.stream = stream;
+            return xobj;
+        },
+
+        YesNormal: function YesNormal(formObject) {
+            var xobj = AcroForm.createFormXObject(formObject);
+            var stream = "";
+            formObject.Q = 1; // set text-alignment as centered
+            var calcRes = AcroForm.internal.calculateX(formObject, "3", "ZapfDingbats", AcroForm.Appearance.internal.getHeight(formObject) * 0.9);
+            stream += "1 g\n\
+0 0 " + AcroForm.Appearance.internal.getWidth(formObject) + " " + AcroForm.Appearance.internal.getHeight(formObject) + " re\n\
+f\n\
+q\n\
+0 0 1 rg\n\
+0 0 " + (AcroForm.Appearance.internal.getWidth(formObject) - 1) + " " + (AcroForm.Appearance.internal.getHeight(formObject) - 1) + " re\n\
+W\n\
+n\n\
+0 g\n\
+BT\n\
+/F13 " + calcRes.fontSize + " Tf 0 g\n";
+            stream += calcRes.text;
+            stream += "ET\n\
+             Q\n";
+            xobj.stream = stream;
+            return xobj;
+        },
+
+        /**
+         * Returns the standard Off Appearance for a CheckBox
+         * @returns {AcroForm.FormXObject}
+         */
+        OffPushDown: function OffPushDown(formObject) {
+            var xobj = AcroForm.createFormXObject(formObject);
+            var stream = "";
+            stream += "0.749023 g\n\
+            0 0 " + AcroForm.Appearance.internal.getWidth(formObject) + " " + AcroForm.Appearance.internal.getHeight(formObject) + " re\n\
+            f\n";
+            xobj.stream = stream;
+            return xobj;
+        }
+    },
+
+    RadioButton: {
+        Circle: {
+            createAppearanceStream: function createAppearanceStream(name) {
+                var appearanceStreamContent = {
+                    D: {
+                        'Off': AcroForm.Appearance.RadioButton.Circle.OffPushDown
+                    },
+                    N: {}
+                };
+                appearanceStreamContent.N[name] = AcroForm.Appearance.RadioButton.Circle.YesNormal;
+                appearanceStreamContent.D[name] = AcroForm.Appearance.RadioButton.Circle.YesPushDown;
+                return appearanceStreamContent;
+            },
+            createMK: function createMK() {
+                return "<< /CA (l)>>";
+            },
+
+            YesNormal: function YesNormal(formObject) {
+                var xobj = AcroForm.createFormXObject(formObject);
+                var stream = "";
+                // Make the Radius of the Circle relative to min(height, width) of formObject
+                var DotRadius = AcroForm.Appearance.internal.getWidth(formObject) <= AcroForm.Appearance.internal.getHeight(formObject) ? AcroForm.Appearance.internal.getWidth(formObject) / 4 : AcroForm.Appearance.internal.getHeight(formObject) / 4;
+                // The Borderpadding...
+                DotRadius *= 0.9;
+                var c = AcroForm.Appearance.internal.Bezier_C;
+                /*
+                 The Following is a Circle created with Bezier-Curves.
+                 */
+                stream += "q\n\
+1 0 0 1 " + AcroForm.Appearance.internal.getWidth(formObject) / 2 + " " + AcroForm.Appearance.internal.getHeight(formObject) / 2 + " cm\n\
+" + DotRadius + " 0 m\n\
+" + DotRadius + " " + DotRadius * c + " " + DotRadius * c + " " + DotRadius + " 0 " + DotRadius + " c\n\
+-" + DotRadius * c + " " + DotRadius + " -" + DotRadius + " " + DotRadius * c + " -" + DotRadius + " 0 c\n\
+-" + DotRadius + " -" + DotRadius * c + " -" + DotRadius * c + " -" + DotRadius + " 0 -" + DotRadius + " c\n\
+" + DotRadius * c + " -" + DotRadius + " " + DotRadius + " -" + DotRadius * c + " " + DotRadius + " 0 c\n\
+f\n\
+Q\n";
+                xobj.stream = stream;
+                return xobj;
+            },
+            YesPushDown: function YesPushDown(formObject) {
+                var xobj = AcroForm.createFormXObject(formObject);
+                var stream = "";
+                var DotRadius = AcroForm.Appearance.internal.getWidth(formObject) <= AcroForm.Appearance.internal.getHeight(formObject) ? AcroForm.Appearance.internal.getWidth(formObject) / 4 : AcroForm.Appearance.internal.getHeight(formObject) / 4;
+                // The Borderpadding...
+                DotRadius *= 0.9;
+                // Save results for later use; no need to waste processor ticks on doing math
+                var k = DotRadius * 2;
+                // var c = AcroForm.Appearance.internal.Bezier_C;
+                var kc = k * AcroForm.Appearance.internal.Bezier_C;
+                var dc = DotRadius * AcroForm.Appearance.internal.Bezier_C;
+                //                 stream += "0.749023 g\n\
+                //             q\n\
+                //           1 0 0 1 " + AcroForm.Appearance.internal.getWidth(formObject) / 2 + " " + AcroForm.Appearance.internal.getHeight(formObject) / 2 + " cm\n\
+                // " + DotRadius * 2 + " 0 m\n\
+                // " + DotRadius * 2 + " " + DotRadius * 2 * c + " " + DotRadius * 2 * c + " " + DotRadius * 2 + " 0 " + DotRadius * 2 + " c\n\
+                // -" + DotRadius * 2 * c + " " + DotRadius * 2 + " -" + DotRadius * 2 + " " + DotRadius * 2 * c + " -" + DotRadius * 2 + " 0 c\n\
+                // -" + DotRadius * 2 + " -" + DotRadius * 2 * c + " -" + DotRadius * 2 * c + " -" + DotRadius * 2 + " 0 -" + DotRadius * 2 + " c\n\
+                // " + DotRadius * 2 * c + " -" + DotRadius * 2 + " " + DotRadius * 2 + " -" + DotRadius * 2 * c + " " + DotRadius * 2 + " 0 c\n\
+                //             f\n\
+                //             Q\n\
+                //             0 g\n\
+                //             q\n\
+                //             1 0 0 1 " + AcroForm.Appearance.internal.getWidth(formObject) / 2 + " " + AcroForm.Appearance.internal.getHeight(formObject) / 2 + " cm\n\
+                // " + DotRadius + " 0 m\n\
+                // " + DotRadius + " " + DotRadius * c + " " + DotRadius * c + " " + DotRadius + " 0 " + DotRadius + " c\n\
+                // -" + DotRadius * c + " " + DotRadius + " -" + DotRadius + " " + DotRadius * c + " -" + DotRadius + " 0 c\n\
+                // -" + DotRadius + " -" + DotRadius * c + " -" + DotRadius * c + " -" + DotRadius + " 0 -" + DotRadius + " c\n\
+                // " + DotRadius * c + " -" + DotRadius + " " + DotRadius + " -" + DotRadius * c + " " + DotRadius + " 0 c\n\
+                //             f\n\
+                //             Q\n";
+
+                //  FASTER VERSION with less processor ticks spent on math operations
+                stream += "0.749023 g\n\
+            q\n\
+           1 0 0 1 " + AcroForm.Appearance.internal.getWidth(formObject) / 2 + " " + AcroForm.Appearance.internal.getHeight(formObject) / 2 + " cm\n\
+" + k + " 0 m\n\
+" + k + " " + kc + " " + kc + " " + k + " 0 " + k + " c\n\
+-" + kc + " " + k + " -" + k + " " + kc + " -" + k + " 0 c\n\
+-" + k + " -" + kc + " -" + kc + " -" + k + " 0 -" + k + " c\n\
+" + kc + " -" + k + " " + k + " -" + kc + " " + k + " 0 c\n\
+            f\n\
+            Q\n\
+            0 g\n\
+            q\n\
+            1 0 0 1 " + AcroForm.Appearance.internal.getWidth(formObject) / 2 + " " + AcroForm.Appearance.internal.getHeight(formObject) / 2 + " cm\n\
+" + DotRadius + " 0 m\n\
+" + DotRadius + " " + dc + " " + dc + " " + DotRadius + " 0 " + DotRadius + " c\n\
+-" + dc + " " + DotRadius + " -" + DotRadius + " " + dc + " -" + DotRadius + " 0 c\n\
+-" + DotRadius + " -" + dc + " -" + dc + " -" + DotRadius + " 0 -" + DotRadius + " c\n\
+" + dc + " -" + DotRadius + " " + DotRadius + " -" + dc + " " + DotRadius + " 0 c\n\
+            f\n\
+            Q\n";
+                xobj.stream = stream;
+                return xobj;
+            },
+            OffPushDown: function OffPushDown(formObject) {
+                var xobj = AcroForm.createFormXObject(formObject);
+                var stream = "";
+                var DotRadius = AcroForm.Appearance.internal.getWidth(formObject) <= AcroForm.Appearance.internal.getHeight(formObject) ? AcroForm.Appearance.internal.getWidth(formObject) / 4 : AcroForm.Appearance.internal.getHeight(formObject) / 4;
+                // The Borderpadding...
+                DotRadius *= 0.9;
+                // Save results for later use; no need to waste processor ticks on doing math
+                var k = DotRadius * 2;
+                // var c = AcroForm.Appearance.internal.Bezier_C;
+                var kc = k * AcroForm.Appearance.internal.Bezier_C;
+                //                 stream += "0.749023 g\n\
+                //             q\n\
+                //  1 0 0 1 " + AcroForm.Appearance.internal.getWidth(formObject) / 2 + " " + AcroForm.Appearance.internal.getHeight(formObject) / 2 + " cm\n\
+                // " + DotRadius * 2 + " 0 m\n\
+                // " + DotRadius * 2 + " " + DotRadius * 2 * c + " " + DotRadius * 2 * c + " " + DotRadius * 2 + " 0 " + DotRadius * 2 + " c\n\
+                // -" + DotRadius * 2 * c + " " + DotRadius * 2 + " -" + DotRadius * 2 + " " + DotRadius * 2 * c + " -" + DotRadius * 2 + " 0 c\n\
+                // -" + DotRadius * 2 + " -" + DotRadius * 2 * c + " -" + DotRadius * 2 * c + " -" + DotRadius * 2 + " 0 -" + DotRadius * 2 + " c\n\
+                // " + DotRadius * 2 * c + " -" + DotRadius * 2 + " " + DotRadius * 2 + " -" + DotRadius * 2 * c + " " + DotRadius * 2 + " 0 c\n\
+                //             f\n\
+                //             Q\n";
+
+                //  FASTER VERSION with less processor ticks spent on math operations
+                stream += "0.749023 g\n\
+            q\n\
+ 1 0 0 1 " + AcroForm.Appearance.internal.getWidth(formObject) / 2 + " " + AcroForm.Appearance.internal.getHeight(formObject) / 2 + " cm\n\
+" + k + " 0 m\n\
+" + k + " " + kc + " " + kc + " " + k + " 0 " + k + " c\n\
+-" + kc + " " + k + " -" + k + " " + kc + " -" + k + " 0 c\n\
+-" + k + " -" + kc + " -" + kc + " -" + k + " 0 -" + k + " c\n\
+" + kc + " -" + k + " " + k + " -" + kc + " " + k + " 0 c\n\
+            f\n\
+            Q\n";
+                xobj.stream = stream;
+                return xobj;
+            }
+        },
+
+        Cross: {
+            /**
+             * Creates the Actual AppearanceDictionary-References
+             * @param name
+             * @returns
+             */
+            createAppearanceStream: function createAppearanceStream(name) {
+                var appearanceStreamContent = {
+                    D: {
+                        'Off': AcroForm.Appearance.RadioButton.Cross.OffPushDown
+                    },
+                    N: {}
+                };
+                appearanceStreamContent.N[name] = AcroForm.Appearance.RadioButton.Cross.YesNormal;
+                appearanceStreamContent.D[name] = AcroForm.Appearance.RadioButton.Cross.YesPushDown;
+                return appearanceStreamContent;
+            },
+            createMK: function createMK() {
+                return "<< /CA (8)>>";
+            },
+
+            YesNormal: function YesNormal(formObject) {
+                var xobj = AcroForm.createFormXObject(formObject);
+                var stream = "";
+                var cross = AcroForm.Appearance.internal.calculateCross(formObject);
+                stream += "q\n\
+            1 1 " + (AcroForm.Appearance.internal.getWidth(formObject) - 2) + " " + (AcroForm.Appearance.internal.getHeight(formObject) - 2) + " re\n\
+            W\n\
+            n\n\
+            " + cross.x1.x + " " + cross.x1.y + " m\n\
+            " + cross.x2.x + " " + cross.x2.y + " l\n\
+            " + cross.x4.x + " " + cross.x4.y + " m\n\
+            " + cross.x3.x + " " + cross.x3.y + " l\n\
+            s\n\
+            Q\n";
+                xobj.stream = stream;
+                return xobj;
+            },
+            YesPushDown: function YesPushDown(formObject) {
+                var xobj = AcroForm.createFormXObject(formObject);
+                var cross = AcroForm.Appearance.internal.calculateCross(formObject);
+                var stream = "";
+                stream += "0.749023 g\n\
+            0 0 " + AcroForm.Appearance.internal.getWidth(formObject) + " " + AcroForm.Appearance.internal.getHeight(formObject) + " re\n\
+            f\n\
+            q\n\
+            1 1 " + (AcroForm.Appearance.internal.getWidth(formObject) - 2) + " " + (AcroForm.Appearance.internal.getHeight(formObject) - 2) + " re\n\
+            W\n\
+            n\n\
+            " + cross.x1.x + " " + cross.x1.y + " m\n\
+            " + cross.x2.x + " " + cross.x2.y + " l\n\
+            " + cross.x4.x + " " + cross.x4.y + " m\n\
+            " + cross.x3.x + " " + cross.x3.y + " l\n\
+            s\n\
+            Q\n";
+                xobj.stream = stream;
+                return xobj;
+            },
+            OffPushDown: function OffPushDown(formObject) {
+                var xobj = AcroForm.createFormXObject(formObject);
+                var stream = "";
+                stream += "0.749023 g\n\
+            0 0 " + AcroForm.Appearance.internal.getWidth(formObject) + " " + AcroForm.Appearance.internal.getHeight(formObject) + " re\n\
+            f\n";
+                xobj.stream = stream;
+                return xobj;
+            }
+        }
+    },
+
+    /**
+     * Returns the standard Appearance
+     * @returns {AcroForm.FormXObject}
+     */
+    createDefaultAppearanceStream: function createDefaultAppearanceStream(formObject) {
+        var stream = "";
+        // Set Helvetica to Standard Font (size: auto)
+        // Color: Black
+        stream += "/Helv 0 Tf 0 g";
+        return stream;
+    }
+};
+
+AcroForm.Appearance.internal = {
+    Bezier_C: 0.551915024494,
+
+    calculateCross: function calculateCross(formObject) {
+        var min = function min(x, y) {
+            return x > y ? y : x;
+        };
+
+        var width = AcroForm.Appearance.internal.getWidth(formObject);
+        var height = AcroForm.Appearance.internal.getHeight(formObject);
+        var a = min(width, height);
+        var crossSize = a;
+        var borderPadding = 2; // The Padding in px
+
+
+        var cross = {
+            x1: { // upperLeft
+                x: (width - a) / 2,
+                y: (height - a) / 2 + a },
+            x2: { // lowerRight
+                x: (width - a) / 2 + a,
+                y: (height - a) / 2 //borderPadding
+            },
+            x3: { // lowerLeft
+                x: (width - a) / 2,
+                y: (height - a) / 2 //borderPadding
+            },
+            x4: { // upperRight
+                x: (width - a) / 2 + a,
+                y: (height - a) / 2 + a }
+        };
+
+        return cross;
+    }
+};
+AcroForm.Appearance.internal.getWidth = function (formObject) {
+    return formObject.Rect[2]; //(formObject.Rect[2] - formObject.Rect[0]) || 0;
+};
+AcroForm.Appearance.internal.getHeight = function (formObject) {
+    return formObject.Rect[3]; //(formObject.Rect[1] - formObject.Rect[3]) || 0;
+};
+
+// ##########################
+
+//### For inheritance:
+AcroForm.internal.inherit = function (child, parent) {
+    var ObjectCreate = Object.create || function (o) {
+        var F = function F() {};
+        F.prototype = o;
+        return new F();
+    };
+    child.prototype = Object.create(parent.prototype);
+    child.prototype.constructor = child;
+};
+
+// ### Handy Functions:
+
+AcroForm.internal.arrayToPdfArray = function (array) {
+    if (Array.isArray(array)) {
+        var content = ' [';
+        for (var i in array) {
+            var element = array[i].toString();
+            content += element;
+            content += i < array.length - 1 ? ' ' : '';
+        }
+        content += ']';
+
+        return content;
+    }
+};
+
+AcroForm.internal.toPdfString = function (string) {
+    string = string || "";
+
+    // put Bracket at the Beginning of the String
+    if (string.indexOf('(') !== 0) {
+        string = '(' + string;
+    }
+
+    if (string.substring(string.length - 1) != ')') {
+        string += '(';
+    }
+    return string;
+};
+
+// ##########################
+//          Classes
+// ##########################
+
+
+AcroForm.PDFObject = function () {
+    // The Object ID in the PDF Object Model
+    // todo
+    var _objId;
+    Object.defineProperty(this, 'objId', {
+        get: function get() {
+            if (!_objId) {
+                if (this.internal) {
+                    _objId = this.internal.newObjectDeferred();
+                } else if (jsPDF.API.acroformPlugin.internal) {
+                    // todo - find better option, that doesn't rely on a Global Static var
+                    _objId = jsPDF.API.acroformPlugin.internal.newObjectDeferred();
+                }
+            }
+            if (!_objId) {
+                console.log("Couldn't create Object ID");
+            }
+            return _objId;
+        },
+        configurable: false
+    });
+};
+
+AcroForm.PDFObject.prototype.toString = function () {
+    return this.objId + " 0 R";
+};
+
+AcroForm.PDFObject.prototype.getString = function () {
+    var res = this.objId + " 0 obj\n<<";
+    var content = this.getContent();
+
+    res += content + ">>\n";
+    if (this.stream) {
+        res += "stream\n";
+        res += this.stream;
+        res += "endstream\n";
+    }
+    res += "endobj\n";
+    return res;
+};
+
+AcroForm.PDFObject.prototype.getContent = function () {
+    /**
+     * Prints out all enumerable Variables from the Object
+     * @param fieldObject
+     * @returns {string}
+     */
+    var createContentFromFieldObject = function createContentFromFieldObject(fieldObject) {
+        var content = '';
+
+        var keys = Object.keys(fieldObject).filter(function (key) {
+            return key != 'content' && key != 'appearanceStreamContent' && key.substring(0, 1) != "_";
+        });
+
+        for (var i in keys) {
+            var key = keys[i];
+            var value = fieldObject[key];
+
+            /*if (key == 'Rect' && value) {
+             value = AcroForm.internal.calculateCoordinates.call(jsPDF.API.acroformPlugin.internal, value);
+             }*/
+
+            if (value) {
+                if (Array.isArray(value)) {
+                    content += '/' + key + ' ' + AcroForm.internal.arrayToPdfArray(value) + "\n";
+                } else if (value instanceof AcroForm.PDFObject) {
+                    // In case it is a reference to another PDFObject, take the referennce number
+                    content += '/' + key + ' ' + value.objId + " 0 R" + "\n";
+                } else {
+                    content += '/' + key + ' ' + value + '\n';
+                }
+            }
+        }
+        return content;
+    };
+
+    var object = "";
+
+    object += createContentFromFieldObject(this);
+    return object;
+};
+
+AcroForm.FormXObject = function () {
+    AcroForm.PDFObject.call(this);
+    this.Type = "/XObject";
+    this.Subtype = "/Form";
+    this.FormType = 1;
+    this.BBox;
+    this.Matrix;
+    this.Resources = "2 0 R";
+    this.PieceInfo;
+    var _stream;
+    Object.defineProperty(this, 'Length', {
+        enumerable: true,
+        get: function get() {
+            return _stream !== undefined ? _stream.length : 0;
+        }
+    });
+    Object.defineProperty(this, 'stream', {
+        enumerable: false,
+        set: function set(val) {
+            _stream = val;
+        },
+        get: function get() {
+            if (_stream) {
+                return _stream;
+            } else {
+                return null;
+            }
+        }
+    });
+};
+
+AcroForm.internal.inherit(AcroForm.FormXObject, AcroForm.PDFObject);
+
+AcroForm.AcroFormDictionary = function () {
+    AcroForm.PDFObject.call(this);
+    var _Kids = [];
+    Object.defineProperty(this, 'Kids', {
+        enumerable: false,
+        configurable: true,
+        get: function get() {
+            if (_Kids.length > 0) {
+                return _Kids;
+            } else {
+                return;
+            }
+        }
+    });
+    Object.defineProperty(this, 'Fields', {
+        enumerable: true,
+        configurable: true,
+        get: function get() {
+            return _Kids;
+        }
+    });
+    // Default Appearance
+    this.DA;
+};
+
+AcroForm.internal.inherit(AcroForm.AcroFormDictionary, AcroForm.PDFObject);
+
+// ##### The Objects, the User can Create:
+
+
+// The Field Object contains the Variables, that every Field needs
+// Rectangle for Appearance: lower_left_X, lower_left_Y, width, height
+AcroForm.Field = function () {
+    'use strict';
+
+    AcroForm.PDFObject.call(this);
+
+    var _Rect;
+    Object.defineProperty(this, 'Rect', {
+        enumerable: true,
+        configurable: false,
+        get: function get() {
+            if (!_Rect) {
+                return;
+            }
+            var tmp = _Rect;
+            //var calculatedRes = AcroForm.internal.calculateCoordinates(_Rect); // do later!
+            return tmp;
+        },
+        set: function set(val) {
+            _Rect = val;
+        }
+    });
+
+    var _FT = "";
+    Object.defineProperty(this, 'FT', {
+        enumerable: true,
+        set: function set(val) {
+            _FT = val;
+        },
+        get: function get() {
+            return _FT;
+        }
+    });
+    /**
+     * The Partial name of the Field Object.
+     * It has to be unique.
+     */
+    var _T;
+
+    Object.defineProperty(this, 'T', {
+        enumerable: true,
+        configurable: false,
+        set: function set(val) {
+            _T = val;
+        },
+        get: function get() {
+            if (!_T || _T.length < 1) {
+                if (this instanceof AcroForm.ChildClass) {
+                    // In case of a Child from a Radio´Group, you don't need a FieldName!!!
+                    return;
+                }
+                return "(FieldObject" + AcroForm.Field.FieldNum++ + ")";
+            }
+            if (_T.substring(0, 1) == "(" && _T.substring(_T.length - 1)) {
+                return _T;
+            }
+            return "(" + _T + ")";
+        }
+    });
+
+    var _DA;
+    // Defines the default appearance (Needed for variable Text)
+    Object.defineProperty(this, 'DA', {
+        enumerable: true,
+        get: function get() {
+            if (!_DA) {
+                return;
+            }
+            return '(' + _DA + ')';
+        },
+        set: function set(val) {
+            _DA = val;
+        }
+    });
+
+    var _DV;
+    // Defines the default value
+    Object.defineProperty(this, 'DV', {
+        enumerable: true,
+        configurable: true,
+        get: function get() {
+            if (!_DV) {
+                return;
+            }
+            return _DV;
+        },
+        set: function set(val) {
+            _DV = val;
+        }
+    });
+
+    //this.Type = "/Annot";
+    //this.Subtype = "/Widget";
+    Object.defineProperty(this, 'Type', {
+        enumerable: true,
+        get: function get() {
+            return this.hasAnnotation ? "/Annot" : null;
+        }
+    });
+
+    Object.defineProperty(this, 'Subtype', {
+        enumerable: true,
+        get: function get() {
+            return this.hasAnnotation ? "/Widget" : null;
+        }
+    });
+
+    /**
+     *
+     * @type {Array}
+     */
+    this.BG;
+
+    Object.defineProperty(this, 'hasAnnotation', {
+        enumerable: false,
+        get: function get() {
+            if (this.Rect || this.BC || this.BG) {
+                return true;
+            }
+            return false;
+        }
+    });
+
+    Object.defineProperty(this, 'hasAppearanceStream', {
+        enumerable: false,
+        configurable: true,
+        writable: true
+    });
+
+    Object.defineProperty(this, 'page', {
+        enumerable: false,
+        configurable: true,
+        writable: true
+    });
+};
+AcroForm.Field.FieldNum = 0;
+
+AcroForm.internal.inherit(AcroForm.Field, AcroForm.PDFObject);
+
+AcroForm.ChoiceField = function () {
+    AcroForm.Field.call(this);
+    // Field Type = Choice Field
+    this.FT = "/Ch";
+    // options
+    this.Opt = [];
+    this.V = '()';
+    // Top Index
+    this.TI = 0;
+    /**
+     * Defines, whether the
+     * @type {boolean}
+     */
+    this.combo = false;
+    /**
+     * Defines, whether the Choice Field is an Edit Field.
+     * An Edit Field is automatically an Combo Field.
+     */
+    Object.defineProperty(this, 'edit', {
+        enumerable: true,
+        set: function set(val) {
+            if (val == true) {
+                this._edit = true;
+                // ComboBox has to be true
+                this.combo = true;
+            } else {
+                this._edit = false;
+            }
+        },
+        get: function get() {
+            if (!this._edit) {
+                return false;
+            }
+            return this._edit;
+        },
+        configurable: false
+    });
+    this.hasAppearanceStream = true;
+    Object.defineProperty(this, 'V', {
+        get: function get() {
+            AcroForm.internal.toPdfString();
+        }
+    });
+};
+AcroForm.internal.inherit(AcroForm.ChoiceField, AcroForm.Field);
+window["ChoiceField"] = AcroForm.ChoiceField;
+
+AcroForm.ListBox = function () {
+    AcroForm.ChoiceField.call(this);
+    //var combo = true;
+};
+AcroForm.internal.inherit(AcroForm.ListBox, AcroForm.ChoiceField);
+window["ListBox"] = AcroForm.ListBox;
+
+AcroForm.ComboBox = function () {
+    AcroForm.ListBox.call(this);
+    this.combo = true;
+};
+AcroForm.internal.inherit(AcroForm.ComboBox, AcroForm.ListBox);
+window["ComboBox"] = AcroForm.ComboBox;
+
+AcroForm.EditBox = function () {
+    AcroForm.ComboBox.call(this);
+    this.edit = true;
+};
+AcroForm.internal.inherit(AcroForm.EditBox, AcroForm.ComboBox);
+window["EditBox"] = AcroForm.EditBox;
+
+AcroForm.Button = function () {
+    AcroForm.Field.call(this);
+    this.FT = "/Btn";
+    //this.hasAnnotation = true;
+};
+AcroForm.internal.inherit(AcroForm.Button, AcroForm.Field);
+window["Button"] = AcroForm.Button;
+
+AcroForm.PushButton = function () {
+    AcroForm.Button.call(this);
+    this.pushbutton = true;
+};
+AcroForm.internal.inherit(AcroForm.PushButton, AcroForm.Button);
+window["PushButton"] = AcroForm.PushButton;
+
+AcroForm.RadioButton = function () {
+    AcroForm.Button.call(this);
+    this.radio = true;
+    var _Kids = [];
+    Object.defineProperty(this, 'Kids', {
+        enumerable: true,
+        get: function get() {
+            if (_Kids.length > 0) {
+                return _Kids;
+            }
+        }
+    });
+
+    Object.defineProperty(this, '__Kids', {
+        get: function get() {
+            return _Kids;
+        }
+    });
+
+    var _noToggleToOff;
+
+    Object.defineProperty(this, 'noToggleToOff', {
+        enumerable: false,
+        get: function get() {
+            return _noToggleToOff;
+        },
+        set: function set(val) {
+            _noToggleToOff = val;
+        }
+    });
+
+    //this.hasAnnotation = false;
+};
+AcroForm.internal.inherit(AcroForm.RadioButton, AcroForm.Button);
+window["RadioButton"] = AcroForm.RadioButton;
+
+/*
+ * The Child classs of a RadioButton (the radioGroup)
+ * -> The single Buttons
+ */
+AcroForm.ChildClass = function (parent, name) {
+    AcroForm.Field.call(this);
+    this.Parent = parent;
+
+    // todo: set AppearanceType as variable that can be set from the outside...
+    this._AppearanceType = AcroForm.Appearance.RadioButton.Circle; // The Default appearanceType is the Circle
+    this.appearanceStreamContent = this._AppearanceType.createAppearanceStream(name);
+
+    // Set Print in the Annot Flag
+    this.F = AcroForm.internal.setBitPosition(this.F, 3, 1);
+
+    // Set AppearanceCharacteristicsDictionary with default appearance if field is not interacting with user
+    this.MK = this._AppearanceType.createMK(); // (8) -> Cross, (1)-> Circle, ()-> nothing
+
+    // Default Appearance is Off
+    this.AS = "/Off"; // + name;
+
+    this._Name = name;
+};
+AcroForm.internal.inherit(AcroForm.ChildClass, AcroForm.Field);
+
+AcroForm.RadioButton.prototype.setAppearance = function (appearance) {
+    if (!('createAppearanceStream' in appearance && 'createMK' in appearance)) {
+        console.log("Couldn't assign Appearance to RadioButton. Appearance was Invalid!");
+        return;
+    }
+    for (var i in this.__Kids) {
+        var child = this.__Kids[i];
+
+        child.appearanceStreamContent = appearance.createAppearanceStream(child._Name);
+        child.MK = appearance.createMK();
+    }
+};
+
+AcroForm.RadioButton.prototype.createOption = function (name) {
+    var parent = this;
+    var kidCount = this.__Kids.length;
+
+    // Create new Child for RadioGroup
+    var child = new AcroForm.ChildClass(parent, name);
+    // Add to Parent
+    this.__Kids.push(child);
+
+    jsPDF.API.addField(child);
+
+    return child;
+};
+
+AcroForm.CheckBox = function () {
+    Button.call(this);
+    this.appearanceStreamContent = AcroForm.Appearance.CheckBox.createAppearanceStream();
+    this.MK = AcroForm.Appearance.CheckBox.createMK();
+    this.AS = "/On";
+    this.V = "/On";
+};
+AcroForm.internal.inherit(AcroForm.CheckBox, AcroForm.Button);
+window["CheckBox"] = AcroForm.CheckBox;
+
+AcroForm.TextField = function () {
+    AcroForm.Field.call(this);
+    this.DA = AcroForm.Appearance.createDefaultAppearanceStream();
+    this.F = 4;
+    var _V;
+    Object.defineProperty(this, 'V', {
+        get: function get() {
+            if (_V) {
+                return "(" + _V + ")";
+            } else {
+                return _V;
+            }
+        },
+        enumerable: true,
+        set: function set(val) {
+            _V = val;
+        }
+    });
+
+    var _DV;
+    Object.defineProperty(this, 'DV', {
+        get: function get() {
+            if (_DV) {
+                return "(" + _DV + ")";
+            } else {
+                return _DV;
+            }
+        },
+        enumerable: true,
+        set: function set(val) {
+            _DV = val;
+        }
+    });
+
+    var _multiline = false;
+    Object.defineProperty(this, 'multiline', {
+        enumerable: false,
+        get: function get() {
+            return _multiline;
+        },
+        set: function set(val) {
+            _multiline = val;
+        }
+    });
+
+    //this.multiline = false;
+    //this.password = false;
+    /**
+     * For PDF 1.4
+     * @type {boolean}
+     */
+    //this.fileSelect = false;
+    /**
+     * For PDF 1.4
+     * @type {boolean}
+     */
+    //this.doNotSpellCheck = false;
+    /**
+     * For PDF 1.4
+     * @type {boolean}
+     */
+    //this.doNotScroll = false;
+
+    var _MaxLen = false;
+    Object.defineProperty(this, 'MaxLen', {
+        enumerable: true,
+        get: function get() {
+            return _MaxLen;
+        },
+        set: function set(val) {
+            _MaxLen = val;
+        }
+    });
+
+    Object.defineProperty(this, 'hasAppearanceStream', {
+        enumerable: false,
+        get: function get() {
+            return this.V || this.DV;
+        }
+    });
+};
+AcroForm.internal.inherit(AcroForm.TextField, AcroForm.Field);
+window["TextField"] = AcroForm.TextField;
+
+AcroForm.PasswordField = function () {
+    TextField.call(this);
+    Object.defineProperty(this, 'password', {
+        value: true,
+        enumerable: false,
+        configurable: false,
+        writable: false
+    });
+};
+AcroForm.internal.inherit(AcroForm.PasswordField, AcroForm.TextField);
+window["PasswordField"] = AcroForm.PasswordField;
+
+// ############ internal functions
+
+/*
+ * small workaround for calculating the TextMetric approximately
+ * @param text
+ * @param fontsize
+ * @returns {TextMetrics} (Has Height and Width)
+ */
+AcroForm.internal.calculateFontSpace = function (text, fontsize, fonttype) {
+    var fonttype = fonttype || "helvetica";
+    //re-use canvas object for speed improvements
+    var canvas = AcroForm.internal.calculateFontSpace.canvas || (AcroForm.internal.calculateFontSpace.canvas = document.createElement('canvas'));
+
+    var context = canvas.getContext('2d');
+    context.save();
+    var newFont = fontsize + " " + fonttype;
+    context.font = newFont;
+    var res = context.measureText(text);
+    context.fontcolor = 'black';
+    // Calculate height:
+    var context = canvas.getContext('2d');
+    res.height = context.measureText("3").width * 1.5; // 3 because in ZapfDingbats its a Hook and a 3 in normal fonts
+    context.restore();
+
+    var width = res.width;
+
+    return res;
+};
+
+AcroForm.internal.calculateX = function (formObject, text, font, maxFontSize) {
+    var maxFontSize = maxFontSize || 12;
+    var font = font || "helvetica";
+    var returnValue = {
+        text: "",
+        fontSize: ""
+    };
+    // Remove Brackets
+    text = text.substr(0, 1) == '(' ? text.substr(1) : text;
+    text = text.substr(text.length - 1) == ')' ? text.substr(0, text.length - 1) : text;
+    // split into array of words
+    var textSplit = text.split(' ');
+
+    /**
+     * the color could be ((alpha)||(r,g,b)||(c,m,y,k))
+     * @type {string}
+     */
+    var color = "0 g\n";
+    var fontSize = maxFontSize; // The Starting fontSize (The Maximum)
+    var lineSpacing = 2;
+    var borderPadding = 2;
+
+    var height = AcroForm.Appearance.internal.getHeight(formObject) || 0;
+    height = height < 0 ? -height : height;
+    var width = AcroForm.Appearance.internal.getWidth(formObject) || 0;
+    width = width < 0 ? -width : width;
+
+    var isSmallerThanWidth = function isSmallerThanWidth(i, lastLine, fontSize) {
+        if (i + 1 < textSplit.length) {
+            var tmp = lastLine + " " + textSplit[i + 1];
+            var TextWidth = AcroForm.internal.calculateFontSpace(tmp, fontSize + "px", font).width;
+            var FieldWidth = width - 2 * borderPadding;
+            return TextWidth <= FieldWidth;
+        } else {
+            return false;
+        }
+    };
+
+    fontSize++;
+    FontSize: while (true) {
+        var text = "";
+        fontSize--;
+        var textHeight = AcroForm.internal.calculateFontSpace("3", fontSize + "px", font).height;
+        var startY = formObject.multiline ? height - fontSize : (height - textHeight) / 2;
+        startY += lineSpacing;
+        var startX = -borderPadding;
+
+        var lastX = startX,
+            lastY = startY;
+        var firstWordInLine = 0,
+            lastWordInLine = 0;
+        var lastLength = 0;
+
+        var y = 0;
+        if (fontSize == 0) {
+            // In case, the Text doesn't fit at all
+            fontSize = 12;
+            text = "(...) Tj\n";
+            text += "% Width of Text: " + AcroForm.internal.calculateFontSpace(text, "1px").width + ", FieldWidth:" + width + "\n";
+            break;
+        }
+
+        lastLength = AcroForm.internal.calculateFontSpace(textSplit[0] + " ", fontSize + "px", font).width;
+
+        var lastLine = "";
+        var lineCount = 0;
+        Line: for (var i in textSplit) {
+            lastLine += textSplit[i] + " ";
+            // Remove last blank
+            lastLine = lastLine.substr(lastLine.length - 1) == " " ? lastLine.substr(0, lastLine.length - 1) : lastLine;
+            var key = parseInt(i);
+            lastLength = AcroForm.internal.calculateFontSpace(lastLine + " ", fontSize + "px", font).width;
+            var nextLineIsSmaller = isSmallerThanWidth(key, lastLine, fontSize);
+            var isLastWord = i >= textSplit.length - 1;
+            if (nextLineIsSmaller && !isLastWord) {
+                lastLine += " ";
+                continue; // Line
+            } else if (!nextLineIsSmaller && !isLastWord) {
+                if (!formObject.multiline) {
+                    continue FontSize;
+                } else {
+                    if ((textHeight + lineSpacing) * (lineCount + 2) + lineSpacing > height) {
+                        // If the Text is higher than the FieldObject
+                        continue FontSize;
+                    }
+                    lastWordInLine = key;
+                    // go on
+                }
+            } else if (isLastWord) {
+                lastWordInLine = key;
+            } else {
+                if (formObject.multiline && (textHeight + lineSpacing) * (lineCount + 2) + lineSpacing > height) {
+                    // If the Text is higher than the FieldObject
+                    continue FontSize;
+                }
+            }
+
+            var line = '';
+
+            for (var x = firstWordInLine; x <= lastWordInLine; x++) {
+                line += textSplit[x] + ' ';
+            }
+
+            // Remove last blank
+            line = line.substr(line.length - 1) == " " ? line.substr(0, line.length - 1) : line;
+            //lastLength -= blankSpace.width;
+            lastLength = AcroForm.internal.calculateFontSpace(line, fontSize + "px", font).width;
+
+            // Calculate startX
+            switch (formObject.Q) {
+                case 2:
+                    // Right justified
+                    startX = width - lastLength - borderPadding;
+                    break;
+                case 1:
+                    // Q = 1 := Text-Alignment: Center
+                    startX = (width - lastLength) / 2;
+                    break;
+                case 0:
+                default:
+                    startX = borderPadding;
+                    break;
+            }
+            text += startX + ' ' + lastY + ' Td\n';
+            text += '(' + line + ') Tj\n';
+            // reset X in PDF
+            text += -startX + ' 0 Td\n';
+
+            // After a Line, adjust y position
+            lastY = -(fontSize + lineSpacing);
+            lastX = startX;
+
+            // Reset for next iteration step
+            lastLength = 0;
+            firstWordInLine = lastWordInLine + 1;
+            lineCount++;
+
+            lastLine = "";
+            continue Line;
+        }
+        break;
+    }
+
+    returnValue.text = text;
+    returnValue.fontSize = fontSize;
+
+    return returnValue;
+};
+
+AcroForm.internal.calculateAppearanceStream = function (formObject) {
+    if (formObject.appearanceStreamContent) {
+        // If appearanceStream is already set, use it
+        return formObject.appearanceStreamContent;
+    }
+
+    if (!formObject.V && !formObject.DV) {
+        return;
+    }
+
+    // else calculate it
+
+    var stream = '';
+
+    var text = formObject.V || formObject.DV;
+
+    var calcRes = AcroForm.internal.calculateX(formObject, text);
+
+    stream += '/Tx BMC\n' + 'q\n' +
+    //color + '\n' +
+    '/F1 ' + calcRes.fontSize + ' Tf\n' +
+    // Text Matrix
+    '1 0 0 1 0 0 Tm\n';
+    // Begin Text
+    stream += 'BT\n';
+    stream += calcRes.text;
+    // End Text
+    stream += 'ET\n';
+    stream += 'Q\n' + 'EMC\n';
+
+    var appearanceStreamContent = new AcroForm.createFormXObject(formObject);
+
+    appearanceStreamContent.stream = stream;
+
+    var appearance = {
+        N: {
+            'Normal': appearanceStreamContent
+        }
+    };
+
+    return appearanceStreamContent;
+};
+
+/*
+ * Converts the Parameters from x,y,w,h to lowerLeftX, lowerLeftY, upperRightX, upperRightY
+ * @param x
+ * @param y
+ * @param w
+ * @param h
+ * @returns {*[]}
+ */
+AcroForm.internal.calculateCoordinates = function (x, y, w, h) {
+    var coordinates = {};
+
+    if (this.internal) {
+        var mmtopx = function mmtopx(x) {
+            return x * this.internal.scaleFactor;
+        };
+
+        if (Array.isArray(x)) {
+            x[0] = AcroForm.scale(x[0]);
+            x[1] = AcroForm.scale(x[1]);
+            x[2] = AcroForm.scale(x[2]);
+            x[3] = AcroForm.scale(x[3]);
+
+            coordinates.lowerLeft_X = x[0] || 0;
+            coordinates.lowerLeft_Y = mmtopx.call(this, this.internal.pageSize.height) - x[3] - x[1] || 0;
+            coordinates.upperRight_X = x[0] + x[2] || 0;
+            coordinates.upperRight_Y = mmtopx.call(this, this.internal.pageSize.height) - x[1] || 0;
+        } else {
+            x = AcroForm.scale(x);
+            y = AcroForm.scale(y);
+            w = AcroForm.scale(w);
+            h = AcroForm.scale(h);
+            coordinates.lowerLeft_X = x || 0;
+            coordinates.lowerLeft_Y = this.internal.pageSize.height - y || 0;
+            coordinates.upperRight_X = x + w || 0;
+            coordinates.upperRight_Y = this.internal.pageSize.height - y + h || 0;
+        }
+    } else {
+        // old method, that is fallback, if we can't get the pageheight, the coordinate-system starts from lower left
+        if (Array.isArray(x)) {
+            coordinates.lowerLeft_X = x[0] || 0;
+            coordinates.lowerLeft_Y = x[1] || 0;
+            coordinates.upperRight_X = x[0] + x[2] || 0;
+            coordinates.upperRight_Y = x[1] + x[3] || 0;
+        } else {
+            coordinates.lowerLeft_X = x || 0;
+            coordinates.lowerLeft_Y = y || 0;
+            coordinates.upperRight_X = x + w || 0;
+            coordinates.upperRight_Y = y + h || 0;
+        }
+    }
+
+    return [coordinates.lowerLeft_X, coordinates.lowerLeft_Y, coordinates.upperRight_X, coordinates.upperRight_Y];
+};
+
+AcroForm.internal.calculateColor = function (r, g, b) {
+    var color = new Array(3);
+    color.r = r | 0;
+    color.g = g | 0;
+    color.b = b | 0;
+    return color;
+};
+
+AcroForm.internal.getBitPosition = function (variable, position) {
+    variable = variable || 0;
+    var bitMask = 1;
+    bitMask = bitMask << position - 1;
+    return variable | bitMask;
+};
+
+AcroForm.internal.setBitPosition = function (variable, position, value) {
+    variable = variable || 0;
+    value = value || 1;
+
+    var bitMask = 1;
+    bitMask = bitMask << position - 1;
+
+    if (value == 1) {
+        // Set the Bit to 1
+        var variable = variable | bitMask;
+    } else {
+        // Set the Bit to 0
+        var variable = variable & ~bitMask;
+    }
+
+    return variable;
+};
+
+/**
+ * jsPDF addHTML PlugIn
+ * Copyright (c) 2014 Diego Casorran
+ *
+ * Licensed under the MIT License.
+ * http://opensource.org/licenses/mit-license
+ */
+
+(function (jsPDFAPI) {
+	'use strict';
+
+	/**
+  * Renders an HTML element to canvas object which added to the PDF
+  *
+  * This feature requires [html2canvas](https://github.com/niklasvh/html2canvas)
+  * or [rasterizeHTML](https://github.com/cburgmer/rasterizeHTML.js)
+  *
+  * @returns {jsPDF}
+  * @name addHTML
+  * @param element {Mixed} HTML Element, or anything supported by html2canvas.
+  * @param x {Number} starting X coordinate in jsPDF instance's declared units.
+  * @param y {Number} starting Y coordinate in jsPDF instance's declared units.
+  * @param options {Object} Additional options, check the code below.
+  * @param callback {Function} to call when the rendering has finished.
+  * NOTE: Every parameter is optional except 'element' and 'callback', in such
+  *       case the image is positioned at 0x0 covering the whole PDF document
+  *       size. Ie, to easily take screenshots of webpages saving them to PDF.
+  * @deprecated This is being replace with a vector-supporting API. See
+  * [this link](https://cdn.rawgit.com/MrRio/jsPDF/master/examples/html2pdf/showcase_supported_html.html)
+  */
+
+	jsPDFAPI.addHTML = function (element, x, y, options, callback) {
+		'use strict';
+
+		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');
+
+		if (typeof x !== 'number') {
+			options = x;
+			callback = y;
+		}
+
+		if (typeof options === 'function') {
+			callback = options;
+			options = null;
+		}
+
+		var I = this.internal,
+		    K = I.scaleFactor,
+		    W = I.pageSize.width,
+		    H = I.pageSize.height;
+
+		options = options || {};
+		options.onrendered = function (obj) {
+			x = parseInt(x) || 0;
+			y = parseInt(y) || 0;
+			var dim = options.dim || {};
+			var h = dim.h || 0;
+			var w = dim.w || Math.min(W, obj.width / K) - x;
+
+			var format = 'JPEG';
+			if (options.format) format = options.format;
+
+			if (obj.height > H && options.pagesplit) {
+				var crop = function () {
+					var cy = 0;
+					while (1) {
+						var canvas = document.createElement('canvas');
+						canvas.width = Math.min(W * K, obj.width);
+						canvas.height = Math.min(H * K, obj.height - cy);
+						var ctx = canvas.getContext('2d');
+						ctx.drawImage(obj, 0, cy, obj.width, canvas.height, 0, 0, canvas.width, canvas.height);
+						var args = [canvas, x, cy ? 0 : y, canvas.width / K, canvas.height / K, format, null, 'SLOW'];
+						this.addImage.apply(this, args);
+						cy += canvas.height;
+						if (cy >= obj.height) break;
+						this.addPage();
+					}
+					callback(w, cy, null, args);
+				}.bind(this);
+				if (obj.nodeName === 'CANVAS') {
+					var img = new Image();
+					img.onload = crop;
+					img.src = obj.toDataURL("image/png");
+					obj = img;
+				} else {
+					crop();
+				}
+			} else {
+				var alias = Math.random().toString(35);
+				var args = [obj, x, y, w, h, format, alias, 'SLOW'];
+
+				this.addImage.apply(this, args);
+
+				callback(w, h, alias, args);
+			}
+		}.bind(this);
+
+		if (typeof html2canvas !== 'undefined' && !options.rstz) {
+			return html2canvas(element, options);
+		}
+
+		if (typeof rasterizeHTML !== 'undefined') {
+			var meth = 'drawDocument';
+			if (typeof element === 'string') {
+				meth = /^http/.test(element) ? 'drawURL' : 'drawHTML';
+			}
+			options.width = options.width || W * K;
+			return rasterizeHTML[meth](element, void 0, options).then(function (r) {
+				options.onrendered(r.image);
+			}, function (e) {
+				callback(null, e);
+			});
+		}
+
+		return null;
+	};
+})(jsPDF.API);
+
+/** @preserve
+ * jsPDF addImage plugin
+ * Copyright (c) 2012 Jason Siefken, https://github.com/siefkenj/
+ *               2013 Chris Dowling, https://github.com/gingerchris
+ *               2013 Trinh Ho, https://github.com/ineedfat
+ *               2013 Edwin Alejandro Perez, https://github.com/eaparango
+ *               2013 Norah Smith, https://github.com/burnburnrocket
+ *               2014 Diego Casorran, https://github.com/diegocr
+ *               2014 James Robb, https://github.com/jamesbrobb
+ *
+ * 
+ */
+
+(function (jsPDFAPI) {
+	'use strict';
+
+	var namespace = 'addImage_',
+	    supported_image_types = ['jpeg', 'jpg', 'png'];
+
+	// Image functionality ported from pdf.js
+	var putImage = function putImage(img) {
+
+		var objectNumber = this.internal.newObject(),
+		    out = this.internal.write,
+		    putStream = this.internal.putStream;
+
+		img['n'] = objectNumber;
+
+		out('<</Type /XObject');
+		out('/Subtype /Image');
+		out('/Width ' + img['w']);
+		out('/Height ' + img['h']);
+		if (img['cs'] === this.color_spaces.INDEXED) {
+			out('/ColorSpace [/Indexed /DeviceRGB '
+			// if an indexed png defines more than one colour with transparency, we've created a smask
+			+ (img['pal'].length / 3 - 1) + ' ' + ('smask' in img ? objectNumber + 2 : objectNumber + 1) + ' 0 R]');
+		} else {
+			out('/ColorSpace /' + img['cs']);
+			if (img['cs'] === this.color_spaces.DEVICE_CMYK) {
+				out('/Decode [1 0 1 0 1 0 1 0]');
+			}
+		}
+		out('/BitsPerComponent ' + img['bpc']);
+		if ('f' in img) {
+			out('/Filter /' + img['f']);
+		}
+		if ('dp' in img) {
+			out('/DecodeParms <<' + img['dp'] + '>>');
+		}
+		if ('trns' in img && img['trns'].constructor == Array) {
+			var trns = '',
+			    i = 0,
+			    len = img['trns'].length;
+			for (; i < len; i++) {
+				trns += img['trns'][i] + ' ' + img['trns'][i] + ' ';
+			}out('/Mask [' + trns + ']');
+		}
+		if ('smask' in img) {
+			out('/SMask ' + (objectNumber + 1) + ' 0 R');
+		}
+		out('/Length ' + img['data'].length + '>>');
+
+		putStream(img['data']);
+
+		out('endobj');
+
+		// Soft mask
+		if ('smask' in img) {
+			var dp = '/Predictor ' + img['p'] + ' /Colors 1 /BitsPerComponent ' + img['bpc'] + ' /Columns ' + img['w'];
+			var smask = { 'w': img['w'], 'h': img['h'], 'cs': 'DeviceGray', 'bpc': img['bpc'], 'dp': dp, 'data': img['smask'] };
+			if ('f' in img) smask.f = img['f'];
+			putImage.call(this, smask);
+		}
+
+		//Palette
+		if (img['cs'] === this.color_spaces.INDEXED) {
+
+			this.internal.newObject();
+			//out('<< /Filter / ' + img['f'] +' /Length ' + img['pal'].length + '>>');
+			//putStream(zlib.compress(img['pal']));
+			out('<< /Length ' + img['pal'].length + '>>');
+			putStream(this.arrayBufferToBinaryString(new Uint8Array(img['pal'])));
+			out('endobj');
+		}
+	},
+	    putResourcesCallback = function putResourcesCallback() {
+		var images = this.internal.collections[namespace + 'images'];
+		for (var i in images) {
+			putImage.call(this, images[i]);
+		}
+	},
+	    putXObjectsDictCallback = function putXObjectsDictCallback() {
+		var images = this.internal.collections[namespace + 'images'],
+		    out = this.internal.write,
+		    image;
+		for (var i in images) {
+			image = images[i];
+			out('/I' + image['i'], image['n'], '0', 'R');
+		}
+	},
+	    checkCompressValue = function checkCompressValue(value) {
+		if (value && typeof value === 'string') value = value.toUpperCase();
+		return value in jsPDFAPI.image_compression ? value : jsPDFAPI.image_compression.NONE;
+	},
+	    getImages = function getImages() {
+		var images = this.internal.collections[namespace + 'images'];
+		//first run, so initialise stuff
+		if (!images) {
+			this.internal.collections[namespace + 'images'] = images = {};
+			this.internal.events.subscribe('putResources', putResourcesCallback);
+			this.internal.events.subscribe('putXobjectDict', putXObjectsDictCallback);
+		}
+
+		return images;
+	},
+	    getImageIndex = function getImageIndex(images) {
+		var imageIndex = 0;
+
+		if (images) {
+			// this is NOT the first time this method is ran on this instance of jsPDF object.
+			imageIndex = Object.keys ? Object.keys(images).length : function (o) {
+				var i = 0;
+				for (var e in o) {
+					if (o.hasOwnProperty(e)) {
+						i++;
+					}
+				}
+				return i;
+			}(images);
+		}
+
+		return imageIndex;
+	},
+	    notDefined = function notDefined(value) {
+		return typeof value === 'undefined' || value === null;
+	},
+	    generateAliasFromData = function generateAliasFromData(data) {
+		return typeof data === 'string' && jsPDFAPI.sHashCode(data);
+	},
+	    doesNotSupportImageType = function doesNotSupportImageType(type) {
+		return supported_image_types.indexOf(type) === -1;
+	},
+	    processMethodNotEnabled = function processMethodNotEnabled(type) {
+		return typeof jsPDFAPI['process' + type.toUpperCase()] !== 'function';
+	},
+	    isDOMElement = function isDOMElement(object) {
+		return (typeof object === 'undefined' ? 'undefined' : _typeof(object)) === 'object' && object.nodeType === 1;
+	},
+	    createDataURIFromElement = function createDataURIFromElement(element, format, angle) {
+
+		//if element is an image which uses data url definition, just return the dataurl
+		if (element.nodeName === 'IMG' && element.hasAttribute('src')) {
+			var src = '' + element.getAttribute('src');
+			if (!angle && src.indexOf('data:image/') === 0) return src;
+
+			// only if the user doesn't care about a format
+			if (!format && /\.png(?:[?#].*)?$/i.test(src)) format = 'png';
+		}
+
+		if (element.nodeName === 'CANVAS') {
+			var canvas = element;
+		} else {
+			var canvas = document.createElement('canvas');
+			canvas.width = element.clientWidth || element.width;
+			canvas.height = element.clientHeight || element.height;
+
+			var ctx = canvas.getContext('2d');
+			if (!ctx) {
+				throw 'addImage requires canvas to be supported by browser.';
+			}
+			if (angle) {
+				var x,
+				    y,
+				    b,
+				    c,
+				    s,
+				    w,
+				    h,
+				    to_radians = Math.PI / 180,
+				    angleInRadians;
+
+				if ((typeof angle === 'undefined' ? 'undefined' : _typeof(angle)) === 'object') {
+					x = angle.x;
+					y = angle.y;
+					b = angle.bg;
+					angle = angle.angle;
+				}
+				angleInRadians = angle * to_radians;
+				c = Math.abs(Math.cos(angleInRadians));
+				s = Math.abs(Math.sin(angleInRadians));
+				w = canvas.width;
+				h = canvas.height;
+				canvas.width = h * s + w * c;
+				canvas.height = h * c + w * s;
+
+				if (isNaN(x)) x = canvas.width / 2;
+				if (isNaN(y)) y = canvas.height / 2;
+
+				ctx.clearRect(0, 0, canvas.width, canvas.height);
+				ctx.fillStyle = b || 'white';
+				ctx.fillRect(0, 0, canvas.width, canvas.height);
+				ctx.save();
+				ctx.translate(x, y);
+				ctx.rotate(angleInRadians);
+				ctx.drawImage(element, -(w / 2), -(h / 2));
+				ctx.rotate(-angleInRadians);
+				ctx.translate(-x, -y);
+				ctx.restore();
+			} else {
+				ctx.drawImage(element, 0, 0, canvas.width, canvas.height);
+			}
+		}
+		return canvas.toDataURL(('' + format).toLowerCase() == 'png' ? 'image/png' : 'image/jpeg');
+	},
+	    checkImagesForAlias = function checkImagesForAlias(alias, images) {
+		var cached_info;
+		if (images) {
+			for (var e in images) {
+				if (alias === images[e].alias) {
+					cached_info = images[e];
+					break;
+				}
+			}
+		}
+		return cached_info;
+	},
+	    determineWidthAndHeight = function determineWidthAndHeight(w, h, info) {
+		if (!w && !h) {
+			w = -96;
+			h = -96;
+		}
+		if (w < 0) {
+			w = -1 * info['w'] * 72 / w / this.internal.scaleFactor;
+		}
+		if (h < 0) {
+			h = -1 * info['h'] * 72 / h / this.internal.scaleFactor;
+		}
+		if (w === 0) {
+			w = h * info['w'] / info['h'];
+		}
+		if (h === 0) {
+			h = w * info['h'] / info['w'];
+		}
+
+		return [w, h];
+	},
+	    writeImageToPDF = function writeImageToPDF(x, y, w, h, info, index, images) {
+		var dims = determineWidthAndHeight.call(this, w, h, info),
+		    coord = this.internal.getCoordinateString,
+		    vcoord = this.internal.getVerticalCoordinateString;
+
+		w = dims[0];
+		h = dims[1];
+
+		images[index] = info;
+
+		this.internal.write('q', coord(w), '0 0', coord(h) // TODO: check if this should be shifted by vcoord
+		, coord(x), vcoord(y + h), 'cm /I' + info['i'], 'Do Q');
+	};
+
+	/**
+  * COLOR SPACES
+  */
+	jsPDFAPI.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'
+	};
+
+	/**
+  * DECODE METHODS
+  */
+	jsPDFAPI.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'
+	};
+
+	/**
+  * IMAGE COMPRESSION TYPES
+  */
+	jsPDFAPI.image_compression = {
+		NONE: 'NONE',
+		FAST: 'FAST',
+		MEDIUM: 'MEDIUM',
+		SLOW: 'SLOW'
+	};
+
+	jsPDFAPI.sHashCode = function (str) {
+		return Array.prototype.reduce && str.split("").reduce(function (a, b) {
+			a = (a << 5) - a + b.charCodeAt(0);return a & a;
+		}, 0);
+	};
+
+	jsPDFAPI.isString = function (object) {
+		return typeof object === 'string';
+	};
+
+	/**
+  * Strips out and returns info from a valid base64 data URI
+  * @param {String[dataURI]} a valid data URI of format 'data:[<MIME-type>][;base64],<data>'
+  * @returns an Array containing the following
+  * [0] the complete data URI
+  * [1] <MIME-type>
+  * [2] format - the second part of the mime-type i.e 'png' in 'image/png'
+  * [4] <data>
+  */
+	jsPDFAPI.extractInfoFromBase64DataURI = function (dataURI) {
+		return (/^data:([\w]+?\/([\w]+?));base64,(.+?)$/g.exec(dataURI)
+		);
+	};
+
+	/**
+  * Check to see if ArrayBuffer is supported
+  */
+	jsPDFAPI.supportsArrayBuffer = function () {
+		return typeof ArrayBuffer !== 'undefined' && typeof Uint8Array !== 'undefined';
+	};
+
+	/**
+  * Tests supplied object to determine if ArrayBuffer
+  * @param {Object[object]}
+  */
+	jsPDFAPI.isArrayBuffer = function (object) {
+		if (!this.supportsArrayBuffer()) return false;
+		return object instanceof ArrayBuffer;
+	};
+
+	/**
+  * Tests supplied object to determine if it implements the ArrayBufferView (TypedArray) interface
+  * @param {Object[object]}
+  */
+	jsPDFAPI.isArrayBufferView = function (object) {
+		if (!this.supportsArrayBuffer()) return false;
+		if (typeof Uint32Array === 'undefined') return false;
+		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;
+	};
+
+	/**
+  * Exactly what it says on the tin
+  */
+	jsPDFAPI.binaryStringToUint8Array = function (binary_string) {
+		/*
+   * not sure how efficient this will be will bigger files. Is there a native method?
+   */
+		var len = binary_string.length;
+		var bytes = new Uint8Array(len);
+		for (var i = 0; i < len; i++) {
+			bytes[i] = binary_string.charCodeAt(i);
+		}
+		return bytes;
+	};
+
+	/**
+  * @see this discussion
+  * http://stackoverflow.com/questions/6965107/converting-between-strings-and-arraybuffers
+  *
+  * As stated, i imagine the method below is highly inefficent for large files.
+  *
+  * Also of note from Mozilla,
+  *
+  * "However, this is slow and error-prone, due to the need for multiple conversions (especially if the binary data is not actually byte-format data, but, for example, 32-bit integers or floats)."
+  *
+  * https://developer.mozilla.org/en-US/Add-ons/Code_snippets/StringView
+  *
+  * Although i'm strugglig to see how StringView solves this issue? Doesn't appear to be a direct method for conversion?
+  *
+  * Async method using Blob and FileReader could be best, but i'm not sure how to fit it into the flow?
+  */
+	jsPDFAPI.arrayBufferToBinaryString = function (buffer) {
+		/*if('TextDecoder' in window){
+  	var decoder = new TextDecoder('ascii');
+  	return decoder.decode(buffer);
+  }*/
+
+		if (this.isArrayBuffer(buffer)) buffer = new Uint8Array(buffer);
+
+		var binary_string = '';
+		var len = buffer.byteLength;
+		for (var i = 0; i < len; i++) {
+			binary_string += String.fromCharCode(buffer[i]);
+		}
+		return binary_string;
+		/*
+   * Another solution is the method below - convert array buffer straight to base64 and then use atob
+   */
+		//return atob(this.arrayBufferToBase64(buffer));
+	};
+
+	/**
+  * Converts an ArrayBuffer directly to base64
+  *
+  * Taken from here
+  *
+  * http://jsperf.com/encoding-xhr-image-data/31
+  *
+  * Need to test if this is a better solution for larger files
+  *
+  */
+	jsPDFAPI.arrayBufferToBase64 = function (arrayBuffer) {
+		var base64 = '';
+		var encodings = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
+
+		var bytes = new Uint8Array(arrayBuffer);
+		var byteLength = bytes.byteLength;
+		var byteRemainder = byteLength % 3;
+		var mainLength = byteLength - byteRemainder;
+
+		var a, b, c, d;
+		var chunk;
+
+		// Main loop deals with bytes in chunks of 3
+		for (var i = 0; i < mainLength; i = i + 3) {
+			// Combine the three bytes into a single integer
+			chunk = bytes[i] << 16 | bytes[i + 1] << 8 | bytes[i + 2];
+
+			// Use bitmasks to extract 6-bit segments from the triplet
+			a = (chunk & 16515072) >> 18; // 16515072 = (2^6 - 1) << 18
+			b = (chunk & 258048) >> 12; // 258048   = (2^6 - 1) << 12
+			c = (chunk & 4032) >> 6; // 4032     = (2^6 - 1) << 6
+			d = chunk & 63; // 63       = 2^6 - 1
+
+			// Convert the raw binary segments to the appropriate ASCII encoding
+			base64 += encodings[a] + encodings[b] + encodings[c] + encodings[d];
+		}
+
+		// Deal with the remaining bytes and padding
+		if (byteRemainder == 1) {
+			chunk = bytes[mainLength];
+
+			a = (chunk & 252) >> 2; // 252 = (2^6 - 1) << 2
+
+			// Set the 4 least significant bits to zero
+			b = (chunk & 3) << 4; // 3   = 2^2 - 1
+
+			base64 += encodings[a] + encodings[b] + '==';
+		} else if (byteRemainder == 2) {
+			chunk = bytes[mainLength] << 8 | bytes[mainLength + 1];
+
+			a = (chunk & 64512) >> 10; // 64512 = (2^6 - 1) << 10
+			b = (chunk & 1008) >> 4; // 1008  = (2^6 - 1) << 4
+
+			// Set the 2 least significant bits to zero
+			c = (chunk & 15) << 2; // 15    = 2^4 - 1
+
+			base64 += encodings[a] + encodings[b] + encodings[c] + '=';
+		}
+
+		return base64;
+	};
+
+	jsPDFAPI.createImageInfo = function (data, wd, ht, cs, bpc, f, imageIndex, alias, dp, trns, pal, smask, p) {
+		var info = {
+			alias: alias,
+			w: wd,
+			h: ht,
+			cs: cs,
+			bpc: bpc,
+			i: imageIndex,
+			data: data
+			// n: objectNumber will be added by putImage code
+		};
+
+		if (f) info.f = f;
+		if (dp) info.dp = dp;
+		if (trns) info.trns = trns;
+		if (pal) info.pal = pal;
+		if (smask) info.smask = smask;
+		if (p) info.p = p; // predictor parameter for PNG compression
+
+		return info;
+	};
+
+	jsPDFAPI.addImage = function (imageData, format, x, y, w, h, alias, compression, rotation) {
+		'use strict';
+
+		if (typeof format !== 'string') {
+			var tmp = h;
+			h = w;
+			w = y;
+			y = x;
+			x = format;
+			format = tmp;
+		}
+
+		if ((typeof imageData === 'undefined' ? 'undefined' : _typeof(imageData)) === 'object' && !isDOMElement(imageData) && "imageData" in imageData) {
+			var options = imageData;
+
+			imageData = options.imageData;
+			format = options.format || format;
+			x = options.x || x || 0;
+			y = options.y || y || 0;
+			w = options.w || w;
+			h = options.h || h;
+			alias = options.alias || alias;
+			compression = options.compression || compression;
+			rotation = options.rotation || options.angle || rotation;
+		}
+
+		if (isNaN(x) || isNaN(y)) {
+			console.error('jsPDF.addImage: Invalid coordinates', arguments);
+			throw new Error('Invalid coordinates passed to jsPDF.addImage');
+		}
+
+		var images = getImages.call(this),
+		    info;
+
+		if (!(info = checkImagesForAlias(imageData, images))) {
+			var dataAsBinaryString;
+
+			if (isDOMElement(imageData)) imageData = createDataURIFromElement(imageData, format, rotation);
+
+			if (notDefined(alias)) alias = generateAliasFromData(imageData);
+
+			if (!(info = checkImagesForAlias(alias, images))) {
+
+				if (this.isString(imageData)) {
+
+					var base64Info = this.extractInfoFromBase64DataURI(imageData);
+
+					if (base64Info) {
+
+						format = base64Info[2];
+						imageData = atob(base64Info[3]); //convert to binary string
+					} else {
+
+						if (imageData.charCodeAt(0) === 0x89 && imageData.charCodeAt(1) === 0x50 && imageData.charCodeAt(2) === 0x4e && imageData.charCodeAt(3) === 0x47) format = 'png';
+					}
+				}
+				format = (format || 'JPEG').toLowerCase();
+
+				if (doesNotSupportImageType(format)) throw new Error('addImage currently only supports formats ' + supported_image_types + ', not \'' + format + '\'');
+
+				if (processMethodNotEnabled(format)) throw new Error('please ensure that the plugin for \'' + format + '\' support is added');
+
+				/**
+     * need to test if it's more efficient to convert all binary strings
+     * to TypedArray - or should we just leave and process as string?
+     */
+				if (this.supportsArrayBuffer()) {
+					// no need to convert if imageData is already uint8array
+					if (!(imageData instanceof Uint8Array)) {
+						dataAsBinaryString = imageData;
+						imageData = this.binaryStringToUint8Array(imageData);
+					}
+				}
+
+				info = this['process' + format.toUpperCase()](imageData, getImageIndex(images), alias, checkCompressValue(compression), dataAsBinaryString);
+
+				if (!info) throw new Error('An unkwown error occurred whilst processing the image');
+			}
+		}
+
+		writeImageToPDF.call(this, x, y, w, h, info, info.i, images);
+
+		return this;
+	};
+
+	/**
+  * JPEG SUPPORT
+  **/
+
+	//takes a string imgData containing the raw bytes of
+	//a jpeg image and returns [width, height]
+	//Algorithm from: http://www.64lines.com/jpeg-width-height
+	var getJpegSize = function getJpegSize(imgData) {
+		'use strict';
+
+		var width, height, numcomponents;
+		// Verify we have a valid jpeg header 0xff,0xd8,0xff,0xe0,?,?,'J','F','I','F',0x00
+		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) {
+			throw new Error('getJpegSize requires a binary string jpeg file');
+		}
+		var blockLength = imgData.charCodeAt(4) * 256 + imgData.charCodeAt(5);
+		var i = 4,
+		    len = imgData.length;
+		while (i < len) {
+			i += blockLength;
+			if (imgData.charCodeAt(i) !== 0xff) {
+				throw new Error('getJpegSize could not find the size of the image');
+			}
+			if (imgData.charCodeAt(i + 1) === 0xc0 || //(SOF) Huffman  - Baseline DCT
+			imgData.charCodeAt(i + 1) === 0xc1 || //(SOF) Huffman  - Extended sequential DCT
+			imgData.charCodeAt(i + 1) === 0xc2 || // Progressive DCT (SOF2)
+			imgData.charCodeAt(i + 1) === 0xc3 || // Spatial (sequential) lossless (SOF3)
+			imgData.charCodeAt(i + 1) === 0xc4 || // Differential sequential DCT (SOF5)
+			imgData.charCodeAt(i + 1) === 0xc5 || // Differential progressive DCT (SOF6)
+			imgData.charCodeAt(i + 1) === 0xc6 || // Differential spatial (SOF7)
+			imgData.charCodeAt(i + 1) === 0xc7) {
+				height = imgData.charCodeAt(i + 5) * 256 + imgData.charCodeAt(i + 6);
+				width = imgData.charCodeAt(i + 7) * 256 + imgData.charCodeAt(i + 8);
+				numcomponents = imgData.charCodeAt(i + 9);
+				return [width, height, numcomponents];
+			} else {
+				i += 2;
+				blockLength = imgData.charCodeAt(i) * 256 + imgData.charCodeAt(i + 1);
+			}
+		}
+	},
+	    getJpegSizeFromBytes = function getJpegSizeFromBytes(data) {
+
+		var hdr = data[0] << 8 | data[1];
+
+		if (hdr !== 0xFFD8) throw new Error('Supplied data is not a JPEG');
+
+		var len = data.length,
+		    block = (data[4] << 8) + data[5],
+		    pos = 4,
+		    bytes,
+		    width,
+		    height,
+		    numcomponents;
+
+		while (pos < len) {
+			pos += block;
+			bytes = readBytes(data, pos);
+			block = (bytes[2] << 8) + bytes[3];
+			if ((bytes[1] === 0xC0 || bytes[1] === 0xC2) && bytes[0] === 0xFF && block > 7) {
+				bytes = readBytes(data, pos + 5);
+				width = (bytes[2] << 8) + bytes[3];
+				height = (bytes[0] << 8) + bytes[1];
+				numcomponents = bytes[4];
+				return { width: width, height: height, numcomponents: numcomponents };
+			}
+
+			pos += 2;
+		}
+
+		throw new Error('getJpegSizeFromBytes could not find the size of the image');
+	},
+	    readBytes = function readBytes(data, offset) {
+		return data.subarray(offset, offset + 5);
+	};
+
+	jsPDFAPI.processJPEG = function (data, index, alias, compression, dataAsBinaryString) {
+		'use strict';
+
+		var colorSpace = this.color_spaces.DEVICE_RGB,
+		    filter = this.decode.DCT_DECODE,
+		    bpc = 8,
+		    dims;
+
+		if (this.isString(data)) {
+			dims = getJpegSize(data);
+			return this.createImageInfo(data, dims[0], dims[1], dims[3] == 1 ? this.color_spaces.DEVICE_GRAY : colorSpace, bpc, filter, index, alias);
+		}
+
+		if (this.isArrayBuffer(data)) data = new Uint8Array(data);
+
+		if (this.isArrayBufferView(data)) {
+
+			dims = getJpegSizeFromBytes(data);
+
+			// if we already have a stored binary string rep use that
+			data = dataAsBinaryString || this.arrayBufferToBinaryString(data);
+
+			return this.createImageInfo(data, dims.width, dims.height, dims.numcomponents == 1 ? this.color_spaces.DEVICE_GRAY : colorSpace, bpc, filter, index, alias);
+		}
+
+		return null;
+	};
+
+	jsPDFAPI.processJPG = function () /*data, index, alias, compression, dataAsBinaryString*/{
+		return this.processJPEG.apply(this, arguments);
+	};
+})(jsPDF.API);
+
+/**
+ * jsPDF Annotations PlugIn
+ * Copyright (c) 2014 Steven Spungin (TwelveTone LLC)  steven@twelvetone.tv
+ *
+ * Licensed under the MIT License.
+ * http://opensource.org/licenses/mit-license
+ */
+
+/**
+ * There are many types of annotations in a PDF document. Annotations are placed
+ * on a page at a particular location. They are not 'attached' to an object.
+ * <br />
+ * This plugin current supports <br />
+ * <li> Goto Page (set pageNumber and top in options)
+ * <li> Goto Name (set name and top in options)
+ * <li> Goto URL (set url in options)
+ * <p>
+ * 	The destination magnification factor can also be specified when goto is a page number or a named destination. (see documentation below)
+ *  (set magFactor in options).  XYZ is the default.
+ * </p>
+ * <p>
+ *  Links, Text, Popup, and FreeText are supported.
+ * </p>
+ * <p>
+ * Options In PDF spec Not Implemented Yet
+ * <li> link border
+ * <li> named target
+ * <li> page coordinates
+ * <li> destination page scaling and layout
+ * <li> actions other than URL and GotoPage
+ * <li> background / hover actions
+ * </p>
+ */
+
+/*
+    Destination Magnification Factors
+    See PDF 1.3 Page 386 for meanings and options
+
+    [supported]
+	XYZ (options; left top zoom)
+	Fit (no options)
+	FitH (options: top)
+	FitV (options: left)
+
+	[not supported]
+	FitR
+	FitB
+	FitBH
+	FitBV
+ */
+
+(function (jsPDFAPI) {
+	'use strict';
+
+	var annotationPlugin = {
+
+		/**
+   * An array of arrays, indexed by <em>pageNumber</em>.
+   */
+		annotations: [],
+
+		f2: function f2(number) {
+			return number.toFixed(2);
+		},
+
+		notEmpty: function notEmpty(obj) {
+			if (typeof obj != 'undefined') {
+				if (obj != '') {
+					return true;
+				}
+			}
+		}
+	};
+
+	jsPDF.API.annotationPlugin = annotationPlugin;
+
+	jsPDF.API.events.push(['addPage', function (info) {
+		this.annotationPlugin.annotations[info.pageNumber] = [];
+	}]);
+
+	jsPDFAPI.events.push(['putPage', function (info) {
+		//TODO store annotations in pageContext so reorder/remove will not affect them.
+		var pageAnnos = this.annotationPlugin.annotations[info.pageNumber];
+
+		var found = false;
+		for (var a = 0; a < pageAnnos.length && !found; a++) {
+			var anno = pageAnnos[a];
+			switch (anno.type) {
+				case 'link':
+					if (annotationPlugin.notEmpty(anno.options.url) || annotationPlugin.notEmpty(anno.options.pageNumber)) {
+						found = true;
+						break;
+					}
+				case 'reference':
+				case 'text':
+				case 'freetext':
+					found = true;
+					break;
+			}
+		}
+		if (found == false) {
+			return;
+		}
+
+		this.internal.write("/Annots [");
+		var f2 = this.annotationPlugin.f2;
+		var k = this.internal.scaleFactor;
+		var pageHeight = this.internal.pageSize.height;
+		var pageInfo = this.internal.getPageInfo(info.pageNumber);
+		for (var a = 0; a < pageAnnos.length; a++) {
+			var anno = pageAnnos[a];
+
+			switch (anno.type) {
+				case 'reference':
+					// References to Widget Anotations (for AcroForm Fields)
+					this.internal.write(' ' + anno.object.objId + ' 0 R ');
+					break;
+				case 'text':
+					// Create a an object for both the text and the popup
+					var objText = this.internal.newAdditionalObject();
+					var objPopup = this.internal.newAdditionalObject();
+
+					var title = anno.title || 'Note';
+					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) + "] ";
+					line = '<</Type /Annot /Subtype /' + 'Text' + ' ' + rect + '/Contents (' + anno.contents + ')';
+					line += ' /Popup ' + objPopup.objId + " 0 R";
+					line += ' /P ' + pageInfo.objId + " 0 R";
+					line += ' /T (' + title + ') >>';
+					objText.content = line;
+
+					var parent = objText.objId + ' 0 R';
+					var popoff = 30;
+					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) + "] ";
+					//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) + "] ";
+					line = '<</Type /Annot /Subtype /' + 'Popup' + ' ' + rect + ' /Parent ' + parent;
+					if (anno.open) {
+						line += ' /Open true';
+					}
+					line += ' >>';
+					objPopup.content = line;
+
+					this.internal.write(objText.objId, '0 R', objPopup.objId, '0 R');
+
+					break;
+				case 'freetext':
+					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) + "] ";
+					var color = anno.color || '#000000';
+					line = '<</Type /Annot /Subtype /' + 'FreeText' + ' ' + rect + '/Contents (' + anno.contents + ')';
+					line += ' /DS(font: Helvetica,sans-serif 12.0pt; text-align:left; color:#' + color + ')';
+					line += ' /Border [0 0 0]';
+					line += ' >>';
+					this.internal.write(line);
+					break;
+				case 'link':
+					if (anno.options.name) {
+						var loc = this.annotations._nameMap[anno.options.name];
+						anno.options.pageNumber = loc.page;
+						anno.options.top = loc.y;
+					} else {
+						if (!anno.options.top) {
+							anno.options.top = 0;
+						}
+					}
+
+					//var pageHeight = this.internal.pageSize.height * this.internal.scaleFactor;
+					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) + "] ";
+
+					var line = '';
+					if (anno.options.url) {
+						line = '<</Type /Annot /Subtype /Link ' + rect + '/Border [0 0 0] /A <</S /URI /URI (' + anno.options.url + ') >>';
+					} else if (anno.options.pageNumber) {
+						// first page is 0
+						var info = this.internal.getPageInfo(anno.options.pageNumber);
+						line = '<</Type /Annot /Subtype /Link ' + rect + '/Border [0 0 0] /Dest [' + info.objId + " 0 R";
+						anno.options.magFactor = anno.options.magFactor || "XYZ";
+						switch (anno.options.magFactor) {
+							case 'Fit':
+								line += ' /Fit]';
+								break;
+							case 'FitH':
+								//anno.options.top = anno.options.top || f2(pageHeight * k);
+								line += ' /FitH ' + anno.options.top + ']';
+								break;
+							case 'FitV':
+								anno.options.left = anno.options.left || 0;
+								line += ' /FitV ' + anno.options.left + ']';
+								break;
+							case 'XYZ':
+							default:
+								var top = f2((pageHeight - anno.options.top) * k); // || f2(pageHeight * k);
+								anno.options.left = anno.options.left || 0;
+								// 0 or null zoom will not change zoom factor
+								if (typeof anno.options.zoom === 'undefined') {
+									anno.options.zoom = 0;
+								}
+								line += ' /XYZ ' + anno.options.left + ' ' + top + ' ' + anno.options.zoom + ']';
+								break;
+						}
+					} else {
+						// TODO error - should not be here
+					}
+					if (line != '') {
+						line += " >>";
+						this.internal.write(line);
+					}
+					break;
+			}
+		}
+		this.internal.write("]");
+	}]);
+
+	jsPDFAPI.createAnnotation = function (options) {
+		switch (options.type) {
+			case 'link':
+				this.link(options.bounds.x, options.bounds.y, options.bounds.w, options.bounds.h, options);
+				break;
+			case 'text':
+			case 'freetext':
+				this.annotationPlugin.annotations[this.internal.getCurrentPageInfo().pageNumber].push(options);
+				break;
+		}
+	};
+
+	/**
+  * valid options
+  * <li> pageNumber or url [required]
+  * <p>If pageNumber is specified, top and zoom may also be specified</p>
+  */
+	jsPDFAPI.link = function (x, y, w, h, options) {
+		'use strict';
+
+		this.annotationPlugin.annotations[this.internal.getCurrentPageInfo().pageNumber].push({
+			x: x,
+			y: y,
+			w: w,
+			h: h,
+			options: options,
+			type: 'link'
+		});
+	};
+
+	/**
+  * valid options
+  * <li> pageNumber or url [required]
+  * <p>If pageNumber is specified, top and zoom may also be specified</p>
+  */
+	jsPDFAPI.link = function (x, y, w, h, options) {
+		'use strict';
+
+		this.annotationPlugin.annotations[this.internal.getCurrentPageInfo().pageNumber].push({
+			x: x,
+			y: y,
+			w: w,
+			h: h,
+			options: options,
+			type: 'link'
+		});
+	};
+
+	/**
+  * Currently only supports single line text.
+  * Returns the width of the text/link
+  */
+	jsPDFAPI.textWithLink = function (text, x, y, options) {
+		'use strict';
+
+		var width = this.getTextWidth(text);
+		var height = this.internal.getLineHeight();
+		this.text(text, x, y);
+		//TODO We really need the text baseline height to do this correctly.
+		// Or ability to draw text on top, bottom, center, or baseline.
+		y += height * .2;
+		this.link(x, y - height, width, height, options);
+		return width;
+	};
+
+	//TODO move into external library
+	jsPDFAPI.getTextWidth = function (text) {
+		'use strict';
+
+		var fontSize = this.internal.getFontSize();
+		var txtWidth = this.getStringUnitWidth(text) * fontSize / this.internal.scaleFactor;
+		return txtWidth;
+	};
+
+	//TODO move into external library
+	jsPDFAPI.getLineHeight = function () {
+		return this.internal.getLineHeight();
+	};
+
+	return this;
+})(jsPDF.API);
+
+/**
+ * jsPDF Autoprint Plugin
+ *
+ * Licensed under the MIT License.
+ * http://opensource.org/licenses/mit-license
+ */
+
+/**
+* Makes the PDF automatically print. This works in Chrome, Firefox, Acrobat
+* Reader.
+*
+* @returns {jsPDF}
+* @name autoPrint
+* @example
+* var doc = new jsPDF()
+* doc.text(10, 10, 'This is a test')
+* doc.autoPrint()
+* doc.save('autoprint.pdf')
+*/
+
+(function (jsPDFAPI) {
+  'use strict';
+
+  jsPDFAPI.autoPrint = function () {
+    'use strict';
+
+    var refAutoPrintTag;
+
+    this.internal.events.subscribe('postPutResources', function () {
+      refAutoPrintTag = this.internal.newObject();
+      this.internal.write("<< /S/Named /Type/Action /N/Print >>", "endobj");
+    });
+
+    this.internal.events.subscribe("putCatalog", function () {
+      this.internal.write("/OpenAction " + refAutoPrintTag + " 0" + " R");
+    });
+    return this;
+  };
+})(jsPDF.API);
+
+/**
+ * jsPDF Canvas PlugIn
+ * Copyright (c) 2014 Steven Spungin (TwelveTone LLC)  steven@twelvetone.tv
+ *
+ * Licensed under the MIT License.
+ * http://opensource.org/licenses/mit-license
+ */
+
+/**
+ * This plugin mimics the HTML5 Canvas
+ * 
+ * The goal is to provide a way for current canvas users to print directly to a PDF.
+ */
+
+(function (jsPDFAPI) {
+	'use strict';
+
+	jsPDFAPI.events.push(['initialized', function () {
+		this.canvas.pdf = this;
+	}]);
+
+	jsPDFAPI.canvas = {
+		getContext: function getContext(name) {
+			this.pdf.context2d._canvas = this;
+			return this.pdf.context2d;
+		},
+		style: {}
+	};
+
+	Object.defineProperty(jsPDFAPI.canvas, 'width', {
+		get: function get() {
+			return this._width;
+		},
+		set: function set(value) {
+			this._width = value;
+			this.getContext('2d').pageWrapX = value + 1;
+		}
+	});
+
+	Object.defineProperty(jsPDFAPI.canvas, 'height', {
+		get: function get() {
+			return this._height;
+		},
+		set: function set(value) {
+			this._height = value;
+			this.getContext('2d').pageWrapY = value + 1;
+		}
+	});
+
+	return this;
+})(jsPDF.API);
+
+/** ====================================================================
+ * jsPDF Cell plugin
+ * Copyright (c) 2013 Youssef Beddad, youssef.beddad@gmail.com
+ *               2013 Eduardo Menezes de Morais, eduardo.morais@usp.br
+ *               2013 Lee Driscoll, https://github.com/lsdriscoll
+ *               2014 Juan Pablo Gaviria, https://github.com/juanpgaviria
+ *               2014 James Hall, james@parall.ax
+ *               2014 Diego Casorran, https://github.com/diegocr
+ *
+ * 
+ * ====================================================================
+ */
+
+(function (jsPDFAPI) {
+    'use strict';
+    /*jslint browser:true */
+    /*global document: false, jsPDF */
+
+    var fontName,
+        fontSize,
+        fontStyle,
+        padding = 3,
+        margin = 13,
+        headerFunction,
+        lastCellPos = { x: undefined, y: undefined, w: undefined, h: undefined, ln: undefined },
+        pages = 1,
+        setLastCellPosition = function setLastCellPosition(x, y, w, h, ln) {
+        lastCellPos = { 'x': x, 'y': y, 'w': w, 'h': h, 'ln': ln };
+    },
+        getLastCellPosition = function getLastCellPosition() {
+        return lastCellPos;
+    },
+        NO_MARGINS = { left: 0, top: 0, bottom: 0 };
+
+    jsPDFAPI.setHeaderFunction = function (func) {
+        headerFunction = func;
+    };
+
+    jsPDFAPI.getTextDimensions = function (txt) {
+        fontName = this.internal.getFont().fontName;
+        fontSize = this.table_font_size || this.internal.getFontSize();
+        fontStyle = this.internal.getFont().fontStyle;
+        // 1 pixel = 0.264583 mm and 1 mm = 72/25.4 point
+        var px2pt = 0.264583 * 72 / 25.4,
+            dimensions,
+            text;
+
+        text = document.createElement('font');
+        text.id = "jsPDFCell";
+
+        try {
+            text.style.fontStyle = fontStyle;
+        } catch (e) {
+            text.style.fontWeight = fontStyle;
+        }
+
+        text.style.fontName = fontName;
+        text.style.fontSize = fontSize + 'pt';
+        try {
+            text.textContent = txt;
+        } catch (e) {
+            text.innerText = txt;
+        }
+
+        document.body.appendChild(text);
+
+        dimensions = { w: (text.offsetWidth + 1) * px2pt, h: (text.offsetHeight + 1) * px2pt };
+
+        document.body.removeChild(text);
+
+        return dimensions;
+    };
+
+    jsPDFAPI.cellAddPage = function () {
+        var margins = this.margins || NO_MARGINS;
+
+        this.addPage();
+
+        setLastCellPosition(margins.left, margins.top, undefined, undefined);
+        //setLastCellPosition(undefined, undefined, undefined, undefined, undefined);
+        pages += 1;
+    };
+
+    jsPDFAPI.cellInitialize = function () {
+        lastCellPos = { x: undefined, y: undefined, w: undefined, h: undefined, ln: undefined };
+        pages = 1;
+    };
+
+    jsPDFAPI.cell = function (x, y, w, h, txt, ln, align) {
+        var curCell = getLastCellPosition();
+        var pgAdded = false;
+
+        // If this is not the first cell, we must change its position
+        if (curCell.ln !== undefined) {
+            if (curCell.ln === ln) {
+                //Same line
+                x = curCell.x + curCell.w;
+                y = curCell.y;
+            } else {
+                //New line
+                var margins = this.margins || NO_MARGINS;
+                if (curCell.y + curCell.h + h + margin >= this.internal.pageSize.height - margins.bottom) {
+                    this.cellAddPage();
+                    pgAdded = true;
+                    if (this.printHeaders && this.tableHeaderRow) {
+                        this.printHeaderRow(ln, true);
+                    }
+                }
+                //We ignore the passed y: the lines may have different heights
+                y = getLastCellPosition().y + getLastCellPosition().h;
+                if (pgAdded) y = margin + 10;
+            }
+        }
+
+        if (txt[0] !== undefined) {
+            if (this.printingHeaderRow) {
+                this.rect(x, y, w, h, 'FD');
+            } else {
+                this.rect(x, y, w, h);
+            }
+            if (align === 'right') {
+                if (!(txt instanceof Array)) {
+                    txt = [txt];
+                }
+                for (var i = 0; i < txt.length; i++) {
+                    var currentLine = txt[i];
+                    var textSize = this.getStringUnitWidth(currentLine) * this.internal.getFontSize();
+                    this.text(currentLine, x + w - textSize - padding, y + this.internal.getLineHeight() * (i + 1));
+                }
+            } else {
+                this.text(txt, x + padding, y + this.internal.getLineHeight());
+            }
+        }
+        setLastCellPosition(x, y, w, h, ln);
+        return this;
+    };
+
+    /**
+     * Return the maximum value from an array
+     * @param array
+     * @param comparisonFn
+     * @returns {*}
+     */
+    jsPDFAPI.arrayMax = function (array, comparisonFn) {
+        var max = array[0],
+            i,
+            ln,
+            item;
+
+        for (i = 0, ln = array.length; i < ln; i += 1) {
+            item = array[i];
+
+            if (comparisonFn) {
+                if (comparisonFn(max, item) === -1) {
+                    max = item;
+                }
+            } else {
+                if (item > max) {
+                    max = item;
+                }
+            }
+        }
+
+        return max;
+    };
+
+    /**
+     * Create a table from a set of data.
+     * @param {Integer} [x] : left-position for top-left corner of table
+     * @param {Integer} [y] top-position for top-left corner of table
+     * @param {Object[]} [data] As array of objects containing key-value pairs corresponding to a row of data.
+     * @param {String[]} [headers] Omit or null to auto-generate headers at a performance cost
+      * @param {Object} [config.printHeaders] True to print column headers at the top of every page
+     * @param {Object} [config.autoSize] True to dynamically set the column widths to match the widest cell value
+     * @param {Object} [config.margins] margin values for left, top, bottom, and width
+     * @param {Object} [config.fontSize] Integer fontSize to use (optional)
+     */
+
+    jsPDFAPI.table = function (x, y, data, headers, config) {
+        if (!data) {
+            throw 'No data for PDF table';
+        }
+
+        var headerNames = [],
+            headerPrompts = [],
+            header,
+            i,
+            ln,
+            cln,
+            columnMatrix = {},
+            columnWidths = {},
+            columnData,
+            column,
+            columnMinWidths = [],
+            j,
+            tableHeaderConfigs = [],
+            model,
+            jln,
+            func,
+
+
+        //set up defaults. If a value is provided in config, defaults will be overwritten:
+        autoSize = false,
+            printHeaders = true,
+            fontSize = 12,
+            margins = NO_MARGINS;
+
+        margins.width = this.internal.pageSize.width;
+
+        if (config) {
+            //override config defaults if the user has specified non-default behavior:
+            if (config.autoSize === true) {
+                autoSize = true;
+            }
+            if (config.printHeaders === false) {
+                printHeaders = false;
+            }
+            if (config.fontSize) {
+                fontSize = config.fontSize;
+            }
+            if (config.css && typeof config.css['font-size'] !== "undefined") {
+                fontSize = config.css['font-size'] * 16;
+            }
+            if (config.margins) {
+                margins = config.margins;
+            }
+        }
+
+        /**
+         * @property {Number} lnMod
+         * Keep track of the current line number modifier used when creating cells
+         */
+        this.lnMod = 0;
+        lastCellPos = { x: undefined, y: undefined, w: undefined, h: undefined, ln: undefined }, pages = 1;
+
+        this.printHeaders = printHeaders;
+        this.margins = margins;
+        this.setFontSize(fontSize);
+        this.table_font_size = fontSize;
+
+        // Set header values
+        if (headers === undefined || headers === null) {
+            // No headers defined so we derive from data
+            headerNames = Object.keys(data[0]);
+        } else if (headers[0] && typeof headers[0] !== 'string') {
+            var px2pt = 0.264583 * 72 / 25.4;
+
+            // Split header configs into names and prompts
+            for (i = 0, ln = headers.length; i < ln; i += 1) {
+                header = headers[i];
+                headerNames.push(header.name);
+                headerPrompts.push(header.prompt);
+                columnWidths[header.name] = header.width * px2pt;
+            }
+        } else {
+            headerNames = headers;
+        }
+
+        if (autoSize) {
+            // Create a matrix of columns e.g., {column_title: [row1_Record, row2_Record]}
+            func = function func(rec) {
+                return rec[header];
+            };
+
+            for (i = 0, ln = headerNames.length; i < ln; i += 1) {
+                header = headerNames[i];
+
+                columnMatrix[header] = data.map(func);
+
+                // get header width
+                columnMinWidths.push(this.getTextDimensions(headerPrompts[i] || header).w);
+                column = columnMatrix[header];
+
+                // get cell widths
+                for (j = 0, cln = column.length; j < cln; j += 1) {
+                    columnData = column[j];
+                    columnMinWidths.push(this.getTextDimensions(columnData).w);
+                }
+
+                // get final column width
+                columnWidths[header] = jsPDFAPI.arrayMax(columnMinWidths);
+
+                //have to reset
+                columnMinWidths = [];
+            }
+        }
+
+        // -- Construct the table
+
+        if (printHeaders) {
+            var lineHeight = this.calculateLineHeight(headerNames, columnWidths, headerPrompts.length ? headerPrompts : headerNames);
+
+            // Construct the header row
+            for (i = 0, ln = headerNames.length; i < ln; i += 1) {
+                header = headerNames[i];
+                tableHeaderConfigs.push([x, y, columnWidths[header], lineHeight, String(headerPrompts.length ? headerPrompts[i] : header)]);
+            }
+
+            // Store the table header config
+            this.setTableHeaderRow(tableHeaderConfigs);
+
+            // Print the header for the start of the table
+            this.printHeaderRow(1, false);
+        }
+
+        // Construct the data rows
+        for (i = 0, ln = data.length; i < ln; i += 1) {
+            var lineHeight;
+            model = data[i];
+            lineHeight = this.calculateLineHeight(headerNames, columnWidths, model);
+
+            for (j = 0, jln = headerNames.length; j < jln; j += 1) {
+                header = headerNames[j];
+                this.cell(x, y, columnWidths[header], lineHeight, model[header], i + 2, header.align);
+            }
+        }
+        this.lastCellPos = lastCellPos;
+        this.table_x = x;
+        this.table_y = y;
+        return this;
+    };
+    /**
+     * Calculate the height for containing the highest column
+     * @param {String[]} headerNames is the header, used as keys to the data
+     * @param {Integer[]} columnWidths is size of each column
+     * @param {Object[]} model is the line of data we want to calculate the height of
+     */
+    jsPDFAPI.calculateLineHeight = function (headerNames, columnWidths, model) {
+        var header,
+            lineHeight = 0;
+        for (var j = 0; j < headerNames.length; j++) {
+            header = headerNames[j];
+            model[header] = this.splitTextToSize(String(model[header]), columnWidths[header] - padding);
+            var h = this.internal.getLineHeight() * model[header].length + padding;
+            if (h > lineHeight) lineHeight = h;
+        }
+        return lineHeight;
+    };
+
+    /**
+     * Store the config for outputting a table header
+     * @param {Object[]} config
+     * An array of cell configs that would define a header row: Each config matches the config used by jsPDFAPI.cell
+     * except the ln parameter is excluded
+     */
+    jsPDFAPI.setTableHeaderRow = function (config) {
+        this.tableHeaderRow = config;
+    };
+
+    /**
+     * Output the store header row
+     * @param lineNumber The line number to output the header at
+     */
+    jsPDFAPI.printHeaderRow = function (lineNumber, new_page) {
+        if (!this.tableHeaderRow) {
+            throw 'Property tableHeaderRow does not exist.';
+        }
+
+        var tableHeaderCell, tmpArray, i, ln;
+
+        this.printingHeaderRow = true;
+        if (headerFunction !== undefined) {
+            var position = headerFunction(this, pages);
+            setLastCellPosition(position[0], position[1], position[2], position[3], -1);
+        }
+        this.setFontStyle('bold');
+        var tempHeaderConf = [];
+        for (i = 0, ln = this.tableHeaderRow.length; i < ln; i += 1) {
+            this.setFillColor(200, 200, 200);
+
+            tableHeaderCell = this.tableHeaderRow[i];
+            if (new_page) {
+                this.margins.top = margin;
+                tableHeaderCell[1] = this.margins && this.margins.top || 0;
+                tempHeaderConf.push(tableHeaderCell);
+            }
+            tmpArray = [].concat(tableHeaderCell);
+            this.cell.apply(this, tmpArray.concat(lineNumber));
+        }
+        if (tempHeaderConf.length > 0) {
+            this.setTableHeaderRow(tempHeaderConf);
+        }
+        this.setFontStyle('normal');
+        this.printingHeaderRow = false;
+    };
+})(jsPDF.API);
+
+/**
+ * jsPDF Context2D PlugIn Copyright (c) 2014 Steven Spungin (TwelveTone LLC) steven@twelvetone.tv
+ *
+ * Licensed under the MIT License. http://opensource.org/licenses/mit-license
+ */
+
+/**
+ * This plugin mimics the HTML5 Canvas's context2d.
+ *
+ * The goal is to provide a way for current canvas implementations to print directly to a PDF.
+ */
+
+/**
+ * TODO implement stroke opacity (refactor from fill() method )
+ * TODO transform angle and radii parameters
+ */
+
+/**
+ * require('jspdf.js'); require('lib/css_colors.js');
+ */
+
+(function (jsPDFAPI) {
+    'use strict';
+
+    jsPDFAPI.events.push(['initialized', function () {
+        this.context2d.pdf = this;
+        this.context2d.internal.pdf = this;
+        this.context2d.ctx = new context();
+        this.context2d.ctxStack = [];
+        this.context2d.path = [];
+    }]);
+
+    jsPDFAPI.context2d = {
+        pageWrapXEnabled: false,
+        pageWrapYEnabled: false,
+        pageWrapX: 9999999,
+        pageWrapY: 9999999,
+        ctx: new context(),
+        f2: function f2(number) {
+            return number.toFixed(2);
+        },
+
+        fillRect: function fillRect(x, y, w, h) {
+            if (this._isFillTransparent()) {
+                return;
+            }
+            x = this._wrapX(x);
+            y = this._wrapY(y);
+
+            var xRect = this._matrix_map_rect(this.ctx._transform, { x: x, y: y, w: w, h: h });
+            this.pdf.rect(xRect.x, xRect.y, xRect.w, xRect.h, "f");
+        },
+
+        strokeRect: function strokeRect(x, y, w, h) {
+            if (this._isStrokeTransparent()) {
+                return;
+            }
+            x = this._wrapX(x);
+            y = this._wrapY(y);
+
+            var xRect = this._matrix_map_rect(this.ctx._transform, { x: x, y: y, w: w, h: h });
+            this.pdf.rect(xRect.x, xRect.y, xRect.w, xRect.h, "s");
+        },
+
+        /**
+         * We cannot clear PDF commands that were already written to PDF, so we use white instead. <br />
+         * As a special case, read a special flag (ignoreClearRect) and do nothing if it is set.
+         * This results in all calls to clearRect() to do nothing, and keep the canvas transparent.
+         * This flag is stored in the save/restore context and is managed the same way as other drawing states.
+         * @param x
+         * @param y
+         * @param w
+         * @param h
+         */
+        clearRect: function clearRect(x, y, w, h) {
+            if (this.ctx.ignoreClearRect) {
+                return;
+            }
+
+            x = this._wrapX(x);
+            y = this._wrapY(y);
+
+            var xRect = this._matrix_map_rect(this.ctx._transform, { x: x, y: y, w: w, h: h });
+            this.save();
+            this.setFillStyle('#ffffff');
+            //TODO This is hack to fill with white.
+            this.pdf.rect(xRect.x, xRect.y, xRect.w, xRect.h, "f");
+            this.restore();
+        },
+
+        save: function save() {
+            this.ctx._fontSize = this.pdf.internal.getFontSize();
+            var ctx = new context();
+            ctx.copy(this.ctx);
+            this.ctxStack.push(this.ctx);
+            this.ctx = ctx;
+        },
+
+        restore: function restore() {
+            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 rect(x, y, w, h) {
+            this.moveTo(x, y);
+            this.lineTo(x + w, y);
+            this.lineTo(x + w, y + h);
+            this.lineTo(x, y + h);
+            this.lineTo(x, y); //TODO not needed
+            this.closePath();
+        },
+
+        beginPath: function beginPath() {
+            this.path = [];
+        },
+
+        closePath: function closePath() {
+            this.path.push({
+                type: 'close'
+            });
+        },
+
+        _getRgba: function _getRgba(style) {
+            // get the decimal values of r, g, and b;
+            var rgba = {};
+
+            if (this.internal.rxTransparent.test(style)) {
+                rgba.r = 0;
+                rgba.g = 0;
+                rgba.b = 0;
+                rgba.a = 0;
+            } else {
+                var m = this.internal.rxRgb.exec(style);
+                if (m != null) {
+                    rgba.r = parseInt(m[1]);
+                    rgba.g = parseInt(m[2]);
+                    rgba.b = parseInt(m[3]);
+                    rgba.a = 1;
+                } else {
+                    m = this.internal.rxRgba.exec(style);
+                    if (m != null) {
+                        rgba.r = parseInt(m[1]);
+                        rgba.g = parseInt(m[2]);
+                        rgba.b = parseInt(m[3]);
+                        rgba.a = parseFloat(m[4]);
+                    } else {
+                        rgba.a = 1;
+                        if (style.charAt(0) != '#') {
+                            style = CssColors.colorNameToHex(style);
+                            if (!style) {
+                                style = '#000000';
+                            }
+                        } else {}
+
+                        if (style.length === 4) {
+                            rgba.r = style.substring(1, 2);
+                            rgba.r += r;
+                            rgba.g = style.substring(2, 3);
+                            rgba.g += g;
+                            rgba.b = style.substring(3, 4);
+                            rgba.b += b;
+                        } else {
+                            rgba.r = style.substring(1, 3);
+                            rgba.g = style.substring(3, 5);
+                            rgba.b = style.substring(5, 7);
+                        }
+                        rgba.r = parseInt(rgba.r, 16);
+                        rgba.g = parseInt(rgba.g, 16);
+                        rgba.b = parseInt(rgba.b, 16);
+                    }
+                }
+            }
+            rgba.style = style;
+            return rgba;
+        },
+
+        setFillStyle: function setFillStyle(style) {
+            // get the decimal values of r, g, and b;
+            var r, g, b, a;
+
+            if (this.internal.rxTransparent.test(style)) {
+                r = 0;
+                g = 0;
+                b = 0;
+                a = 0;
+            } else {
+                var m = this.internal.rxRgb.exec(style);
+                if (m != null) {
+                    r = parseInt(m[1]);
+                    g = parseInt(m[2]);
+                    b = parseInt(m[3]);
+                    a = 1;
+                } else {
+                    m = this.internal.rxRgba.exec(style);
+                    if (m != null) {
+                        r = parseInt(m[1]);
+                        g = parseInt(m[2]);
+                        b = parseInt(m[3]);
+                        a = parseFloat(m[4]);
+                    } else {
+                        a = 1;
+                        if (style.charAt(0) != '#') {
+                            style = CssColors.colorNameToHex(style);
+                            if (!style) {
+                                style = '#000000';
+                            }
+                        } else {}
+
+                        if (style.length === 4) {
+                            r = style.substring(1, 2);
+                            r += r;
+                            g = style.substring(2, 3);
+                            g += g;
+                            b = style.substring(3, 4);
+                            b += b;
+                        } else {
+                            r = style.substring(1, 3);
+                            g = style.substring(3, 5);
+                            b = style.substring(5, 7);
+                        }
+                        r = parseInt(r, 16);
+                        g = parseInt(g, 16);
+                        b = parseInt(b, 16);
+                    }
+                }
+            }
+
+            this.ctx.fillStyle = style;
+            this.ctx._isFillTransparent = a == 0;
+            this.ctx._fillOpacity = a;
+
+            this.pdf.setFillColor(r, g, b, {
+                a: a
+            });
+            this.pdf.setTextColor(r, g, b, {
+                a: a
+            });
+        },
+
+        setStrokeStyle: function setStrokeStyle(style) {
+            var rgba = this._getRgba(style);
+
+            this.ctx.strokeStyle = rgba.style;
+            this.ctx._isStrokeTransparent = rgba.a == 0;
+            this.ctx._strokeOpacity = rgba.a;
+
+            //TODO jsPDF to handle rgba
+            if (rgba.a === 0) {
+                this.pdf.setDrawColor(255, 255, 255);
+            } else if (rgba.a === 1) {
+                this.pdf.setDrawColor(rgba.r, rgba.g, rgba.b);
+            } else {
+                //this.pdf.setDrawColor(rgba.r, rgba.g, rgba.b, {a: rgba.a});
+                this.pdf.setDrawColor(rgba.r, rgba.g, rgba.b);
+            }
+        },
+
+        fillText: function fillText(text, x, y, maxWidth) {
+            if (this._isFillTransparent()) {
+                return;
+            }
+            x = this._wrapX(x);
+            y = this._wrapY(y);
+
+            var xpt = this._matrix_map_point(this.ctx._transform, [x, y]);
+            x = xpt[0];
+            y = xpt[1];
+            var rads = this._matrix_rotation(this.ctx._transform);
+            var degs = rads * 57.2958;
+
+            //TODO only push the clip if it has not been applied to the current PDF context
+            if (this.ctx._clip_path.length > 0) {
+                var lines;
+                if (window.outIntercept) {
+                    lines = window.outIntercept.type === 'group' ? window.outIntercept.stream : window.outIntercept;
+                } else {
+                    lines = this.internal.getCurrentPage();
+                }
+                lines.push("q");
+                var origPath = this.path;
+                this.path = this.ctx._clip_path;
+                this.ctx._clip_path = [];
+                this._fill(null, true);
+                this.ctx._clip_path = this.path;
+                this.path = origPath;
+            }
+
+            // We only use X axis as scale hint 
+            var scale = 1;
+            try {
+                scale = this._matrix_decompose(this._getTransform()).scale[0];
+            } catch (e) {
+                console.warn(e);
+            }
+
+            // In some cases the transform was very small (5.715760606202283e-17).  Most likely a canvg rounding error.
+            if (scale < .01) {
+                this.pdf.text(text, x, this._getBaseline(y), null, degs);
+            } else {
+                var oldSize = this.pdf.internal.getFontSize();
+                this.pdf.setFontSize(oldSize * scale);
+                this.pdf.text(text, x, this._getBaseline(y), null, degs);
+                this.pdf.setFontSize(oldSize);
+            }
+
+            if (this.ctx._clip_path.length > 0) {
+                lines.push('Q');
+            }
+        },
+
+        strokeText: function strokeText(text, x, y, maxWidth) {
+            if (this._isStrokeTransparent()) {
+                return;
+            }
+            x = this._wrapX(x);
+            y = this._wrapY(y);
+
+            var xpt = this._matrix_map_point(this.ctx._transform, [x, y]);
+            x = xpt[0];
+            y = xpt[1];
+            var rads = this._matrix_rotation(this.ctx._transform);
+            var degs = rads * 57.2958;
+
+            //TODO only push the clip if it has not been applied to the current PDF context
+            if (this.ctx._clip_path.length > 0) {
+                var lines;
+                if (window.outIntercept) {
+                    lines = window.outIntercept.type === 'group' ? window.outIntercept.stream : window.outIntercept;
+                } else {
+                    lines = this.internal.getCurrentPage();
+                }
+                lines.push("q");
+                var origPath = this.path;
+                this.path = this.ctx._clip_path;
+                this.ctx._clip_path = [];
+                this._fill(null, true);
+                this.ctx._clip_path = this.path;
+                this.path = origPath;
+            }
+
+            var scale = 1;
+            // We only use the X axis as scale hint 
+            try {
+                scale = this._matrix_decompose(this._getTransform()).scale[0];
+            } catch (e) {
+                console.warn(e);
+            }
+
+            if (scale === 1) {
+                this.pdf.text(text, x, this._getBaseline(y), {
+                    stroke: true
+                }, degs);
+            } else {
+                var oldSize = this.pdf.internal.getFontSize();
+                this.pdf.setFontSize(oldSize * scale);
+                this.pdf.text(text, x, this._getBaseline(y), {
+                    stroke: true
+                }, degs);
+                this.pdf.setFontSize(oldSize);
+            }
+
+            if (this.ctx._clip_path.length > 0) {
+                lines.push('Q');
+            }
+        },
+
+        setFont: function setFont(font) {
+            this.ctx.font = font;
+
+            //var rx = /\s*(\w+)\s+(\w+)\s+(\w+)\s+([\d\.]+)(px|pt|em)\s+["']?(\w+)['"]?/;
+            var rx = /\s*(\w+)\s+(\w+)\s+(\w+)\s+([\d\.]+)(px|pt|em)\s+(.*)?/;
+            m = rx.exec(font);
+            if (m != null) {
+                var fontStyle = m[1];
+                var fontVariant = m[2];
+                var fontWeight = m[3];
+                var fontSize = m[4];
+                var fontSizeUnit = m[5];
+                var fontFamily = m[6];
+
+                if ('px' === fontSizeUnit) {
+                    fontSize = Math.floor(parseFloat(fontSize));
+                    // fontSize = fontSize * 1.25;
+                } else if ('em' === fontSizeUnit) {
+                    fontSize = Math.floor(parseFloat(fontSize) * this.pdf.getFontSize());
+                } else {
+                    fontSize = Math.floor(parseFloat(fontSize));
+                }
+
+                this.pdf.setFontSize(fontSize);
+
+                if (fontWeight === 'bold' || fontWeight === '700') {
+                    this.pdf.setFontStyle('bold');
+                } else {
+                    if (fontStyle === 'italic') {
+                        this.pdf.setFontStyle('italic');
+                    } else {
+                        this.pdf.setFontStyle('normal');
+                    }
+                }
+
+                var name = fontFamily;
+                var parts = name.toLowerCase().split(/\s*,\s*/);
+                var jsPdfFontName;
+
+                if (parts.indexOf('arial') != -1) {
+                    jsPdfFontName = 'Arial';
+                } else if (parts.indexOf('verdana') != -1) {
+                    jsPdfFontName = 'Verdana';
+                } else if (parts.indexOf('helvetica') != -1) {
+                    jsPdfFontName = 'Helvetica';
+                } else if (parts.indexOf('sans-serif') != -1) {
+                    jsPdfFontName = 'sans-serif';
+                } else if (parts.indexOf('fixed') != -1) {
+                    jsPdfFontName = 'Fixed';
+                } else if (parts.indexOf('monospace') != -1) {
+                    jsPdfFontName = 'Monospace';
+                } else if (parts.indexOf('terminal') != -1) {
+                    jsPdfFontName = 'Terminal';
+                } else if (parts.indexOf('courier') != -1) {
+                    jsPdfFontName = 'Courier';
+                } else if (parts.indexOf('times') != -1) {
+                    jsPdfFontName = 'Times';
+                } else if (parts.indexOf('cursive') != -1) {
+                    jsPdfFontName = 'Cursive';
+                } else if (parts.indexOf('fantasy') != -1) {
+                    jsPdfFontName = 'Fantasy';
+                } else if (parts.indexOf('serif') != -1) {
+                    jsPdfFontName = 'Serif';
+                } else {
+                    jsPdfFontName = 'Serif';
+                }
+
+                //TODO check more cases
+                var style;
+                if ('bold' === fontWeight) {
+                    style = 'bold';
+                } else {
+                    style = 'normal';
+                }
+
+                this.pdf.setFont(jsPdfFontName, style);
+            } else {
+                var rx = /\s*(\d+)(pt|px|em)\s+([\w "]+)\s*([\w "]+)?/;
+                var m = rx.exec(font);
+                if (m != null) {
+                    var size = m[1];
+                    var unit = m[2];
+                    var name = m[3];
+                    var style = m[4];
+                    if (!style) {
+                        style = 'normal';
+                    }
+                    if ('em' === fontSizeUnit) {
+                        size = Math.floor(parseFloat(fontSize) * this.pdf.getFontSize());
+                    } else {
+                        size = Math.floor(parseFloat(size));
+                    }
+                    this.pdf.setFontSize(size);
+                    this.pdf.setFont(name, style);
+                }
+            }
+        },
+
+        setTextBaseline: function setTextBaseline(baseline) {
+            this.ctx.textBaseline = baseline;
+        },
+
+        getTextBaseline: function getTextBaseline() {
+            return this.ctx.textBaseline;
+        },
+
+        //TODO implement textAlign
+        setTextAlign: function setTextAlign(align) {
+            this.ctx.textAlign = align;
+        },
+
+        getTextAlign: function getTextAlign() {
+            return this.ctx.textAlign;
+        },
+
+        setLineWidth: function setLineWidth(width) {
+            this.ctx.lineWidth = width;
+            this.pdf.setLineWidth(width);
+        },
+
+        setLineCap: function setLineCap(style) {
+            this.ctx.lineCap = style;
+            this.pdf.setLineCap(style);
+        },
+
+        setLineJoin: function setLineJoin(style) {
+            this.ctx.lineJoin = style;
+            this.pdf.setLineJoin(style);
+        },
+
+        moveTo: function moveTo(x, y) {
+            x = this._wrapX(x);
+            y = this._wrapY(y);
+
+            var xpt = this._matrix_map_point(this.ctx._transform, [x, y]);
+            x = xpt[0];
+            y = xpt[1];
+
+            var obj = {
+                type: 'mt',
+                x: x,
+                y: y
+            };
+            this.path.push(obj);
+        },
+
+        _wrapX: function _wrapX(x) {
+            if (this.pageWrapXEnabled) {
+                return x % this.pageWrapX;
+            } else {
+                return x;
+            }
+        },
+
+        _wrapY: function _wrapY(y) {
+            if (this.pageWrapYEnabled) {
+                this._gotoPage(this._page(y));
+                return (y - this.lastBreak) % this.pageWrapY;
+            } else {
+                return y;
+            }
+        },
+
+        transform: function transform(a, b, c, d, e, f) {
+            //TODO apply to current transformation instead of replacing
+            this.ctx._transform = [a, b, c, d, e, f];
+        },
+
+        setTransform: function setTransform(a, b, c, d, e, f) {
+            this.ctx._transform = [a, b, c, d, e, f];
+        },
+
+        _getTransform: function _getTransform() {
+            return this.ctx._transform;
+        },
+
+        lastBreak: 0,
+        // Y Position of page breaks.
+        pageBreaks: [],
+        // returns: One-based Page Number
+        // Should only be used if pageWrapYEnabled is true
+        _page: function _page(y) {
+            if (this.pageWrapYEnabled) {
+                this.lastBreak = 0;
+                var manualBreaks = 0;
+                var autoBreaks = 0;
+                for (var i = 0; i < this.pageBreaks.length; i++) {
+                    if (y >= this.pageBreaks[i]) {
+                        manualBreaks++;
+                        if (this.lastBreak === 0) {
+                            autoBreaks++;
+                        }
+                        var spaceBetweenLastBreak = this.pageBreaks[i] - this.lastBreak;
+                        this.lastBreak = this.pageBreaks[i];
+                        var pagesSinceLastBreak = Math.floor(spaceBetweenLastBreak / this.pageWrapY);
+                        autoBreaks += pagesSinceLastBreak;
+                    }
+                }
+                if (this.lastBreak === 0) {
+                    var pagesSinceLastBreak = Math.floor(y / this.pageWrapY) + 1;
+                    autoBreaks += pagesSinceLastBreak;
+                }
+                return autoBreaks + manualBreaks;
+            } else {
+                return this.pdf.internal.getCurrentPageInfo().pageNumber;
+            }
+        },
+
+        _gotoPage: function _gotoPage(pageOneBased) {
+            // This is a stub to be overriden if needed
+        },
+
+        lineTo: function lineTo(x, y) {
+            x = this._wrapX(x);
+            y = this._wrapY(y);
+
+            var xpt = this._matrix_map_point(this.ctx._transform, [x, y]);
+            x = xpt[0];
+            y = xpt[1];
+
+            var obj = {
+                type: 'lt',
+                x: x,
+                y: y
+            };
+            this.path.push(obj);
+        },
+
+        bezierCurveTo: function bezierCurveTo(x1, y1, x2, y2, x, y) {
+            x1 = this._wrapX(x1);
+            y1 = this._wrapY(y1);
+            x2 = this._wrapX(x2);
+            y2 = this._wrapY(y2);
+            x = this._wrapX(x);
+            y = this._wrapY(y);
+
+            var xpt;
+            xpt = this._matrix_map_point(this.ctx._transform, [x, y]);
+            x = xpt[0];
+            y = xpt[1];
+            xpt = this._matrix_map_point(this.ctx._transform, [x1, y1]);
+            x1 = xpt[0];
+            y1 = xpt[1];
+            xpt = this._matrix_map_point(this.ctx._transform, [x2, y2]);
+            x2 = xpt[0];
+            y2 = xpt[1];
+
+            var obj = {
+                type: 'bct',
+                x1: x1,
+                y1: y1,
+                x2: x2,
+                y2: y2,
+                x: x,
+                y: y
+            };
+            this.path.push(obj);
+        },
+
+        quadraticCurveTo: function quadraticCurveTo(x1, y1, x, y) {
+            x1 = this._wrapX(x1);
+            y1 = this._wrapY(y1);
+            x = this._wrapX(x);
+            y = this._wrapY(y);
+
+            var xpt;
+            xpt = this._matrix_map_point(this.ctx._transform, [x, y]);
+            x = xpt[0];
+            y = xpt[1];
+            xpt = this._matrix_map_point(this.ctx._transform, [x1, y1]);
+            x1 = xpt[0];
+            y1 = xpt[1];
+
+            var obj = {
+                type: 'qct',
+                x1: x1,
+                y1: y1,
+                x: x,
+                y: y
+            };
+            this.path.push(obj);
+        },
+
+        arc: function arc(x, y, radius, startAngle, endAngle, anticlockwise) {
+            x = this._wrapX(x);
+            y = this._wrapY(y);
+
+            if (!this._matrix_is_identity(this.ctx._transform)) {
+                var xpt = this._matrix_map_point(this.ctx._transform, [x, y]);
+                x = xpt[0];
+                y = xpt[1];
+
+                var x_radPt0 = this._matrix_map_point(this.ctx._transform, [0, 0]);
+                var x_radPt = this._matrix_map_point(this.ctx._transform, [0, radius]);
+                radius = Math.sqrt(Math.pow(x_radPt[0] - x_radPt0[0], 2) + Math.pow(x_radPt[1] - x_radPt0[1], 2));
+
+                //TODO angles need to be transformed
+            }
+
+            var obj = {
+                type: 'arc',
+                x: x,
+                y: y,
+                radius: radius,
+                startAngle: startAngle,
+                endAngle: endAngle,
+                anticlockwise: anticlockwise
+            };
+            this.path.push(obj);
+        },
+
+        drawImage: function drawImage(img, x, y, w, h, x2, y2, w2, h2) {
+            if (x2 !== undefined) {
+                x = x2;
+                y = y2;
+                w = w2;
+                h = h2;
+            }
+            x = this._wrapX(x);
+            y = this._wrapY(y);
+
+            var xRect = this._matrix_map_rect(this.ctx._transform, { x: x, y: y, w: w, h: h });
+            var xRect2 = this._matrix_map_rect(this.ctx._transform, { x: x2, y: y2, w: w2, h: h2 });
+
+            // TODO implement source clipping and image scaling
+            var format;
+            var rx = /data:image\/(\w+).*/i;
+            var m = rx.exec(img);
+            if (m != null) {
+                format = m[1];
+            } else {
+                // format = "jpeg";
+                format = "png";
+            }
+
+            this.pdf.addImage(img, format, xRect.x, xRect.y, xRect.w, xRect.h);
+        },
+
+        /**
+         * Multiply the first matrix by the second
+         * @param m1
+         * @param m2
+         * @returns {*[]}
+         * @private
+         */
+        _matrix_multiply: function _matrix_multiply(m2, m1) {
+            var sx = m1[0];
+            var shy = m1[1];
+            var shx = m1[2];
+            var sy = m1[3];
+            var tx = m1[4];
+            var ty = m1[5];
+
+            var t0 = sx * m2[0] + shy * m2[2];
+            var t2 = shx * m2[0] + sy * m2[2];
+            var t4 = tx * m2[0] + ty * m2[2] + m2[4];
+            shy = sx * m2[1] + shy * m2[3];
+            sy = shx * m2[1] + sy * m2[3];
+            ty = tx * m2[1] + ty * m2[3] + m2[5];
+            sx = t0;
+            shx = t2;
+            tx = t4;
+
+            return [sx, shy, shx, sy, tx, ty];
+        },
+
+        _matrix_rotation: function _matrix_rotation(m) {
+            return Math.atan2(m[2], m[0]);
+        },
+
+        _matrix_decompose: function _matrix_decompose(matrix) {
+
+            var a = matrix[0];
+            var b = matrix[1];
+            var c = matrix[2];
+            var d = matrix[3];
+
+            var scaleX = Math.sqrt(a * a + b * b);
+            a /= scaleX;
+            b /= scaleX;
+
+            var shear = a * c + b * d;
+            c -= a * shear;
+            d -= b * shear;
+
+            var scaleY = Math.sqrt(c * c + d * d);
+            c /= scaleY;
+            d /= scaleY;
+            shear /= scaleY;
+
+            if (a * d < b * c) {
+                a = -a;
+                b = -b;
+                shear = -shear;
+                scaleX = -scaleX;
+            }
+
+            return {
+                scale: [scaleX, 0, 0, scaleY, 0, 0],
+                translate: [1, 0, 0, 1, matrix[4], matrix[5]],
+                rotate: [a, b, -b, a, 0, 0],
+                skew: [1, 0, shear, 1, 0, 0]
+            };
+        },
+
+        _matrix_map_point: function _matrix_map_point(m1, pt) {
+            var sx = m1[0];
+            var shy = m1[1];
+            var shx = m1[2];
+            var sy = m1[3];
+            var tx = m1[4];
+            var ty = m1[5];
+
+            var px = pt[0];
+            var py = pt[1];
+
+            var x = px * sx + py * shx + tx;
+            var y = px * shy + py * sy + ty;
+            return [x, y];
+        },
+
+        _matrix_map_point_obj: function _matrix_map_point_obj(m1, pt) {
+            var xpt = this._matrix_map_point(m1, [pt.x, pt.y]);
+            return { x: xpt[0], y: xpt[1] };
+        },
+
+        _matrix_map_rect: function _matrix_map_rect(m1, rect) {
+            var p1 = this._matrix_map_point(m1, [rect.x, rect.y]);
+            var p2 = this._matrix_map_point(m1, [rect.x + rect.w, rect.y + rect.h]);
+            return { x: p1[0], y: p1[1], w: p2[0] - p1[0], h: p2[1] - p1[1] };
+        },
+
+        _matrix_is_identity: function _matrix_is_identity(m1) {
+            if (m1[0] != 1) {
+                return false;
+            }
+            if (m1[1] != 0) {
+                return false;
+            }
+            if (m1[2] != 0) {
+                return false;
+            }
+            if (m1[3] != 1) {
+                return false;
+            }
+            if (m1[4] != 0) {
+                return false;
+            }
+            if (m1[5] != 0) {
+                return false;
+            }
+            return true;
+        },
+
+        rotate: function rotate(angle) {
+            var matrix = [Math.cos(angle), Math.sin(angle), -Math.sin(angle), Math.cos(angle), 0.0, 0.0];
+            this.ctx._transform = this._matrix_multiply(this.ctx._transform, matrix);
+        },
+
+        scale: function scale(sx, sy) {
+            var matrix = [sx, 0.0, 0.0, sy, 0.0, 0.0];
+            this.ctx._transform = this._matrix_multiply(this.ctx._transform, matrix);
+        },
+
+        translate: function translate(x, y) {
+            var matrix = [1.0, 0.0, 0.0, 1.0, x, y];
+            this.ctx._transform = this._matrix_multiply(this.ctx._transform, matrix);
+        },
+
+        stroke: function stroke() {
+            if (this.ctx._clip_path.length > 0) {
+
+                var lines;
+                if (window.outIntercept) {
+                    lines = window.outIntercept.type === 'group' ? window.outIntercept.stream : window.outIntercept;
+                } else {
+                    lines = this.internal.getCurrentPage();
+                }
+                lines.push("q");
+
+                var origPath = this.path;
+                this.path = this.ctx._clip_path;
+                this.ctx._clip_path = [];
+                this._stroke(true);
+
+                this.ctx._clip_path = this.path;
+                this.path = origPath;
+                this._stroke(false);
+
+                lines.push("Q");
+            } else {
+                this._stroke(false);
+            }
+        },
+
+        _stroke: function _stroke(isClip) {
+            if (!isClip && this._isStrokeTransparent()) {
+                return;
+            }
+
+            //TODO opacity
+
+            var moves = [];
+            var closed = false;
+
+            var xPath = this.path;
+
+            for (var i = 0; i < xPath.length; i++) {
+                var pt = xPath[i];
+                switch (pt.type) {
+                    case 'mt':
+                        moves.push({ start: pt, deltas: [], abs: [] });
+                        break;
+                    case 'lt':
+                        var delta = [pt.x - xPath[i - 1].x, pt.y - xPath[i - 1].y];
+                        moves[moves.length - 1].deltas.push(delta);
+                        moves[moves.length - 1].abs.push(pt);
+                        break;
+                    case 'bct':
+                        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];
+                        moves[moves.length - 1].deltas.push(delta);
+                        break;
+                    case 'qct':
+                        // convert to bezier
+                        var x1 = xPath[i - 1].x + 2.0 / 3.0 * (pt.x1 - xPath[i - 1].x);
+                        var y1 = xPath[i - 1].y + 2.0 / 3.0 * (pt.y1 - xPath[i - 1].y);
+                        var x2 = pt.x + 2.0 / 3.0 * (pt.x1 - pt.x);
+                        var y2 = pt.y + 2.0 / 3.0 * (pt.y1 - pt.y);
+                        var x3 = pt.x;
+                        var y3 = pt.y;
+                        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];
+                        moves[moves.length - 1].deltas.push(delta);
+                        break;
+                    case 'arc':
+                        //TODO this was hack to avoid out-of-bounds issue
+                        // No move-to before drawing the arc
+                        if (moves.length == 0) {
+                            moves.push({ start: { x: 0, y: 0 }, deltas: [], abs: [] });
+                        }
+                        moves[moves.length - 1].arc = true;
+                        moves[moves.length - 1].abs.push(pt);
+                        break;
+                    case 'close':
+                        closed = true;
+                        break;
+                }
+            }
+
+            for (var i = 0; i < moves.length; i++) {
+                var style;
+                if (i == moves.length - 1) {
+                    style = 's';
+                } else {
+                    style = null;
+                }
+                if (moves[i].arc) {
+                    var arcs = moves[i].abs;
+                    for (var ii = 0; ii < arcs.length; ii++) {
+                        var arc = arcs[ii];
+                        var start = arc.startAngle * 360 / (2 * Math.PI);
+                        var end = arc.endAngle * 360 / (2 * Math.PI);
+                        var x = arc.x;
+                        var y = arc.y;
+                        this.internal.arc2(this, x, y, arc.radius, start, end, arc.anticlockwise, style, isClip);
+                    }
+                } else {
+                    var x = moves[i].start.x;
+                    var y = moves[i].start.y;
+                    if (!isClip) {
+                        this.pdf.lines(moves[i].deltas, x, y, null, style);
+                    } else {
+                        this.pdf.lines(moves[i].deltas, x, y, null, null);
+                        this.pdf.clip_fixed();
+                    }
+                }
+            }
+        },
+
+        _isFillTransparent: function _isFillTransparent() {
+            return this.ctx._isFillTransparent || this.globalAlpha == 0;
+        },
+
+        _isStrokeTransparent: function _isStrokeTransparent() {
+            return this.ctx._isStrokeTransparent || this.globalAlpha == 0;
+        },
+
+        fill: function fill(fillRule) {
+            //evenodd or nonzero (default)
+            if (this.ctx._clip_path.length > 0) {
+
+                var lines;
+                if (window.outIntercept) {
+                    lines = window.outIntercept.type === 'group' ? window.outIntercept.stream : window.outIntercept;
+                } else {
+                    lines = this.internal.getCurrentPage();
+                }
+                lines.push("q");
+
+                var origPath = this.path;
+                this.path = this.ctx._clip_path;
+                this.ctx._clip_path = [];
+                this._fill(fillRule, true);
+
+                this.ctx._clip_path = this.path;
+                this.path = origPath;
+                this._fill(fillRule, false);
+
+                lines.push('Q');
+            } else {
+                this._fill(fillRule, false);
+            }
+        },
+
+        _fill: function _fill(fillRule, isClip) {
+            if (this._isFillTransparent()) {
+                return;
+            }
+            var v2Support = typeof this.pdf.internal.newObject2 === 'function';
+
+            var lines;
+            if (window.outIntercept) {
+                lines = window.outIntercept.type === 'group' ? window.outIntercept.stream : window.outIntercept;
+            } else {
+                lines = this.internal.getCurrentPage();
+            }
+
+            // if (this.ctx._clip_path.length > 0) {
+            //     lines.push('q');
+            //     var oldPath = this.path;
+            //     this.path = this.ctx._clip_path;
+            //     this.ctx._clip_path = [];
+            //     this._fill(fillRule, true);
+            //     this.ctx._clip_path = this.path;
+            //     this.path = oldPath;
+            // }
+
+            var moves = [];
+            var outInterceptOld = window.outIntercept;
+
+            if (v2Support) {
+                // Blend and Mask
+                switch (this.ctx.globalCompositeOperation) {
+                    case 'normal':
+                    case 'source-over':
+                        break;
+                    case 'destination-in':
+                    case 'destination-out':
+                        //TODO this need to be added to the current group or page
+                        // define a mask stream
+                        var obj = this.pdf.internal.newStreamObject();
+
+                        // define a mask state
+                        var obj2 = this.pdf.internal.newObject2();
+                        obj2.push('<</Type /ExtGState');
+                        obj2.push('/SMask <</S /Alpha /G ' + obj.objId + ' 0 R>>'); // /S /Luminosity will need to define color space
+                        obj2.push('>>');
+
+                        // add mask to page resources
+                        var gsName = 'MASK' + obj2.objId;
+                        this.pdf.internal.addGraphicsState(gsName, obj2.objId);
+
+                        var instruction = '/' + gsName + ' gs';
+                        // add mask to page, group, or stream
+                        lines.splice(0, 0, 'q');
+                        lines.splice(1, 0, instruction);
+                        lines.push('Q');
+
+                        window.outIntercept = obj;
+                        break;
+                    default:
+                        var dictionaryEntry = '/' + this.pdf.internal.blendModeMap[this.ctx.globalCompositeOperation.toUpperCase()];
+                        if (dictionaryEntry) {
+                            this.pdf.internal.out(dictionaryEntry + ' gs');
+                        }
+                        break;
+                }
+            }
+
+            var alpha = this.ctx.globalAlpha;
+            if (this.ctx._fillOpacity < 1) {
+                // TODO combine this with global opacity
+                alpha = this.ctx._fillOpacity;
+            }
+
+            //TODO check for an opacity graphics state that was already created
+            //TODO do not set opacity if current value is already active
+            if (v2Support) {
+                var objOpac = this.pdf.internal.newObject2();
+                objOpac.push('<</Type /ExtGState');
+                //objOpac.push(this.ctx.globalAlpha + " CA"); // Stroke
+                //objOpac.push(this.ctx.globalAlpha + " ca"); // Not Stroke
+                objOpac.push('/CA ' + alpha); // Stroke
+                objOpac.push('/ca ' + alpha); // Not Stroke
+                objOpac.push('>>');
+                var gsName = 'GS_O_' + objOpac.objId;
+                this.pdf.internal.addGraphicsState(gsName, objOpac.objId);
+                this.pdf.internal.out('/' + gsName + ' gs');
+            }
+
+            var xPath = this.path;
+
+            for (var i = 0; i < xPath.length; i++) {
+                var pt = xPath[i];
+                switch (pt.type) {
+                    case 'mt':
+                        moves.push({ start: pt, deltas: [], abs: [] });
+                        break;
+                    case 'lt':
+                        var delta = [pt.x - xPath[i - 1].x, pt.y - xPath[i - 1].y];
+                        moves[moves.length - 1].deltas.push(delta);
+                        moves[moves.length - 1].abs.push(pt);
+                        break;
+                    case 'bct':
+                        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];
+                        moves[moves.length - 1].deltas.push(delta);
+                        break;
+                    case 'qct':
+                        // convert to bezier
+                        var x1 = xPath[i - 1].x + 2.0 / 3.0 * (pt.x1 - xPath[i - 1].x);
+                        var y1 = xPath[i - 1].y + 2.0 / 3.0 * (pt.y1 - xPath[i - 1].y);
+                        var x2 = pt.x + 2.0 / 3.0 * (pt.x1 - pt.x);
+                        var y2 = pt.y + 2.0 / 3.0 * (pt.y1 - pt.y);
+                        var x3 = pt.x;
+                        var y3 = pt.y;
+                        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];
+                        moves[moves.length - 1].deltas.push(delta);
+                        break;
+                    case 'arc':
+                        //TODO this was hack to avoid out-of-bounds issue when drawing circle
+                        // No move-to before drawing the arc
+                        if (moves.length === 0) {
+                            moves.push({ deltas: [], abs: [] });
+                        }
+                        moves[moves.length - 1].arc = true;
+                        moves[moves.length - 1].abs.push(pt);
+                        break;
+                    case 'close':
+                        moves.push({ close: true });
+                        break;
+                }
+            }
+
+            for (var i = 0; i < moves.length; i++) {
+                var style;
+                if (i == moves.length - 1) {
+                    style = 'f';
+                    if (fillRule === 'evenodd') {
+                        style += '*';
+                    }
+                } else {
+                    style = null;
+                }
+
+                if (moves[i].close) {
+                    this.pdf.internal.out('h');
+                    this.pdf.internal.out('f');
+                } else if (moves[i].arc) {
+                    if (moves[i].start) {
+                        this.internal.move2(this, moves[i].start.x, moves[i].start.y);
+                    }
+                    var arcs = moves[i].abs;
+                    for (var ii = 0; ii < arcs.length; ii++) {
+                        var arc = arcs[ii];
+                        //TODO lines deltas were getting in here
+                        if (typeof arc.startAngle !== 'undefined') {
+                            var start = arc.startAngle * 360 / (2 * Math.PI);
+                            var end = arc.endAngle * 360 / (2 * Math.PI);
+                            var x = arc.x;
+                            var y = arc.y;
+                            if (ii === 0) {
+                                this.internal.move2(this, x, y);
+                            }
+                            this.internal.arc2(this, x, y, arc.radius, start, end, arc.anticlockwise, null, isClip);
+                            if (ii === arcs.length - 1) {
+                                // The original arc move did not occur because of the algorithm
+                                if (moves[i].start) {
+                                    var x = moves[i].start.x;
+                                    var y = moves[i].start.y;
+                                    this.internal.line2(c2d, x, y);
+                                }
+                            }
+                        } else {
+                            this.internal.line2(c2d, arc.x, arc.y);
+                        }
+                    }
+                } else {
+                    var x = moves[i].start.x;
+                    var y = moves[i].start.y;
+                    if (!isClip) {
+                        this.pdf.lines(moves[i].deltas, x, y, null, style);
+                    } else {
+                        this.pdf.lines(moves[i].deltas, x, y, null, null);
+                        this.pdf.clip_fixed();
+                    }
+                }
+            }
+
+            window.outIntercept = outInterceptOld;
+
+            // if (this.ctx._clip_path.length > 0) {
+            //     lines.push('Q');
+            // }
+        },
+
+        pushMask: function pushMask() {
+            var v2Support = typeof this.pdf.internal.newObject2 === 'function';
+
+            if (!v2Support) {
+                console.log('jsPDF v2 not enabled');
+                return;
+            }
+
+            // define a mask stream
+            var obj = this.pdf.internal.newStreamObject();
+
+            // define a mask state
+            var obj2 = this.pdf.internal.newObject2();
+            obj2.push('<</Type /ExtGState');
+            obj2.push('/SMask <</S /Alpha /G ' + obj.objId + ' 0 R>>'); // /S /Luminosity will need to define color space
+            obj2.push('>>');
+
+            // add mask to page resources
+            var gsName = 'MASK' + obj2.objId;
+            this.pdf.internal.addGraphicsState(gsName, obj2.objId);
+
+            var instruction = '/' + gsName + ' gs';
+            this.pdf.internal.out(instruction);
+        },
+
+        clip: function clip() {
+            //TODO do we reset the path, or just copy it?
+            if (this.ctx._clip_path.length > 0) {
+                for (var i = 0; i < this.path.length; i++) {
+                    this.ctx._clip_path.push(this.path[i]);
+                }
+            } else {
+                this.ctx._clip_path = this.path;
+            }
+            this.path = [];
+        },
+
+        measureText: function measureText(text) {
+            var pdf = this.pdf;
+            return {
+                getWidth: function getWidth() {
+                    var fontSize = pdf.internal.getFontSize();
+                    var txtWidth = pdf.getStringUnitWidth(text) * fontSize / pdf.internal.scaleFactor;
+                    // Convert points to pixels
+                    txtWidth *= 1.3333;
+                    return txtWidth;
+                },
+
+                get width() {
+                    return this.getWidth(text);
+                }
+            };
+        },
+        _getBaseline: function _getBaseline(y) {
+            var height = parseInt(this.pdf.internal.getFontSize());
+            // TODO Get descent from font descriptor
+            var descent = height * .25;
+            switch (this.ctx.textBaseline) {
+                case 'bottom':
+                    return y - descent;
+                case 'top':
+                    return y + height;
+                case 'hanging':
+                    return y + height - descent;
+                case 'middle':
+                    return y + height / 2 - descent;
+                case 'ideographic':
+                    // TODO not implemented
+                    return y;
+                case 'alphabetic':
+                default:
+                    return y;
+            }
+        }
+    };
+
+    var c2d = jsPDFAPI.context2d;
+
+    // accessor methods
+    Object.defineProperty(c2d, 'fillStyle', {
+        set: function set(value) {
+            this.setFillStyle(value);
+        },
+        get: function get() {
+            return this.ctx.fillStyle;
+        }
+    });
+    Object.defineProperty(c2d, 'strokeStyle', {
+        set: function set(value) {
+            this.setStrokeStyle(value);
+        },
+        get: function get() {
+            return this.ctx.strokeStyle;
+        }
+    });
+    Object.defineProperty(c2d, 'lineWidth', {
+        set: function set(value) {
+            this.setLineWidth(value);
+        },
+        get: function get() {
+            return this.ctx.lineWidth;
+        }
+    });
+    Object.defineProperty(c2d, 'lineCap', {
+        set: function set(val) {
+            this.setLineCap(val);
+        },
+        get: function get() {
+            return this.ctx.lineCap;
+        }
+    });
+    Object.defineProperty(c2d, 'lineJoin', {
+        set: function set(val) {
+            this.setLineJoin(val);
+        },
+        get: function get() {
+            return this.ctx.lineJoin;
+        }
+    });
+    Object.defineProperty(c2d, 'miterLimit', {
+        set: function set(val) {
+            this.ctx.miterLimit = val;
+        },
+        get: function get() {
+            return this.ctx.miterLimit;
+        }
+    });
+    Object.defineProperty(c2d, 'textBaseline', {
+        set: function set(value) {
+            this.setTextBaseline(value);
+        },
+        get: function get() {
+            return this.getTextBaseline();
+        }
+    });
+    Object.defineProperty(c2d, 'textAlign', {
+        set: function set(value) {
+            this.setTextAlign(value);
+        },
+        get: function get() {
+            return this.getTextAlign();
+        }
+    });
+    Object.defineProperty(c2d, 'font', {
+        set: function set(value) {
+            this.setFont(value);
+        },
+        get: function get() {
+            return this.ctx.font;
+        }
+    });
+    Object.defineProperty(c2d, 'globalCompositeOperation', {
+        set: function set(value) {
+            this.ctx.globalCompositeOperation = value;
+        },
+        get: function get() {
+            return this.ctx.globalCompositeOperation;
+        }
+    });
+    Object.defineProperty(c2d, 'globalAlpha', {
+        set: function set(value) {
+            this.ctx.globalAlpha = value;
+        },
+        get: function get() {
+            return this.ctx.globalAlpha;
+        }
+    });
+    // Not HTML API
+    Object.defineProperty(c2d, 'ignoreClearRect', {
+        set: function set(value) {
+            this.ctx.ignoreClearRect = value;
+        },
+        get: function get() {
+            return this.ctx.ignoreClearRect;
+        }
+    });
+    // End Not HTML API
+
+    c2d.internal = {};
+
+    c2d.internal.rxRgb = /rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/;
+    c2d.internal.rxRgba = /rgba\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*([\d\.]+)\s*\)/;
+    c2d.internal.rxTransparent = /transparent|rgba\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*0+\s*\)/;
+
+    // http://hansmuller-flex.blogspot.com/2011/10/more-about-approximating-circular-arcs.html
+    c2d.internal.arc = function (c2d, xc, yc, r, a1, a2, anticlockwise, style) {
+        var includeMove = true;
+
+        var k = this.pdf.internal.scaleFactor;
+        var pageHeight = this.pdf.internal.pageSize.height;
+        var f2 = this.pdf.internal.f2;
+
+        var a1r = a1 * (Math.PI / 180);
+        var a2r = a2 * (Math.PI / 180);
+        var curves = this.createArc(r, a1r, a2r, anticlockwise);
+        var pathData = null;
+
+        for (var i = 0; i < curves.length; i++) {
+            var curve = curves[i];
+            if (includeMove && i === 0) {
+                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(' '));
+            } else {
+                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(' '));
+            }
+
+            //c2d._lastPoint = {x: curve.x1 + xc, y: curve.y1 + yc};
+            c2d._lastPoint = { x: xc, y: yc };
+            // 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'
+        }
+
+        if (style !== null) {
+            this.pdf.internal.out(this.pdf.internal.getStyle(style));
+        }
+    };
+
+    /**
+     *
+     * @param x Edge point X
+     * @param y Edge point Y
+     * @param r Radius
+     * @param a1 start angle
+     * @param a2 end angle
+     * @param anticlockwise
+     * @param style
+     * @param isClip
+     */
+    c2d.internal.arc2 = function (c2d, x, y, r, a1, a2, anticlockwise, style, isClip) {
+        // we need to convert from cartesian to polar here methinks.
+        var centerX = x; // + r;
+        var centerY = y;
+
+        if (!isClip) {
+            this.arc(c2d, centerX, centerY, r, a1, a2, anticlockwise, style);
+        } else {
+            this.arc(c2d, centerX, centerY, r, a1, a2, anticlockwise, null);
+            this.pdf.clip_fixed();
+        }
+    };
+
+    c2d.internal.move2 = function (c2d, x, y) {
+        var k = this.pdf.internal.scaleFactor;
+        var pageHeight = this.pdf.internal.pageSize.height;
+        var f2 = this.pdf.internal.f2;
+
+        this.pdf.internal.out([f2(x * k), f2((pageHeight - y) * k), 'm'].join(' '));
+        c2d._lastPoint = { x: x, y: y };
+    };
+
+    c2d.internal.line2 = function (c2d, dx, dy) {
+        var k = this.pdf.internal.scaleFactor;
+        var pageHeight = this.pdf.internal.pageSize.height;
+        var f2 = this.pdf.internal.f2;
+
+        //var pt = {x: c2d._lastPoint.x + dx, y: c2d._lastPoint.y + dy};
+        var pt = { x: dx, y: dy };
+
+        this.pdf.internal.out([f2(pt.x * k), f2((pageHeight - pt.y) * k), 'l'].join(' '));
+        //this.pdf.internal.out('f');
+        c2d._lastPoint = pt;
+    };
+
+    /**
+     * 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.
+     *
+     * 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.
+     */
+
+    c2d.internal.createArc = function (radius, startAngle, endAngle, anticlockwise) {
+        var EPSILON = 0.00001; // Roughly 1/1000th of a degree, see below
+        var twoPI = Math.PI * 2;
+        var piOverTwo = Math.PI / 2.0;
+
+        // normalize startAngle, endAngle to [0, 2PI]
+        var startAngleN = startAngle;
+        if (startAngleN < twoPI || startAngleN > twoPI) {
+            startAngleN = startAngleN % twoPI;
+        }
+        if (startAngleN < 0) {
+            startAngleN = twoPI + startAngleN;
+        }
+
+        while (startAngle > endAngle) {
+            startAngle = startAngle - twoPI;
+        }
+        var totalAngle = Math.abs(endAngle - startAngle);
+        if (totalAngle < twoPI) {
+            if (anticlockwise) {
+                totalAngle = twoPI - totalAngle;
+            }
+        }
+
+        // Compute the sequence of arc curves, up to PI/2 at a time.
+        var curves = [];
+        var sgn = anticlockwise ? -1 : +1;
+
+        var a1 = startAngleN;
+        for (; totalAngle > EPSILON;) {
+            var remain = sgn * Math.min(totalAngle, piOverTwo);
+            var a2 = a1 + remain;
+            curves.push(this.createSmallArc(radius, a1, a2));
+            totalAngle -= Math.abs(a2 - a1);
+            a1 = a2;
+        }
+
+        return curves;
+    };
+
+    c2d.internal.getCurrentPage = function () {
+        return this.pdf.internal.pages[this.pdf.internal.getCurrentPageInfo().pageNumber];
+    };
+
+    /**
+     * 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.
+     *
+     * 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.
+     *
+     * 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.
+     */
+
+    c2d.internal.createSmallArc = function (r, a1, a2) {
+        // Compute all four points for an arc that subtends the same total angle
+        // but is centered on the X-axis
+
+        var a = (a2 - a1) / 2.0;
+
+        var x4 = r * Math.cos(a);
+        var y4 = r * Math.sin(a);
+        var x1 = x4;
+        var y1 = -y4;
+
+        var q1 = x1 * x1 + y1 * y1;
+        var q2 = q1 + x1 * x4 + y1 * y4;
+        var k2 = 4 / 3 * (Math.sqrt(2 * q1 * q2) - q2) / (x1 * y4 - y1 * x4);
+
+        var x2 = x1 - k2 * y1;
+        var y2 = y1 + k2 * x1;
+        var x3 = x2;
+        var y3 = -y2;
+
+        // Find the arc points' actual locations by computing x1,y1 and x4,y4
+        // and rotating the control points by a + a1
+
+        var ar = a + a1;
+        var cos_ar = Math.cos(ar);
+        var sin_ar = Math.sin(ar);
+
+        return {
+            x1: r * Math.cos(a1),
+            y1: r * Math.sin(a1),
+            x2: x2 * cos_ar - y2 * sin_ar,
+            y2: x2 * sin_ar + y2 * cos_ar,
+            x3: x3 * cos_ar - y3 * sin_ar,
+            y3: x3 * sin_ar + y3 * cos_ar,
+            x4: r * Math.cos(a2),
+            y4: r * Math.sin(a2)
+        };
+    };
+
+    function context() {
+        this._isStrokeTransparent = false;
+        this._strokeOpacity = 1;
+        this.strokeStyle = '#000000';
+        this.fillStyle = '#000000';
+        this._isFillTransparent = false;
+        this._fillOpacity = 1;
+        this.font = "12pt times";
+        this.textBaseline = 'alphabetic'; // top,bottom,middle,ideographic,alphabetic,hanging
+        this.textAlign = 'start';
+        this.lineWidth = 1;
+        this.lineJoin = 'miter'; // round, bevel, miter
+        this.lineCap = 'butt'; // butt, round, square
+        this._transform = [1, 0, 0, 1, 0, 0]; // sx, shy, shx, sy, tx, ty
+        this.globalCompositeOperation = 'normal';
+        this.globalAlpha = 1.0;
+        this._clip_path = [];
+        // TODO miter limit //default 10
+
+        // Not HTML API
+        this.ignoreClearRect = false;
+
+        this.copy = function (ctx) {
+            this._isStrokeTransparent = ctx._isStrokeTransparent;
+            this._strokeOpacity = ctx._strokeOpacity;
+            this.strokeStyle = ctx.strokeStyle;
+            this._isFillTransparent = ctx._isFillTransparent;
+            this._fillOpacity = ctx._fillOpacity;
+            this.fillStyle = ctx.fillStyle;
+            this.font = ctx.font;
+            this.lineWidth = ctx.lineWidth;
+            this.lineJoin = ctx.lineJoin;
+            this.lineCap = ctx.lineCap;
+            this.textBaseline = ctx.textBaseline;
+            this.textAlign = ctx.textAlign;
+            this._fontSize = ctx._fontSize;
+            this._transform = ctx._transform.slice(0);
+            this.globalCompositeOperation = ctx.globalCompositeOperation;
+            this.globalAlpha = ctx.globalAlpha;
+            this._clip_path = ctx._clip_path.slice(0); //TODO deep copy?
+
+            // Not HTML API
+            this.ignoreClearRect = ctx.ignoreClearRect;
+        };
+    }
+
+    return this;
+})(jsPDF.API);
+
+/** @preserve
+ * jsPDF fromHTML plugin. BETA stage. API subject to change. Needs browser
+ * Copyright (c) 2012 Willow Systems Corporation, willow-systems.com
+ *               2014 Juan Pablo Gaviria, https://github.com/juanpgaviria
+ *               2014 Diego Casorran, https://github.com/diegocr
+ *               2014 Daniel Husar, https://github.com/danielhusar
+ *               2014 Wolfgang Gassler, https://github.com/woolfg
+ *               2014 Steven Spungin, https://github.com/flamenco
+ *
+ * 
+ * ====================================================================
+ */
+
+(function (jsPDFAPI) {
+	var clone, _DrillForContent, FontNameDB, FontStyleMap, TextAlignMap, FontWeightMap, FloatMap, ClearMap, GetCSS, PurgeWhiteSpace, Renderer, ResolveFont, ResolveUnitedNumber, UnitedNumberMap, elementHandledElsewhere, images, loadImgs, checkForFooter, process, tableToJson;
+	clone = function () {
+		return function (obj) {
+			Clone.prototype = obj;
+			return new Clone();
+		};
+		function Clone() {}
+	}();
+	PurgeWhiteSpace = function PurgeWhiteSpace(array) {
+		var fragment, i, l, lTrimmed, r, rTrimmed, trailingSpace;
+		i = 0;
+		l = array.length;
+		fragment = void 0;
+		lTrimmed = false;
+		rTrimmed = false;
+		while (!lTrimmed && i !== l) {
+			fragment = array[i] = array[i].trimLeft();
+			if (fragment) {
+				lTrimmed = true;
+			}
+			i++;
+		}
+		i = l - 1;
+		while (l && !rTrimmed && i !== -1) {
+			fragment = array[i] = array[i].trimRight();
+			if (fragment) {
+				rTrimmed = true;
+			}
+			i--;
+		}
+		r = /\s+$/g;
+		trailingSpace = true;
+		i = 0;
+		while (i !== l) {
+			// Leave the line breaks intact
+			if (array[i] != "\u2028") {
+				fragment = array[i].replace(/\s+/g, " ");
+				if (trailingSpace) {
+					fragment = fragment.trimLeft();
+				}
+				if (fragment) {
+					trailingSpace = r.test(fragment);
+				}
+				array[i] = fragment;
+			}
+			i++;
+		}
+		return array;
+	};
+	Renderer = function Renderer(pdf, x, y, settings) {
+		this.pdf = pdf;
+		this.x = x;
+		this.y = y;
+		this.settings = settings;
+		//list of functions which are called after each element-rendering process
+		this.watchFunctions = [];
+		this.init();
+		return this;
+	};
+	ResolveFont = function ResolveFont(css_font_family_string) {
+		var name, part, parts;
+		name = void 0;
+		parts = css_font_family_string.split(",");
+		part = parts.shift();
+		while (!name && part) {
+			name = FontNameDB[part.trim().toLowerCase()];
+			part = parts.shift();
+		}
+		return name;
+	};
+	ResolveUnitedNumber = function ResolveUnitedNumber(css_line_height_string) {
+
+		//IE8 issues
+		css_line_height_string = css_line_height_string === "auto" ? "0px" : css_line_height_string;
+		if (css_line_height_string.indexOf("em") > -1 && !isNaN(Number(css_line_height_string.replace("em", "")))) {
+			css_line_height_string = Number(css_line_height_string.replace("em", "")) * 18.719 + "px";
+		}
+		if (css_line_height_string.indexOf("pt") > -1 && !isNaN(Number(css_line_height_string.replace("pt", "")))) {
+			css_line_height_string = Number(css_line_height_string.replace("pt", "")) * 1.333 + "px";
+		}
+
+		var normal, undef, value;
+		undef = void 0;
+		normal = 16.00;
+		value = UnitedNumberMap[css_line_height_string];
+		if (value) {
+			return value;
+		}
+		value = {
+			"xx-small": 9,
+			"x-small": 11,
+			small: 13,
+			medium: 16,
+			large: 19,
+			"x-large": 23,
+			"xx-large": 28,
+			auto: 0
+		}[{ css_line_height_string: css_line_height_string }];
+
+		if (value !== undef) {
+			return UnitedNumberMap[css_line_height_string] = value / normal;
+		}
+		if (value = parseFloat(css_line_height_string)) {
+			return UnitedNumberMap[css_line_height_string] = value / normal;
+		}
+		value = css_line_height_string.match(/([\d\.]+)(px)/);
+		if (value.length === 3) {
+			return UnitedNumberMap[css_line_height_string] = parseFloat(value[1]) / normal;
+		}
+		return UnitedNumberMap[css_line_height_string] = 1;
+	};
+	GetCSS = function GetCSS(element) {
+		var css, tmp, computedCSSElement;
+		computedCSSElement = function (el) {
+			var compCSS;
+			compCSS = function (el) {
+				if (document.defaultView && document.defaultView.getComputedStyle) {
+					return document.defaultView.getComputedStyle(el, null);
+				} else if (el.currentStyle) {
+					return el.currentStyle;
+				} else {
+					return el.style;
+				}
+			}(el);
+			return function (prop) {
+				prop = prop.replace(/-\D/g, function (match) {
+					return match.charAt(1).toUpperCase();
+				});
+				return compCSS[prop];
+			};
+		}(element);
+		css = {};
+		tmp = void 0;
+		css["font-family"] = ResolveFont(computedCSSElement("font-family")) || "times";
+		css["font-style"] = FontStyleMap[computedCSSElement("font-style")] || "normal";
+		css["text-align"] = TextAlignMap[computedCSSElement("text-align")] || "left";
+		tmp = FontWeightMap[computedCSSElement("font-weight")] || "normal";
+		if (tmp === "bold") {
+			if (css["font-style"] === "normal") {
+				css["font-style"] = tmp;
+			} else {
+				css["font-style"] = tmp + css["font-style"];
+			}
+		}
+		css["font-size"] = ResolveUnitedNumber(computedCSSElement("font-size")) || 1;
+		css["line-height"] = ResolveUnitedNumber(computedCSSElement("line-height")) || 1;
+		css["display"] = computedCSSElement("display") === "inline" ? "inline" : "block";
+
+		tmp = css["display"] === "block";
+		css["margin-top"] = tmp && ResolveUnitedNumber(computedCSSElement("margin-top")) || 0;
+		css["margin-bottom"] = tmp && ResolveUnitedNumber(computedCSSElement("margin-bottom")) || 0;
+		css["padding-top"] = tmp && ResolveUnitedNumber(computedCSSElement("padding-top")) || 0;
+		css["padding-bottom"] = tmp && ResolveUnitedNumber(computedCSSElement("padding-bottom")) || 0;
+		css["margin-left"] = tmp && ResolveUnitedNumber(computedCSSElement("margin-left")) || 0;
+		css["margin-right"] = tmp && ResolveUnitedNumber(computedCSSElement("margin-right")) || 0;
+		css["padding-left"] = tmp && ResolveUnitedNumber(computedCSSElement("padding-left")) || 0;
+		css["padding-right"] = tmp && ResolveUnitedNumber(computedCSSElement("padding-right")) || 0;
+
+		css["page-break-before"] = computedCSSElement("page-break-before") || "auto";
+
+		//float and clearing of floats
+		css["float"] = FloatMap[computedCSSElement("cssFloat")] || "none";
+		css["clear"] = ClearMap[computedCSSElement("clear")] || "none";
+
+		css["color"] = computedCSSElement("color");
+
+		return css;
+	};
+	elementHandledElsewhere = function elementHandledElsewhere(element, renderer, elementHandlers) {
+		var handlers, i, isHandledElsewhere, l, t;
+		isHandledElsewhere = false;
+		i = void 0;
+		l = void 0;
+		t = void 0;
+		handlers = elementHandlers["#" + element.id];
+		if (handlers) {
+			if (typeof handlers === "function") {
+				isHandledElsewhere = handlers(element, renderer);
+			} else {
+				i = 0;
+				l = handlers.length;
+				while (!isHandledElsewhere && i !== l) {
+					isHandledElsewhere = handlers[i](element, renderer);
+					i++;
+				}
+			}
+		}
+		handlers = elementHandlers[element.nodeName];
+		if (!isHandledElsewhere && handlers) {
+			if (typeof handlers === "function") {
+				isHandledElsewhere = handlers(element, renderer);
+			} else {
+				i = 0;
+				l = handlers.length;
+				while (!isHandledElsewhere && i !== l) {
+					isHandledElsewhere = handlers[i](element, renderer);
+					i++;
+				}
+			}
+		}
+		return isHandledElsewhere;
+	};
+	tableToJson = function tableToJson(table, renderer) {
+		var data, headers, i, j, rowData, tableRow, table_obj, table_with, cell, l;
+		data = [];
+		headers = [];
+		i = 0;
+		l = table.rows[0].cells.length;
+		table_with = table.clientWidth;
+		while (i < l) {
+			cell = table.rows[0].cells[i];
+			headers[i] = {
+				name: cell.textContent.toLowerCase().replace(/\s+/g, ''),
+				prompt: cell.textContent.replace(/\r?\n/g, ''),
+				width: cell.clientWidth / table_with * renderer.pdf.internal.pageSize.width
+			};
+			i++;
+		}
+		i = 1;
+		while (i < table.rows.length) {
+			tableRow = table.rows[i];
+			rowData = {};
+			j = 0;
+			while (j < tableRow.cells.length) {
+				rowData[headers[j].name] = tableRow.cells[j].textContent.replace(/\r?\n/g, '');
+				j++;
+			}
+			data.push(rowData);
+			i++;
+		}
+		return table_obj = {
+			rows: data,
+			headers: headers
+		};
+	};
+	var SkipNode = {
+		SCRIPT: 1,
+		STYLE: 1,
+		NOSCRIPT: 1,
+		OBJECT: 1,
+		EMBED: 1,
+		SELECT: 1
+	};
+	var listCount = 1;
+	_DrillForContent = function DrillForContent(element, renderer, elementHandlers) {
+		var cn, cns, fragmentCSS, i, isBlock, l, px2pt, table2json, cb;
+		cns = element.childNodes;
+		cn = void 0;
+		fragmentCSS = GetCSS(element);
+		isBlock = fragmentCSS.display === "block";
+		if (isBlock) {
+			renderer.setBlockBoundary();
+			renderer.setBlockStyle(fragmentCSS);
+		}
+		px2pt = 0.264583 * 72 / 25.4;
+		i = 0;
+		l = cns.length;
+		while (i < l) {
+			cn = cns[i];
+			if ((typeof cn === "undefined" ? "undefined" : _typeof(cn)) === "object") {
+
+				//execute all watcher functions to e.g. reset floating
+				renderer.executeWatchFunctions(cn);
+
+				/*** HEADER rendering **/
+				if (cn.nodeType === 1 && cn.nodeName === 'HEADER') {
+					var header = cn;
+					//store old top margin
+					var oldMarginTop = renderer.pdf.margins_doc.top;
+					//subscribe for new page event and render header first on every page
+					renderer.pdf.internal.events.subscribe('addPage', function (pageInfo) {
+						//set current y position to old margin
+						renderer.y = oldMarginTop;
+						//render all child nodes of the header element
+						_DrillForContent(header, renderer, elementHandlers);
+						//set margin to old margin + rendered header + 10 space to prevent overlapping
+						//important for other plugins (e.g. table) to start rendering at correct position after header
+						renderer.pdf.margins_doc.top = renderer.y + 10;
+						renderer.y += 10;
+					}, false);
+				}
+
+				if (cn.nodeType === 8 && cn.nodeName === "#comment") {
+					if (~cn.textContent.indexOf("ADD_PAGE")) {
+						renderer.pdf.addPage();
+						renderer.y = renderer.pdf.margins_doc.top;
+					}
+				} else if (cn.nodeType === 1 && !SkipNode[cn.nodeName]) {
+					/*** IMAGE RENDERING ***/
+					var cached_image;
+					if (cn.nodeName === "IMG") {
+						var url = cn.getAttribute("src");
+						cached_image = images[renderer.pdf.sHashCode(url) || url];
+					}
+					if (cached_image) {
+						if (renderer.pdf.internal.pageSize.height - renderer.pdf.margins_doc.bottom < renderer.y + cn.height && renderer.y > renderer.pdf.margins_doc.top) {
+							renderer.pdf.addPage();
+							renderer.y = renderer.pdf.margins_doc.top;
+							//check if we have to set back some values due to e.g. header rendering for new page
+							renderer.executeWatchFunctions(cn);
+						}
+
+						var imagesCSS = GetCSS(cn);
+						var imageX = renderer.x;
+						var fontToUnitRatio = 12 / renderer.pdf.internal.scaleFactor;
+
+						//define additional paddings, margins which have to be taken into account for margin calculations
+						var additionalSpaceLeft = (imagesCSS["margin-left"] + imagesCSS["padding-left"]) * fontToUnitRatio;
+						var additionalSpaceRight = (imagesCSS["margin-right"] + imagesCSS["padding-right"]) * fontToUnitRatio;
+						var additionalSpaceTop = (imagesCSS["margin-top"] + imagesCSS["padding-top"]) * fontToUnitRatio;
+						var additionalSpaceBottom = (imagesCSS["margin-bottom"] + imagesCSS["padding-bottom"]) * fontToUnitRatio;
+
+						//if float is set to right, move the image to the right border
+						//add space if margin is set
+						if (imagesCSS['float'] !== undefined && imagesCSS['float'] === 'right') {
+							imageX += renderer.settings.width - cn.width - additionalSpaceRight;
+						} else {
+							imageX += additionalSpaceLeft;
+						}
+
+						renderer.pdf.addImage(cached_image, imageX, renderer.y + additionalSpaceTop, cn.width, cn.height);
+						cached_image = undefined;
+						//if the float prop is specified we have to float the text around the image
+						if (imagesCSS['float'] === 'right' || imagesCSS['float'] === 'left') {
+							//add functiont to set back coordinates after image rendering
+							renderer.watchFunctions.push(function (diffX, thresholdY, diffWidth, el) {
+								//undo drawing box adaptions which were set by floating
+								if (renderer.y >= thresholdY) {
+									renderer.x += diffX;
+									renderer.settings.width += diffWidth;
+									return true;
+								} else if (el && el.nodeType === 1 && !SkipNode[el.nodeName] && renderer.x + el.width > renderer.pdf.margins_doc.left + renderer.pdf.margins_doc.width) {
+									renderer.x += diffX;
+									renderer.y = thresholdY;
+									renderer.settings.width += diffWidth;
+									return true;
+								} else {
+									return false;
+								}
+							}.bind(this, imagesCSS['float'] === 'left' ? -cn.width - additionalSpaceLeft - additionalSpaceRight : 0, renderer.y + cn.height + additionalSpaceTop + additionalSpaceBottom, cn.width));
+							//reset floating by clear:both divs
+							//just set cursorY after the floating element
+							renderer.watchFunctions.push(function (yPositionAfterFloating, pages, el) {
+								if (renderer.y < yPositionAfterFloating && pages === renderer.pdf.internal.getNumberOfPages()) {
+									if (el.nodeType === 1 && GetCSS(el).clear === 'both') {
+										renderer.y = yPositionAfterFloating;
+										return true;
+									} else {
+										return false;
+									}
+								} else {
+									return true;
+								}
+							}.bind(this, renderer.y + cn.height, renderer.pdf.internal.getNumberOfPages()));
+
+							//if floating is set we decrease the available width by the image width
+							renderer.settings.width -= cn.width + additionalSpaceLeft + additionalSpaceRight;
+							//if left just add the image width to the X coordinate
+							if (imagesCSS['float'] === 'left') {
+								renderer.x += cn.width + additionalSpaceLeft + additionalSpaceRight;
+							}
+						} else {
+							//if no floating is set, move the rendering cursor after the image height
+							renderer.y += cn.height + additionalSpaceTop + additionalSpaceBottom;
+						}
+
+						/*** TABLE RENDERING ***/
+					} else if (cn.nodeName === "TABLE") {
+						table2json = tableToJson(cn, renderer);
+						renderer.y += 10;
+						renderer.pdf.table(renderer.x, renderer.y, table2json.rows, table2json.headers, {
+							autoSize: false,
+							printHeaders: elementHandlers.printHeaders,
+							margins: renderer.pdf.margins_doc,
+							css: GetCSS(cn)
+						});
+						renderer.y = renderer.pdf.lastCellPos.y + renderer.pdf.lastCellPos.h + 20;
+					} else if (cn.nodeName === "OL" || cn.nodeName === "UL") {
+						listCount = 1;
+						if (!elementHandledElsewhere(cn, renderer, elementHandlers)) {
+							_DrillForContent(cn, renderer, elementHandlers);
+						}
+						renderer.y += 10;
+					} else if (cn.nodeName === "LI") {
+						var temp = renderer.x;
+						renderer.x += 20 / renderer.pdf.internal.scaleFactor;
+						renderer.y += 3;
+						if (!elementHandledElsewhere(cn, renderer, elementHandlers)) {
+							_DrillForContent(cn, renderer, elementHandlers);
+						}
+						renderer.x = temp;
+					} else if (cn.nodeName === "BR") {
+						renderer.y += fragmentCSS["font-size"] * renderer.pdf.internal.scaleFactor;
+						renderer.addText("\u2028", clone(fragmentCSS));
+					} else {
+						if (!elementHandledElsewhere(cn, renderer, elementHandlers)) {
+							_DrillForContent(cn, renderer, elementHandlers);
+						}
+					}
+				} else if (cn.nodeType === 3) {
+					var value = cn.nodeValue;
+					if (cn.nodeValue && cn.parentNode.nodeName === "LI") {
+						if (cn.parentNode.parentNode.nodeName === "OL") {
+							value = listCount++ + '. ' + value;
+						} else {
+							var fontSize = fragmentCSS["font-size"];
+							var offsetX = (3 - fontSize * 0.75) * renderer.pdf.internal.scaleFactor;
+							var offsetY = fontSize * 0.75 * renderer.pdf.internal.scaleFactor;
+							var radius = fontSize * 1.74 / renderer.pdf.internal.scaleFactor;
+							cb = function cb(x, y) {
+								this.pdf.circle(x + offsetX, y + offsetY, radius, 'FD');
+							};
+						}
+					}
+					// Only add the text if the text node is in the body element
+					// Add compatibility with IE11
+					if (!!(cn.ownerDocument.body.compareDocumentPosition(cn) & 16)) {
+						renderer.addText(value, fragmentCSS);
+					}
+				} else if (typeof cn === "string") {
+					renderer.addText(cn, fragmentCSS);
+				}
+			}
+			i++;
+		}
+		elementHandlers.outY = renderer.y;
+
+		if (isBlock) {
+			return renderer.setBlockBoundary(cb);
+		}
+	};
+	images = {};
+	loadImgs = function loadImgs(element, renderer, elementHandlers, cb) {
+		var imgs = element.getElementsByTagName('img'),
+		    l = imgs.length,
+		    found_images,
+		    x = 0;
+		function done() {
+			renderer.pdf.internal.events.publish('imagesLoaded');
+			cb(found_images);
+		}
+		function loadImage(url, width, height) {
+			if (!url) return;
+			var img = new Image();
+			found_images = ++x;
+			img.crossOrigin = '';
+			img.onerror = img.onload = function () {
+				if (img.complete) {
+					//to support data urls in images, set width and height
+					//as those values are not recognized automatically
+					if (img.src.indexOf('data:image/') === 0) {
+						img.width = width || img.width || 0;
+						img.height = height || img.height || 0;
+					}
+					//if valid image add to known images array
+					if (img.width + img.height) {
+						var hash = renderer.pdf.sHashCode(url) || url;
+						images[hash] = images[hash] || img;
+					}
+				}
+				if (! --x) {
+					done();
+				}
+			};
+			img.src = url;
+		}
+		while (l--) {
+			loadImage(imgs[l].getAttribute("src"), imgs[l].width, imgs[l].height);
+		}return x || done();
+	};
+	checkForFooter = function checkForFooter(elem, renderer, elementHandlers) {
+		//check if we can found a <footer> element
+		var footer = elem.getElementsByTagName("footer");
+		if (footer.length > 0) {
+
+			footer = footer[0];
+
+			//bad hack to get height of footer
+			//creat dummy out and check new y after fake rendering
+			var oldOut = renderer.pdf.internal.write;
+			var oldY = renderer.y;
+			renderer.pdf.internal.write = function () {};
+			_DrillForContent(footer, renderer, elementHandlers);
+			var footerHeight = Math.ceil(renderer.y - oldY) + 5;
+			renderer.y = oldY;
+			renderer.pdf.internal.write = oldOut;
+
+			//add 20% to prevent overlapping
+			renderer.pdf.margins_doc.bottom += footerHeight;
+
+			//Create function render header on every page
+			var renderFooter = function renderFooter(pageInfo) {
+				var pageNumber = pageInfo !== undefined ? pageInfo.pageNumber : 1;
+				//set current y position to old margin
+				var oldPosition = renderer.y;
+				//render all child nodes of the header element
+				renderer.y = renderer.pdf.internal.pageSize.height - renderer.pdf.margins_doc.bottom;
+				renderer.pdf.margins_doc.bottom -= footerHeight;
+
+				//check if we have to add page numbers
+				var spans = footer.getElementsByTagName('span');
+				for (var i = 0; i < spans.length; ++i) {
+					//if we find some span element with class pageCounter, set the page
+					if ((" " + spans[i].className + " ").replace(/[\n\t]/g, " ").indexOf(" pageCounter ") > -1) {
+						spans[i].innerHTML = pageNumber;
+					}
+					//if we find some span element with class totalPages, set a variable which is replaced after rendering of all pages
+					if ((" " + spans[i].className + " ").replace(/[\n\t]/g, " ").indexOf(" totalPages ") > -1) {
+						spans[i].innerHTML = '###jsPDFVarTotalPages###';
+					}
+				}
+
+				//render footer content
+				_DrillForContent(footer, renderer, elementHandlers);
+				//set bottom margin to previous height including the footer height
+				renderer.pdf.margins_doc.bottom += footerHeight;
+				//important for other plugins (e.g. table) to start rendering at correct position after header
+				renderer.y = oldPosition;
+			};
+
+			//check if footer contains totalPages which should be replace at the disoposal of the document
+			var spans = footer.getElementsByTagName('span');
+			for (var i = 0; i < spans.length; ++i) {
+				if ((" " + spans[i].className + " ").replace(/[\n\t]/g, " ").indexOf(" totalPages ") > -1) {
+					renderer.pdf.internal.events.subscribe('htmlRenderingFinished', renderer.pdf.putTotalPages.bind(renderer.pdf, '###jsPDFVarTotalPages###'), true);
+				}
+			}
+
+			//register event to render footer on every new page
+			renderer.pdf.internal.events.subscribe('addPage', renderFooter, false);
+			//render footer on first page
+			renderFooter();
+
+			//prevent footer rendering
+			SkipNode['FOOTER'] = 1;
+		}
+	};
+	process = function process(pdf, element, x, y, settings, callback) {
+		if (!element) return false;
+		if (typeof element !== "string" && !element.parentNode) element = '' + element.innerHTML;
+		if (typeof element === "string") {
+			element = function (element) {
+				var $frame, $hiddendiv, framename, visuallyhidden;
+				framename = "jsPDFhtmlText" + Date.now().toString() + (Math.random() * 1000).toFixed(0);
+				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;";
+				$hiddendiv = document.createElement('div');
+				$hiddendiv.style.cssText = visuallyhidden;
+				$hiddendiv.innerHTML = "<iframe style=\"height:1px;width:1px\" name=\"" + framename + "\" />";
+				document.body.appendChild($hiddendiv);
+				$frame = window.frames[framename];
+				$frame.document.open();
+				$frame.document.writeln(element);
+				$frame.document.close();
+				return $frame.document.body;
+			}(element.replace(/<\/?script[^>]*?>/gi, ''));
+		}
+		var r = new Renderer(pdf, x, y, settings),
+		    out;
+
+		// 1. load images
+		// 2. prepare optional footer elements
+		// 3. render content
+		loadImgs.call(this, element, r, settings.elementHandlers, function (found_images) {
+			checkForFooter(element, r, settings.elementHandlers);
+			_DrillForContent(element, r, settings.elementHandlers);
+			//send event dispose for final taks (e.g. footer totalpage replacement)
+			r.pdf.internal.events.publish('htmlRenderingFinished');
+			out = r.dispose();
+			if (typeof callback === 'function') callback(out);else if (found_images) console.error('jsPDF Warning: rendering issues? provide a callback to fromHTML!');
+		});
+		return out || { x: r.x, y: r.y };
+	};
+	Renderer.prototype.init = function () {
+		this.paragraph = {
+			text: [],
+			style: []
+		};
+		return this.pdf.internal.write("q");
+	};
+	Renderer.prototype.dispose = function () {
+		this.pdf.internal.write("Q");
+		return {
+			x: this.x,
+			y: this.y,
+			ready: true
+		};
+	};
+
+	//Checks if we have to execute some watcher functions
+	//e.g. to end text floating around an image
+	Renderer.prototype.executeWatchFunctions = function (el) {
+		var ret = false;
+		var narray = [];
+		if (this.watchFunctions.length > 0) {
+			for (var i = 0; i < this.watchFunctions.length; ++i) {
+				if (this.watchFunctions[i](el) === true) {
+					ret = true;
+				} else {
+					narray.push(this.watchFunctions[i]);
+				}
+			}
+			this.watchFunctions = narray;
+		}
+		return ret;
+	};
+
+	Renderer.prototype.splitFragmentsIntoLines = function (fragments, styles) {
+		var currentLineLength, defaultFontSize, ff, fontMetrics, fontMetricsCache, fragment, fragmentChopped, fragmentLength, fragmentSpecificMetrics, fs, k, line, lines, maxLineLength, style;
+		defaultFontSize = 12;
+		k = this.pdf.internal.scaleFactor;
+		fontMetricsCache = {};
+		ff = void 0;
+		fs = void 0;
+		fontMetrics = void 0;
+		fragment = void 0;
+		style = void 0;
+		fragmentSpecificMetrics = void 0;
+		fragmentLength = void 0;
+		fragmentChopped = void 0;
+		line = [];
+		lines = [line];
+		currentLineLength = 0;
+		maxLineLength = this.settings.width;
+		while (fragments.length) {
+			fragment = fragments.shift();
+			style = styles.shift();
+			if (fragment) {
+				ff = style["font-family"];
+				fs = style["font-style"];
+				fontMetrics = fontMetricsCache[ff + fs];
+				if (!fontMetrics) {
+					fontMetrics = this.pdf.internal.getFont(ff, fs).metadata.Unicode;
+					fontMetricsCache[ff + fs] = fontMetrics;
+				}
+				fragmentSpecificMetrics = {
+					widths: fontMetrics.widths,
+					kerning: fontMetrics.kerning,
+					fontSize: style["font-size"] * defaultFontSize,
+					textIndent: currentLineLength
+				};
+				fragmentLength = this.pdf.getStringUnitWidth(fragment, fragmentSpecificMetrics) * fragmentSpecificMetrics.fontSize / k;
+				if (fragment == "\u2028") {
+					line = [];
+					lines.push(line);
+				} else if (currentLineLength + fragmentLength > maxLineLength) {
+					fragmentChopped = this.pdf.splitTextToSize(fragment, maxLineLength, fragmentSpecificMetrics);
+					line.push([fragmentChopped.shift(), style]);
+					while (fragmentChopped.length) {
+						line = [[fragmentChopped.shift(), style]];
+						lines.push(line);
+					}
+					currentLineLength = this.pdf.getStringUnitWidth(line[0][0], fragmentSpecificMetrics) * fragmentSpecificMetrics.fontSize / k;
+				} else {
+					line.push([fragment, style]);
+					currentLineLength += fragmentLength;
+				}
+			}
+		}
+
+		//if text alignment was set, set margin/indent of each line
+		if (style['text-align'] !== undefined && (style['text-align'] === 'center' || style['text-align'] === 'right' || style['text-align'] === 'justify')) {
+			for (var i = 0; i < lines.length; ++i) {
+				var length = this.pdf.getStringUnitWidth(lines[i][0][0], fragmentSpecificMetrics) * fragmentSpecificMetrics.fontSize / k;
+				//if there is more than on line we have to clone the style object as all lines hold a reference on this object
+				if (i > 0) {
+					lines[i][0][1] = clone(lines[i][0][1]);
+				}
+				var space = maxLineLength - length;
+
+				if (style['text-align'] === 'right') {
+					lines[i][0][1]['margin-left'] = space;
+					//if alignment is not right, it has to be center so split the space to the left and the right
+				} else if (style['text-align'] === 'center') {
+					lines[i][0][1]['margin-left'] = space / 2;
+					//if justify was set, calculate the word spacing and define in by using the css property
+				} else if (style['text-align'] === 'justify') {
+					var countSpaces = lines[i][0][0].split(' ').length - 1;
+					lines[i][0][1]['word-spacing'] = space / countSpaces;
+					//ignore the last line in justify mode
+					if (i === lines.length - 1) {
+						lines[i][0][1]['word-spacing'] = 0;
+					}
+				}
+			}
+		}
+
+		return lines;
+	};
+	Renderer.prototype.RenderTextFragment = function (text, style) {
+		var defaultFontSize, font, maxLineHeight;
+
+		maxLineHeight = 0;
+		defaultFontSize = 12;
+
+		if (this.pdf.internal.pageSize.height - 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 0 g", this.pdf.internal.getCoordinateString(this.x), this.pdf.internal.getVerticalCoordinateString(this.y), style.color, "Td");
+			//move cursor by one line on new page
+			maxLineHeight = Math.max(maxLineHeight, style["line-height"], style["font-size"]);
+			this.pdf.internal.write(0, (-1 * defaultFontSize * maxLineHeight).toFixed(2), "Td");
+		}
+
+		font = this.pdf.internal.getFont(style["font-family"], style["font-style"]);
+
+		// text color
+		var pdfTextColor = this.getPdfColor(style["color"]);
+		if (pdfTextColor !== this.lastTextColor) {
+			this.pdf.internal.write(pdfTextColor);
+			this.lastTextColor = pdfTextColor;
+		}
+
+		//set the word spacing for e.g. justify style
+		if (style['word-spacing'] !== undefined && style['word-spacing'] > 0) {
+			this.pdf.internal.write(style['word-spacing'].toFixed(2), "Tw");
+		}
+
+		this.pdf.internal.write("/" + font.id, (defaultFontSize * style["font-size"]).toFixed(2), "Tf", "(" + this.pdf.internal.pdfEscape(text) + ") Tj");
+
+		//set the word spacing back to neutral => 0
+		if (style['word-spacing'] !== undefined) {
+			this.pdf.internal.write(0, "Tw");
+		}
+	};
+
+	// Accepts #FFFFFF, rgb(int,int,int), or CSS Color Name
+	Renderer.prototype.getPdfColor = function (style) {
+		var textColor;
+		var r, g, b;
+
+		var rx = /rgb\s*\(\s*(\d+),\s*(\d+),\s*(\d+\s*)\)/;
+		var m = rx.exec(style);
+		if (m != null) {
+			r = parseInt(m[1]);
+			g = parseInt(m[2]);
+			b = parseInt(m[3]);
+		} else {
+			if (style.charAt(0) != '#') {
+				style = CssColors.colorNameToHex(style);
+				if (!style) {
+					style = '#000000';
+				}
+			}
+			r = style.substring(1, 3);
+			r = parseInt(r, 16);
+			g = style.substring(3, 5);
+			g = parseInt(g, 16);
+			b = style.substring(5, 7);
+			b = parseInt(b, 16);
+		}
+
+		if (typeof r === 'string' && /^#[0-9A-Fa-f]{6}$/.test(r)) {
+			var hex = parseInt(r.substr(1), 16);
+			r = hex >> 16 & 255;
+			g = hex >> 8 & 255;
+			b = hex & 255;
+		}
+
+		var f3 = this.f3;
+		if (r === 0 && g === 0 && b === 0 || typeof g === 'undefined') {
+			textColor = f3(r / 255) + ' g';
+		} else {
+			textColor = [f3(r / 255), f3(g / 255), f3(b / 255), 'rg'].join(' ');
+		}
+		return textColor;
+	};
+
+	Renderer.prototype.f3 = function (number) {
+		return number.toFixed(3); // Ie, %.3f
+	}, Renderer.prototype.renderParagraph = function (cb) {
+		var blockstyle, defaultFontSize, fontToUnitRatio, fragments, i, l, line, lines, maxLineHeight, out, paragraphspacing_after, paragraphspacing_before, priorblockstyle, styles, fontSize;
+		fragments = PurgeWhiteSpace(this.paragraph.text);
+		styles = this.paragraph.style;
+		blockstyle = this.paragraph.blockstyle;
+		priorblockstyle = this.paragraph.priorblockstyle || {};
+		this.paragraph = {
+			text: [],
+			style: [],
+			blockstyle: {},
+			priorblockstyle: blockstyle
+		};
+		if (!fragments.join("").trim()) {
+			return;
+		}
+		lines = this.splitFragmentsIntoLines(fragments, styles);
+		line = void 0;
+		maxLineHeight = void 0;
+		defaultFontSize = 12;
+		fontToUnitRatio = defaultFontSize / this.pdf.internal.scaleFactor;
+		this.priorMarginBottom = this.priorMarginBottom || 0;
+		paragraphspacing_before = (Math.max((blockstyle["margin-top"] || 0) - this.priorMarginBottom, 0) + (blockstyle["padding-top"] || 0)) * fontToUnitRatio;
+		paragraphspacing_after = ((blockstyle["margin-bottom"] || 0) + (blockstyle["padding-bottom"] || 0)) * fontToUnitRatio;
+		this.priorMarginBottom = blockstyle["margin-bottom"] || 0;
+
+		if (blockstyle['page-break-before'] === 'always') {
+			this.pdf.addPage();
+			this.y = 0;
+			paragraphspacing_before = ((blockstyle["margin-top"] || 0) + (blockstyle["padding-top"] || 0)) * fontToUnitRatio;
+		}
+
+		out = this.pdf.internal.write;
+		i = void 0;
+		l = void 0;
+		this.y += paragraphspacing_before;
+		out("q", "BT 0 g", this.pdf.internal.getCoordinateString(this.x), this.pdf.internal.getVerticalCoordinateString(this.y), "Td");
+
+		//stores the current indent of cursor position
+		var currentIndent = 0;
+
+		while (lines.length) {
+			line = lines.shift();
+			maxLineHeight = 0;
+			i = 0;
+			l = line.length;
+			while (i !== l) {
+				if (line[i][0].trim()) {
+					maxLineHeight = Math.max(maxLineHeight, line[i][1]["line-height"], line[i][1]["font-size"]);
+					fontSize = line[i][1]["font-size"] * 7;
+				}
+				i++;
+			}
+			//if we have to move the cursor to adapt the indent
+			var indentMove = 0;
+			var wantedIndent = 0;
+			//if a margin was added (by e.g. a text-alignment), move the cursor
+			if (line[0][1]["margin-left"] !== undefined && line[0][1]["margin-left"] > 0) {
+				wantedIndent = this.pdf.internal.getCoordinateString(line[0][1]["margin-left"]);
+				indentMove = wantedIndent - currentIndent;
+				currentIndent = wantedIndent;
+			}
+			var indentMore = Math.max(blockstyle["margin-left"] || 0, 0) * fontToUnitRatio;
+			//move the cursor
+			out(indentMove + indentMore, (-1 * defaultFontSize * maxLineHeight).toFixed(2), "Td");
+			i = 0;
+			l = line.length;
+			while (i !== l) {
+				if (line[i][0]) {
+					this.RenderTextFragment(line[i][0], line[i][1]);
+				}
+				i++;
+			}
+			this.y += maxLineHeight * fontToUnitRatio;
+
+			//if some watcher function was executed successful, so e.g. margin and widths were changed,
+			//reset line drawing and calculate position and lines again
+			//e.g. to stop text floating around an image
+			if (this.executeWatchFunctions(line[0][1]) && lines.length > 0) {
+				var localFragments = [];
+				var localStyles = [];
+				//create fragment array of
+				lines.forEach(function (localLine) {
+					var i = 0;
+					var l = localLine.length;
+					while (i !== l) {
+						if (localLine[i][0]) {
+							localFragments.push(localLine[i][0] + ' ');
+							localStyles.push(localLine[i][1]);
+						}
+						++i;
+					}
+				});
+				//split lines again due to possible coordinate changes
+				lines = this.splitFragmentsIntoLines(PurgeWhiteSpace(localFragments), localStyles);
+				//reposition the current cursor
+				out("ET", "Q");
+				out("q", "BT 0 g", this.pdf.internal.getCoordinateString(this.x), this.pdf.internal.getVerticalCoordinateString(this.y), "Td");
+			}
+		}
+		if (cb && typeof cb === "function") {
+			cb.call(this, this.x - 9, this.y - fontSize / 2);
+		}
+		out("ET", "Q");
+		return this.y += paragraphspacing_after;
+	};
+	Renderer.prototype.setBlockBoundary = function (cb) {
+		return this.renderParagraph(cb);
+	};
+	Renderer.prototype.setBlockStyle = function (css) {
+		return this.paragraph.blockstyle = css;
+	};
+	Renderer.prototype.addText = function (text, css) {
+		this.paragraph.text.push(text);
+		return this.paragraph.style.push(css);
+	};
+	FontNameDB = {
+		helvetica: "helvetica",
+		"sans-serif": "helvetica",
+		"times new roman": "times",
+		serif: "times",
+		times: "times",
+		monospace: "courier",
+		courier: "courier"
+	};
+	FontWeightMap = {
+		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"
+	};
+	FontStyleMap = {
+		normal: "normal",
+		italic: "italic",
+		oblique: "italic"
+	};
+	TextAlignMap = {
+		left: "left",
+		right: "right",
+		center: "center",
+		justify: "justify"
+	};
+	FloatMap = {
+		none: 'none',
+		right: 'right',
+		left: 'left'
+	};
+	ClearMap = {
+		none: 'none',
+		both: 'both'
+	};
+	UnitedNumberMap = {
+		normal: 1
+	};
+	/**
+  * Converts HTML-formatted text into formatted PDF text.
+  *
+  * Notes:
+  * 2012-07-18
+  * Plugin relies on having browser, DOM around. The HTML is pushed into dom and traversed.
+  * Plugin relies on jQuery for CSS extraction.
+  * Targeting HTML output from Markdown templating, which is a very simple
+  * markup - div, span, em, strong, p. No br-based paragraph separation supported explicitly (but still may work.)
+  * Images, tables are NOT supported.
+  *
+  * @public
+  * @function
+  * @param HTML {String or DOM Element} HTML-formatted text, or pointer to DOM element that is to be rendered into PDF.
+  * @param x {Number} starting X coordinate in jsPDF instance's declared units.
+  * @param y {Number} starting Y coordinate in jsPDF instance's declared units.
+  * @param settings {Object} Additional / optional variables controlling parsing, rendering.
+  * @returns {Object} jsPDF instance
+  */
+	jsPDFAPI.fromHTML = function (HTML, x, y, settings, callback, margins) {
+		"use strict";
+
+		this.margins_doc = margins || {
+			top: 0,
+			bottom: 0
+		};
+		if (!settings) settings = {};
+		if (!settings.elementHandlers) settings.elementHandlers = {};
+
+		return process(this, HTML, isNaN(x) ? 4 : x, isNaN(y) ? 4 : y, settings, callback);
+	};
+})(jsPDF.API);
+
+/** ==================================================================== 
+ * jsPDF JavaScript plugin
+ * Copyright (c) 2013 Youssef Beddad, youssef.beddad@gmail.com
+ * 
+ * 
+ * ====================================================================
+ */
+
+/*global jsPDF */
+
+(function (jsPDFAPI) {
+    'use strict';
+
+    var jsNamesObj, jsJsObj, text;
+    jsPDFAPI.addJS = function (txt) {
+        text = txt;
+        this.internal.events.subscribe('postPutResources', function (txt) {
+            jsNamesObj = this.internal.newObject();
+            this.internal.write('<< /Names [(EmbeddedJS) ' + (jsNamesObj + 1) + ' 0 R] >>', 'endobj');
+            jsJsObj = this.internal.newObject();
+            this.internal.write('<< /S /JavaScript /JS (', text, ') >>', 'endobj');
+        });
+        this.internal.events.subscribe('putCatalog', function () {
+            if (jsNamesObj !== undefined && jsJsObj !== undefined) {
+                this.internal.write('/Names <</JavaScript ' + jsNamesObj + ' 0 R>>');
+            }
+        });
+        return this;
+    };
+})(jsPDF.API);
+
+/**
+ * jsPDF Outline PlugIn
+ * Copyright (c) 2014 Steven Spungin (TwelveTone LLC)  steven@twelvetone.tv
+ *
+ * Licensed under the MIT License.
+ * http://opensource.org/licenses/mit-license
+ */
+
+/**
+ * Generates a PDF Outline
+ */
+
+(function (jsPDFAPI) {
+	'use strict';
+
+	jsPDFAPI.events.push(['postPutResources', function () {
+		var pdf = this;
+		var rx = /^(\d+) 0 obj$/;
+
+		// Write action goto objects for each page
+		// this.outline.destsGoto = [];
+		// for (var i = 0; i < totalPages; i++) {
+		// var id = pdf.internal.newObject();
+		// this.outline.destsGoto.push(id);
+		// pdf.internal.write("<</D[" + (i * 2 + 3) + " 0 R /XYZ null
+		// null null]/S/GoTo>> endobj");
+		// }
+		//
+		// for (var i = 0; i < dests.length; i++) {
+		// pdf.internal.write("(page_" + (i + 1) + ")" + dests[i] + " 0
+		// R");
+		// }
+		//				
+		if (this.outline.root.children.length > 0) {
+			var lines = pdf.outline.render().split(/\r\n/);
+			for (var i = 0; i < lines.length; i++) {
+				var line = lines[i];
+				var m = rx.exec(line);
+				if (m != null) {
+					var oid = m[1];
+					pdf.internal.newObjectDeferredBegin(oid);
+				}
+				pdf.internal.write(line);
+			}
+		}
+
+		// This code will write named destination for each page reference
+		// (page_1, etc)
+		if (this.outline.createNamedDestinations) {
+			var totalPages = this.internal.pages.length;
+			// WARNING: this assumes jsPDF starts on page 3 and pageIDs
+			// follow 5, 7, 9, etc
+			// Write destination objects for each page
+			var dests = [];
+			for (var i = 0; i < totalPages; i++) {
+				var id = pdf.internal.newObject();
+				dests.push(id);
+				var info = pdf.internal.getPageInfo(i + 1);
+				pdf.internal.write("<< /D[" + info.objId + " 0 R /XYZ null null null]>> endobj");
+			}
+
+			// assign a name for each destination
+			var names2Oid = pdf.internal.newObject();
+			pdf.internal.write('<< /Names [ ');
+			for (var i = 0; i < dests.length; i++) {
+				pdf.internal.write("(page_" + (i + 1) + ")" + dests[i] + " 0 R");
+			}
+			pdf.internal.write(' ] >>', 'endobj');
+
+			// var kids = pdf.internal.newObject();
+			// pdf.internal.write('<< /Kids [ ' + names2Oid + ' 0 R');
+			// pdf.internal.write(' ] >>', 'endobj');
+
+			var namesOid = pdf.internal.newObject();
+			pdf.internal.write('<< /Dests ' + names2Oid + " 0 R");
+			pdf.internal.write('>>', 'endobj');
+		}
+	}]);
+
+	jsPDFAPI.events.push(['putCatalog', function () {
+		var pdf = this;
+		if (pdf.outline.root.children.length > 0) {
+			pdf.internal.write("/Outlines", this.outline.makeRef(this.outline.root));
+			if (this.outline.createNamedDestinations) {
+				pdf.internal.write("/Names " + namesOid + " 0 R");
+			}
+			// Open with Bookmarks showing
+			// pdf.internal.write("/PageMode /UseOutlines");
+		}
+	}]);
+
+	jsPDFAPI.events.push(['initialized', function () {
+		var pdf = this;
+
+		pdf.outline = {
+			createNamedDestinations: false,
+			root: {
+				children: []
+			}
+		};
+
+		var namesOid;
+		var destsGoto = [];
+
+		/**
+   * Options: pageNumber
+   */
+		pdf.outline.add = function (parent, title, options) {
+			var item = {
+				title: title,
+				options: options,
+				children: []
+			};
+			if (parent == null) {
+				parent = this.root;
+			}
+			parent.children.push(item);
+			return item;
+		};
+
+		pdf.outline.render = function () {
+			this.ctx = {};
+			this.ctx.val = '';
+			this.ctx.pdf = pdf;
+
+			this.genIds_r(this.root);
+			this.renderRoot(this.root);
+			this.renderItems(this.root);
+
+			return this.ctx.val;
+		};
+
+		pdf.outline.genIds_r = function (node) {
+			node.id = pdf.internal.newObjectDeferred();
+			for (var i = 0; i < node.children.length; i++) {
+				this.genIds_r(node.children[i]);
+			}
+		};
+
+		pdf.outline.renderRoot = function (node) {
+			this.objStart(node);
+			this.line('/Type /Outlines');
+			if (node.children.length > 0) {
+				this.line('/First ' + this.makeRef(node.children[0]));
+				this.line('/Last ' + this.makeRef(node.children[node.children.length - 1]));
+			}
+			this.line('/Count ' + this.count_r({
+				count: 0
+			}, node));
+			this.objEnd();
+		};
+
+		pdf.outline.renderItems = function (node) {
+			for (var i = 0; i < node.children.length; i++) {
+				var item = node.children[i];
+				this.objStart(item);
+
+				this.line('/Title ' + this.makeString(item.title));
+
+				this.line('/Parent ' + this.makeRef(node));
+				if (i > 0) {
+					this.line('/Prev ' + this.makeRef(node.children[i - 1]));
+				}
+				if (i < node.children.length - 1) {
+					this.line('/Next ' + this.makeRef(node.children[i + 1]));
+				}
+				if (item.children.length > 0) {
+					this.line('/First ' + this.makeRef(item.children[0]));
+					this.line('/Last ' + this.makeRef(item.children[item.children.length - 1]));
+				}
+
+				var count = this.count = this.count_r({
+					count: 0
+				}, item);
+				if (count > 0) {
+					this.line('/Count ' + count);
+				}
+
+				if (item.options) {
+					if (item.options.pageNumber) {
+						// Explicit Destination
+						//WARNING this assumes page ids are 3,5,7, etc.
+						var info = pdf.internal.getPageInfo(item.options.pageNumber);
+						this.line('/Dest ' + '[' + info.objId + ' 0 R /XYZ 0 ' + this.ctx.pdf.internal.pageSize.height + ' 0]');
+						// this line does not work on all clients (pageNumber instead of page ref)
+						//this.line('/Dest ' + '[' + (item.options.pageNumber - 1) + ' /XYZ 0 ' + this.ctx.pdf.internal.pageSize.height + ' 0]');
+
+						// Named Destination
+						// this.line('/Dest (page_' + (item.options.pageNumber) + ')');
+
+						// Action Destination
+						// var id = pdf.internal.newObject();
+						// pdf.internal.write('<</D[' + (item.options.pageNumber - 1) + ' /XYZ null null null]/S/GoTo>> endobj');
+						// this.line('/A ' + id + ' 0 R' );
+					}
+				}
+				this.objEnd();
+			}
+			for (var i = 0; i < node.children.length; i++) {
+				var item = node.children[i];
+				this.renderItems(item);
+			}
+		};
+
+		pdf.outline.line = function (text) {
+			this.ctx.val += text + '\r\n';
+		};
+
+		pdf.outline.makeRef = function (node) {
+			return node.id + ' 0 R';
+		};
+
+		pdf.outline.makeString = function (val) {
+			return '(' + pdf.internal.pdfEscape(val) + ')';
+		};
+
+		pdf.outline.objStart = function (node) {
+			this.ctx.val += '\r\n' + node.id + ' 0 obj' + '\r\n<<\r\n';
+		};
+
+		pdf.outline.objEnd = function (node) {
+			this.ctx.val += '>> \r\n' + 'endobj' + '\r\n';
+		};
+
+		pdf.outline.count_r = function (ctx, node) {
+			for (var i = 0; i < node.children.length; i++) {
+				ctx.count++;
+				this.count_r(ctx, node.children[i]);
+			}
+			return ctx.count;
+		};
+	}]);
+
+	return this;
+})(jsPDF.API);
+
+/**@preserve
+ *  ====================================================================
+ * jsPDF PNG PlugIn
+ * Copyright (c) 2014 James Robb, https://github.com/jamesbrobb
+ *
+ * 
+ * ====================================================================
+ */
+
+(function (jsPDFAPI) {
+	'use strict';
+
+	/*
+  * @see http://www.w3.org/TR/PNG-Chunks.html
+  *
+  Color    Allowed      Interpretation
+  Type     Bit Depths
+ 	   0       1,2,4,8,16  Each pixel is a grayscale sample.
+ 	   2       8,16        Each pixel is an R,G,B triple.
+ 	   3       1,2,4,8     Each pixel is a palette index;
+                        a PLTE chunk must appear.
+ 	   4       8,16        Each pixel is a grayscale sample,
+                        followed by an alpha sample.
+ 	   6       8,16        Each pixel is an R,G,B triple,
+                        followed by an alpha sample.
+ */
+
+	/*
+  * PNG filter method types
+  *
+  * @see http://www.w3.org/TR/PNG-Filters.html
+  * @see http://www.libpng.org/pub/png/book/chapter09.html
+  *
+  * This is what the value 'Predictor' in decode params relates to
+  *
+  * 15 is "optimal prediction", which means the prediction algorithm can change from line to line.
+  * 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.
+  *
+    0       None
+    1       Sub
+    2       Up
+    3       Average
+    4       Paeth
+  */
+
+	var doesNotHavePngJS = function doesNotHavePngJS() {
+		return typeof PNG !== 'function' || typeof FlateStream !== 'function';
+	},
+	    canCompress = function canCompress(value) {
+		return value !== jsPDFAPI.image_compression.NONE && hasCompressionJS();
+	},
+	    hasCompressionJS = function hasCompressionJS() {
+		var inst = typeof Deflater === 'function';
+		if (!inst) throw new Error("requires deflate.js for compression");
+		return inst;
+	},
+	    compressBytes = function compressBytes(bytes, lineLength, colorsPerPixel, compression) {
+
+		var level = 5,
+		    filter_method = filterUp;
+
+		switch (compression) {
+
+			case jsPDFAPI.image_compression.FAST:
+
+				level = 3;
+				filter_method = filterSub;
+				break;
+
+			case jsPDFAPI.image_compression.MEDIUM:
+
+				level = 6;
+				filter_method = filterAverage;
+				break;
+
+			case jsPDFAPI.image_compression.SLOW:
+
+				level = 9;
+				filter_method = filterPaeth; //uses to sum to choose best filter for each line
+				break;
+		}
+
+		bytes = applyPngFilterMethod(bytes, lineLength, colorsPerPixel, filter_method);
+
+		var header = new Uint8Array(createZlibHeader(level));
+		var checksum = adler32(bytes);
+
+		var deflate = new Deflater(level);
+		var a = deflate.append(bytes);
+		var cBytes = deflate.flush();
+
+		var len = header.length + a.length + cBytes.length;
+
+		var cmpd = new Uint8Array(len + 4);
+		cmpd.set(header);
+		cmpd.set(a, header.length);
+		cmpd.set(cBytes, header.length + a.length);
+
+		cmpd[len++] = checksum >>> 24 & 0xff;
+		cmpd[len++] = checksum >>> 16 & 0xff;
+		cmpd[len++] = checksum >>> 8 & 0xff;
+		cmpd[len++] = checksum & 0xff;
+
+		return jsPDFAPI.arrayBufferToBinaryString(cmpd);
+	},
+	    createZlibHeader = function createZlibHeader(bytes, level) {
+		/*
+   * @see http://www.ietf.org/rfc/rfc1950.txt for zlib header
+   */
+		var cm = 8;
+		var cinfo = Math.LOG2E * Math.log(0x8000) - 8;
+		var cmf = cinfo << 4 | cm;
+
+		var hdr = cmf << 8;
+		var flevel = Math.min(3, (level - 1 & 0xff) >> 1);
+
+		hdr |= flevel << 6;
+		hdr |= 0; //FDICT
+		hdr += 31 - hdr % 31;
+
+		return [cmf, hdr & 0xff & 0xff];
+	},
+	    adler32 = function adler32(array, param) {
+		var adler = 1;
+		var s1 = adler & 0xffff,
+		    s2 = adler >>> 16 & 0xffff;
+		var len = array.length;
+		var tlen;
+		var i = 0;
+
+		while (len > 0) {
+			tlen = len > param ? param : len;
+			len -= tlen;
+			do {
+				s1 += array[i++];
+				s2 += s1;
+			} while (--tlen);
+
+			s1 %= 65521;
+			s2 %= 65521;
+		}
+
+		return (s2 << 16 | s1) >>> 0;
+	},
+	    applyPngFilterMethod = function applyPngFilterMethod(bytes, lineLength, colorsPerPixel, filter_method) {
+		var lines = bytes.length / lineLength,
+		    result = new Uint8Array(bytes.length + lines),
+		    filter_methods = getFilterMethods(),
+		    i = 0,
+		    line,
+		    prevLine,
+		    offset;
+
+		for (; i < lines; i++) {
+			offset = i * lineLength;
+			line = bytes.subarray(offset, offset + lineLength);
+
+			if (filter_method) {
+				result.set(filter_method(line, colorsPerPixel, prevLine), offset + i);
+			} else {
+
+				var j = 0,
+				    len = filter_methods.length,
+				    results = [];
+
+				for (; j < len; j++) {
+					results[j] = filter_methods[j](line, colorsPerPixel, prevLine);
+				}var ind = getIndexOfSmallestSum(results.concat());
+
+				result.set(results[ind], offset + i);
+			}
+
+			prevLine = line;
+		}
+
+		return result;
+	},
+	    filterNone = function filterNone(line, colorsPerPixel, prevLine) {
+		/*var result = new Uint8Array(line.length + 1);
+  result[0] = 0;
+  result.set(line, 1);*/
+
+		var result = Array.apply([], line);
+		result.unshift(0);
+
+		return result;
+	},
+	    filterSub = function filterSub(line, colorsPerPixel, prevLine) {
+		var result = [],
+		    i = 0,
+		    len = line.length,
+		    left;
+
+		result[0] = 1;
+
+		for (; i < len; i++) {
+			left = line[i - colorsPerPixel] || 0;
+			result[i + 1] = line[i] - left + 0x0100 & 0xff;
+		}
+
+		return result;
+	},
+	    filterUp = function filterUp(line, colorsPerPixel, prevLine) {
+		var result = [],
+		    i = 0,
+		    len = line.length,
+		    up;
+
+		result[0] = 2;
+
+		for (; i < len; i++) {
+			up = prevLine && prevLine[i] || 0;
+			result[i + 1] = line[i] - up + 0x0100 & 0xff;
+		}
+
+		return result;
+	},
+	    filterAverage = function filterAverage(line, colorsPerPixel, prevLine) {
+		var result = [],
+		    i = 0,
+		    len = line.length,
+		    left,
+		    up;
+
+		result[0] = 3;
+
+		for (; i < len; i++) {
+			left = line[i - colorsPerPixel] || 0;
+			up = prevLine && prevLine[i] || 0;
+			result[i + 1] = line[i] + 0x0100 - (left + up >>> 1) & 0xff;
+		}
+
+		return result;
+	},
+	    filterPaeth = function filterPaeth(line, colorsPerPixel, prevLine) {
+		var result = [],
+		    i = 0,
+		    len = line.length,
+		    left,
+		    up,
+		    upLeft,
+		    paeth;
+
+		result[0] = 4;
+
+		for (; i < len; i++) {
+			left = line[i - colorsPerPixel] || 0;
+			up = prevLine && prevLine[i] || 0;
+			upLeft = prevLine && prevLine[i - colorsPerPixel] || 0;
+			paeth = paethPredictor(left, up, upLeft);
+			result[i + 1] = line[i] - paeth + 0x0100 & 0xff;
+		}
+
+		return result;
+	},
+	    paethPredictor = function paethPredictor(left, up, upLeft) {
+
+		var p = left + up - upLeft,
+		    pLeft = Math.abs(p - left),
+		    pUp = Math.abs(p - up),
+		    pUpLeft = Math.abs(p - upLeft);
+
+		return pLeft <= pUp && pLeft <= pUpLeft ? left : pUp <= pUpLeft ? up : upLeft;
+	},
+	    getFilterMethods = function getFilterMethods() {
+		return [filterNone, filterSub, filterUp, filterAverage, filterPaeth];
+	},
+	    getIndexOfSmallestSum = function getIndexOfSmallestSum(arrays) {
+		var i = 0,
+		    len = arrays.length,
+		    sum,
+		    min,
+		    ind;
+
+		while (i < len) {
+			sum = absSum(arrays[i].slice(1));
+
+			if (sum < min || !min) {
+				min = sum;
+				ind = i;
+			}
+
+			i++;
+		}
+
+		return ind;
+	},
+	    absSum = function absSum(array) {
+		var i = 0,
+		    len = array.length,
+		    sum = 0;
+
+		while (i < len) {
+			sum += Math.abs(array[i++]);
+		}return sum;
+	},
+	    getPredictorFromCompression = function getPredictorFromCompression(compression) {
+		var predictor;
+		switch (compression) {
+			case jsPDFAPI.image_compression.FAST:
+				predictor = 11;
+				break;
+
+			case jsPDFAPI.image_compression.MEDIUM:
+				predictor = 13;
+				break;
+
+			case jsPDFAPI.image_compression.SLOW:
+				predictor = 14;
+				break;
+
+			default:
+				predictor = 12;
+				break;
+		}
+		return predictor;
+	},
+	    logImg = function logImg(img) {
+		console.log("width: " + img.width);
+		console.log("height: " + img.height);
+		console.log("bits: " + img.bits);
+		console.log("colorType: " + img.colorType);
+		console.log("transparency:");
+		console.log(img.transparency);
+		console.log("text:");
+		console.log(img.text);
+		console.log("compressionMethod: " + img.compressionMethod);
+		console.log("filterMethod: " + img.filterMethod);
+		console.log("interlaceMethod: " + img.interlaceMethod);
+		console.log("imgData:");
+		console.log(img.imgData);
+		console.log("palette:");
+		console.log(img.palette);
+		console.log("colors: " + img.colors);
+		console.log("colorSpace: " + img.colorSpace);
+		console.log("pixelBitlength: " + img.pixelBitlength);
+		console.log("hasAlphaChannel: " + img.hasAlphaChannel);
+	};
+
+	jsPDFAPI.processPNG = function (imageData, imageIndex, alias, compression, dataAsBinaryString) {
+		'use strict';
+
+		var colorSpace = this.color_spaces.DEVICE_RGB,
+		    decode = this.decode.FLATE_DECODE,
+		    bpc = 8,
+		    img,
+		    dp,
+		    trns,
+		    colors,
+		    pal,
+		    smask;
+
+		/*	if(this.isString(imageData)) {
+  		}*/
+
+		if (this.isArrayBuffer(imageData)) imageData = new Uint8Array(imageData);
+
+		if (this.isArrayBufferView(imageData)) {
+
+			if (doesNotHavePngJS()) throw new Error("PNG support requires png.js and zlib.js");
+
+			img = new PNG(imageData);
+			imageData = img.imgData;
+			bpc = img.bits;
+			colorSpace = img.colorSpace;
+			colors = img.colors;
+
+			//logImg(img);
+
+			/*
+    * colorType 6 - Each pixel is an R,G,B triple, followed by an alpha sample.
+    *
+    * colorType 4 - Each pixel is a grayscale sample, followed by an alpha sample.
+    *
+    * Extract alpha to create two separate images, using the alpha as a sMask
+    */
+			if ([4, 6].indexOf(img.colorType) !== -1) {
+
+				/*
+     * processes 8 bit RGBA and grayscale + alpha images
+     */
+				if (img.bits === 8) {
+
+					var pixels = img.pixelBitlength == 32 ? new Uint32Array(img.decodePixels().buffer) : img.pixelBitlength == 16 ? new Uint16Array(img.decodePixels().buffer) : new Uint8Array(img.decodePixels().buffer),
+					    len = pixels.length,
+					    imgData = new Uint8Array(len * img.colors),
+					    alphaData = new Uint8Array(len),
+					    pDiff = img.pixelBitlength - img.bits,
+					    i = 0,
+					    n = 0,
+					    pixel,
+					    pbl;
+
+					for (; i < len; i++) {
+						pixel = pixels[i];
+						pbl = 0;
+
+						while (pbl < pDiff) {
+
+							imgData[n++] = pixel >>> pbl & 0xff;
+							pbl = pbl + img.bits;
+						}
+
+						alphaData[i] = pixel >>> pbl & 0xff;
+					}
+				}
+
+				/*
+     * processes 16 bit RGBA and grayscale + alpha images
+     */
+				if (img.bits === 16) {
+
+					var pixels = new Uint32Array(img.decodePixels().buffer),
+					    len = pixels.length,
+					    imgData = new Uint8Array(len * (32 / img.pixelBitlength) * img.colors),
+					    alphaData = new Uint8Array(len * (32 / img.pixelBitlength)),
+					    hasColors = img.colors > 1,
+					    i = 0,
+					    n = 0,
+					    a = 0,
+					    pixel;
+
+					while (i < len) {
+						pixel = pixels[i++];
+
+						imgData[n++] = pixel >>> 0 & 0xFF;
+
+						if (hasColors) {
+							imgData[n++] = pixel >>> 16 & 0xFF;
+
+							pixel = pixels[i++];
+							imgData[n++] = pixel >>> 0 & 0xFF;
+						}
+
+						alphaData[a++] = pixel >>> 16 & 0xFF;
+					}
+
+					bpc = 8;
+				}
+
+				if (canCompress(compression)) {
+
+					imageData = compressBytes(imgData, img.width * img.colors, img.colors, compression);
+					smask = compressBytes(alphaData, img.width, 1, compression);
+				} else {
+
+					imageData = imgData;
+					smask = alphaData;
+					decode = null;
+				}
+			}
+
+			/*
+    * Indexed png. Each pixel is a palette index.
+    */
+			if (img.colorType === 3) {
+
+				colorSpace = this.color_spaces.INDEXED;
+				pal = img.palette;
+
+				if (img.transparency.indexed) {
+
+					var trans = img.transparency.indexed;
+
+					var total = 0,
+					    i = 0,
+					    len = trans.length;
+
+					for (; i < len; ++i) {
+						total += trans[i];
+					}total = total / 255;
+
+					/*
+      * a single color is specified as 100% transparent (0),
+      * so we set trns to use a /Mask with that index
+      */
+					if (total === len - 1 && trans.indexOf(0) !== -1) {
+						trns = [trans.indexOf(0)];
+
+						/*
+       * there's more than one colour within the palette that specifies
+       * a transparency value less than 255, so we unroll the pixels to create an image sMask
+       */
+					} else if (total !== len) {
+
+						var pixels = img.decodePixels(),
+						    alphaData = new Uint8Array(pixels.length),
+						    i = 0,
+						    len = pixels.length;
+
+						for (; i < len; i++) {
+							alphaData[i] = trans[pixels[i]];
+						}smask = compressBytes(alphaData, img.width, 1);
+					}
+				}
+			}
+
+			var predictor = getPredictorFromCompression(compression);
+
+			if (decode === this.decode.FLATE_DECODE) dp = '/Predictor ' + predictor + ' /Colors ' + colors + ' /BitsPerComponent ' + bpc + ' /Columns ' + img.width;else
+				//remove 'Predictor' as it applies to the type of png filter applied to its IDAT - we only apply with compression
+				dp = '/Colors ' + colors + ' /BitsPerComponent ' + bpc + ' /Columns ' + img.width;
+
+			if (this.isArrayBuffer(imageData) || this.isArrayBufferView(imageData)) imageData = this.arrayBufferToBinaryString(imageData);
+
+			if (smask && this.isArrayBuffer(smask) || this.isArrayBufferView(smask)) smask = this.arrayBufferToBinaryString(smask);
+
+			return this.createImageInfo(imageData, img.width, img.height, colorSpace, bpc, decode, imageIndex, alias, dp, trns, pal, smask, predictor);
+		}
+
+		throw new Error("Unsupported PNG image data, try using JPEG instead.");
+	};
+})(jsPDF.API);
+
+/**
+ * jsPDF Autoprint Plugin
+ *
+ * Licensed under the MIT License.
+ * http://opensource.org/licenses/mit-license
+ */
+
+(function (jsPDFAPI) {
+  'use strict';
+
+  jsPDFAPI.autoPrint = function () {
+    'use strict';
+
+    var refAutoPrintTag;
+
+    this.internal.events.subscribe('postPutResources', function () {
+      refAutoPrintTag = this.internal.newObject();
+      this.internal.write("<< /S/Named /Type/Action /N/Print >>", "endobj");
+    });
+
+    this.internal.events.subscribe("putCatalog", function () {
+      this.internal.write("/OpenAction " + refAutoPrintTag + " 0" + " R");
+    });
+    return this;
+  };
+})(jsPDF.API);
+
+/** @preserve
+ * jsPDF split_text_to_size plugin - MIT license.
+ * Copyright (c) 2012 Willow Systems Corporation, willow-systems.com
+ *               2014 Diego Casorran, https://github.com/diegocr
+ */
+/**
+ * 
+ * ====================================================================
+ */
+
+(function (API) {
+	'use strict';
+
+	/**
+ Returns an array of length matching length of the 'word' string, with each
+ cell ocupied by the width of the char in that position.
+ 
+ @function
+ @param word {String}
+ @param widths {Object}
+ @param kerning {Object}
+ @returns {Array}
+ */
+
+	var getCharWidthsArray = API.getCharWidthsArray = function (text, options) {
+
+		if (!options) {
+			options = {};
+		}
+
+		var widths = options.widths ? options.widths : this.internal.getFont().metadata.Unicode.widths,
+		    widthsFractionOf = widths.fof ? widths.fof : 1,
+		    kerning = options.kerning ? options.kerning : this.internal.getFont().metadata.Unicode.kerning,
+		    kerningFractionOf = kerning.fof ? kerning.fof : 1;
+
+		// console.log("widths, kergnings", widths, kerning)
+
+		var i,
+		    l,
+		    char_code,
+		    prior_char_code = 0 // for kerning
+		,
+		    default_char_width = widths[0] || widthsFractionOf,
+		    output = [];
+
+		for (i = 0, l = text.length; i < l; i++) {
+			char_code = text.charCodeAt(i);
+			output.push((widths[char_code] || default_char_width) / widthsFractionOf + (kerning[char_code] && kerning[char_code][prior_char_code] || 0) / kerningFractionOf);
+			prior_char_code = char_code;
+		}
+
+		return output;
+	};
+	var getArraySum = function getArraySum(array) {
+		var i = array.length,
+		    output = 0;
+		while (i) {
+			i--;
+			output += array[i];
+		}
+		return output;
+	};
+	/**
+ Returns a widths of string in a given font, if the font size is set as 1 point.
+ 
+ In other words, this is "proportional" value. For 1 unit of font size, the length
+ of the string will be that much.
+ 
+ Multiply by font size to get actual width in *points*
+ Then divide by 72 to get inches or divide by (72/25.6) to get 'mm' etc.
+ 
+ @public
+ @function
+ @param
+ @returns {Type}
+ */
+	var getStringUnitWidth = API.getStringUnitWidth = function (text, options) {
+		return getArraySum(getCharWidthsArray.call(this, text, options));
+	};
+
+	/**
+ returns array of lines
+ */
+	var splitLongWord = function splitLongWord(word, widths_array, firstLineMaxLen, maxLen) {
+		var answer = [];
+
+		// 1st, chop off the piece that can fit on the hanging line.
+		var i = 0,
+		    l = word.length,
+		    workingLen = 0;
+		while (i !== l && workingLen + widths_array[i] < firstLineMaxLen) {
+			workingLen += widths_array[i];i++;
+		}
+		// this is first line.
+		answer.push(word.slice(0, i));
+
+		// 2nd. Split the rest into maxLen pieces.
+		var startOfLine = i;
+		workingLen = 0;
+		while (i !== l) {
+			if (workingLen + widths_array[i] > maxLen) {
+				answer.push(word.slice(startOfLine, i));
+				workingLen = 0;
+				startOfLine = i;
+			}
+			workingLen += widths_array[i];i++;
+		}
+		if (startOfLine !== i) {
+			answer.push(word.slice(startOfLine, i));
+		}
+
+		return answer;
+	};
+
+	// Note, all sizing inputs for this function must be in "font measurement units"
+	// By default, for PDF, it's "point".
+	var splitParagraphIntoLines = function splitParagraphIntoLines(text, maxlen, options) {
+		// at this time works only on Western scripts, ones with space char
+		// separating the words. Feel free to expand.
+
+		if (!options) {
+			options = {};
+		}
+
+		var line = [],
+		    lines = [line],
+		    line_length = options.textIndent || 0,
+		    separator_length = 0,
+		    current_word_length = 0,
+		    word,
+		    widths_array,
+		    words = text.split(' '),
+		    spaceCharWidth = getCharWidthsArray(' ', options)[0],
+		    i,
+		    l,
+		    tmp,
+		    lineIndent;
+
+		if (options.lineIndent === -1) {
+			lineIndent = words[0].length + 2;
+		} else {
+			lineIndent = options.lineIndent || 0;
+		}
+		if (lineIndent) {
+			var pad = Array(lineIndent).join(" "),
+			    wrds = [];
+			words.map(function (wrd) {
+				wrd = wrd.split(/\s*\n/);
+				if (wrd.length > 1) {
+					wrds = wrds.concat(wrd.map(function (wrd, idx) {
+						return (idx && wrd.length ? "\n" : "") + wrd;
+					}));
+				} else {
+					wrds.push(wrd[0]);
+				}
+			});
+			words = wrds;
+			lineIndent = getStringUnitWidth(pad, options);
+		}
+
+		for (i = 0, l = words.length; i < l; i++) {
+			var force = 0;
+
+			word = words[i];
+			if (lineIndent && word[0] == "\n") {
+				word = word.substr(1);
+				force = 1;
+			}
+			widths_array = getCharWidthsArray(word, options);
+			current_word_length = getArraySum(widths_array);
+
+			if (line_length + separator_length + current_word_length > maxlen || force) {
+				if (current_word_length > maxlen) {
+					// this happens when you have space-less long URLs for example.
+					// we just chop these to size. We do NOT insert hiphens
+					tmp = splitLongWord(word, widths_array, maxlen - (line_length + separator_length), maxlen);
+					// first line we add to existing line object
+					line.push(tmp.shift()); // it's ok to have extra space indicator there
+					// last line we make into new line object
+					line = [tmp.pop()];
+					// lines in the middle we apped to lines object as whole lines
+					while (tmp.length) {
+						lines.push([tmp.shift()]); // single fragment occupies whole line
+					}
+					current_word_length = getArraySum(widths_array.slice(word.length - line[0].length));
+				} else {
+					// just put it on a new line
+					line = [word];
+				}
+
+				// now we attach new line to lines
+				lines.push(line);
+				line_length = current_word_length + lineIndent;
+				separator_length = spaceCharWidth;
+			} else {
+				line.push(word);
+
+				line_length += separator_length + current_word_length;
+				separator_length = spaceCharWidth;
+			}
+		}
+
+		if (lineIndent) {
+			var postProcess = function postProcess(ln, idx) {
+				return (idx ? pad : '') + ln.join(" ");
+			};
+		} else {
+			var postProcess = function postProcess(ln) {
+				return ln.join(" ");
+			};
+		}
+
+		return lines.map(postProcess);
+	};
+
+	/**
+ Splits a given string into an array of strings. Uses 'size' value
+ (in measurement units declared as default for the jsPDF instance)
+ and the font's "widths" and "Kerning" tables, where available, to
+ determine display length of a given string for a given font.
+ 
+ We use character's 100% of unit size (height) as width when Width
+ table or other default width is not available.
+ 
+ @public
+ @function
+ @param text {String} Unencoded, regular JavaScript (Unicode, UTF-16 / UCS-2) string.
+ @param size {Number} Nominal number, measured in units default to this instance of jsPDF.
+ @param options {Object} Optional flags needed for chopper to do the right thing.
+ @returns {Array} with strings chopped to size.
+ */
+	API.splitTextToSize = function (text, maxlen, options) {
+		'use strict';
+
+		if (!options) {
+			options = {};
+		}
+
+		var fsize = options.fontSize || this.internal.getFontSize(),
+		    newOptions = function (options) {
+			var widths = { 0: 1 },
+			    kerning = {};
+
+			if (!options.widths || !options.kerning) {
+				var f = this.internal.getFont(options.fontName, options.fontStyle),
+				    encoding = 'Unicode';
+				// NOT UTF8, NOT UTF16BE/LE, NOT UCS2BE/LE
+				// Actual JavaScript-native String's 16bit char codes used.
+				// no multi-byte logic here
+
+				if (f.metadata[encoding]) {
+					return {
+						widths: f.metadata[encoding].widths || widths,
+						kerning: f.metadata[encoding].kerning || kerning
+					};
+				}
+			} else {
+				return {
+					widths: options.widths,
+					kerning: options.kerning
+				};
+			}
+
+			// then use default values
+			return {
+				widths: widths,
+				kerning: kerning
+			};
+		}.call(this, options);
+
+		// first we split on end-of-line chars
+		var paragraphs;
+		if (Array.isArray(text)) {
+			paragraphs = text;
+		} else {
+			paragraphs = text.split(/\r?\n/);
+		}
+
+		// now we convert size (max length of line) into "font size units"
+		// at present time, the "font size unit" is always 'point'
+		// 'proportional' means, "in proportion to font size"
+		var fontUnit_maxLen = 1.0 * this.internal.scaleFactor * maxlen / fsize;
+		// at this time, fsize is always in "points" regardless of the default measurement unit of the doc.
+		// this may change in the future?
+		// until then, proportional_maxlen is likely to be in 'points'
+
+		// If first line is to be indented (shorter or longer) than maxLen
+		// we indicate that by using CSS-style "text-indent" option.
+		// here it's in font units too (which is likely 'points')
+		// it can be negative (which makes the first line longer than maxLen)
+		newOptions.textIndent = options.textIndent ? options.textIndent * 1.0 * this.internal.scaleFactor / fsize : 0;
+		newOptions.lineIndent = options.lineIndent;
+
+		var i,
+		    l,
+		    output = [];
+		for (i = 0, l = paragraphs.length; i < l; i++) {
+			output = output.concat(splitParagraphIntoLines(paragraphs[i], fontUnit_maxLen, newOptions));
+		}
+
+		return output;
+	};
+})(jsPDF.API);
+
+/** @preserve 
+jsPDF standard_fonts_metrics plugin
+Copyright (c) 2012 Willow Systems Corporation, willow-systems.com
+MIT license.
+*/
+/**
+ * 
+ * ====================================================================
+ */
+
+(function (API) {
+	'use strict';
+
+	/*
+ # reference (Python) versions of 'compress' and 'uncompress'
+ # only 'uncompress' function is featured lower as JavaScript
+ # if you want to unit test "roundtrip", just transcribe the reference
+ # 'compress' function from Python into JavaScript
+ 
+ def compress(data):
+ 
+ 	keys =   '0123456789abcdef'
+ 	values = 'klmnopqrstuvwxyz'
+ 	mapping = dict(zip(keys, values))
+ 	vals = []
+ 	for key in data.keys():
+ 		value = data[key]
+ 		try:
+ 			keystring = hex(key)[2:]
+ 			keystring = keystring[:-1] + mapping[keystring[-1:]]
+ 		except:
+ 			keystring = key.join(["'","'"])
+ 			#print('Keystring is %s' % keystring)
+ 
+ 		try:
+ 			if value < 0:
+ 				valuestring = hex(value)[3:]
+ 				numberprefix = '-'
+ 			else:
+ 				valuestring = hex(value)[2:]
+ 				numberprefix = ''
+ 			valuestring = numberprefix + valuestring[:-1] + mapping[valuestring[-1:]]
+ 		except:
+ 			if type(value) == dict:
+ 				valuestring = compress(value)
+ 			else:
+ 				raise Exception("Don't know what to do with value type %s" % type(value))
+ 
+ 		vals.append(keystring+valuestring)
+ 	
+ 	return '{' + ''.join(vals) + '}'
+ 
+ def uncompress(data):
+ 
+ 	decoded = '0123456789abcdef'
+ 	encoded = 'klmnopqrstuvwxyz'
+ 	mapping = dict(zip(encoded, decoded))
+ 
+ 	sign = +1
+ 	stringmode = False
+ 	stringparts = []
+ 
+ 	output = {}
+ 
+ 	activeobject = output
+ 	parentchain = []
+ 
+ 	keyparts = ''
+ 	valueparts = ''
+ 
+ 	key = None
+ 
+ 	ending = set(encoded)
+ 
+ 	i = 1
+ 	l = len(data) - 1 # stripping starting, ending {}
+ 	while i != l: # stripping {}
+ 		# -, {, }, ' are special.
+ 
+ 		ch = data[i]
+ 		i += 1
+ 
+ 		if ch == "'":
+ 			if stringmode:
+ 				# end of string mode
+ 				stringmode = False
+ 				key = ''.join(stringparts)
+ 			else:
+ 				# start of string mode
+ 				stringmode = True
+ 				stringparts = []
+ 		elif stringmode == True:
+ 			#print("Adding %s to stringpart" % ch)
+ 			stringparts.append(ch)
+ 
+ 		elif ch == '{':
+ 			# start of object
+ 			parentchain.append( [activeobject, key] )
+ 			activeobject = {}
+ 			key = None
+ 			#DEBUG = True
+ 		elif ch == '}':
+ 			# end of object
+ 			parent, key = parentchain.pop()
+ 			parent[key] = activeobject
+ 			key = None
+ 			activeobject = parent
+ 			#DEBUG = False
+ 
+ 		elif ch == '-':
+ 			sign = -1
+ 		else:
+ 			# must be number
+ 			if key == None:
+ 				#debug("In Key. It is '%s', ch is '%s'" % (keyparts, ch))
+ 				if ch in ending:
+ 					#debug("End of key")
+ 					keyparts += mapping[ch]
+ 					key = int(keyparts, 16) * sign
+ 					sign = +1
+ 					keyparts = ''
+ 				else:
+ 					keyparts += ch
+ 			else:
+ 				#debug("In value. It is '%s', ch is '%s'" % (valueparts, ch))
+ 				if ch in ending:
+ 					#debug("End of value")
+ 					valueparts += mapping[ch]
+ 					activeobject[key] = int(valueparts, 16) * sign
+ 					sign = +1
+ 					key = None
+ 					valueparts = ''
+ 				else:
+ 					valueparts += ch
+ 
+ 			#debug(activeobject)
+ 
+ 	return output
+ 
+ */
+
+	/**
+ Uncompresses data compressed into custom, base16-like format. 
+ @public
+ @function
+ @param
+ @returns {Type}
+ */
+
+	var uncompress = function uncompress(data) {
+
+		var decoded = '0123456789abcdef',
+		    encoded = 'klmnopqrstuvwxyz',
+		    mapping = {};
+
+		for (var i = 0; i < encoded.length; i++) {
+			mapping[encoded[i]] = decoded[i];
+		}
+
+		var undef,
+		    output = {},
+		    sign = 1,
+		    stringparts // undef. will be [] in string mode
+
+		,
+		    activeobject = output,
+		    parentchain = [],
+		    parent_key_pair,
+		    keyparts = '',
+		    valueparts = '',
+		    key // undef. will be Truthy when Key is resolved.
+		,
+		    datalen = data.length - 1 // stripping ending }
+		,
+		    ch;
+
+		i = 1; // stripping starting {
+
+		while (i != datalen) {
+			// - { } ' are special.
+
+			ch = data[i];
+			i += 1;
+
+			if (ch == "'") {
+				if (stringparts) {
+					// end of string mode
+					key = stringparts.join('');
+					stringparts = undef;
+				} else {
+					// start of string mode
+					stringparts = [];
+				}
+			} else if (stringparts) {
+				stringparts.push(ch);
+			} else if (ch == '{') {
+				// start of object
+				parentchain.push([activeobject, key]);
+				activeobject = {};
+				key = undef;
+			} else if (ch == '}') {
+				// end of object
+				parent_key_pair = parentchain.pop();
+				parent_key_pair[0][parent_key_pair[1]] = activeobject;
+				key = undef;
+				activeobject = parent_key_pair[0];
+			} else if (ch == '-') {
+				sign = -1;
+			} else {
+				// must be number
+				if (key === undef) {
+					if (mapping.hasOwnProperty(ch)) {
+						keyparts += mapping[ch];
+						key = parseInt(keyparts, 16) * sign;
+						sign = +1;
+						keyparts = '';
+					} else {
+						keyparts += ch;
+					}
+				} else {
+					if (mapping.hasOwnProperty(ch)) {
+						valueparts += mapping[ch];
+						activeobject[key] = parseInt(valueparts, 16) * sign;
+						sign = +1;
+						key = undef;
+						valueparts = '';
+					} else {
+						valueparts += ch;
+					}
+				}
+			}
+		} // end while
+
+		return output;
+	};
+
+	// encoding = 'Unicode' 
+	// NOT UTF8, NOT UTF16BE/LE, NOT UCS2BE/LE. NO clever BOM behavior
+	// Actual 16bit char codes used.
+	// no multi-byte logic here
+
+	// Unicode characters to WinAnsiEncoding:
+	// {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}
+	// as you can see, all Unicode chars are outside of 0-255 range. No char code conflicts.
+	// this means that you can give Win cp1252 encoded strings to jsPDF for rendering directly
+	// as well as give strings with some (supported by these fonts) Unicode characters and 
+	// these will be mapped to win cp1252 
+	// for example, you can send char code (cp1252) 0x80 or (unicode) 0x20AC, getting "Euro" glyph displayed in both cases.
+
+	var encodingBlock = {
+		'codePages': ['WinAnsiEncoding'],
+		'WinAnsiEncoding': uncompress("{19m8n201n9q201o9r201s9l201t9m201u8m201w9n201x9o201y8o202k8q202l8r202m9p202q8p20aw8k203k8t203t8v203u9v2cq8s212m9t15m8w15n9w2dw9s16k8u16l9u17s9z17x8y17y9y}")
+	},
+	    encodings = { 'Unicode': {
+			'Courier': encodingBlock,
+			'Courier-Bold': encodingBlock,
+			'Courier-BoldOblique': encodingBlock,
+			'Courier-Oblique': encodingBlock,
+			'Helvetica': encodingBlock,
+			'Helvetica-Bold': encodingBlock,
+			'Helvetica-BoldOblique': encodingBlock,
+			'Helvetica-Oblique': encodingBlock,
+			'Times-Roman': encodingBlock,
+			'Times-Bold': encodingBlock,
+			'Times-BoldItalic': encodingBlock,
+			'Times-Italic': encodingBlock
+			//	, 'Symbol'
+			//	, 'ZapfDingbats'
+		} }
+	/** 
+ Resources:
+ Font metrics data is reprocessed derivative of contents of
+ "Font Metrics for PDF Core 14 Fonts" package, which exhibits the following copyright and license:
+ 
+ Copyright (c) 1989, 1990, 1991, 1992, 1993, 1997 Adobe Systems Incorporated. All Rights Reserved.
+ 
+ This file and the 14 PostScript(R) AFM files it accompanies may be used,
+ copied, and distributed for any purpose and without charge, with or without
+ modification, provided that all copyright notices are retained; that the AFM
+ files are not distributed without this file; that all modifications to this
+ file or any of the AFM files are prominently noted in the modified file(s);
+ and that this paragraph is not modified. Adobe Systems has no responsibility
+ or obligation to support the use of the AFM files.
+ 
+ */
+	,
+	    fontMetrics = { 'Unicode': {
+			// all sizing numbers are n/fontMetricsFractionOf = one font size unit
+			// this means that if fontMetricsFractionOf = 1000, and letter A's width is 476, it's
+			// width is 476/1000 or 47.6% of its height (regardless of font size)
+			// At this time this value applies to "widths" and "kerning" numbers.
+
+			// char code 0 represents "default" (average) width - use it for chars missing in this table.
+			// key 'fof' represents the "fontMetricsFractionOf" value
+
+			'Courier-Oblique': uncompress("{'widths'{k3w'fof'6o}'kerning'{'fof'-6o}}"),
+			'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}}}"),
+			'Helvetica-Bold': uncompress("{'widths'{k3s2q4scx1w201n3r201o6o201s1w201t1w201u1w201w3m201x3m201y3m2k1w2l2l202m2n2n3r2o3r2p5t202q6o2r1s2s2l2t2l2u2r2v3u2w1w2x2l2y1w2z1w3k3r3l3r3m3r3n3r3o3r3p3r3q3r3r3r3s3r203t2l203u2l3v2l3w3u3x3u3y3u3z3x4k6l4l4s4m4s4n4s4o4s4p4m4q3x4r4y4s4s4t1w4u3r4v4s4w3x4x5n4y4s4z4y5k4m5l4y5m4s5n4m5o3x5p4s5q4m5r5y5s4m5t4m5u3x5v2l5w1w5x2l5y3u5z3r6k2l6l3r6m3x6n3r6o3x6p3r6q2l6r3x6s3x6t1w6u1w6v3r6w1w6x5t6y3x6z3x7k3x7l3x7m2r7n3r7o2l7p3x7q3r7r4y7s3r7t3r7u3m7v2r7w1w7x2r7y3u202l3rcl4sal2lam3ran3rao3rap3rar3ras2lat4tau2pav3raw3uay4taz2lbk2sbl3u'fof'6obo2lbp3xbq3rbr1wbs2lbu2obv3rbz3xck4s202k3rcm4scn4sco4scp4scq6ocr4scs4mct4mcu4mcv4mcw1w2m2zcy1wcz1wdl4sdm4ydn4ydo4ydp4ydq4yds4ydt4sdu4sdv4sdw4sdz3xek3rel3rem3ren3reo3rep3req5ter3res3ret3reu3rev3rew1wex1wey1wez1wfl3xfm3xfn3xfo3xfp3xfq3xfr3ufs3xft3xfu3xfv3xfw3xfz3r203k6o212m6o2dw2l2cq2l3t3r3u2l17s4m19m3r}'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': uncompress("{'widths'{k3w'fof'6o}'kerning'{'fof'-6o}}"),
+			'Courier-BoldOblique': uncompress("{'widths'{k3w'fof'6o}'kerning'{'fof'-6o}}"),
+			'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}}}")
+			//, 'Symbol': uncompress("{'widths'{k3uaw4r19m3m2k1t2l2l202m2y2n3m2p5n202q6o3k3m2s2l2t2l2v3r2w1t3m3m2y1t2z1wbk2sbl3r'fof'6o3n3m3o3m3p3m3q3m3r3m3s3m3t3m3u1w3v1w3w3r3x3r3y3r3z2wbp3t3l3m5v2l5x2l5z3m2q4yfr3r7v3k7w1o7x3k}'kerning'{'fof'-6o}}")
+			, 'Helvetica': uncompress("{'widths'{k3p2q4mcx1w201n3r201o6o201s1q201t1q201u1q201w2l201x2l201y2l2k1w2l1w202m2n2n3r2o3r2p5t202q6o2r1n2s2l2t2l2u2r2v3u2w1w2x2l2y1w2z1w3k3r3l3r3m3r3n3r3o3r3p3r3q3r3r3r3s3r203t2l203u2l3v1w3w3u3x3u3y3u3z3r4k6p4l4m4m4m4n4s4o4s4p4m4q3x4r4y4s4s4t1w4u3m4v4m4w3r4x5n4y4s4z4y5k4m5l4y5m4s5n4m5o3x5p4s5q4m5r5y5s4m5t4m5u3x5v1w5w1w5x1w5y2z5z3r6k2l6l3r6m3r6n3m6o3r6p3r6q1w6r3r6s3r6t1q6u1q6v3m6w1q6x5n6y3r6z3r7k3r7l3r7m2l7n3m7o1w7p3r7q3m7r4s7s3m7t3m7u3m7v2l7w1u7x2l7y3u202l3rcl4mal2lam3ran3rao3rap3rar3ras2lat4tau2pav3raw3uay4taz2lbk2sbl3u'fof'6obo2lbp3rbr1wbs2lbu2obv3rbz3xck4m202k3rcm4mcn4mco4mcp4mcq6ocr4scs4mct4mcu4mcv4mcw1w2m2ncy1wcz1wdl4sdm4ydn4ydo4ydp4ydq4yds4ydt4sdu4sdv4sdw4sdz3xek3rel3rem3ren3reo3rep3req5ter3mes3ret3reu3rev3rew1wex1wey1wez1wfl3rfm3rfn3rfo3rfp3rfq3rfr3ufs3xft3rfu3rfv3rfw3rfz3m203k6o212m6o2dw2l2cq2l3t3r3u1w17s4m19m3r}'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': uncompress("{'widths'{k3s2q4scx1w201n3r201o6o201s1w201t1w201u1w201w3m201x3m201y3m2k1w2l2l202m2n2n3r2o3r2p5t202q6o2r1s2s2l2t2l2u2r2v3u2w1w2x2l2y1w2z1w3k3r3l3r3m3r3n3r3o3r3p3r3q3r3r3r3s3r203t2l203u2l3v2l3w3u3x3u3y3u3z3x4k6l4l4s4m4s4n4s4o4s4p4m4q3x4r4y4s4s4t1w4u3r4v4s4w3x4x5n4y4s4z4y5k4m5l4y5m4s5n4m5o3x5p4s5q4m5r5y5s4m5t4m5u3x5v2l5w1w5x2l5y3u5z3r6k2l6l3r6m3x6n3r6o3x6p3r6q2l6r3x6s3x6t1w6u1w6v3r6w1w6x5t6y3x6z3x7k3x7l3x7m2r7n3r7o2l7p3x7q3r7r4y7s3r7t3r7u3m7v2r7w1w7x2r7y3u202l3rcl4sal2lam3ran3rao3rap3rar3ras2lat4tau2pav3raw3uay4taz2lbk2sbl3u'fof'6obo2lbp3xbq3rbr1wbs2lbu2obv3rbz3xck4s202k3rcm4scn4sco4scp4scq6ocr4scs4mct4mcu4mcv4mcw1w2m2zcy1wcz1wdl4sdm4ydn4ydo4ydp4ydq4yds4ydt4sdu4sdv4sdw4sdz3xek3rel3rem3ren3reo3rep3req5ter3res3ret3reu3rev3rew1wex1wey1wez1wfl3xfm3xfn3xfo3xfp3xfq3xfr3ufs3xft3xfu3xfv3xfw3xfz3r203k6o212m6o2dw2l2cq2l3t3r3u2l17s4m19m3r}'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': uncompress("{'widths'{k4u2k1w'fof'6o}'kerning'{'fof'-6o}}")
+			, 'Courier-Bold': uncompress("{'widths'{k3w'fof'6o}'kerning'{'fof'-6o}}"),
+			'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}fv{17su5tu5qs}fw{17su5tu5qs}}}"),
+			'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}}}"),
+			'Helvetica-Oblique': uncompress("{'widths'{k3p2q4mcx1w201n3r201o6o201s1q201t1q201u1q201w2l201x2l201y2l2k1w2l1w202m2n2n3r2o3r2p5t202q6o2r1n2s2l2t2l2u2r2v3u2w1w2x2l2y1w2z1w3k3r3l3r3m3r3n3r3o3r3p3r3q3r3r3r3s3r203t2l203u2l3v1w3w3u3x3u3y3u3z3r4k6p4l4m4m4m4n4s4o4s4p4m4q3x4r4y4s4s4t1w4u3m4v4m4w3r4x5n4y4s4z4y5k4m5l4y5m4s5n4m5o3x5p4s5q4m5r5y5s4m5t4m5u3x5v1w5w1w5x1w5y2z5z3r6k2l6l3r6m3r6n3m6o3r6p3r6q1w6r3r6s3r6t1q6u1q6v3m6w1q6x5n6y3r6z3r7k3r7l3r7m2l7n3m7o1w7p3r7q3m7r4s7s3m7t3m7u3m7v2l7w1u7x2l7y3u202l3rcl4mal2lam3ran3rao3rap3rar3ras2lat4tau2pav3raw3uay4taz2lbk2sbl3u'fof'6obo2lbp3rbr1wbs2lbu2obv3rbz3xck4m202k3rcm4mcn4mco4mcp4mcq6ocr4scs4mct4mcu4mcv4mcw1w2m2ncy1wcz1wdl4sdm4ydn4ydo4ydp4ydq4yds4ydt4sdu4sdv4sdw4sdz3xek3rel3rem3ren3reo3rep3req5ter3mes3ret3reu3rev3rew1wex1wey1wez1wfl3rfm3rfn3rfo3rfp3rfq3rfr3ufs3xft3rfu3rfv3rfw3rfz3m203k6o212m6o2dw2l2cq2l3t3r3u1w17s4m19m3r}'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}}}")
+		} };
+
+	/*
+ This event handler is fired when a new jsPDF object is initialized
+ This event handler appends metrics data to standard fonts within
+ that jsPDF instance. The metrics are mapped over Unicode character
+ codes, NOT CIDs or other codes matching the StandardEncoding table of the
+ standard PDF fonts.
+ Future:
+ Also included is the encoding maping table, converting Unicode (UCS-2, UTF-16)
+ char codes to StandardEncoding character codes. The encoding table is to be used
+ somewhere around "pdfEscape" call.
+ */
+
+	API.events.push(['addFont', function (font) {
+		var metrics,
+		    unicode_section,
+		    encoding = 'Unicode',
+		    encodingBlock;
+
+		metrics = fontMetrics[encoding][font.PostScriptName];
+		if (metrics) {
+			if (font.metadata[encoding]) {
+				unicode_section = font.metadata[encoding];
+			} else {
+				unicode_section = font.metadata[encoding] = {};
+			}
+
+			unicode_section.widths = metrics.widths;
+			unicode_section.kerning = metrics.kerning;
+		}
+
+		encodingBlock = encodings[encoding][font.PostScriptName];
+		if (encodingBlock) {
+			if (font.metadata[encoding]) {
+				unicode_section = font.metadata[encoding];
+			} else {
+				unicode_section = font.metadata[encoding] = {};
+			}
+
+			unicode_section.encoding = encodingBlock;
+			if (encodingBlock.codePages && encodingBlock.codePages.length) {
+				font.encoding = encodingBlock.codePages[0];
+			}
+		}
+	}]); // end of adding event handler
+})(jsPDF.API);
+
+/** @preserve
+jsPDF SVG plugin
+Copyright (c) 2012 Willow Systems Corporation, willow-systems.com
+*/
+/**
+ * 
+ * ====================================================================
+ */
+
+(function (jsPDFAPI) {
+	'use strict';
+
+	/**
+ Parses SVG XML and converts only some of the SVG elements into
+ PDF elements.
+ 
+ Supports:
+  paths
+ 
+ @public
+ @function
+ @param
+ @returns {Type}
+ */
+
+	jsPDFAPI.addSVG = function (svgtext, x, y, w, h) {
+		// 'this' is _jsPDF object returned when jsPDF is inited (new jsPDF())
+
+		var undef;
+
+		if (x === undef || y === undef) {
+			throw new Error("addSVG needs values for 'x' and 'y'");
+		}
+
+		function InjectCSS(cssbody, document) {
+			var styletag = document.createElement('style');
+			styletag.type = 'text/css';
+			if (styletag.styleSheet) {
+				// ie
+				styletag.styleSheet.cssText = cssbody;
+			} else {
+				// others
+				styletag.appendChild(document.createTextNode(cssbody));
+			}
+			document.getElementsByTagName("head")[0].appendChild(styletag);
+		}
+
+		function createWorkerNode(document) {
+
+			var frameID = 'childframe' // Date.now().toString() + '_' + (Math.random() * 100).toString()
+			,
+			    frame = document.createElement('iframe');
+
+			InjectCSS('.jsPDF_sillysvg_iframe {display:none;position:absolute;}', document);
+
+			frame.name = frameID;
+			frame.setAttribute("width", 0);
+			frame.setAttribute("height", 0);
+			frame.setAttribute("frameborder", "0");
+			frame.setAttribute("scrolling", "no");
+			frame.setAttribute("seamless", "seamless");
+			frame.setAttribute("class", "jsPDF_sillysvg_iframe");
+
+			document.body.appendChild(frame);
+
+			return frame;
+		}
+
+		function attachSVGToWorkerNode(svgtext, frame) {
+			var framedoc = (frame.contentWindow || frame.contentDocument).document;
+			framedoc.write(svgtext);
+			framedoc.close();
+			return framedoc.getElementsByTagName('svg')[0];
+		}
+
+		function convertPathToPDFLinesArgs(path) {
+			'use strict';
+			// we will use 'lines' method call. it needs:
+			// - starting coordinate pair
+			// - array of arrays of vector shifts (2-len for line, 6 len for bezier)
+			// - scale array [horizontal, vertical] ratios
+			// - style (stroke, fill, both)
+
+			var x = parseFloat(path[1]),
+			    y = parseFloat(path[2]),
+			    vectors = [],
+			    position = 3,
+			    len = path.length;
+
+			while (position < len) {
+				if (path[position] === 'c') {
+					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])]);
+					position += 7;
+				} else if (path[position] === 'l') {
+					vectors.push([parseFloat(path[position + 1]), parseFloat(path[position + 2])]);
+					position += 3;
+				} else {
+					position += 1;
+				}
+			}
+			return [x, y, vectors];
+		}
+
+		var workernode = createWorkerNode(document),
+		    svgnode = attachSVGToWorkerNode(svgtext, workernode),
+		    scale = [1, 1],
+		    svgw = parseFloat(svgnode.getAttribute('width')),
+		    svgh = parseFloat(svgnode.getAttribute('height'));
+
+		if (svgw && svgh) {
+			// setting both w and h makes image stretch to size.
+			// this may distort the image, but fits your demanded size
+			if (w && h) {
+				scale = [w / svgw, h / svgh];
+			}
+			// if only one is set, that value is set as max and SVG
+			// is scaled proportionately.
+			else if (w) {
+					scale = [w / svgw, w / svgw];
+				} else if (h) {
+					scale = [h / svgh, h / svgh];
+				}
+		}
+
+		var i,
+		    l,
+		    tmp,
+		    linesargs,
+		    items = svgnode.childNodes;
+		for (i = 0, l = items.length; i < l; i++) {
+			tmp = items[i];
+			if (tmp.tagName && tmp.tagName.toUpperCase() === 'PATH') {
+				linesargs = convertPathToPDFLinesArgs(tmp.getAttribute("d").split(' '));
+				// path start x coordinate
+				linesargs[0] = linesargs[0] * scale[0] + x; // where x is upper left X of image
+				// path start y coordinate
+				linesargs[1] = linesargs[1] * scale[1] + y; // where y is upper left Y of image
+				// the rest of lines are vectors. these will adjust with scale value auto.
+				this.lines.call(this, linesargs[2] // lines
+				, linesargs[0] // starting x
+				, linesargs[1] // starting y
+				, scale);
+			}
+		}
+
+		// clean up
+		// workernode.parentNode.removeChild(workernode)
+
+		return this;
+	};
+})(jsPDF.API);
+
+/** ==================================================================== 
+ * jsPDF total_pages plugin
+ * Copyright (c) 2013 Eduardo Menezes de Morais, eduardo.morais@usp.br
+ * 
+ * 
+ * ====================================================================
+ */
+
+(function (jsPDFAPI) {
+  'use strict';
+
+  jsPDFAPI.putTotalPages = function (pageExpression) {
+    'use strict';
+
+    var replaceExpression = new RegExp(pageExpression, 'g');
+    for (var n = 1; n <= this.internal.getNumberOfPages(); n++) {
+      for (var i = 0; i < this.internal.pages[n].length; i++) {
+        this.internal.pages[n][i] = this.internal.pages[n][i].replace(replaceExpression, this.internal.getNumberOfPages());
+      }
+    }
+    return this;
+  };
+})(jsPDF.API);
+
+/** ==================================================================== 
+ * jsPDF XMP metadata plugin
+ * Copyright (c) 2016 Jussi Utunen, u-jussi@suomi24.fi
+ * 
+ * 
+ * ====================================================================
+ */
+
+/*global jsPDF */
+
+/**
+* Adds XMP formatted metadata to PDF
+*
+* @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.
+* @param {String} namespaceuri Sets the namespace URI for the metadata. Last character should be slash or hash.
+* @function
+* @returns {jsPDF}
+* @methodOf jsPDF#
+* @name addMetadata
+*/
+
+(function (jsPDFAPI) {
+    'use strict';
+
+    var xmpmetadata = "";
+    var xmpnamespaceuri = "";
+    var metadata_object_number = "";
+
+    jsPDFAPI.addMetadata = function (metadata, namespaceuri) {
+        xmpnamespaceuri = namespaceuri || "http://jspdf.default.namespaceuri/"; //The namespace URI for an XMP name shall not be empty
+        xmpmetadata = metadata;
+        this.internal.events.subscribe('postPutResources', function () {
+            if (!xmpmetadata) {
+                metadata_object_number = "";
+            } else {
+                var xmpmeta_beginning = '<x:xmpmeta xmlns:x="adobe:ns:meta/">';
+                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>';
+                var rdf_ending = '</jspdf:metadata></rdf:Description></rdf:RDF>';
+                var xmpmeta_ending = '</x:xmpmeta>';
+                var utf8_xmpmeta_beginning = unescape(encodeURIComponent(xmpmeta_beginning));
+                var utf8_rdf_beginning = unescape(encodeURIComponent(rdf_beginning));
+                var utf8_metadata = unescape(encodeURIComponent(xmpmetadata));
+                var utf8_rdf_ending = unescape(encodeURIComponent(rdf_ending));
+                var utf8_xmpmeta_ending = unescape(encodeURIComponent(xmpmeta_ending));
+
+                var total_len = utf8_rdf_beginning.length + utf8_metadata.length + utf8_rdf_ending.length + utf8_xmpmeta_beginning.length + utf8_xmpmeta_ending.length;
+
+                metadata_object_number = this.internal.newObject();
+                this.internal.write('<< /Type /Metadata /Subtype /XML /Length ' + total_len + ' >>');
+                this.internal.write('stream');
+                this.internal.write(utf8_xmpmeta_beginning + utf8_rdf_beginning + utf8_metadata + utf8_rdf_ending + utf8_xmpmeta_ending);
+                this.internal.write('endstream');
+                this.internal.write('endobj');
+            }
+        });
+        this.internal.events.subscribe('putCatalog', function () {
+            if (metadata_object_number) {
+                this.internal.write('/Metadata ' + metadata_object_number + ' 0 R');
+            }
+        });
+        return this;
+    };
+})(jsPDF.API);
+
+/* Blob.js
+ * A Blob implementation.
+ * 2014-07-24
+ *
+ * By Eli Grey, http://eligrey.com
+ * By Devin Samarin, https://github.com/dsamarin
+ * License: X11/MIT
+ *   See https://github.com/eligrey/Blob.js/blob/master/LICENSE.md
+ */
+
+/*global self, unescape */
+/*jslint bitwise: true, regexp: true, confusion: true, es5: true, vars: true, white: true,
+  plusplus: true */
+
+/*! @source http://purl.eligrey.com/github/Blob.js/blob/master/Blob.js */
+
+(function (view) {
+	"use strict";
+
+	view.URL = view.URL || view.webkitURL;
+
+	if (view.Blob && view.URL) {
+		try {
+			new Blob;
+			return;
+		} catch (e) {}
+	}
+
+	// Internally we use a BlobBuilder implementation to base Blob off of
+	// in order to support older browsers that only have BlobBuilder
+	var BlobBuilder = view.BlobBuilder || view.WebKitBlobBuilder || view.MozBlobBuilder || (function(view) {
+		var
+			  get_class = function(object) {
+				return Object.prototype.toString.call(object).match(/^\[object\s(.*)\]$/)[1];
+			}
+			, FakeBlobBuilder = function BlobBuilder() {
+				this.data = [];
+			}
+			, FakeBlob = function Blob(data, type, encoding) {
+				this.data = data;
+				this.size = data.length;
+				this.type = type;
+				this.encoding = encoding;
+			}
+			, FBB_proto = FakeBlobBuilder.prototype
+			, FB_proto = FakeBlob.prototype
+			, FileReaderSync = view.FileReaderSync
+			, FileException = function(type) {
+				this.code = this[this.name = type];
+			}
+			, file_ex_codes = (
+				  "NOT_FOUND_ERR SECURITY_ERR ABORT_ERR NOT_READABLE_ERR ENCODING_ERR "
+				+ "NO_MODIFICATION_ALLOWED_ERR INVALID_STATE_ERR SYNTAX_ERR"
+			).split(" ")
+			, file_ex_code = file_ex_codes.length
+			, real_URL = view.URL || view.webkitURL || view
+			, real_create_object_URL = real_URL.createObjectURL
+			, real_revoke_object_URL = real_URL.revokeObjectURL
+			, URL = real_URL
+			, btoa = view.btoa
+			, atob = view.atob
+
+			, ArrayBuffer = view.ArrayBuffer
+			, Uint8Array = view.Uint8Array
+
+			, origin = /^[\w-]+:\/*\[?[\w\.:-]+\]?(?::[0-9]+)?/;
+		FakeBlob.fake = FB_proto.fake = true;
+		while (file_ex_code--) {
+			FileException.prototype[file_ex_codes[file_ex_code]] = file_ex_code + 1;
+		}
+		// Polyfill URL
+		if (!real_URL.createObjectURL) {
+			URL = view.URL = function(uri) {
+				var
+					  uri_info = document.createElementNS("http://www.w3.org/1999/xhtml", "a")
+					, uri_origin;
+				uri_info.href = uri;
+				if (!("origin" in uri_info)) {
+					if (uri_info.protocol.toLowerCase() === "data:") {
+						uri_info.origin = null;
+					} else {
+						uri_origin = uri.match(origin);
+						uri_info.origin = uri_origin && uri_origin[1];
+					}
+				}
+				return uri_info;
+			};
+		}
+		URL.createObjectURL = function(blob) {
+			var
+				  type = blob.type
+				, data_URI_header;
+			if (type === null) {
+				type = "application/octet-stream";
+			}
+			if (blob instanceof FakeBlob) {
+				data_URI_header = "data:" + type;
+				if (blob.encoding === "base64") {
+					return data_URI_header + ";base64," + blob.data;
+				} else if (blob.encoding === "URI") {
+					return data_URI_header + "," + decodeURIComponent(blob.data);
+				} if (btoa) {
+					return data_URI_header + ";base64," + btoa(blob.data);
+				} else {
+					return data_URI_header + "," + encodeURIComponent(blob.data);
+				}
+			} else if (real_create_object_URL) {
+				return real_create_object_URL.call(real_URL, blob);
+			}
+		};
+		URL.revokeObjectURL = function(object_URL) {
+			if (object_URL.substring(0, 5) !== "data:" && real_revoke_object_URL) {
+				real_revoke_object_URL.call(real_URL, object_URL);
+			}
+		};
+		FBB_proto.append = function(data/*, endings*/) {
+			var bb = this.data;
+			// decode data to a binary string
+			if (Uint8Array && (data instanceof ArrayBuffer || data instanceof Uint8Array)) {
+				var
+					  str = ""
+					, buf = new Uint8Array(data)
+					, i = 0
+					, buf_len = buf.length;
+				for (; i < buf_len; i++) {
+					str += String.fromCharCode(buf[i]);
+				}
+				bb.push(str);
+			} else if (get_class(data) === "Blob" || get_class(data) === "File") {
+				if (FileReaderSync) {
+					var fr = new FileReaderSync;
+					bb.push(fr.readAsBinaryString(data));
+				} else {
+					// async FileReader won't work as BlobBuilder is sync
+					throw new FileException("NOT_READABLE_ERR");
+				}
+			} else if (data instanceof FakeBlob) {
+				if (data.encoding === "base64" && atob) {
+					bb.push(atob(data.data));
+				} else if (data.encoding === "URI") {
+					bb.push(decodeURIComponent(data.data));
+				} else if (data.encoding === "raw") {
+					bb.push(data.data);
+				}
+			} else {
+				if (typeof data !== "string") {
+					data += ""; // convert unsupported types to strings
+				}
+				// decode UTF-16 to binary string
+				bb.push(unescape(encodeURIComponent(data)));
+			}
+		};
+		FBB_proto.getBlob = function(type) {
+			if (!arguments.length) {
+				type = null;
+			}
+			return new FakeBlob(this.data.join(""), type, "raw");
+		};
+		FBB_proto.toString = function() {
+			return "[object BlobBuilder]";
+		};
+		FB_proto.slice = function(start, end, type) {
+			var args = arguments.length;
+			if (args < 3) {
+				type = null;
+			}
+			return new FakeBlob(
+				  this.data.slice(start, args > 1 ? end : this.data.length)
+				, type
+				, this.encoding
+			);
+		};
+		FB_proto.toString = function() {
+			return "[object Blob]";
+		};
+		FB_proto.close = function() {
+			this.size = 0;
+			delete this.data;
+		};
+		return FakeBlobBuilder;
+	}(view));
+
+	view.Blob = function(blobParts, options) {
+		var type = options ? (options.type || "") : "";
+		var builder = new BlobBuilder();
+		if (blobParts) {
+			for (var i = 0, len = blobParts.length; i < len; i++) {
+				if (Uint8Array && blobParts[i] instanceof Uint8Array) {
+					builder.append(blobParts[i].buffer);
+				}
+				else {
+					builder.append(blobParts[i]);
+				}
+			}
+		}
+		var blob = builder.getBlob(type);
+		if (!blob.slice && blob.webkitSlice) {
+			blob.slice = blob.webkitSlice;
+		}
+		return blob;
+	};
+
+	var getPrototypeOf = Object.getPrototypeOf || function(object) {
+		return object.__proto__;
+	};
+	view.Blob.prototype = getPrototypeOf(new view.Blob());
+}(typeof self !== "undefined" && self || typeof window !== "undefined" && window || undefined.content || undefined));
+
+/* FileSaver.js
+ * A saveAs() FileSaver implementation.
+ * 1.1.20151003
+ *
+ * By Eli Grey, http://eligrey.com
+ * License: MIT
+ *   See https://github.com/eligrey/FileSaver.js/blob/master/LICENSE.md
+ */
+
+/*global self */
+/*jslint bitwise: true, indent: 4, laxbreak: true, laxcomma: true, smarttabs: true, plusplus: true */
+
+/*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js */
+
+var saveAs = saveAs || (function(view) {
+	"use strict";
+	// IE <10 is explicitly unsupported
+	if (typeof navigator !== "undefined" && /MSIE [1-9]\./.test(navigator.userAgent)) {
+		return;
+	}
+	var
+		  doc = view.document
+		  // only get URL when necessary in case Blob.js hasn't overridden it yet
+		, get_URL = function() {
+			return view.URL || view.webkitURL || view;
+		}
+		, save_link = doc.createElementNS("http://www.w3.org/1999/xhtml", "a")
+		, can_use_save_link = "download" in save_link
+		, click = function(node) {
+			var event = new MouseEvent("click");
+			node.dispatchEvent(event);
+		}
+		, is_safari = /Version\/[\d\.]+.*Safari/.test(navigator.userAgent)
+		, webkit_req_fs = view.webkitRequestFileSystem
+		, req_fs = view.requestFileSystem || webkit_req_fs || view.mozRequestFileSystem
+		, throw_outside = function(ex) {
+			(view.setImmediate || view.setTimeout)(function() {
+				throw ex;
+			}, 0);
+		}
+		, force_saveable_type = "application/octet-stream"
+		, fs_min_size = 0
+		// See https://code.google.com/p/chromium/issues/detail?id=375297#c7 and
+		// https://github.com/eligrey/FileSaver.js/commit/485930a#commitcomment-8768047
+		// for the reasoning behind the timeout and revocation flow
+		, arbitrary_revoke_timeout = 500 // in ms
+		, revoke = function(file) {
+			var revoker = function() {
+				if (typeof file === "string") { // file is an object URL
+					get_URL().revokeObjectURL(file);
+				} else { // file is a File
+					file.remove();
+				}
+			};
+			if (view.chrome) {
+				revoker();
+			} else {
+				setTimeout(revoker, arbitrary_revoke_timeout);
+			}
+		}
+		, dispatch = function(filesaver, event_types, event) {
+			event_types = [].concat(event_types);
+			var i = event_types.length;
+			while (i--) {
+				var listener = filesaver["on" + event_types[i]];
+				if (typeof listener === "function") {
+					try {
+						listener.call(filesaver, event || filesaver);
+					} catch (ex) {
+						throw_outside(ex);
+					}
+				}
+			}
+		}
+		, auto_bom = function(blob) {
+			// prepend BOM for UTF-8 XML and text/* types (including HTML)
+			if (/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(blob.type)) {
+				return new Blob(["\ufeff", blob], {type: blob.type});
+			}
+			return blob;
+		}
+		, FileSaver = function(blob, name, no_auto_bom) {
+			if (!no_auto_bom) {
+				blob = auto_bom(blob);
+			}
+			// First try a.download, then web filesystem, then object URLs
+			var
+				  filesaver = this
+				, type = blob.type
+				, blob_changed = false
+				, object_url
+				, target_view
+				, dispatch_all = function() {
+					dispatch(filesaver, "writestart progress write writeend".split(" "));
+				}
+				// on any filesys errors revert to saving with object URLs
+				, fs_error = function() {
+					if (target_view && is_safari && typeof FileReader !== "undefined") {
+						// Safari doesn't allow downloading of blob urls
+						var reader = new FileReader();
+						reader.onloadend = function() {
+							var base64Data = reader.result;
+							target_view.location.href = "data:attachment/file" + base64Data.slice(base64Data.search(/[,;]/));
+							filesaver.readyState = filesaver.DONE;
+							dispatch_all();
+						};
+						reader.readAsDataURL(blob);
+						filesaver.readyState = filesaver.INIT;
+						return;
+					}
+					// don't create more object URLs than needed
+					if (blob_changed || !object_url) {
+						object_url = get_URL().createObjectURL(blob);
+					}
+					if (target_view) {
+						target_view.location.href = object_url;
+					} else {
+						var new_tab = view.open(object_url, "_blank");
+						if (new_tab == undefined && is_safari) {
+							//Apple do not allow window.open, see http://bit.ly/1kZffRI
+							view.location.href = object_url;
+						}
+					}
+					filesaver.readyState = filesaver.DONE;
+					dispatch_all();
+					revoke(object_url);
+				}
+				, abortable = function(func) {
+					return function() {
+						if (filesaver.readyState !== filesaver.DONE) {
+							return func.apply(this, arguments);
+						}
+					};
+				}
+				, create_if_not_found = {create: true, exclusive: false}
+				, slice;
+			filesaver.readyState = filesaver.INIT;
+			if (!name) {
+				name = "download";
+			}
+			if (can_use_save_link) {
+				object_url = get_URL().createObjectURL(blob);
+				setTimeout(function() {
+					save_link.href = object_url;
+					save_link.download = name;
+					click(save_link);
+					dispatch_all();
+					revoke(object_url);
+					filesaver.readyState = filesaver.DONE;
+				});
+				return;
+			}
+			// Object and web filesystem URLs have a problem saving in Google Chrome when
+			// viewed in a tab, so I force save with application/octet-stream
+			// http://code.google.com/p/chromium/issues/detail?id=91158
+			// Update: Google errantly closed 91158, I submitted it again:
+			// https://code.google.com/p/chromium/issues/detail?id=389642
+			if (view.chrome && type && type !== force_saveable_type) {
+				slice = blob.slice || blob.webkitSlice;
+				blob = slice.call(blob, 0, blob.size, force_saveable_type);
+				blob_changed = true;
+			}
+			// Since I can't be sure that the guessed media type will trigger a download
+			// in WebKit, I append .download to the filename.
+			// https://bugs.webkit.org/show_bug.cgi?id=65440
+			if (webkit_req_fs && name !== "download") {
+				name += ".download";
+			}
+			if (type === force_saveable_type || webkit_req_fs) {
+				target_view = view;
+			}
+			if (!req_fs) {
+				fs_error();
+				return;
+			}
+			fs_min_size += blob.size;
+			req_fs(view.TEMPORARY, fs_min_size, abortable(function(fs) {
+				fs.root.getDirectory("saved", create_if_not_found, abortable(function(dir) {
+					var save = function() {
+						dir.getFile(name, create_if_not_found, abortable(function(file) {
+							file.createWriter(abortable(function(writer) {
+								writer.onwriteend = function(event) {
+									target_view.location.href = file.toURL();
+									filesaver.readyState = filesaver.DONE;
+									dispatch(filesaver, "writeend", event);
+									revoke(file);
+								};
+								writer.onerror = function() {
+									var error = writer.error;
+									if (error.code !== error.ABORT_ERR) {
+										fs_error();
+									}
+								};
+								"writestart progress write abort".split(" ").forEach(function(event) {
+									writer["on" + event] = filesaver["on" + event];
+								});
+								writer.write(blob);
+								filesaver.abort = function() {
+									writer.abort();
+									filesaver.readyState = filesaver.DONE;
+								};
+								filesaver.readyState = filesaver.WRITING;
+							}), fs_error);
+						}), fs_error);
+					};
+					dir.getFile(name, {create: false}, abortable(function(file) {
+						// delete file if it already exists
+						file.remove();
+						save();
+					}), abortable(function(ex) {
+						if (ex.code === ex.NOT_FOUND_ERR) {
+							save();
+						} else {
+							fs_error();
+						}
+					}));
+				}), fs_error);
+			}), fs_error);
+		}
+		, FS_proto = FileSaver.prototype
+		, saveAs = function(blob, name, no_auto_bom) {
+			return new FileSaver(blob, name, no_auto_bom);
+		};
+	// IE 10+ (native saveAs)
+	if (typeof navigator !== "undefined" && navigator.msSaveOrOpenBlob) {
+		return function(blob, name, no_auto_bom) {
+			if (!no_auto_bom) {
+				blob = auto_bom(blob);
+			}
+			return navigator.msSaveOrOpenBlob(blob, name || "download");
+		};
+	}
+
+	FS_proto.abort = function() {
+		var filesaver = this;
+		filesaver.readyState = filesaver.DONE;
+		dispatch(filesaver, "abort");
+	};
+	FS_proto.readyState = FS_proto.INIT = 0;
+	FS_proto.WRITING = 1;
+	FS_proto.DONE = 2;
+
+	FS_proto.error =
+	FS_proto.onwritestart =
+	FS_proto.onprogress =
+	FS_proto.onwrite =
+	FS_proto.onabort =
+	FS_proto.onerror =
+	FS_proto.onwriteend =
+		null;
+
+	return saveAs;
+}(
+	   typeof self !== "undefined" && self
+	|| typeof window !== "undefined" && window
+	|| undefined.content
+));
+// `self` is undefined in Firefox for Android content script context
+// while `this` is nsIContentFrameMessageManager
+// with an attribute `content` that corresponds to the window
+
+if (typeof module !== "undefined" && module.exports) {
+  module.exports.saveAs = saveAs;
+} else if ((typeof define !== "undefined" && define !== null) && (define.amd != null)) {
+  define([], function() {
+    return saveAs;
+  });
+}
+
+/*
+ * Copyright (c) 2012 chick307 <chick307@gmail.com>
+ *
+ * Licensed under the MIT License.
+ * http://opensource.org/licenses/mit-license
+ */
+
+void function(global, callback) {
+	if (typeof module === 'object') {
+		module.exports = callback();
+	} else if (typeof define === 'function') {
+		define(callback);
+	} else {
+		global.adler32cs = callback();
+	}
+}(jsPDF, function() {
+	var _hasArrayBuffer = typeof ArrayBuffer === 'function' &&
+		typeof Uint8Array === 'function';
+
+	var _Buffer = null, _isBuffer = (function() {
+		if (!_hasArrayBuffer)
+			return function _isBuffer() { return false };
+
+		try {
+			var buffer = {};
+			if (typeof buffer.Buffer === 'function')
+				_Buffer = buffer.Buffer;
+		} catch (error) {}
+
+		return function _isBuffer(value) {
+			return value instanceof ArrayBuffer ||
+				_Buffer !== null && value instanceof _Buffer;
+		};
+	}());
+
+	var _utf8ToBinary = (function() {
+		if (_Buffer !== null) {
+			return function _utf8ToBinary(utf8String) {
+				return new _Buffer(utf8String, 'utf8').toString('binary');
+			};
+		} else {
+			return function _utf8ToBinary(utf8String) {
+				return unescape(encodeURIComponent(utf8String));
+			};
+		}
+	}());
+
+	var MOD = 65521;
+
+	var _update = function _update(checksum, binaryString) {
+		var a = checksum & 0xFFFF, b = checksum >>> 16;
+		for (var i = 0, length = binaryString.length; i < length; i++) {
+			a = (a + (binaryString.charCodeAt(i) & 0xFF)) % MOD;
+			b = (b + a) % MOD;
+		}
+		return (b << 16 | a) >>> 0;
+	};
+
+	var _updateUint8Array = function _updateUint8Array(checksum, uint8Array) {
+		var a = checksum & 0xFFFF, b = checksum >>> 16;
+		for (var i = 0, length = uint8Array.length, x; i < length; i++) {
+			a = (a + uint8Array[i]) % MOD;
+			b = (b + a) % MOD;
+		}
+		return (b << 16 | a) >>> 0
+	};
+
+	var exports = {};
+
+	var Adler32 = exports.Adler32 = (function() {
+		var ctor = function Adler32(checksum) {
+			if (!(this instanceof ctor)) {
+				throw new TypeError(
+					'Constructor cannot called be as a function.');
+			}
+			if (!isFinite(checksum = checksum == null ? 1 : +checksum)) {
+				throw new Error(
+					'First arguments needs to be a finite number.');
+			}
+			this.checksum = checksum >>> 0;
+		};
+
+		var proto = ctor.prototype = {};
+		proto.constructor = ctor;
+
+		ctor.from = function(from) {
+			from.prototype = proto;
+			return from;
+		}(function from(binaryString) {
+			if (!(this instanceof ctor)) {
+				throw new TypeError(
+					'Constructor cannot called be as a function.');
+			}
+			if (binaryString == null)
+				throw new Error('First argument needs to be a string.');
+			this.checksum = _update(1, binaryString.toString());
+		});
+
+		ctor.fromUtf8 = function(fromUtf8) {
+			fromUtf8.prototype = proto;
+			return fromUtf8;
+		}(function fromUtf8(utf8String) {
+			if (!(this instanceof ctor)) {
+				throw new TypeError(
+					'Constructor cannot called be as a function.');
+			}
+			if (utf8String == null)
+				throw new Error('First argument needs to be a string.');
+			var binaryString = _utf8ToBinary(utf8String.toString());
+			this.checksum = _update(1, binaryString);
+		});
+
+		if (_hasArrayBuffer) {
+			ctor.fromBuffer = function(fromBuffer) {
+				fromBuffer.prototype = proto;
+				return fromBuffer;
+			}(function fromBuffer(buffer) {
+				if (!(this instanceof ctor)) {
+					throw new TypeError(
+						'Constructor cannot called be as a function.');
+				}
+				if (!_isBuffer(buffer))
+					throw new Error('First argument needs to be ArrayBuffer.');
+				var array = new Uint8Array(buffer);
+				return this.checksum = _updateUint8Array(1, array);
+			});
+		}
+
+		proto.update = function update(binaryString) {
+			if (binaryString == null)
+				throw new Error('First argument needs to be a string.');
+			binaryString = binaryString.toString();
+			return this.checksum = _update(this.checksum, binaryString);
+		};
+
+		proto.updateUtf8 = function updateUtf8(utf8String) {
+			if (utf8String == null)
+				throw new Error('First argument needs to be a string.');
+			var binaryString = _utf8ToBinary(utf8String.toString());
+			return this.checksum = _update(this.checksum, binaryString);
+		};
+
+		if (_hasArrayBuffer) {
+			proto.updateBuffer = function updateBuffer(buffer) {
+				if (!_isBuffer(buffer))
+					throw new Error('First argument needs to be ArrayBuffer.');
+				var array = new Uint8Array(buffer);
+				return this.checksum = _updateUint8Array(this.checksum, array);
+			};
+		}
+
+		proto.clone = function clone() {
+			return new Adler32(this.checksum);
+		};
+
+		return ctor;
+	}());
+
+	exports.from = function from(binaryString) {
+		if (binaryString == null)
+			throw new Error('First argument needs to be a string.');
+		return _update(1, binaryString.toString());
+	};
+
+	exports.fromUtf8 = function fromUtf8(utf8String) {
+		if (utf8String == null)
+			throw new Error('First argument needs to be a string.');
+		var binaryString = _utf8ToBinary(utf8String.toString());
+		return _update(1, binaryString);
+	};
+
+	if (_hasArrayBuffer) {
+		exports.fromBuffer = function fromBuffer(buffer) {
+			if (!_isBuffer(buffer))
+				throw new Error('First argument need to be ArrayBuffer.');
+			var array = new Uint8Array(buffer);
+			return _updateUint8Array(1, array);
+		};
+	}
+
+	return exports;
+});
+
+/**
+ * CssColors
+ * Copyright (c) 2014 Steven Spungin (TwelveTone LLC)  steven@twelvetone.tv
+ *
+ * Licensed under the MIT License.
+ * http://opensource.org/licenses/mit-license
+ */
+
+/**
+ * Usage CssColors('red');
+ * Returns RGB hex color with '#' prefix
+ */
+
+var CssColors = {};
+CssColors._colorsTable = {
+	"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",
+	"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" : "#90ee90",
+	"lightpink" : "#ffb6c1",
+	"lightsalmon" : "#ffa07a",
+	"lightseagreen" : "#20b2aa",
+	"lightskyblue" : "#87cefa",
+	"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",
+	"wheat" : "#f5deb3",
+	"white" : "#ffffff",
+	"whitesmoke" : "#f5f5f5",
+	"yellow" : "#ffff00",
+	"yellowgreen" : "#9acd32"
+};
+
+CssColors.colorNameToHex = function(color) {
+	color = color.toLowerCase();
+	if (typeof this._colorsTable[color] != 'undefined')
+		return this._colorsTable[color];
+
+	return false;
+};
+
+/*
+ Deflate.js - https://github.com/gildas-lormeau/zip.js
+ Copyright (c) 2013 Gildas Lormeau. All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+
+ 1. Redistributions of source code must retain the above copyright notice,
+ this list of conditions and the following disclaimer.
+
+ 2. Redistributions in binary form must reproduce the above copyright 
+ notice, this list of conditions and the following disclaimer in 
+ the documentation and/or other materials provided with the distribution.
+
+ 3. The names of the authors may not be used to endorse or promote products
+ derived from this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
+ INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
+ FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
+ INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
+ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
+ OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
+ EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/*
+ * This program is based on JZlib 1.0.2 ymnk, JCraft,Inc.
+ * JZlib is based on zlib-1.1.3, so all credit should go authors
+ * Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
+ * and contributors of zlib.
+ */
+
+var Deflater = (function(obj) {
+
+	// Global
+
+	var MAX_BITS = 15;
+	var D_CODES = 30;
+	var BL_CODES = 19;
+
+	var LENGTH_CODES = 29;
+	var LITERALS = 256;
+	var L_CODES = (LITERALS + 1 + LENGTH_CODES);
+	var HEAP_SIZE = (2 * L_CODES + 1);
+
+	var END_BLOCK = 256;
+
+	// Bit length codes must not exceed MAX_BL_BITS bits
+	var MAX_BL_BITS = 7;
+
+	// repeat previous bit length 3-6 times (2 bits of repeat count)
+	var REP_3_6 = 16;
+
+	// repeat a zero length 3-10 times (3 bits of repeat count)
+	var REPZ_3_10 = 17;
+
+	// repeat a zero length 11-138 times (7 bits of repeat count)
+	var REPZ_11_138 = 18;
+
+	// The lengths of the bit length codes are sent in order of decreasing
+	// probability, to avoid transmitting the lengths for unused bit
+	// length codes.
+
+	var Buf_size = 8 * 2;
+
+	// JZlib version : "1.0.2"
+	var Z_DEFAULT_COMPRESSION = -1;
+
+	// compression strategy
+	var Z_FILTERED = 1;
+	var Z_HUFFMAN_ONLY = 2;
+	var Z_DEFAULT_STRATEGY = 0;
+
+	var Z_NO_FLUSH = 0;
+	var Z_PARTIAL_FLUSH = 1;
+	var Z_FULL_FLUSH = 3;
+	var Z_FINISH = 4;
+
+	var Z_OK = 0;
+	var Z_STREAM_END = 1;
+	var Z_NEED_DICT = 2;
+	var Z_STREAM_ERROR = -2;
+	var Z_DATA_ERROR = -3;
+	var Z_BUF_ERROR = -5;
+
+	// Tree
+
+	// see definition of array dist_code below
+	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,
+			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 Tree() {
+		var that = this;
+
+		// dyn_tree; // the dynamic tree
+		// max_code; // largest code with non zero frequency
+		// stat_desc; // the corresponding static tree
+
+		// Compute the optimal bit lengths for a tree and update the total bit
+		// length
+		// for the current block.
+		// IN assertion: the fields freq and dad are set, heap[heap_max] and
+		// above are the tree nodes sorted by increasing frequency.
+		// OUT assertions: the field len is set to the optimal bit length, the
+		// array bl_count contains the frequencies for each bit length.
+		// The length opt_len is updated; static_len is also updated if stree is
+		// not null.
+		function gen_bitlen(s) {
+			var tree = that.dyn_tree;
+			var stree = that.stat_desc.static_tree;
+			var extra = that.stat_desc.extra_bits;
+			var base = that.stat_desc.extra_base;
+			var max_length = that.stat_desc.max_length;
+			var h; // heap index
+			var n, m; // iterate over the tree elements
+			var bits; // bit length
+			var xbits; // extra bits
+			var f; // frequency
+			var overflow = 0; // number of elements with bit length too large
+
+			for (bits = 0; bits <= MAX_BITS; bits++)
+				s.bl_count[bits] = 0;
+
+			// In a first pass, compute the optimal bit lengths (which may
+			// overflow in the case of the bit length tree).
+			tree[s.heap[s.heap_max] * 2 + 1] = 0; // root of the heap
+
+			for (h = s.heap_max + 1; h < HEAP_SIZE; h++) {
+				n = s.heap[h];
+				bits = tree[tree[n * 2 + 1] * 2 + 1] + 1;
+				if (bits > max_length) {
+					bits = max_length;
+					overflow++;
+				}
+				tree[n * 2 + 1] = bits;
+				// We overwrite tree[n*2+1] which is no longer needed
+
+				if (n > that.max_code)
+					continue; // not a leaf node
+
+				s.bl_count[bits]++;
+				xbits = 0;
+				if (n >= base)
+					xbits = extra[n - base];
+				f = tree[n * 2];
+				s.opt_len += f * (bits + xbits);
+				if (stree)
+					s.static_len += f * (stree[n * 2 + 1] + xbits);
+			}
+			if (overflow === 0)
+				return;
+
+			// This happens for example on obj2 and pic of the Calgary corpus
+			// Find the first bit length which could increase:
+			do {
+				bits = max_length - 1;
+				while (s.bl_count[bits] === 0)
+					bits--;
+				s.bl_count[bits]--; // move one leaf down the tree
+				s.bl_count[bits + 1] += 2; // move one overflow item as its brother
+				s.bl_count[max_length]--;
+				// The brother of the overflow item also moves one step up,
+				// but this does not affect bl_count[max_length]
+				overflow -= 2;
+			} while (overflow > 0);
+
+			for (bits = max_length; bits !== 0; bits--) {
+				n = s.bl_count[bits];
+				while (n !== 0) {
+					m = s.heap[--h];
+					if (m > that.max_code)
+						continue;
+					if (tree[m * 2 + 1] != bits) {
+						s.opt_len += (bits - tree[m * 2 + 1]) * tree[m * 2];
+						tree[m * 2 + 1] = bits;
+					}
+					n--;
+				}
+			}
+		}
+
+		// Reverse the first len bits of a code, using straightforward code (a
+		// faster
+		// method would use a table)
+		// IN assertion: 1 <= len <= 15
+		function bi_reverse(code, // the value to invert
+		len // its bit length
+		) {
+			var res = 0;
+			do {
+				res |= code & 1;
+				code >>>= 1;
+				res <<= 1;
+			} while (--len > 0);
+			return res >>> 1;
+		}
+
+		// Generate the codes for a given tree and bit counts (which need not be
+		// optimal).
+		// IN assertion: the array bl_count contains the bit length statistics for
+		// the given tree and the field len is set for all tree elements.
+		// OUT assertion: the field code is set for all tree elements of non
+		// zero code length.
+		function gen_codes(tree, // the tree to decorate
+		max_code, // largest code with non zero frequency
+		bl_count // number of codes at each bit length
+		) {
+			var next_code = []; // next code value for each
+			// bit length
+			var code = 0; // running code value
+			var bits; // bit index
+			var n; // code index
+			var len;
+
+			// The distribution counts are first used to generate the code values
+			// without bit reversal.
+			for (bits = 1; bits <= MAX_BITS; bits++) {
+				next_code[bits] = code = ((code + bl_count[bits - 1]) << 1);
+			}
+
+			// Check that the bit counts in bl_count are consistent. The last code
+			// must be all ones.
+			// Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
+			// "inconsistent bit counts");
+			// Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
+
+			for (n = 0; n <= max_code; n++) {
+				len = tree[n * 2 + 1];
+				if (len === 0)
+					continue;
+				// Now reverse the bits
+				tree[n * 2] = bi_reverse(next_code[len]++, len);
+			}
+		}
+
+		// Construct one Huffman tree and assigns the code bit strings and lengths.
+		// Update the total bit length for the current block.
+		// IN assertion: the field freq is set for all tree elements.
+		// OUT assertions: the fields len and code are set to the optimal bit length
+		// and corresponding code. The length opt_len is updated; static_len is
+		// also updated if stree is not null. The field max_code is set.
+		that.build_tree = function(s) {
+			var tree = that.dyn_tree;
+			var stree = that.stat_desc.static_tree;
+			var elems = that.stat_desc.elems;
+			var n, m; // iterate over heap elements
+			var max_code = -1; // largest code with non zero frequency
+			var node; // new node being created
+
+			// Construct the initial heap, with least frequent element in
+			// heap[1]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
+			// heap[0] is not used.
+			s.heap_len = 0;
+			s.heap_max = HEAP_SIZE;
+
+			for (n = 0; n < elems; n++) {
+				if (tree[n * 2] !== 0) {
+					s.heap[++s.heap_len] = max_code = n;
+					s.depth[n] = 0;
+				} else {
+					tree[n * 2 + 1] = 0;
+				}
+			}
+
+			// The pkzip format requires that at least one distance code exists,
+			// and that at least one bit should be sent even if there is only one
+			// possible code. So to avoid special checks later on we force at least
+			// two codes of non zero frequency.
+			while (s.heap_len < 2) {
+				node = s.heap[++s.heap_len] = max_code < 2 ? ++max_code : 0;
+				tree[node * 2] = 1;
+				s.depth[node] = 0;
+				s.opt_len--;
+				if (stree)
+					s.static_len -= stree[node * 2 + 1];
+				// node is 0 or 1 so it does not have extra bits
+			}
+			that.max_code = max_code;
+
+			// The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
+			// establish sub-heaps of increasing lengths:
+
+			for (n = Math.floor(s.heap_len / 2); n >= 1; n--)
+				s.pqdownheap(tree, n);
+
+			// Construct the Huffman tree by repeatedly combining the least two
+			// frequent nodes.
+
+			node = elems; // next internal node of the tree
+			do {
+				// n = node of least frequency
+				n = s.heap[1];
+				s.heap[1] = s.heap[s.heap_len--];
+				s.pqdownheap(tree, 1);
+				m = s.heap[1]; // m = node of next least frequency
+
+				s.heap[--s.heap_max] = n; // keep the nodes sorted by frequency
+				s.heap[--s.heap_max] = m;
+
+				// Create a new node father of n and m
+				tree[node * 2] = (tree[n * 2] + tree[m * 2]);
+				s.depth[node] = Math.max(s.depth[n], s.depth[m]) + 1;
+				tree[n * 2 + 1] = tree[m * 2 + 1] = node;
+
+				// and insert the new node in the heap
+				s.heap[1] = node++;
+				s.pqdownheap(tree, 1);
+			} while (s.heap_len >= 2);
+
+			s.heap[--s.heap_max] = s.heap[1];
+
+			// At this point, the fields freq and dad are set. We can now
+			// generate the bit lengths.
+
+			gen_bitlen(s);
+
+			// The field len is now set, we can generate the bit codes
+			gen_codes(tree, that.max_code, s.bl_count);
+		};
+
+	}
+
+	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,
+			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 ];
+
+	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 ];
+
+	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,
+			24576 ];
+
+	// Mapping from a distance to a distance code. dist is the distance - 1 and
+	// must not have side effects. _dist_code[256] and _dist_code[257] are never
+	// used.
+	Tree.d_code = function(dist) {
+		return ((dist) < 256 ? _dist_code[dist] : _dist_code[256 + ((dist) >>> 7)]);
+	};
+
+	// extra bits for each length code
+	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 ];
+
+	// extra bits for each distance code
+	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 ];
+
+	// extra bits for each bit length code
+	Tree.extra_blbits = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 7 ];
+
+	Tree.bl_order = [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];
+
+	// StaticTree
+
+	function StaticTree(static_tree, extra_bits, extra_base, elems, max_length) {
+		var that = this;
+		that.static_tree = static_tree;
+		that.extra_bits = extra_bits;
+		that.extra_base = extra_base;
+		that.elems = elems;
+		that.max_length = max_length;
+	}
+
+	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,
+			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 ];
+
+	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,
+			25, 5, 5, 5, 21, 5, 13, 5, 29, 5, 3, 5, 19, 5, 11, 5, 27, 5, 7, 5, 23, 5 ];
+
+	StaticTree.static_l_desc = new StaticTree(StaticTree.static_ltree, Tree.extra_lbits, LITERALS + 1, L_CODES, MAX_BITS);
+
+	StaticTree.static_d_desc = new StaticTree(StaticTree.static_dtree, Tree.extra_dbits, 0, D_CODES, MAX_BITS);
+
+	StaticTree.static_bl_desc = new StaticTree(null, Tree.extra_blbits, 0, BL_CODES, MAX_BL_BITS);
+
+	// Deflate
+
+	var MAX_MEM_LEVEL = 9;
+	var DEF_MEM_LEVEL = 8;
+
+	function Config(good_length, max_lazy, nice_length, max_chain, func) {
+		var that = this;
+		that.good_length = good_length;
+		that.max_lazy = max_lazy;
+		that.nice_length = nice_length;
+		that.max_chain = max_chain;
+		that.func = func;
+	}
+
+	var STORED = 0;
+	var FAST = 1;
+	var SLOW = 2;
+	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),
+			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),
+			new Config(32, 128, 258, 1024, SLOW), new Config(32, 258, 258, 4096, SLOW) ];
+
+	var z_errmsg = [ "need dictionary", // Z_NEED_DICT
+	// 2
+	"stream end", // Z_STREAM_END 1
+	"", // Z_OK 0
+	"", // Z_ERRNO (-1)
+	"stream error", // Z_STREAM_ERROR (-2)
+	"data error", // Z_DATA_ERROR (-3)
+	"", // Z_MEM_ERROR (-4)
+	"buffer error", // Z_BUF_ERROR (-5)
+	"",// Z_VERSION_ERROR (-6)
+	"" ];
+
+	// block not completed, need more input or more output
+	var NeedMore = 0;
+
+	// block flush performed
+	var BlockDone = 1;
+
+	// finish started, need only more output at next deflate
+	var FinishStarted = 2;
+
+	// finish done, accept no more input or output
+	var FinishDone = 3;
+
+	// preset dictionary flag in zlib header
+	var PRESET_DICT = 0x20;
+
+	var INIT_STATE = 42;
+	var BUSY_STATE = 113;
+	var FINISH_STATE = 666;
+
+	// The deflate compression method
+	var Z_DEFLATED = 8;
+
+	var STORED_BLOCK = 0;
+	var STATIC_TREES = 1;
+	var DYN_TREES = 2;
+
+	var MIN_MATCH = 3;
+	var MAX_MATCH = 258;
+	var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
+
+	function smaller(tree, n, m, depth) {
+		var tn2 = tree[n * 2];
+		var tm2 = tree[m * 2];
+		return (tn2 < tm2 || (tn2 == tm2 && depth[n] <= depth[m]));
+	}
+
+	function Deflate() {
+
+		var that = this;
+		var strm; // pointer back to this zlib stream
+		var status; // as the name implies
+		// pending_buf; // output still pending
+		var pending_buf_size; // size of pending_buf
+		// pending_out; // next pending byte to output to the stream
+		// pending; // nb of bytes in the pending buffer
+		var method; // STORED (for zip only) or DEFLATED
+		var last_flush; // value of flush param for previous deflate call
+
+		var w_size; // LZ77 window size (32K by default)
+		var w_bits; // log2(w_size) (8..16)
+		var w_mask; // w_size - 1
+
+		var window;
+		// Sliding window. Input bytes are read into the second half of the window,
+		// and move to the first half later to keep a dictionary of at least wSize
+		// bytes. With this organization, matches are limited to a distance of
+		// wSize-MAX_MATCH bytes, but this ensures that IO is always
+		// performed with a length multiple of the block size. Also, it limits
+		// the window size to 64K, which is quite useful on MSDOS.
+		// To do: use the user input buffer as sliding window.
+
+		var window_size;
+		// Actual size of window: 2*wSize, except when the user input buffer
+		// is directly used as sliding window.
+
+		var prev;
+		// Link to older string with same hash index. To limit the size of this
+		// array to 64K, this link is maintained only for the last 32K strings.
+		// An index in this array is thus a window index modulo 32K.
+
+		var head; // Heads of the hash chains or NIL.
+
+		var ins_h; // hash index of string to be inserted
+		var hash_size; // number of elements in hash table
+		var hash_bits; // log2(hash_size)
+		var hash_mask; // hash_size-1
+
+		// Number of bits by which ins_h must be shifted at each input
+		// step. It must be such that after MIN_MATCH steps, the oldest
+		// byte no longer takes part in the hash key, that is:
+		// hash_shift * MIN_MATCH >= hash_bits
+		var hash_shift;
+
+		// Window position at the beginning of the current output block. Gets
+		// negative when the window is moved backwards.
+
+		var block_start;
+
+		var match_length; // length of best match
+		var prev_match; // previous match
+		var match_available; // set if previous match exists
+		var strstart; // start of string to insert
+		var match_start; // start of matching string
+		var lookahead; // number of valid bytes ahead in window
+
+		// Length of the best match at previous step. Matches not greater than this
+		// are discarded. This is used in the lazy match evaluation.
+		var prev_length;
+
+		// To speed up deflation, hash chains are never searched beyond this
+		// length. A higher limit improves compression ratio but degrades the speed.
+		var max_chain_length;
+
+		// Attempt to find a better match only when the current match is strictly
+		// smaller than this value. This mechanism is used only for compression
+		// levels >= 4.
+		var max_lazy_match;
+
+		// Insert new strings in the hash table only if the match length is not
+		// greater than this length. This saves time but degrades compression.
+		// max_insert_length is used only for compression levels <= 3.
+
+		var level; // compression level (1..9)
+		var strategy; // favor or force Huffman coding
+
+		// Use a faster search when the previous match is longer than this
+		var good_match;
+
+		// Stop searching when current match exceeds this
+		var nice_match;
+
+		var dyn_ltree; // literal and length tree
+		var dyn_dtree; // distance tree
+		var bl_tree; // Huffman tree for bit lengths
+
+		var l_desc = new Tree(); // desc for literal tree
+		var d_desc = new Tree(); // desc for distance tree
+		var bl_desc = new Tree(); // desc for bit length tree
+
+		// that.heap_len; // number of elements in the heap
+		// that.heap_max; // element of largest frequency
+		// The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
+		// The same heap array is used to build all trees.
+
+		// Depth of each subtree used as tie breaker for trees of equal frequency
+		that.depth = [];
+
+		var l_buf; // index for literals or lengths */
+
+		// Size of match buffer for literals/lengths. There are 4 reasons for
+		// limiting lit_bufsize to 64K:
+		// - frequencies can be kept in 16 bit counters
+		// - if compression is not successful for the first block, all input
+		// data is still in the window so we can still emit a stored block even
+		// when input comes from standard input. (This can also be done for
+		// all blocks if lit_bufsize is not greater than 32K.)
+		// - if compression is not successful for a file smaller than 64K, we can
+		// even emit a stored file instead of a stored block (saving 5 bytes).
+		// This is applicable only for zip (not gzip or zlib).
+		// - creating new Huffman trees less frequently may not provide fast
+		// adaptation to changes in the input data statistics. (Take for
+		// example a binary file with poorly compressible code followed by
+		// a highly compressible string table.) Smaller buffer sizes give
+		// fast adaptation but have of course the overhead of transmitting
+		// trees more frequently.
+		// - I can't count above 4
+		var lit_bufsize;
+
+		var last_lit; // running index in l_buf
+
+		// Buffer for distances. To simplify the code, d_buf and l_buf have
+		// the same number of elements. To use different lengths, an extra flag
+		// array would be necessary.
+
+		var d_buf; // index of pendig_buf
+
+		// that.opt_len; // bit length of current block with optimal trees
+		// that.static_len; // bit length of current block with static trees
+		var matches; // number of string matches in current block
+		var last_eob_len; // bit length of EOB code for last block
+
+		// Output buffer. bits are inserted starting at the bottom (least
+		// significant bits).
+		var bi_buf;
+
+		// Number of valid bits in bi_buf. All bits above the last valid bit
+		// are always zero.
+		var bi_valid;
+
+		// number of codes at each bit length for an optimal tree
+		that.bl_count = [];
+
+		// heap used to build the Huffman trees
+		that.heap = [];
+
+		dyn_ltree = [];
+		dyn_dtree = [];
+		bl_tree = [];
+
+		function lm_init() {
+			var i;
+			window_size = 2 * w_size;
+
+			head[hash_size - 1] = 0;
+			for (i = 0; i < hash_size - 1; i++) {
+				head[i] = 0;
+			}
+
+			// Set the default configuration parameters:
+			max_lazy_match = config_table[level].max_lazy;
+			good_match = config_table[level].good_length;
+			nice_match = config_table[level].nice_length;
+			max_chain_length = config_table[level].max_chain;
+
+			strstart = 0;
+			block_start = 0;
+			lookahead = 0;
+			match_length = prev_length = MIN_MATCH - 1;
+			match_available = 0;
+			ins_h = 0;
+		}
+
+		function init_block() {
+			var i;
+			// Initialize the trees.
+			for (i = 0; i < L_CODES; i++)
+				dyn_ltree[i * 2] = 0;
+			for (i = 0; i < D_CODES; i++)
+				dyn_dtree[i * 2] = 0;
+			for (i = 0; i < BL_CODES; i++)
+				bl_tree[i * 2] = 0;
+
+			dyn_ltree[END_BLOCK * 2] = 1;
+			that.opt_len = that.static_len = 0;
+			last_lit = matches = 0;
+		}
+
+		// Initialize the tree data structures for a new zlib stream.
+		function tr_init() {
+
+			l_desc.dyn_tree = dyn_ltree;
+			l_desc.stat_desc = StaticTree.static_l_desc;
+
+			d_desc.dyn_tree = dyn_dtree;
+			d_desc.stat_desc = StaticTree.static_d_desc;
+
+			bl_desc.dyn_tree = bl_tree;
+			bl_desc.stat_desc = StaticTree.static_bl_desc;
+
+			bi_buf = 0;
+			bi_valid = 0;
+			last_eob_len = 8; // enough lookahead for inflate
+
+			// Initialize the first block of the first file:
+			init_block();
+		}
+
+		// Restore the heap property by moving down the tree starting at node k,
+		// exchanging a node with the smallest of its two sons if necessary,
+		// stopping
+		// when the heap property is re-established (each father smaller than its
+		// two sons).
+		that.pqdownheap = function(tree, // the tree to restore
+		k // node to move down
+		) {
+			var heap = that.heap;
+			var v = heap[k];
+			var j = k << 1; // left son of k
+			while (j <= that.heap_len) {
+				// Set j to the smallest of the two sons:
+				if (j < that.heap_len && smaller(tree, heap[j + 1], heap[j], that.depth)) {
+					j++;
+				}
+				// Exit if v is smaller than both sons
+				if (smaller(tree, v, heap[j], that.depth))
+					break;
+
+				// Exchange v with the smallest son
+				heap[k] = heap[j];
+				k = j;
+				// And continue down the tree, setting j to the left son of k
+				j <<= 1;
+			}
+			heap[k] = v;
+		};
+
+		// Scan a literal or distance tree to determine the frequencies of the codes
+		// in the bit length tree.
+		function scan_tree(tree,// the tree to be scanned
+		max_code // and its largest code of non zero frequency
+		) {
+			var n; // iterates over all tree elements
+			var prevlen = -1; // last emitted length
+			var curlen; // length of current code
+			var nextlen = tree[0 * 2 + 1]; // length of next code
+			var count = 0; // repeat count of the current code
+			var max_count = 7; // max repeat count
+			var min_count = 4; // min repeat count
+
+			if (nextlen === 0) {
+				max_count = 138;
+				min_count = 3;
+			}
+			tree[(max_code + 1) * 2 + 1] = 0xffff; // guard
+
+			for (n = 0; n <= max_code; n++) {
+				curlen = nextlen;
+				nextlen = tree[(n + 1) * 2 + 1];
+				if (++count < max_count && curlen == nextlen) {
+					continue;
+				} else if (count < min_count) {
+					bl_tree[curlen * 2] += count;
+				} else if (curlen !== 0) {
+					if (curlen != prevlen)
+						bl_tree[curlen * 2]++;
+					bl_tree[REP_3_6 * 2]++;
+				} else if (count <= 10) {
+					bl_tree[REPZ_3_10 * 2]++;
+				} else {
+					bl_tree[REPZ_11_138 * 2]++;
+				}
+				count = 0;
+				prevlen = curlen;
+				if (nextlen === 0) {
+					max_count = 138;
+					min_count = 3;
+				} else if (curlen == nextlen) {
+					max_count = 6;
+					min_count = 3;
+				} else {
+					max_count = 7;
+					min_count = 4;
+				}
+			}
+		}
+
+		// Construct the Huffman tree for the bit lengths and return the index in
+		// bl_order of the last bit length code to send.
+		function build_bl_tree() {
+			var max_blindex; // index of last bit length code of non zero freq
+
+			// Determine the bit length frequencies for literal and distance trees
+			scan_tree(dyn_ltree, l_desc.max_code);
+			scan_tree(dyn_dtree, d_desc.max_code);
+
+			// Build the bit length tree:
+			bl_desc.build_tree(that);
+			// opt_len now includes the length of the tree representations, except
+			// the lengths of the bit lengths codes and the 5+5+4 bits for the
+			// counts.
+
+			// Determine the number of bit length codes to send. The pkzip format
+			// requires that at least 4 bit length codes be sent. (appnote.txt says
+			// 3 but the actual value used is 4.)
+			for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {
+				if (bl_tree[Tree.bl_order[max_blindex] * 2 + 1] !== 0)
+					break;
+			}
+			// Update opt_len to include the bit length tree and counts
+			that.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
+
+			return max_blindex;
+		}
+
+		// Output a byte on the stream.
+		// IN assertion: there is enough room in pending_buf.
+		function put_byte(p) {
+			that.pending_buf[that.pending++] = p;
+		}
+
+		function put_short(w) {
+			put_byte(w & 0xff);
+			put_byte((w >>> 8) & 0xff);
+		}
+
+		function putShortMSB(b) {
+			put_byte((b >> 8) & 0xff);
+			put_byte((b & 0xff) & 0xff);
+		}
+
+		function send_bits(value, length) {
+			var val, len = length;
+			if (bi_valid > Buf_size - len) {
+				val = value;
+				// bi_buf |= (val << bi_valid);
+				bi_buf |= ((val << bi_valid) & 0xffff);
+				put_short(bi_buf);
+				bi_buf = val >>> (Buf_size - bi_valid);
+				bi_valid += len - Buf_size;
+			} else {
+				// bi_buf |= (value) << bi_valid;
+				bi_buf |= (((value) << bi_valid) & 0xffff);
+				bi_valid += len;
+			}
+		}
+
+		function send_code(c, tree) {
+			var c2 = c * 2;
+			send_bits(tree[c2] & 0xffff, tree[c2 + 1] & 0xffff);
+		}
+
+		// Send a literal or distance tree in compressed form, using the codes in
+		// bl_tree.
+		function send_tree(tree,// the tree to be sent
+		max_code // and its largest code of non zero frequency
+		) {
+			var n; // iterates over all tree elements
+			var prevlen = -1; // last emitted length
+			var curlen; // length of current code
+			var nextlen = tree[0 * 2 + 1]; // length of next code
+			var count = 0; // repeat count of the current code
+			var max_count = 7; // max repeat count
+			var min_count = 4; // min repeat count
+
+			if (nextlen === 0) {
+				max_count = 138;
+				min_count = 3;
+			}
+
+			for (n = 0; n <= max_code; n++) {
+				curlen = nextlen;
+				nextlen = tree[(n + 1) * 2 + 1];
+				if (++count < max_count && curlen == nextlen) {
+					continue;
+				} else if (count < min_count) {
+					do {
+						send_code(curlen, bl_tree);
+					} while (--count !== 0);
+				} else if (curlen !== 0) {
+					if (curlen != prevlen) {
+						send_code(curlen, bl_tree);
+						count--;
+					}
+					send_code(REP_3_6, bl_tree);
+					send_bits(count - 3, 2);
+				} else if (count <= 10) {
+					send_code(REPZ_3_10, bl_tree);
+					send_bits(count - 3, 3);
+				} else {
+					send_code(REPZ_11_138, bl_tree);
+					send_bits(count - 11, 7);
+				}
+				count = 0;
+				prevlen = curlen;
+				if (nextlen === 0) {
+					max_count = 138;
+					min_count = 3;
+				} else if (curlen == nextlen) {
+					max_count = 6;
+					min_count = 3;
+				} else {
+					max_count = 7;
+					min_count = 4;
+				}
+			}
+		}
+
+		// Send the header for a block using dynamic Huffman trees: the counts, the
+		// lengths of the bit length codes, the literal tree and the distance tree.
+		// IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
+		function send_all_trees(lcodes, dcodes, blcodes) {
+			var rank; // index in bl_order
+
+			send_bits(lcodes - 257, 5); // not +255 as stated in appnote.txt
+			send_bits(dcodes - 1, 5);
+			send_bits(blcodes - 4, 4); // not -3 as stated in appnote.txt
+			for (rank = 0; rank < blcodes; rank++) {
+				send_bits(bl_tree[Tree.bl_order[rank] * 2 + 1], 3);
+			}
+			send_tree(dyn_ltree, lcodes - 1); // literal tree
+			send_tree(dyn_dtree, dcodes - 1); // distance tree
+		}
+
+		// Flush the bit buffer, keeping at most 7 bits in it.
+		function bi_flush() {
+			if (bi_valid == 16) {
+				put_short(bi_buf);
+				bi_buf = 0;
+				bi_valid = 0;
+			} else if (bi_valid >= 8) {
+				put_byte(bi_buf & 0xff);
+				bi_buf >>>= 8;
+				bi_valid -= 8;
+			}
+		}
+
+		// Send one empty static block to give enough lookahead for inflate.
+		// This takes 10 bits, of which 7 may remain in the bit buffer.
+		// The current inflate code requires 9 bits of lookahead. If the
+		// last two codes for the previous block (real code plus EOB) were coded
+		// on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
+		// the last real code. In this case we send two empty static blocks instead
+		// of one. (There are no problems if the previous block is stored or fixed.)
+		// To simplify the code, we assume the worst case of last real code encoded
+		// on one bit only.
+		function _tr_align() {
+			send_bits(STATIC_TREES << 1, 3);
+			send_code(END_BLOCK, StaticTree.static_ltree);
+
+			bi_flush();
+
+			// Of the 10 bits for the empty block, we have already sent
+			// (10 - bi_valid) bits. The lookahead for the last real code (before
+			// the EOB of the previous block) was thus at least one plus the length
+			// of the EOB plus what we have just sent of the empty static block.
+			if (1 + last_eob_len + 10 - bi_valid < 9) {
+				send_bits(STATIC_TREES << 1, 3);
+				send_code(END_BLOCK, StaticTree.static_ltree);
+				bi_flush();
+			}
+			last_eob_len = 7;
+		}
+
+		// Save the match info and tally the frequency counts. Return true if
+		// the current block must be flushed.
+		function _tr_tally(dist, // distance of matched string
+		lc // match length-MIN_MATCH or unmatched char (if dist==0)
+		) {
+			var out_length, in_length, dcode;
+			that.pending_buf[d_buf + last_lit * 2] = (dist >>> 8) & 0xff;
+			that.pending_buf[d_buf + last_lit * 2 + 1] = dist & 0xff;
+
+			that.pending_buf[l_buf + last_lit] = lc & 0xff;
+			last_lit++;
+
+			if (dist === 0) {
+				// lc is the unmatched char
+				dyn_ltree[lc * 2]++;
+			} else {
+				matches++;
+				// Here, lc is the match length - MIN_MATCH
+				dist--; // dist = match distance - 1
+				dyn_ltree[(Tree._length_code[lc] + LITERALS + 1) * 2]++;
+				dyn_dtree[Tree.d_code(dist) * 2]++;
+			}
+
+			if ((last_lit & 0x1fff) === 0 && level > 2) {
+				// Compute an upper bound for the compressed length
+				out_length = last_lit * 8;
+				in_length = strstart - block_start;
+				for (dcode = 0; dcode < D_CODES; dcode++) {
+					out_length += dyn_dtree[dcode * 2] * (5 + Tree.extra_dbits[dcode]);
+				}
+				out_length >>>= 3;
+				if ((matches < Math.floor(last_lit / 2)) && out_length < Math.floor(in_length / 2))
+					return true;
+			}
+
+			return (last_lit == lit_bufsize - 1);
+			// We avoid equality with lit_bufsize because of wraparound at 64K
+			// on 16 bit machines and because stored blocks are restricted to
+			// 64K-1 bytes.
+		}
+
+		// Send the block data compressed using the given Huffman trees
+		function compress_block(ltree, dtree) {
+			var dist; // distance of matched string
+			var lc; // match length or unmatched char (if dist === 0)
+			var lx = 0; // running index in l_buf
+			var code; // the code to send
+			var extra; // number of extra bits to send
+
+			if (last_lit !== 0) {
+				do {
+					dist = ((that.pending_buf[d_buf + lx * 2] << 8) & 0xff00) | (that.pending_buf[d_buf + lx * 2 + 1] & 0xff);
+					lc = (that.pending_buf[l_buf + lx]) & 0xff;
+					lx++;
+
+					if (dist === 0) {
+						send_code(lc, ltree); // send a literal byte
+					} else {
+						// Here, lc is the match length - MIN_MATCH
+						code = Tree._length_code[lc];
+
+						send_code(code + LITERALS + 1, ltree); // send the length
+						// code
+						extra = Tree.extra_lbits[code];
+						if (extra !== 0) {
+							lc -= Tree.base_length[code];
+							send_bits(lc, extra); // send the extra length bits
+						}
+						dist--; // dist is now the match distance - 1
+						code = Tree.d_code(dist);
+
+						send_code(code, dtree); // send the distance code
+						extra = Tree.extra_dbits[code];
+						if (extra !== 0) {
+							dist -= Tree.base_dist[code];
+							send_bits(dist, extra); // send the extra distance bits
+						}
+					} // literal or match pair ?
+
+					// Check that the overlay between pending_buf and d_buf+l_buf is
+					// ok:
+				} while (lx < last_lit);
+			}
+
+			send_code(END_BLOCK, ltree);
+			last_eob_len = ltree[END_BLOCK * 2 + 1];
+		}
+
+		// Flush the bit buffer and align the output on a byte boundary
+		function bi_windup() {
+			if (bi_valid > 8) {
+				put_short(bi_buf);
+			} else if (bi_valid > 0) {
+				put_byte(bi_buf & 0xff);
+			}
+			bi_buf = 0;
+			bi_valid = 0;
+		}
+
+		// Copy a stored block, storing first the length and its
+		// one's complement if requested.
+		function copy_block(buf, // the input data
+		len, // its length
+		header // true if block header must be written
+		) {
+			bi_windup(); // align on byte boundary
+			last_eob_len = 8; // enough lookahead for inflate
+
+			if (header) {
+				put_short(len);
+				put_short(~len);
+			}
+
+			that.pending_buf.set(window.subarray(buf, buf + len), that.pending);
+			that.pending += len;
+		}
+
+		// Send a stored block
+		function _tr_stored_block(buf, // input block
+		stored_len, // length of input block
+		eof // true if this is the last block for a file
+		) {
+			send_bits((STORED_BLOCK << 1) + (eof ? 1 : 0), 3); // send block type
+			copy_block(buf, stored_len, true); // with header
+		}
+
+		// Determine the best encoding for the current block: dynamic trees, static
+		// trees or store, and output the encoded block to the zip file.
+		function _tr_flush_block(buf, // input block, or NULL if too old
+		stored_len, // length of input block
+		eof // true if this is the last block for a file
+		) {
+			var opt_lenb, static_lenb;// opt_len and static_len in bytes
+			var max_blindex = 0; // index of last bit length code of non zero freq
+
+			// Build the Huffman trees unless a stored block is forced
+			if (level > 0) {
+				// Construct the literal and distance trees
+				l_desc.build_tree(that);
+
+				d_desc.build_tree(that);
+
+				// At this point, opt_len and static_len are the total bit lengths
+				// of
+				// the compressed block data, excluding the tree representations.
+
+				// Build the bit length tree for the above two trees, and get the
+				// index
+				// in bl_order of the last bit length code to send.
+				max_blindex = build_bl_tree();
+
+				// Determine the best encoding. Compute first the block length in
+				// bytes
+				opt_lenb = (that.opt_len + 3 + 7) >>> 3;
+				static_lenb = (that.static_len + 3 + 7) >>> 3;
+
+				if (static_lenb <= opt_lenb)
+					opt_lenb = static_lenb;
+			} else {
+				opt_lenb = static_lenb = stored_len + 5; // force a stored block
+			}
+
+			if ((stored_len + 4 <= opt_lenb) && buf != -1) {
+				// 4: two words for the lengths
+				// The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
+				// Otherwise we can't have processed more than WSIZE input bytes
+				// since
+				// the last block flush, because compression would have been
+				// successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
+				// transform a block into a stored block.
+				_tr_stored_block(buf, stored_len, eof);
+			} else if (static_lenb == opt_lenb) {
+				send_bits((STATIC_TREES << 1) + (eof ? 1 : 0), 3);
+				compress_block(StaticTree.static_ltree, StaticTree.static_dtree);
+			} else {
+				send_bits((DYN_TREES << 1) + (eof ? 1 : 0), 3);
+				send_all_trees(l_desc.max_code + 1, d_desc.max_code + 1, max_blindex + 1);
+				compress_block(dyn_ltree, dyn_dtree);
+			}
+
+			// The above check is made mod 2^32, for files larger than 512 MB
+			// and uLong implemented on 32 bits.
+
+			init_block();
+
+			if (eof) {
+				bi_windup();
+			}
+		}
+
+		function flush_block_only(eof) {
+			_tr_flush_block(block_start >= 0 ? block_start : -1, strstart - block_start, eof);
+			block_start = strstart;
+			strm.flush_pending();
+		}
+
+		// Fill the window when the lookahead becomes insufficient.
+		// Updates strstart and lookahead.
+		//
+		// IN assertion: lookahead < MIN_LOOKAHEAD
+		// OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
+		// At least one byte has been read, or avail_in === 0; reads are
+		// performed for at least two bytes (required for the zip translate_eol
+		// option -- not supported here).
+		function fill_window() {
+			var n, m;
+			var p;
+			var more; // Amount of free space at the end of the window.
+
+			do {
+				more = (window_size - lookahead - strstart);
+
+				// Deal with !@#$% 64K limit:
+				if (more === 0 && strstart === 0 && lookahead === 0) {
+					more = w_size;
+				} else if (more == -1) {
+					// Very unlikely, but possible on 16 bit machine if strstart ==
+					// 0
+					// and lookahead == 1 (input done one byte at time)
+					more--;
+
+					// If the window is almost full and there is insufficient
+					// lookahead,
+					// move the upper half to the lower one to make room in the
+					// upper half.
+				} else if (strstart >= w_size + w_size - MIN_LOOKAHEAD) {
+					window.set(window.subarray(w_size, w_size + w_size), 0);
+
+					match_start -= w_size;
+					strstart -= w_size; // we now have strstart >= MAX_DIST
+					block_start -= w_size;
+
+					// Slide the hash table (could be avoided with 32 bit values
+					// at the expense of memory usage). We slide even when level ==
+					// 0
+					// to keep the hash table consistent if we switch back to level
+					// > 0
+					// later. (Using level 0 permanently is not an optimal usage of
+					// zlib, so we don't care about this pathological case.)
+
+					n = hash_size;
+					p = n;
+					do {
+						m = (head[--p] & 0xffff);
+						head[p] = (m >= w_size ? m - w_size : 0);
+					} while (--n !== 0);
+
+					n = w_size;
+					p = n;
+					do {
+						m = (prev[--p] & 0xffff);
+						prev[p] = (m >= w_size ? m - w_size : 0);
+						// If n is not on any hash chain, prev[n] is garbage but
+						// its value will never be used.
+					} while (--n !== 0);
+					more += w_size;
+				}
+
+				if (strm.avail_in === 0)
+					return;
+
+				// If there was no sliding:
+				// strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
+				// more == window_size - lookahead - strstart
+				// => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
+				// => more >= window_size - 2*WSIZE + 2
+				// In the BIG_MEM or MMAP case (not yet supported),
+				// window_size == input_size + MIN_LOOKAHEAD &&
+				// strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
+				// Otherwise, window_size == 2*WSIZE so more >= 2.
+				// If there was sliding, more >= WSIZE. So in all cases, more >= 2.
+
+				n = strm.read_buf(window, strstart + lookahead, more);
+				lookahead += n;
+
+				// Initialize the hash value now that we have some input:
+				if (lookahead >= MIN_MATCH) {
+					ins_h = window[strstart] & 0xff;
+					ins_h = (((ins_h) << hash_shift) ^ (window[strstart + 1] & 0xff)) & hash_mask;
+				}
+				// If the whole input has less than MIN_MATCH bytes, ins_h is
+				// garbage,
+				// but this is not important since only literal bytes will be
+				// emitted.
+			} while (lookahead < MIN_LOOKAHEAD && strm.avail_in !== 0);
+		}
+
+		// Copy without compression as much as possible from the input stream,
+		// return
+		// the current block state.
+		// This function does not insert new strings in the dictionary since
+		// uncompressible data is probably not useful. This function is used
+		// only for the level=0 compression option.
+		// NOTE: this function should be optimized to avoid extra copying from
+		// window to pending_buf.
+		function deflate_stored(flush) {
+			// Stored blocks are limited to 0xffff bytes, pending_buf is limited
+			// to pending_buf_size, and each stored block has a 5 byte header:
+
+			var max_block_size = 0xffff;
+			var max_start;
+
+			if (max_block_size > pending_buf_size - 5) {
+				max_block_size = pending_buf_size - 5;
+			}
+
+			// Copy as much as possible from input to output:
+			while (true) {
+				// Fill the window as much as possible:
+				if (lookahead <= 1) {
+					fill_window();
+					if (lookahead === 0 && flush == Z_NO_FLUSH)
+						return NeedMore;
+					if (lookahead === 0)
+						break; // flush the current block
+				}
+
+				strstart += lookahead;
+				lookahead = 0;
+
+				// Emit a stored block if pending_buf will be full:
+				max_start = block_start + max_block_size;
+				if (strstart === 0 || strstart >= max_start) {
+					// strstart === 0 is possible when wraparound on 16-bit machine
+					lookahead = (strstart - max_start);
+					strstart = max_start;
+
+					flush_block_only(false);
+					if (strm.avail_out === 0)
+						return NeedMore;
+
+				}
+
+				// Flush if we may have to slide, otherwise block_start may become
+				// negative and the data will be gone:
+				if (strstart - block_start >= w_size - MIN_LOOKAHEAD) {
+					flush_block_only(false);
+					if (strm.avail_out === 0)
+						return NeedMore;
+				}
+			}
+
+			flush_block_only(flush == Z_FINISH);
+			if (strm.avail_out === 0)
+				return (flush == Z_FINISH) ? FinishStarted : NeedMore;
+
+			return flush == Z_FINISH ? FinishDone : BlockDone;
+		}
+
+		function longest_match(cur_match) {
+			var chain_length = max_chain_length; // max hash chain length
+			var scan = strstart; // current string
+			var match; // matched string
+			var len; // length of current match
+			var best_len = prev_length; // best match length so far
+			var limit = strstart > (w_size - MIN_LOOKAHEAD) ? strstart - (w_size - MIN_LOOKAHEAD) : 0;
+			var _nice_match = nice_match;
+
+			// Stop when cur_match becomes <= limit. To simplify the code,
+			// we prevent matches with the string of window index 0.
+
+			var wmask = w_mask;
+
+			var strend = strstart + MAX_MATCH;
+			var scan_end1 = window[scan + best_len - 1];
+			var scan_end = window[scan + best_len];
+
+			// The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of
+			// 16.
+			// It is easy to get rid of this optimization if necessary.
+
+			// Do not waste too much time if we already have a good match:
+			if (prev_length >= good_match) {
+				chain_length >>= 2;
+			}
+
+			// Do not look for matches beyond the end of the input. This is
+			// necessary
+			// to make deflate deterministic.
+			if (_nice_match > lookahead)
+				_nice_match = lookahead;
+
+			do {
+				match = cur_match;
+
+				// Skip to next match if the match length cannot increase
+				// or if the match length is less than 2:
+				if (window[match + best_len] != scan_end || window[match + best_len - 1] != scan_end1 || window[match] != window[scan]
+						|| window[++match] != window[scan + 1])
+					continue;
+
+				// The check at best_len-1 can be removed because it will be made
+				// again later. (This heuristic is not always a win.)
+				// It is not necessary to compare scan[2] and match[2] since they
+				// are always equal when the other bytes match, given that
+				// the hash keys are equal and that HASH_BITS >= 8.
+				scan += 2;
+				match++;
+
+				// We check for insufficient lookahead only every 8th comparison;
+				// the 256th check will be made at strstart+258.
+				do {
+				} while (window[++scan] == window[++match] && window[++scan] == window[++match] && window[++scan] == window[++match]
+						&& window[++scan] == window[++match] && window[++scan] == window[++match] && window[++scan] == window[++match]
+						&& window[++scan] == window[++match] && window[++scan] == window[++match] && scan < strend);
+
+				len = MAX_MATCH - (strend - scan);
+				scan = strend - MAX_MATCH;
+
+				if (len > best_len) {
+					match_start = cur_match;
+					best_len = len;
+					if (len >= _nice_match)
+						break;
+					scan_end1 = window[scan + best_len - 1];
+					scan_end = window[scan + best_len];
+				}
+
+			} while ((cur_match = (prev[cur_match & wmask] & 0xffff)) > limit && --chain_length !== 0);
+
+			if (best_len <= lookahead)
+				return best_len;
+			return lookahead;
+		}
+
+		// Compress as much as possible from the input stream, return the current
+		// block state.
+		// This function does not perform lazy evaluation of matches and inserts
+		// new strings in the dictionary only for unmatched strings or for short
+		// matches. It is used only for the fast compression options.
+		function deflate_fast(flush) {
+			// short hash_head = 0; // head of the hash chain
+			var hash_head = 0; // head of the hash chain
+			var bflush; // set if current block must be flushed
+
+			while (true) {
+				// Make sure that we always have enough lookahead, except
+				// at the end of the input file. We need MAX_MATCH bytes
+				// for the next match, plus MIN_MATCH bytes to insert the
+				// string following the next match.
+				if (lookahead < MIN_LOOKAHEAD) {
+					fill_window();
+					if (lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
+						return NeedMore;
+					}
+					if (lookahead === 0)
+						break; // flush the current block
+				}
+
+				// Insert the string window[strstart .. strstart+2] in the
+				// dictionary, and set hash_head to the head of the hash chain:
+				if (lookahead >= MIN_MATCH) {
+					ins_h = (((ins_h) << hash_shift) ^ (window[(strstart) + (MIN_MATCH - 1)] & 0xff)) & hash_mask;
+
+					// prev[strstart&w_mask]=hash_head=head[ins_h];
+					hash_head = (head[ins_h] & 0xffff);
+					prev[strstart & w_mask] = head[ins_h];
+					head[ins_h] = strstart;
+				}
+
+				// Find the longest match, discarding those <= prev_length.
+				// At this point we have always match_length < MIN_MATCH
+
+				if (hash_head !== 0 && ((strstart - hash_head) & 0xffff) <= w_size - MIN_LOOKAHEAD) {
+					// To simplify the code, we prevent matches with the string
+					// of window index 0 (in particular we have to avoid a match
+					// of the string with itself at the start of the input file).
+					if (strategy != Z_HUFFMAN_ONLY) {
+						match_length = longest_match(hash_head);
+					}
+					// longest_match() sets match_start
+				}
+				if (match_length >= MIN_MATCH) {
+					// check_match(strstart, match_start, match_length);
+
+					bflush = _tr_tally(strstart - match_start, match_length - MIN_MATCH);
+
+					lookahead -= match_length;
+
+					// Insert new strings in the hash table only if the match length
+					// is not too large. This saves time but degrades compression.
+					if (match_length <= max_lazy_match && lookahead >= MIN_MATCH) {
+						match_length--; // string at strstart already in hash table
+						do {
+							strstart++;
+
+							ins_h = ((ins_h << hash_shift) ^ (window[(strstart) + (MIN_MATCH - 1)] & 0xff)) & hash_mask;
+							// prev[strstart&w_mask]=hash_head=head[ins_h];
+							hash_head = (head[ins_h] & 0xffff);
+							prev[strstart & w_mask] = head[ins_h];
+							head[ins_h] = strstart;
+
+							// strstart never exceeds WSIZE-MAX_MATCH, so there are
+							// always MIN_MATCH bytes ahead.
+						} while (--match_length !== 0);
+						strstart++;
+					} else {
+						strstart += match_length;
+						match_length = 0;
+						ins_h = window[strstart] & 0xff;
+
+						ins_h = (((ins_h) << hash_shift) ^ (window[strstart + 1] & 0xff)) & hash_mask;
+						// If lookahead < MIN_MATCH, ins_h is garbage, but it does
+						// not
+						// matter since it will be recomputed at next deflate call.
+					}
+				} else {
+					// No match, output a literal byte
+
+					bflush = _tr_tally(0, window[strstart] & 0xff);
+					lookahead--;
+					strstart++;
+				}
+				if (bflush) {
+
+					flush_block_only(false);
+					if (strm.avail_out === 0)
+						return NeedMore;
+				}
+			}
+
+			flush_block_only(flush == Z_FINISH);
+			if (strm.avail_out === 0) {
+				if (flush == Z_FINISH)
+					return FinishStarted;
+				else
+					return NeedMore;
+			}
+			return flush == Z_FINISH ? FinishDone : BlockDone;
+		}
+
+		// Same as above, but achieves better compression. We use a lazy
+		// evaluation for matches: a match is finally adopted only if there is
+		// no better match at the next window position.
+		function deflate_slow(flush) {
+			// short hash_head = 0; // head of hash chain
+			var hash_head = 0; // head of hash chain
+			var bflush; // set if current block must be flushed
+			var max_insert;
+
+			// Process the input block.
+			while (true) {
+				// Make sure that we always have enough lookahead, except
+				// at the end of the input file. We need MAX_MATCH bytes
+				// for the next match, plus MIN_MATCH bytes to insert the
+				// string following the next match.
+
+				if (lookahead < MIN_LOOKAHEAD) {
+					fill_window();
+					if (lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
+						return NeedMore;
+					}
+					if (lookahead === 0)
+						break; // flush the current block
+				}
+
+				// Insert the string window[strstart .. strstart+2] in the
+				// dictionary, and set hash_head to the head of the hash chain:
+
+				if (lookahead >= MIN_MATCH) {
+					ins_h = (((ins_h) << hash_shift) ^ (window[(strstart) + (MIN_MATCH - 1)] & 0xff)) & hash_mask;
+					// prev[strstart&w_mask]=hash_head=head[ins_h];
+					hash_head = (head[ins_h] & 0xffff);
+					prev[strstart & w_mask] = head[ins_h];
+					head[ins_h] = strstart;
+				}
+
+				// Find the longest match, discarding those <= prev_length.
+				prev_length = match_length;
+				prev_match = match_start;
+				match_length = MIN_MATCH - 1;
+
+				if (hash_head !== 0 && prev_length < max_lazy_match && ((strstart - hash_head) & 0xffff) <= w_size - MIN_LOOKAHEAD) {
+					// To simplify the code, we prevent matches with the string
+					// of window index 0 (in particular we have to avoid a match
+					// of the string with itself at the start of the input file).
+
+					if (strategy != Z_HUFFMAN_ONLY) {
+						match_length = longest_match(hash_head);
+					}
+					// longest_match() sets match_start
+
+					if (match_length <= 5 && (strategy == Z_FILTERED || (match_length == MIN_MATCH && strstart - match_start > 4096))) {
+
+						// If prev_match is also MIN_MATCH, match_start is garbage
+						// but we will ignore the current match anyway.
+						match_length = MIN_MATCH - 1;
+					}
+				}
+
+				// If there was a match at the previous step and the current
+				// match is not better, output the previous match:
+				if (prev_length >= MIN_MATCH && match_length <= prev_length) {
+					max_insert = strstart + lookahead - MIN_MATCH;
+					// Do not insert strings in hash table beyond this.
+
+					// check_match(strstart-1, prev_match, prev_length);
+
+					bflush = _tr_tally(strstart - 1 - prev_match, prev_length - MIN_MATCH);
+
+					// Insert in hash table all strings up to the end of the match.
+					// strstart-1 and strstart are already inserted. If there is not
+					// enough lookahead, the last two strings are not inserted in
+					// the hash table.
+					lookahead -= prev_length - 1;
+					prev_length -= 2;
+					do {
+						if (++strstart <= max_insert) {
+							ins_h = (((ins_h) << hash_shift) ^ (window[(strstart) + (MIN_MATCH - 1)] & 0xff)) & hash_mask;
+							// prev[strstart&w_mask]=hash_head=head[ins_h];
+							hash_head = (head[ins_h] & 0xffff);
+							prev[strstart & w_mask] = head[ins_h];
+							head[ins_h] = strstart;
+						}
+					} while (--prev_length !== 0);
+					match_available = 0;
+					match_length = MIN_MATCH - 1;
+					strstart++;
+
+					if (bflush) {
+						flush_block_only(false);
+						if (strm.avail_out === 0)
+							return NeedMore;
+					}
+				} else if (match_available !== 0) {
+
+					// If there was no match at the previous position, output a
+					// single literal. If there was a match but the current match
+					// is longer, truncate the previous match to a single literal.
+
+					bflush = _tr_tally(0, window[strstart - 1] & 0xff);
+
+					if (bflush) {
+						flush_block_only(false);
+					}
+					strstart++;
+					lookahead--;
+					if (strm.avail_out === 0)
+						return NeedMore;
+				} else {
+					// There is no previous match to compare with, wait for
+					// the next step to decide.
+
+					match_available = 1;
+					strstart++;
+					lookahead--;
+				}
+			}
+
+			if (match_available !== 0) {
+				bflush = _tr_tally(0, window[strstart - 1] & 0xff);
+				match_available = 0;
+			}
+			flush_block_only(flush == Z_FINISH);
+
+			if (strm.avail_out === 0) {
+				if (flush == Z_FINISH)
+					return FinishStarted;
+				else
+					return NeedMore;
+			}
+
+			return flush == Z_FINISH ? FinishDone : BlockDone;
+		}
+
+		function deflateReset(strm) {
+			strm.total_in = strm.total_out = 0;
+			strm.msg = null; //
+			
+			that.pending = 0;
+			that.pending_out = 0;
+
+			status = BUSY_STATE;
+
+			last_flush = Z_NO_FLUSH;
+
+			tr_init();
+			lm_init();
+			return Z_OK;
+		}
+
+		that.deflateInit = function(strm, _level, bits, _method, memLevel, _strategy) {
+			if (!_method)
+				_method = Z_DEFLATED;
+			if (!memLevel)
+				memLevel = DEF_MEM_LEVEL;
+			if (!_strategy)
+				_strategy = Z_DEFAULT_STRATEGY;
+
+			// byte[] my_version=ZLIB_VERSION;
+
+			//
+			// if (!version || version[0] != my_version[0]
+			// || stream_size != sizeof(z_stream)) {
+			// return Z_VERSION_ERROR;
+			// }
+
+			strm.msg = null;
+
+			if (_level == Z_DEFAULT_COMPRESSION)
+				_level = 6;
+
+			if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || _method != Z_DEFLATED || bits < 9 || bits > 15 || _level < 0 || _level > 9 || _strategy < 0
+					|| _strategy > Z_HUFFMAN_ONLY) {
+				return Z_STREAM_ERROR;
+			}
+
+			strm.dstate = that;
+
+			w_bits = bits;
+			w_size = 1 << w_bits;
+			w_mask = w_size - 1;
+
+			hash_bits = memLevel + 7;
+			hash_size = 1 << hash_bits;
+			hash_mask = hash_size - 1;
+			hash_shift = Math.floor((hash_bits + MIN_MATCH - 1) / MIN_MATCH);
+
+			window = new Uint8Array(w_size * 2);
+			prev = [];
+			head = [];
+
+			lit_bufsize = 1 << (memLevel + 6); // 16K elements by default
+
+			// We overlay pending_buf and d_buf+l_buf. This works since the average
+			// output size for (length,distance) codes is <= 24 bits.
+			that.pending_buf = new Uint8Array(lit_bufsize * 4);
+			pending_buf_size = lit_bufsize * 4;
+
+			d_buf = Math.floor(lit_bufsize / 2);
+			l_buf = (1 + 2) * lit_bufsize;
+
+			level = _level;
+
+			strategy = _strategy;
+			method = _method & 0xff;
+
+			return deflateReset(strm);
+		};
+
+		that.deflateEnd = function() {
+			if (status != INIT_STATE && status != BUSY_STATE && status != FINISH_STATE) {
+				return Z_STREAM_ERROR;
+			}
+			// Deallocate in reverse order of allocations:
+			that.pending_buf = null;
+			head = null;
+			prev = null;
+			window = null;
+			// free
+			that.dstate = null;
+			return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
+		};
+
+		that.deflateParams = function(strm, _level, _strategy) {
+			var err = Z_OK;
+
+			if (_level == Z_DEFAULT_COMPRESSION) {
+				_level = 6;
+			}
+			if (_level < 0 || _level > 9 || _strategy < 0 || _strategy > Z_HUFFMAN_ONLY) {
+				return Z_STREAM_ERROR;
+			}
+
+			if (config_table[level].func != config_table[_level].func && strm.total_in !== 0) {
+				// Flush the last buffer:
+				err = strm.deflate(Z_PARTIAL_FLUSH);
+			}
+
+			if (level != _level) {
+				level = _level;
+				max_lazy_match = config_table[level].max_lazy;
+				good_match = config_table[level].good_length;
+				nice_match = config_table[level].nice_length;
+				max_chain_length = config_table[level].max_chain;
+			}
+			strategy = _strategy;
+			return err;
+		};
+
+		that.deflateSetDictionary = function(strm, dictionary, dictLength) {
+			var length = dictLength;
+			var n, index = 0;
+
+			if (!dictionary || status != INIT_STATE)
+				return Z_STREAM_ERROR;
+
+			if (length < MIN_MATCH)
+				return Z_OK;
+			if (length > w_size - MIN_LOOKAHEAD) {
+				length = w_size - MIN_LOOKAHEAD;
+				index = dictLength - length; // use the tail of the dictionary
+			}
+			window.set(dictionary.subarray(index, index + length), 0);
+
+			strstart = length;
+			block_start = length;
+
+			// Insert all strings in the hash table (except for the last two bytes).
+			// s->lookahead stays null, so s->ins_h will be recomputed at the next
+			// call of fill_window.
+
+			ins_h = window[0] & 0xff;
+			ins_h = (((ins_h) << hash_shift) ^ (window[1] & 0xff)) & hash_mask;
+
+			for (n = 0; n <= length - MIN_MATCH; n++) {
+				ins_h = (((ins_h) << hash_shift) ^ (window[(n) + (MIN_MATCH - 1)] & 0xff)) & hash_mask;
+				prev[n & w_mask] = head[ins_h];
+				head[ins_h] = n;
+			}
+			return Z_OK;
+		};
+
+		that.deflate = function(_strm, flush) {
+			var i, header, level_flags, old_flush, bstate;
+
+			if (flush > Z_FINISH || flush < 0) {
+				return Z_STREAM_ERROR;
+			}
+
+			if (!_strm.next_out || (!_strm.next_in && _strm.avail_in !== 0) || (status == FINISH_STATE && flush != Z_FINISH)) {
+				_strm.msg = z_errmsg[Z_NEED_DICT - (Z_STREAM_ERROR)];
+				return Z_STREAM_ERROR;
+			}
+			if (_strm.avail_out === 0) {
+				_strm.msg = z_errmsg[Z_NEED_DICT - (Z_BUF_ERROR)];
+				return Z_BUF_ERROR;
+			}
+
+			strm = _strm; // just in case
+			old_flush = last_flush;
+			last_flush = flush;
+
+			// Write the zlib header
+			if (status == INIT_STATE) {
+				header = (Z_DEFLATED + ((w_bits - 8) << 4)) << 8;
+				level_flags = ((level - 1) & 0xff) >> 1;
+
+				if (level_flags > 3)
+					level_flags = 3;
+				header |= (level_flags << 6);
+				if (strstart !== 0)
+					header |= PRESET_DICT;
+				header += 31 - (header % 31);
+
+				status = BUSY_STATE;
+				putShortMSB(header);
+			}
+
+			// Flush as much pending output as possible
+			if (that.pending !== 0) {
+				strm.flush_pending();
+				if (strm.avail_out === 0) {
+					// console.log(" avail_out==0");
+					// Since avail_out is 0, deflate will be called again with
+					// more output space, but possibly with both pending and
+					// avail_in equal to zero. There won't be anything to do,
+					// but this is not an error situation so make sure we
+					// return OK instead of BUF_ERROR at next call of deflate:
+					last_flush = -1;
+					return Z_OK;
+				}
+
+				// Make sure there is something to do and avoid duplicate
+				// consecutive
+				// flushes. For repeated and useless calls with Z_FINISH, we keep
+				// returning Z_STREAM_END instead of Z_BUFF_ERROR.
+			} else if (strm.avail_in === 0 && flush <= old_flush && flush != Z_FINISH) {
+				strm.msg = z_errmsg[Z_NEED_DICT - (Z_BUF_ERROR)];
+				return Z_BUF_ERROR;
+			}
+
+			// User must not provide more input after the first FINISH:
+			if (status == FINISH_STATE && strm.avail_in !== 0) {
+				_strm.msg = z_errmsg[Z_NEED_DICT - (Z_BUF_ERROR)];
+				return Z_BUF_ERROR;
+			}
+
+			// Start a new block or continue the current one.
+			if (strm.avail_in !== 0 || lookahead !== 0 || (flush != Z_NO_FLUSH && status != FINISH_STATE)) {
+				bstate = -1;
+				switch (config_table[level].func) {
+				case STORED:
+					bstate = deflate_stored(flush);
+					break;
+				case FAST:
+					bstate = deflate_fast(flush);
+					break;
+				case SLOW:
+					bstate = deflate_slow(flush);
+					break;
+				default:
+				}
+
+				if (bstate == FinishStarted || bstate == FinishDone) {
+					status = FINISH_STATE;
+				}
+				if (bstate == NeedMore || bstate == FinishStarted) {
+					if (strm.avail_out === 0) {
+						last_flush = -1; // avoid BUF_ERROR next call, see above
+					}
+					return Z_OK;
+					// If flush != Z_NO_FLUSH && avail_out === 0, the next call
+					// of deflate should use the same flush parameter to make sure
+					// that the flush is complete. So we don't have to output an
+					// empty block here, this will be done at next call. This also
+					// ensures that for a very small output buffer, we emit at most
+					// one empty block.
+				}
+
+				if (bstate == BlockDone) {
+					if (flush == Z_PARTIAL_FLUSH) {
+						_tr_align();
+					} else { // FULL_FLUSH or SYNC_FLUSH
+						_tr_stored_block(0, 0, false);
+						// For a full flush, this empty block will be recognized
+						// as a special marker by inflate_sync().
+						if (flush == Z_FULL_FLUSH) {
+							// state.head[s.hash_size-1]=0;
+							for (i = 0; i < hash_size/*-1*/; i++)
+								// forget history
+								head[i] = 0;
+						}
+					}
+					strm.flush_pending();
+					if (strm.avail_out === 0) {
+						last_flush = -1; // avoid BUF_ERROR at next call, see above
+						return Z_OK;
+					}
+				}
+			}
+
+			if (flush != Z_FINISH)
+				return Z_OK;
+			return Z_STREAM_END;
+		};
+	}
+
+	// ZStream
+
+	function ZStream() {
+		var that = this;
+		that.next_in_index = 0;
+		that.next_out_index = 0;
+		// that.next_in; // next input byte
+		that.avail_in = 0; // number of bytes available at next_in
+		that.total_in = 0; // total nb of input bytes read so far
+		// that.next_out; // next output byte should be put there
+		that.avail_out = 0; // remaining free space at next_out
+		that.total_out = 0; // total nb of bytes output so far
+		// that.msg;
+		// that.dstate;
+	}
+
+	ZStream.prototype = {
+		deflateInit : function(level, bits) {
+			var that = this;
+			that.dstate = new Deflate();
+			if (!bits)
+				bits = MAX_BITS;
+			return that.dstate.deflateInit(that, level, bits);
+		},
+
+		deflate : function(flush) {
+			var that = this;
+			if (!that.dstate) {
+				return Z_STREAM_ERROR;
+			}
+			return that.dstate.deflate(that, flush);
+		},
+
+		deflateEnd : function() {
+			var that = this;
+			if (!that.dstate)
+				return Z_STREAM_ERROR;
+			var ret = that.dstate.deflateEnd();
+			that.dstate = null;
+			return ret;
+		},
+
+		deflateParams : function(level, strategy) {
+			var that = this;
+			if (!that.dstate)
+				return Z_STREAM_ERROR;
+			return that.dstate.deflateParams(that, level, strategy);
+		},
+
+		deflateSetDictionary : function(dictionary, dictLength) {
+			var that = this;
+			if (!that.dstate)
+				return Z_STREAM_ERROR;
+			return that.dstate.deflateSetDictionary(that, dictionary, dictLength);
+		},
+
+		// Read a new buffer from the current input stream, update the
+		// total number of bytes read. All deflate() input goes through
+		// this function so some applications may wish to modify it to avoid
+		// allocating a large strm->next_in buffer and copying from it.
+		// (See also flush_pending()).
+		read_buf : function(buf, start, size) {
+			var that = this;
+			var len = that.avail_in;
+			if (len > size)
+				len = size;
+			if (len === 0)
+				return 0;
+			that.avail_in -= len;
+			buf.set(that.next_in.subarray(that.next_in_index, that.next_in_index + len), start);
+			that.next_in_index += len;
+			that.total_in += len;
+			return len;
+		},
+
+		// Flush as much pending output as possible. All deflate() output goes
+		// through this function so some applications may wish to modify it
+		// to avoid allocating a large strm->next_out buffer and copying into it.
+		// (See also read_buf()).
+		flush_pending : function() {
+			var that = this;
+			var len = that.dstate.pending;
+
+			if (len > that.avail_out)
+				len = that.avail_out;
+			if (len === 0)
+				return;
+
+			// if (that.dstate.pending_buf.length <= that.dstate.pending_out || that.next_out.length <= that.next_out_index
+			// || that.dstate.pending_buf.length < (that.dstate.pending_out + len) || that.next_out.length < (that.next_out_index +
+			// len)) {
+			// console.log(that.dstate.pending_buf.length + ", " + that.dstate.pending_out + ", " + that.next_out.length + ", " +
+			// that.next_out_index + ", " + len);
+			// console.log("avail_out=" + that.avail_out);
+			// }
+
+			that.next_out.set(that.dstate.pending_buf.subarray(that.dstate.pending_out, that.dstate.pending_out + len), that.next_out_index);
+
+			that.next_out_index += len;
+			that.dstate.pending_out += len;
+			that.total_out += len;
+			that.avail_out -= len;
+			that.dstate.pending -= len;
+			if (that.dstate.pending === 0) {
+				that.dstate.pending_out = 0;
+			}
+		}
+	};
+
+	// Deflater
+
+	return function Deflater(level) {
+		var that = this;
+		var z = new ZStream();
+		var bufsize = 512;
+		var flush = Z_NO_FLUSH;
+		var buf = new Uint8Array(bufsize);
+
+		if (typeof level == "undefined")
+			level = Z_DEFAULT_COMPRESSION;
+		z.deflateInit(level);
+		z.next_out = buf;
+
+		that.append = function(data, onprogress) {
+			var err, buffers = [], lastIndex = 0, bufferIndex = 0, bufferSize = 0, array;
+			if (!data.length)
+				return;
+			z.next_in_index = 0;
+			z.next_in = data;
+			z.avail_in = data.length;
+			do {
+				z.next_out_index = 0;
+				z.avail_out = bufsize;
+				err = z.deflate(flush);
+				if (err != Z_OK)
+					throw "deflating: " + z.msg;
+				if (z.next_out_index)
+					if (z.next_out_index == bufsize)
+						buffers.push(new Uint8Array(buf));
+					else
+						buffers.push(new Uint8Array(buf.subarray(0, z.next_out_index)));
+				bufferSize += z.next_out_index;
+				if (onprogress && z.next_in_index > 0 && z.next_in_index != lastIndex) {
+					onprogress(z.next_in_index);
+					lastIndex = z.next_in_index;
+				}
+			} while (z.avail_in > 0 || z.avail_out === 0);
+			array = new Uint8Array(bufferSize);
+			buffers.forEach(function(chunk) {
+				array.set(chunk, bufferIndex);
+				bufferIndex += chunk.length;
+			});
+			return array;
+		};
+		that.flush = function() {
+			var err, buffers = [], bufferIndex = 0, bufferSize = 0, array;
+			do {
+				z.next_out_index = 0;
+				z.avail_out = bufsize;
+				err = z.deflate(Z_FINISH);
+				if (err != Z_STREAM_END && err != Z_OK)
+					throw "deflating: " + z.msg;
+				if (bufsize - z.avail_out > 0)
+					buffers.push(new Uint8Array(buf.subarray(0, z.next_out_index)));
+				bufferSize += z.next_out_index;
+			} while (z.avail_in > 0 || z.avail_out === 0);
+			z.deflateEnd();
+			array = new Uint8Array(bufferSize);
+			buffers.forEach(function(chunk) {
+				array.set(chunk, bufferIndex);
+				bufferIndex += chunk.length;
+			});
+			return array;
+		};
+	};
+})(undefined);
+
+
+/*
+  html2canvas 0.5.0-beta3 <http://html2canvas.hertzen.com>
+  Copyright (c) 2016 Niklas von Hertzen
+
+  Released under  License
+*/
+
+!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,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(_dereq_,module,exports){
+(function (global){
+/*! http://mths.be/punycode v1.2.4 by @mathias */
+(function(root) {
+
+	/** Detect free variables */
+	var freeExports = typeof exports == 'object' && exports;
+	var freeModule = typeof module == 'object' && module &&
+		module.exports == freeExports && module;
+	var freeGlobal = typeof global == 'object' && global;
+	if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) {
+		root = freeGlobal;
+	}
+
+	/**
+	 * The `punycode` object.
+	 * @name punycode
+	 * @type Object
+	 */
+	var punycode,
+
+	/** Highest positive signed 32-bit float value */
+	maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1
+
+	/** Bootstring parameters */
+	base = 36,
+	tMin = 1,
+	tMax = 26,
+	skew = 38,
+	damp = 700,
+	initialBias = 72,
+	initialN = 128, // 0x80
+	delimiter = '-', // '\x2D'
+
+	/** Regular expressions */
+	regexPunycode = /^xn--/,
+	regexNonASCII = /[^ -~]/, // unprintable ASCII chars + non-ASCII chars
+	regexSeparators = /\x2E|\u3002|\uFF0E|\uFF61/g, // RFC 3490 separators
+
+	/** Error messages */
+	errors = {
+		'overflow': 'Overflow: input needs wider integers to process',
+		'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
+		'invalid-input': 'Invalid input'
+	},
+
+	/** Convenience shortcuts */
+	baseMinusTMin = base - tMin,
+	floor = Math.floor,
+	stringFromCharCode = String.fromCharCode,
+
+	/** Temporary variable */
+	key;
+
+	/*--------------------------------------------------------------------------*/
+
+	/**
+	 * A generic error utility function.
+	 * @private
+	 * @param {String} type The error type.
+	 * @returns {Error} Throws a `RangeError` with the applicable error message.
+	 */
+	function error(type) {
+		throw RangeError(errors[type]);
+	}
+
+	/**
+	 * A generic `Array#map` utility function.
+	 * @private
+	 * @param {Array} array The array to iterate over.
+	 * @param {Function} callback The function that gets called for every array
+	 * item.
+	 * @returns {Array} A new array of values returned by the callback function.
+	 */
+	function map(array, fn) {
+		var length = array.length;
+		while (length--) {
+			array[length] = fn(array[length]);
+		}
+		return array;
+	}
+
+	/**
+	 * A simple `Array#map`-like wrapper to work with domain name strings.
+	 * @private
+	 * @param {String} domain The domain name.
+	 * @param {Function} callback The function that gets called for every
+	 * character.
+	 * @returns {Array} A new string of characters returned by the callback
+	 * function.
+	 */
+	function mapDomain(string, fn) {
+		return map(string.split(regexSeparators), fn).join('.');
+	}
+
+	/**
+	 * Creates an array containing the numeric code points of each Unicode
+	 * character in the string. While JavaScript uses UCS-2 internally,
+	 * this function will convert a pair of surrogate halves (each of which
+	 * UCS-2 exposes as separate characters) into a single code point,
+	 * matching UTF-16.
+	 * @see `punycode.ucs2.encode`
+	 * @see <http://mathiasbynens.be/notes/javascript-encoding>
+	 * @memberOf punycode.ucs2
+	 * @name decode
+	 * @param {String} string The Unicode input string (UCS-2).
+	 * @returns {Array} The new array of code points.
+	 */
+	function ucs2decode(string) {
+		var output = [],
+		    counter = 0,
+		    length = string.length,
+		    value,
+		    extra;
+		while (counter < length) {
+			value = string.charCodeAt(counter++);
+			if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
+				// high surrogate, and there is a next character
+				extra = string.charCodeAt(counter++);
+				if ((extra & 0xFC00) == 0xDC00) { // low surrogate
+					output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
+				} else {
+					// unmatched surrogate; only append this code unit, in case the next
+					// code unit is the high surrogate of a surrogate pair
+					output.push(value);
+					counter--;
+				}
+			} else {
+				output.push(value);
+			}
+		}
+		return output;
+	}
+
+	/**
+	 * Creates a string based on an array of numeric code points.
+	 * @see `punycode.ucs2.decode`
+	 * @memberOf punycode.ucs2
+	 * @name encode
+	 * @param {Array} codePoints The array of numeric code points.
+	 * @returns {String} The new Unicode string (UCS-2).
+	 */
+	function ucs2encode(array) {
+		return map(array, function(value) {
+			var output = '';
+			if (value > 0xFFFF) {
+				value -= 0x10000;
+				output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
+				value = 0xDC00 | value & 0x3FF;
+			}
+			output += stringFromCharCode(value);
+			return output;
+		}).join('');
+	}
+
+	/**
+	 * Converts a basic code point into a digit/integer.
+	 * @see `digitToBasic()`
+	 * @private
+	 * @param {Number} codePoint The basic numeric code point value.
+	 * @returns {Number} The numeric value of a basic code point (for use in
+	 * representing integers) in the range `0` to `base - 1`, or `base` if
+	 * the code point does not represent a value.
+	 */
+	function basicToDigit(codePoint) {
+		if (codePoint - 48 < 10) {
+			return codePoint - 22;
+		}
+		if (codePoint - 65 < 26) {
+			return codePoint - 65;
+		}
+		if (codePoint - 97 < 26) {
+			return codePoint - 97;
+		}
+		return base;
+	}
+
+	/**
+	 * Converts a digit/integer into a basic code point.
+	 * @see `basicToDigit()`
+	 * @private
+	 * @param {Number} digit The numeric value of a basic code point.
+	 * @returns {Number} The basic code point whose value (when used for
+	 * representing integers) is `digit`, which needs to be in the range
+	 * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
+	 * used; else, the lowercase form is used. The behavior is undefined
+	 * if `flag` is non-zero and `digit` has no uppercase form.
+	 */
+	function digitToBasic(digit, flag) {
+		//  0..25 map to ASCII a..z or A..Z
+		// 26..35 map to ASCII 0..9
+		return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
+	}
+
+	/**
+	 * Bias adaptation function as per section 3.4 of RFC 3492.
+	 * http://tools.ietf.org/html/rfc3492#section-3.4
+	 * @private
+	 */
+	function adapt(delta, numPoints, firstTime) {
+		var k = 0;
+		delta = firstTime ? floor(delta / damp) : delta >> 1;
+		delta += floor(delta / numPoints);
+		for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
+			delta = floor(delta / baseMinusTMin);
+		}
+		return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
+	}
+
+	/**
+	 * Converts a Punycode string of ASCII-only symbols to a string of Unicode
+	 * symbols.
+	 * @memberOf punycode
+	 * @param {String} input The Punycode string of ASCII-only symbols.
+	 * @returns {String} The resulting string of Unicode symbols.
+	 */
+	function decode(input) {
+		// Don't use UCS-2
+		var output = [],
+		    inputLength = input.length,
+		    out,
+		    i = 0,
+		    n = initialN,
+		    bias = initialBias,
+		    basic,
+		    j,
+		    index,
+		    oldi,
+		    w,
+		    k,
+		    digit,
+		    t,
+		    /** Cached calculation results */
+		    baseMinusT;
+
+		// Handle the basic code points: let `basic` be the number of input code
+		// points before the last delimiter, or `0` if there is none, then copy
+		// the first basic code points to the output.
+
+		basic = input.lastIndexOf(delimiter);
+		if (basic < 0) {
+			basic = 0;
+		}
+
+		for (j = 0; j < basic; ++j) {
+			// if it's not a basic code point
+			if (input.charCodeAt(j) >= 0x80) {
+				error('not-basic');
+			}
+			output.push(input.charCodeAt(j));
+		}
+
+		// Main decoding loop: start just after the last delimiter if any basic code
+		// points were copied; start at the beginning otherwise.
+
+		for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {
+
+			// `index` is the index of the next character to be consumed.
+			// Decode a generalized variable-length integer into `delta`,
+			// which gets added to `i`. The overflow checking is easier
+			// if we increase `i` as we go, then subtract off its starting
+			// value at the end to obtain `delta`.
+			for (oldi = i, w = 1, k = base; /* no condition */; k += base) {
+
+				if (index >= inputLength) {
+					error('invalid-input');
+				}
+
+				digit = basicToDigit(input.charCodeAt(index++));
+
+				if (digit >= base || digit > floor((maxInt - i) / w)) {
+					error('overflow');
+				}
+
+				i += digit * w;
+				t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
+
+				if (digit < t) {
+					break;
+				}
+
+				baseMinusT = base - t;
+				if (w > floor(maxInt / baseMinusT)) {
+					error('overflow');
+				}
+
+				w *= baseMinusT;
+
+			}
+
+			out = output.length + 1;
+			bias = adapt(i - oldi, out, oldi == 0);
+
+			// `i` was supposed to wrap around from `out` to `0`,
+			// incrementing `n` each time, so we'll fix that now:
+			if (floor(i / out) > maxInt - n) {
+				error('overflow');
+			}
+
+			n += floor(i / out);
+			i %= out;
+
+			// Insert `n` at position `i` of the output
+			output.splice(i++, 0, n);
+
+		}
+
+		return ucs2encode(output);
+	}
+
+	/**
+	 * Converts a string of Unicode symbols to a Punycode string of ASCII-only
+	 * symbols.
+	 * @memberOf punycode
+	 * @param {String} input The string of Unicode symbols.
+	 * @returns {String} The resulting Punycode string of ASCII-only symbols.
+	 */
+	function encode(input) {
+		var n,
+		    delta,
+		    handledCPCount,
+		    basicLength,
+		    bias,
+		    j,
+		    m,
+		    q,
+		    k,
+		    t,
+		    currentValue,
+		    output = [],
+		    /** `inputLength` will hold the number of code points in `input`. */
+		    inputLength,
+		    /** Cached calculation results */
+		    handledCPCountPlusOne,
+		    baseMinusT,
+		    qMinusT;
+
+		// Convert the input in UCS-2 to Unicode
+		input = ucs2decode(input);
+
+		// Cache the length
+		inputLength = input.length;
+
+		// Initialize the state
+		n = initialN;
+		delta = 0;
+		bias = initialBias;
+
+		// Handle the basic code points
+		for (j = 0; j < inputLength; ++j) {
+			currentValue = input[j];
+			if (currentValue < 0x80) {
+				output.push(stringFromCharCode(currentValue));
+			}
+		}
+
+		handledCPCount = basicLength = output.length;
+
+		// `handledCPCount` is the number of code points that have been handled;
+		// `basicLength` is the number of basic code points.
+
+		// Finish the basic string - if it is not empty - with a delimiter
+		if (basicLength) {
+			output.push(delimiter);
+		}
+
+		// Main encoding loop:
+		while (handledCPCount < inputLength) {
+
+			// All non-basic code points < n have been handled already. Find the next
+			// larger one:
+			for (m = maxInt, j = 0; j < inputLength; ++j) {
+				currentValue = input[j];
+				if (currentValue >= n && currentValue < m) {
+					m = currentValue;
+				}
+			}
+
+			// Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
+			// but guard against overflow
+			handledCPCountPlusOne = handledCPCount + 1;
+			if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
+				error('overflow');
+			}
+
+			delta += (m - n) * handledCPCountPlusOne;
+			n = m;
+
+			for (j = 0; j < inputLength; ++j) {
+				currentValue = input[j];
+
+				if (currentValue < n && ++delta > maxInt) {
+					error('overflow');
+				}
+
+				if (currentValue == n) {
+					// Represent delta as a generalized variable-length integer
+					for (q = delta, k = base; /* no condition */; k += base) {
+						t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
+						if (q < t) {
+							break;
+						}
+						qMinusT = q - t;
+						baseMinusT = base - t;
+						output.push(
+							stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
+						);
+						q = floor(qMinusT / baseMinusT);
+					}
+
+					output.push(stringFromCharCode(digitToBasic(q, 0)));
+					bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
+					delta = 0;
+					++handledCPCount;
+				}
+			}
+
+			++delta;
+			++n;
+
+		}
+		return output.join('');
+	}
+
+	/**
+	 * Converts a Punycode string representing a domain name to Unicode. Only the
+	 * Punycoded parts of the domain name will be converted, i.e. it doesn't
+	 * matter if you call it on a string that has already been converted to
+	 * Unicode.
+	 * @memberOf punycode
+	 * @param {String} domain The Punycode domain name to convert to Unicode.
+	 * @returns {String} The Unicode representation of the given Punycode
+	 * string.
+	 */
+	function toUnicode(domain) {
+		return mapDomain(domain, function(string) {
+			return regexPunycode.test(string)
+				? decode(string.slice(4).toLowerCase())
+				: string;
+		});
+	}
+
+	/**
+	 * Converts a Unicode string representing a domain name to Punycode. Only the
+	 * non-ASCII parts of the domain name will be converted, i.e. it doesn't
+	 * matter if you call it with a domain that's already in ASCII.
+	 * @memberOf punycode
+	 * @param {String} domain The domain name to convert, as a Unicode string.
+	 * @returns {String} The Punycode representation of the given domain name.
+	 */
+	function toASCII(domain) {
+		return mapDomain(domain, function(string) {
+			return regexNonASCII.test(string)
+				? 'xn--' + encode(string)
+				: string;
+		});
+	}
+
+	/*--------------------------------------------------------------------------*/
+
+	/** Define the public API */
+	punycode = {
+		/**
+		 * A string representing the current Punycode.js version number.
+		 * @memberOf punycode
+		 * @type String
+		 */
+		'version': '1.2.4',
+		/**
+		 * An object of methods to convert from JavaScript's internal character
+		 * representation (UCS-2) to Unicode code points, and back.
+		 * @see <http://mathiasbynens.be/notes/javascript-encoding>
+		 * @memberOf punycode
+		 * @type Object
+		 */
+		'ucs2': {
+			'decode': ucs2decode,
+			'encode': ucs2encode
+		},
+		'decode': decode,
+		'encode': encode,
+		'toASCII': toASCII,
+		'toUnicode': toUnicode
+	};
+
+	/** Expose `punycode` */
+	// Some AMD build optimizers, like r.js, check for specific condition patterns
+	// like the following:
+	if (
+		typeof define == 'function' &&
+		typeof define.amd == 'object' &&
+		define.amd
+	) {
+		define('punycode', function() {
+			return punycode;
+		});
+	} else if (freeExports && !freeExports.nodeType) {
+		if (freeModule) { // in Node.js or RingoJS v0.8.0+
+			freeModule.exports = punycode;
+		} else { // in Narwhal or RingoJS v0.7.0-
+			for (key in punycode) {
+				punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]);
+			}
+		}
+	} else { // in Rhino or a web browser
+		root.punycode = punycode;
+	}
+
+}(this));
+
+}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {});
+},{}],2:[function(_dereq_,module,exports){
+var log = _dereq_('./log');
+
+function restoreOwnerScroll(ownerDocument, x, y) {
+    if (ownerDocument.defaultView && (x !== ownerDocument.defaultView.pageXOffset || y !== ownerDocument.defaultView.pageYOffset)) {
+        ownerDocument.defaultView.scrollTo(x, y);
+    }
+}
+
+function cloneCanvasContents(canvas, clonedCanvas) {
+    try {
+        if (clonedCanvas) {
+            clonedCanvas.width = canvas.width;
+            clonedCanvas.height = canvas.height;
+            clonedCanvas.getContext("2d").putImageData(canvas.getContext("2d").getImageData(0, 0, canvas.width, canvas.height), 0, 0);
+        }
+    } catch(e) {
+        log("Unable to copy canvas content from", canvas, e);
+    }
+}
+
+function cloneNode(node, javascriptEnabled) {
+    var clone = node.nodeType === 3 ? document.createTextNode(node.nodeValue) : node.cloneNode(false);
+
+    var child = node.firstChild;
+    while(child) {
+        if (javascriptEnabled === true || child.nodeType !== 1 || child.nodeName !== 'SCRIPT') {
+            clone.appendChild(cloneNode(child, javascriptEnabled));
+        }
+        child = child.nextSibling;
+    }
+
+    if (node.nodeType === 1) {
+        clone._scrollTop = node.scrollTop;
+        clone._scrollLeft = node.scrollLeft;
+        if (node.nodeName === "CANVAS") {
+            cloneCanvasContents(node, clone);
+        } else if (node.nodeName === "TEXTAREA" || node.nodeName === "SELECT") {
+            clone.value = node.value;
+        }
+    }
+
+    return clone;
+}
+
+function initNode(node) {
+    if (node.nodeType === 1) {
+        node.scrollTop = node._scrollTop;
+        node.scrollLeft = node._scrollLeft;
+
+        var child = node.firstChild;
+        while(child) {
+            initNode(child);
+            child = child.nextSibling;
+        }
+    }
+}
+
+module.exports = function(ownerDocument, containerDocument, width, height, options, x ,y) {
+    var documentElement = cloneNode(ownerDocument.documentElement, options.javascriptEnabled);
+    var container = containerDocument.createElement("iframe");
+
+    container.className = "html2canvas-container";
+    container.style.visibility = "hidden";
+    container.style.position = "fixed";
+    container.style.left = "-10000px";
+    container.style.top = "0px";
+    container.style.border = "0";
+    container.width = width;
+    container.height = height;
+    container.scrolling = "no"; // ios won't scroll without it
+    containerDocument.body.appendChild(container);
+
+    return new Promise(function(resolve) {
+        var documentClone = container.contentWindow.document;
+
+        /* Chrome doesn't detect relative background-images assigned in inline <style> sheets when fetched through getComputedStyle
+         if window url is about:blank, we can assign the url to current by writing onto the document
+         */
+        container.contentWindow.onload = container.onload = function() {
+            var interval = setInterval(function() {
+                if (documentClone.body.childNodes.length > 0) {
+                    initNode(documentClone.documentElement);
+                    clearInterval(interval);
+                    if (options.type === "view") {
+                        container.contentWindow.scrollTo(x, y);
+                        if ((/(iPad|iPhone|iPod)/g).test(navigator.userAgent) && (container.contentWindow.scrollY !== y || container.contentWindow.scrollX !== x)) {
+                            documentClone.documentElement.style.top = (-y) + "px";
+                            documentClone.documentElement.style.left = (-x) + "px";
+                            documentClone.documentElement.style.position = 'absolute';
+                        }
+                    }
+                    resolve(container);
+                }
+            }, 50);
+        };
+
+        documentClone.open();
+        documentClone.write("<!DOCTYPE html><html></html>");
+        // Chrome scrolls the parent document for some reason after the write to the cloned window???
+        restoreOwnerScroll(ownerDocument, x, y);
+        documentClone.replaceChild(documentClone.adoptNode(documentElement), documentClone.documentElement);
+        documentClone.close();
+    });
+};
+
+},{"./log":13}],3:[function(_dereq_,module,exports){
+// http://dev.w3.org/csswg/css-color/
+
+function Color(value) {
+    this.r = 0;
+    this.g = 0;
+    this.b = 0;
+    this.a = null;
+    var result = this.fromArray(value) ||
+        this.namedColor(value) ||
+        this.rgb(value) ||
+        this.rgba(value) ||
+        this.hex6(value) ||
+        this.hex3(value);
+}
+
+Color.prototype.darken = function(amount) {
+    var a = 1 - amount;
+    return  new Color([
+        Math.round(this.r * a),
+        Math.round(this.g * a),
+        Math.round(this.b * a),
+        this.a
+    ]);
+};
+
+Color.prototype.isTransparent = function() {
+    return this.a === 0;
+};
+
+Color.prototype.isBlack = function() {
+    return this.r === 0 && this.g === 0 && this.b === 0;
+};
+
+Color.prototype.fromArray = function(array) {
+    if (Array.isArray(array)) {
+        this.r = Math.min(array[0], 255);
+        this.g = Math.min(array[1], 255);
+        this.b = Math.min(array[2], 255);
+        if (array.length > 3) {
+            this.a = array[3];
+        }
+    }
+
+    return (Array.isArray(array));
+};
+
+var _hex3 = /^#([a-f0-9]{3})$/i;
+
+Color.prototype.hex3 = function(value) {
+    var match = null;
+    if ((match = value.match(_hex3)) !== null) {
+        this.r = parseInt(match[1][0] + match[1][0], 16);
+        this.g = parseInt(match[1][1] + match[1][1], 16);
+        this.b = parseInt(match[1][2] + match[1][2], 16);
+    }
+    return match !== null;
+};
+
+var _hex6 = /^#([a-f0-9]{6})$/i;
+
+Color.prototype.hex6 = function(value) {
+    var match = null;
+    if ((match = value.match(_hex6)) !== null) {
+        this.r = parseInt(match[1].substring(0, 2), 16);
+        this.g = parseInt(match[1].substring(2, 4), 16);
+        this.b = parseInt(match[1].substring(4, 6), 16);
+    }
+    return match !== null;
+};
+
+
+var _rgb = /^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/;
+
+Color.prototype.rgb = function(value) {
+    var match = null;
+    if ((match = value.match(_rgb)) !== null) {
+        this.r = Number(match[1]);
+        this.g = Number(match[2]);
+        this.b = Number(match[3]);
+    }
+    return match !== null;
+};
+
+var _rgba = /^rgba\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d?\.?\d+)\s*\)$/;
+
+Color.prototype.rgba = function(value) {
+    var match = null;
+    if ((match = value.match(_rgba)) !== null) {
+        this.r = Number(match[1]);
+        this.g = Number(match[2]);
+        this.b = Number(match[3]);
+        this.a = Number(match[4]);
+    }
+    return match !== null;
+};
+
+Color.prototype.toString = function() {
+    return this.a !== null && this.a !== 1 ?
+    "rgba(" + [this.r, this.g, this.b, this.a].join(",") + ")" :
+    "rgb(" + [this.r, this.g, this.b].join(",") + ")";
+};
+
+Color.prototype.namedColor = function(value) {
+    value = value.toLowerCase();
+    var color = colors[value];
+    if (color) {
+        this.r = color[0];
+        this.g = color[1];
+        this.b = color[2];
+    } else if (value === "transparent") {
+        this.r = this.g = this.b = this.a = 0;
+        return true;
+    }
+
+    return !!color;
+};
+
+Color.prototype.isColor = true;
+
+// 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}, {}))
+var colors = {
+    "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]
+};
+
+module.exports = Color;
+
+},{}],4:[function(_dereq_,module,exports){
+var Support = _dereq_('./support');
+var CanvasRenderer = _dereq_('./renderers/canvas');
+var ImageLoader = _dereq_('./imageloader');
+var NodeParser = _dereq_('./nodeparser');
+var NodeContainer = _dereq_('./nodecontainer');
+var log = _dereq_('./log');
+var utils = _dereq_('./utils');
+var createWindowClone = _dereq_('./clone');
+var loadUrlDocument = _dereq_('./proxy').loadUrlDocument;
+var getBounds = utils.getBounds;
+
+var html2canvasNodeAttribute = "data-html2canvas-node";
+var html2canvasCloneIndex = 0;
+
+function html2canvas(nodeList, options) {
+    var index = html2canvasCloneIndex++;
+    options = options || {};
+    if (options.logging) {
+        log.options.logging = true;
+        log.options.start = Date.now();
+    }
+
+    options.async = typeof(options.async) === "undefined" ? true : options.async;
+    options.allowTaint = typeof(options.allowTaint) === "undefined" ? false : options.allowTaint;
+    options.removeContainer = typeof(options.removeContainer) === "undefined" ? true : options.removeContainer;
+    options.javascriptEnabled = typeof(options.javascriptEnabled) === "undefined" ? false : options.javascriptEnabled;
+    options.imageTimeout = typeof(options.imageTimeout) === "undefined" ? 10000 : options.imageTimeout;
+    options.renderer = typeof(options.renderer) === "function" ? options.renderer : CanvasRenderer;
+    options.strict = !!options.strict;
+
+    if (typeof(nodeList) === "string") {
+        if (typeof(options.proxy) !== "string") {
+            return Promise.reject("Proxy must be used when rendering url");
+        }
+        var width = options.width != null ? options.width : window.innerWidth;
+        var height = options.height != null ? options.height : window.innerHeight;
+        return loadUrlDocument(absoluteUrl(nodeList), options.proxy, document, width, height, options).then(function(container) {
+            return renderWindow(container.contentWindow.document.documentElement, container, options, width, height);
+        });
+    }
+
+    var node = ((nodeList === undefined) ? [document.documentElement] : ((nodeList.length) ? nodeList : [nodeList]))[0];
+    node.setAttribute(html2canvasNodeAttribute + index, index);
+    return renderDocument(node.ownerDocument, options, node.ownerDocument.defaultView.innerWidth, node.ownerDocument.defaultView.innerHeight, index).then(function(canvas) {
+        if (typeof(options.onrendered) === "function") {
+            log("options.onrendered is deprecated, html2canvas returns a Promise containing the canvas");
+            options.onrendered(canvas);
+        }
+        return canvas;
+    });
+}
+
+html2canvas.CanvasRenderer = CanvasRenderer;
+html2canvas.NodeContainer = NodeContainer;
+html2canvas.log = log;
+html2canvas.utils = utils;
+
+var html2canvasExport = (typeof(document) === "undefined" || typeof(Object.create) !== "function" || typeof(document.createElement("canvas").getContext) !== "function") ? function() {
+    return Promise.reject("No canvas support");
+} : html2canvas;
+
+module.exports = html2canvasExport;
+
+if (typeof(define) === 'function' && define.amd) {
+    define('html2canvas', [], function() {
+        return html2canvasExport;
+    });
+}
+
+function renderDocument(document, options, windowWidth, windowHeight, html2canvasIndex) {
+    return createWindowClone(document, document, windowWidth, windowHeight, options, document.defaultView.pageXOffset, document.defaultView.pageYOffset).then(function(container) {
+        log("Document cloned");
+        var attributeName = html2canvasNodeAttribute + html2canvasIndex;
+        var selector = "[" + attributeName + "='" + html2canvasIndex + "']";
+        document.querySelector(selector).removeAttribute(attributeName);
+        var clonedWindow = container.contentWindow;
+        var node = clonedWindow.document.querySelector(selector);
+        var oncloneHandler = (typeof(options.onclone) === "function") ? Promise.resolve(options.onclone(clonedWindow.document)) : Promise.resolve(true);
+        return oncloneHandler.then(function() {
+            return renderWindow(node, container, options, windowWidth, windowHeight);
+        });
+    });
+}
+
+function renderWindow(node, container, options, windowWidth, windowHeight) {
+    var clonedWindow = container.contentWindow;
+    var support = new Support(clonedWindow.document);
+    var imageLoader = new ImageLoader(options, support);
+    var bounds = getBounds(node);
+    var width = options.type === "view" ? windowWidth : documentWidth(clonedWindow.document);
+    var height = options.type === "view" ? windowHeight : documentHeight(clonedWindow.document);
+    var renderer = new options.renderer(width, height, imageLoader, options, document);
+    var parser = new NodeParser(node, renderer, support, imageLoader, options);
+    return parser.ready.then(function() {
+        log("Finished rendering");
+        var canvas;
+
+        if (options.type === "view") {
+            canvas = crop(renderer.canvas, {width: renderer.canvas.width, height: renderer.canvas.height, top: 0, left: 0, x: 0, y: 0});
+        } else if (node === clonedWindow.document.body || node === clonedWindow.document.documentElement || options.canvas != null) {
+            canvas = renderer.canvas;
+        } else {
+            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});
+        }
+
+        cleanupContainer(container, options);
+        return canvas;
+    });
+}
+
+function cleanupContainer(container, options) {
+    if (options.removeContainer) {
+        container.parentNode.removeChild(container);
+        log("Cleaned up container");
+    }
+}
+
+function crop(canvas, bounds) {
+    var croppedCanvas = document.createElement("canvas");
+    var x1 = Math.min(canvas.width - 1, Math.max(0, bounds.left));
+    var x2 = Math.min(canvas.width, Math.max(1, bounds.left + bounds.width));
+    var y1 = Math.min(canvas.height - 1, Math.max(0, bounds.top));
+    var y2 = Math.min(canvas.height, Math.max(1, bounds.top + bounds.height));
+    croppedCanvas.width = bounds.width;
+    croppedCanvas.height =  bounds.height;
+    var width = x2-x1;
+    var height = y2-y1;
+    log("Cropping canvas at:", "left:", bounds.left, "top:", bounds.top, "width:", width, "height:", height);
+    log("Resulting crop with width", bounds.width, "and height", bounds.height, "with x", x1, "and y", y1);
+    croppedCanvas.getContext("2d").drawImage(canvas, x1, y1, width, height, bounds.x, bounds.y, width, height);
+    return croppedCanvas;
+}
+
+function documentWidth (doc) {
+    return Math.max(
+        Math.max(doc.body.scrollWidth, doc.documentElement.scrollWidth),
+        Math.max(doc.body.offsetWidth, doc.documentElement.offsetWidth),
+        Math.max(doc.body.clientWidth, doc.documentElement.clientWidth)
+    );
+}
+
+function documentHeight (doc) {
+    return Math.max(
+        Math.max(doc.body.scrollHeight, doc.documentElement.scrollHeight),
+        Math.max(doc.body.offsetHeight, doc.documentElement.offsetHeight),
+        Math.max(doc.body.clientHeight, doc.documentElement.clientHeight)
+    );
+}
+
+function absoluteUrl(url) {
+    var link = document.createElement("a");
+    link.href = url;
+    link.href = link.href;
+    return link;
+}
+
+},{"./clone":2,"./imageloader":11,"./log":13,"./nodecontainer":14,"./nodeparser":15,"./proxy":16,"./renderers/canvas":20,"./support":22,"./utils":26}],5:[function(_dereq_,module,exports){
+var log = _dereq_('./log');
+var smallImage = _dereq_('./utils').smallImage;
+
+function DummyImageContainer(src) {
+    this.src = src;
+    log("DummyImageContainer for", src);
+    if (!this.promise || !this.image) {
+        log("Initiating DummyImageContainer");
+        DummyImageContainer.prototype.image = new Image();
+        var image = this.image;
+        DummyImageContainer.prototype.promise = new Promise(function(resolve, reject) {
+            image.onload = resolve;
+            image.onerror = reject;
+            image.src = smallImage();
+            if (image.complete === true) {
+                resolve(image);
+            }
+        });
+    }
+}
+
+module.exports = DummyImageContainer;
+
+},{"./log":13,"./utils":26}],6:[function(_dereq_,module,exports){
+var smallImage = _dereq_('./utils').smallImage;
+
+function Font(family, size) {
+    var container = document.createElement('div'),
+        img = document.createElement('img'),
+        span = document.createElement('span'),
+        sampleText = 'Hidden Text',
+        baseline,
+        middle;
+
+    container.style.visibility = "hidden";
+    container.style.fontFamily = family;
+    container.style.fontSize = size;
+    container.style.margin = 0;
+    container.style.padding = 0;
+
+    document.body.appendChild(container);
+
+    img.src = smallImage();
+    img.width = 1;
+    img.height = 1;
+
+    img.style.margin = 0;
+    img.style.padding = 0;
+    img.style.verticalAlign = "baseline";
+
+    span.style.fontFamily = family;
+    span.style.fontSize = size;
+    span.style.margin = 0;
+    span.style.padding = 0;
+
+    span.appendChild(document.createTextNode(sampleText));
+    container.appendChild(span);
+    container.appendChild(img);
+    baseline = (img.offsetTop - span.offsetTop) + 1;
+
+    container.removeChild(span);
+    container.appendChild(document.createTextNode(sampleText));
+
+    container.style.lineHeight = "normal";
+    img.style.verticalAlign = "super";
+
+    middle = (img.offsetTop-container.offsetTop) + 1;
+
+    document.body.removeChild(container);
+
+    this.baseline = baseline;
+    this.lineWidth = 1;
+    this.middle = middle;
+}
+
+module.exports = Font;
+
+},{"./utils":26}],7:[function(_dereq_,module,exports){
+var Font = _dereq_('./font');
+
+function FontMetrics() {
+    this.data = {};
+}
+
+FontMetrics.prototype.getMetrics = function(family, size) {
+    if (this.data[family + "-" + size] === undefined) {
+        this.data[family + "-" + size] = new Font(family, size);
+    }
+    return this.data[family + "-" + size];
+};
+
+module.exports = FontMetrics;
+
+},{"./font":6}],8:[function(_dereq_,module,exports){
+var utils = _dereq_('./utils');
+var getBounds = utils.getBounds;
+var loadUrlDocument = _dereq_('./proxy').loadUrlDocument;
+
+function FrameContainer(container, sameOrigin, options) {
+    this.image = null;
+    this.src = container;
+    var self = this;
+    var bounds = getBounds(container);
+    this.promise = (!sameOrigin ? this.proxyLoad(options.proxy, bounds, options) : new Promise(function(resolve) {
+        if (container.contentWindow.document.URL === "about:blank" || container.contentWindow.document.documentElement == null) {
+            container.contentWindow.onload = container.onload = function() {
+                resolve(container);
+            };
+        } else {
+            resolve(container);
+        }
+    })).then(function(container) {
+        var html2canvas = _dereq_('./core');
+        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});
+    }).then(function(canvas) {
+        return self.image = canvas;
+    });
+}
+
+FrameContainer.prototype.proxyLoad = function(proxy, bounds, options) {
+    var container = this.src;
+    return loadUrlDocument(container.src, proxy, container.ownerDocument, bounds.width, bounds.height, options);
+};
+
+module.exports = FrameContainer;
+
+},{"./core":4,"./proxy":16,"./utils":26}],9:[function(_dereq_,module,exports){
+function GradientContainer(imageData) {
+    this.src = imageData.value;
+    this.colorStops = [];
+    this.type = null;
+    this.x0 = 0.5;
+    this.y0 = 0.5;
+    this.x1 = 0.5;
+    this.y1 = 0.5;
+    this.promise = Promise.resolve(true);
+}
+
+GradientContainer.TYPES = {
+    LINEAR: 1,
+    RADIAL: 2
+};
+
+// TODO: support hsl[a], negative %/length values
+// TODO: support <angle> (e.g. -?\d{1,3}(?:\.\d+)deg, etc. : https://developer.mozilla.org/docs/Web/CSS/angle )
+GradientContainer.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;
+
+module.exports = GradientContainer;
+
+},{}],10:[function(_dereq_,module,exports){
+function ImageContainer(src, cors) {
+    this.src = src;
+    this.image = new Image();
+    var self = this;
+    this.tainted = null;
+    this.promise = new Promise(function(resolve, reject) {
+        self.image.onload = resolve;
+        self.image.onerror = reject;
+        if (cors) {
+            self.image.crossOrigin = "anonymous";
+        }
+        self.image.src = src;
+        if (self.image.complete === true) {
+            resolve(self.image);
+        }
+    });
+}
+
+module.exports = ImageContainer;
+
+},{}],11:[function(_dereq_,module,exports){
+var log = _dereq_('./log');
+var ImageContainer = _dereq_('./imagecontainer');
+var DummyImageContainer = _dereq_('./dummyimagecontainer');
+var ProxyImageContainer = _dereq_('./proxyimagecontainer');
+var FrameContainer = _dereq_('./framecontainer');
+var SVGContainer = _dereq_('./svgcontainer');
+var SVGNodeContainer = _dereq_('./svgnodecontainer');
+var LinearGradientContainer = _dereq_('./lineargradientcontainer');
+var WebkitGradientContainer = _dereq_('./webkitgradientcontainer');
+var bind = _dereq_('./utils').bind;
+
+function ImageLoader(options, support) {
+    this.link = null;
+    this.options = options;
+    this.support = support;
+    this.origin = this.getOrigin(window.location.href);
+}
+
+ImageLoader.prototype.findImages = function(nodes) {
+    var images = [];
+    nodes.reduce(function(imageNodes, container) {
+        switch(container.node.nodeName) {
+        case "IMG":
+            return imageNodes.concat([{
+                args: [container.node.src],
+                method: "url"
+            }]);
+        case "svg":
+        case "IFRAME":
+            return imageNodes.concat([{
+                args: [container.node],
+                method: container.node.nodeName
+            }]);
+        }
+        return imageNodes;
+    }, []).forEach(this.addImage(images, this.loadImage), this);
+    return images;
+};
+
+ImageLoader.prototype.findBackgroundImage = function(images, container) {
+    container.parseBackgroundImages().filter(this.hasImageBackground).forEach(this.addImage(images, this.loadImage), this);
+    return images;
+};
+
+ImageLoader.prototype.addImage = function(images, callback) {
+    return function(newImage) {
+        newImage.args.forEach(function(image) {
+            if (!this.imageExists(images, image)) {
+                images.splice(0, 0, callback.call(this, newImage));
+                log('Added image #' + (images.length), typeof(image) === "string" ? image.substring(0, 100) : image);
+            }
+        }, this);
+    };
+};
+
+ImageLoader.prototype.hasImageBackground = function(imageData) {
+    return imageData.method !== "none";
+};
+
+ImageLoader.prototype.loadImage = function(imageData) {
+    if (imageData.method === "url") {
+        var src = imageData.args[0];
+        if (this.isSVG(src) && !this.support.svg && !this.options.allowTaint) {
+            return new SVGContainer(src);
+        } else if (src.match(/data:image\/.*;base64,/i)) {
+            return new ImageContainer(src.replace(/url\(['"]{0,}|['"]{0,}\)$/ig, ''), false);
+        } else if (this.isSameOrigin(src) || this.options.allowTaint === true || this.isSVG(src)) {
+            return new ImageContainer(src, false);
+        } else if (this.support.cors && !this.options.allowTaint && this.options.useCORS) {
+            return new ImageContainer(src, true);
+        } else if (this.options.proxy) {
+            return new ProxyImageContainer(src, this.options.proxy);
+        } else {
+            return new DummyImageContainer(src);
+        }
+    } else if (imageData.method === "linear-gradient") {
+        return new LinearGradientContainer(imageData);
+    } else if (imageData.method === "gradient") {
+        return new WebkitGradientContainer(imageData);
+    } else if (imageData.method === "svg") {
+        return new SVGNodeContainer(imageData.args[0], this.support.svg);
+    } else if (imageData.method === "IFRAME") {
+        return new FrameContainer(imageData.args[0], this.isSameOrigin(imageData.args[0].src), this.options);
+    } else {
+        return new DummyImageContainer(imageData);
+    }
+};
+
+ImageLoader.prototype.isSVG = function(src) {
+    return src.substring(src.length - 3).toLowerCase() === "svg" || SVGContainer.prototype.isInline(src);
+};
+
+ImageLoader.prototype.imageExists = function(images, src) {
+    return images.some(function(image) {
+        return image.src === src;
+    });
+};
+
+ImageLoader.prototype.isSameOrigin = function(url) {
+    return (this.getOrigin(url) === this.origin);
+};
+
+ImageLoader.prototype.getOrigin = function(url) {
+    var link = this.link || (this.link = document.createElement("a"));
+    link.href = url;
+    link.href = link.href; // IE9, LOL! - http://jsfiddle.net/niklasvh/2e48b/
+    return link.protocol + link.hostname + link.port;
+};
+
+ImageLoader.prototype.getPromise = function(container) {
+    return this.timeout(container, this.options.imageTimeout)['catch'](function() {
+        var dummy = new DummyImageContainer(container.src);
+        return dummy.promise.then(function(image) {
+            container.image = image;
+        });
+    });
+};
+
+ImageLoader.prototype.get = function(src) {
+    var found = null;
+    return this.images.some(function(img) {
+        return (found = img).src === src;
+    }) ? found : null;
+};
+
+ImageLoader.prototype.fetch = function(nodes) {
+    this.images = nodes.reduce(bind(this.findBackgroundImage, this), this.findImages(nodes));
+    this.images.forEach(function(image, index) {
+        image.promise.then(function() {
+            log("Succesfully loaded image #"+ (index+1), image);
+        }, function(e) {
+            log("Failed loading image #"+ (index+1), image, e);
+        });
+    });
+    this.ready = Promise.all(this.images.map(this.getPromise, this));
+    log("Finished searching images");
+    return this;
+};
+
+ImageLoader.prototype.timeout = function(container, timeout) {
+    var timer;
+    var promise = Promise.race([container.promise, new Promise(function(res, reject) {
+        timer = setTimeout(function() {
+            log("Timed out loading image", container);
+            reject(container);
+        }, timeout);
+    })]).then(function(container) {
+        clearTimeout(timer);
+        return container;
+    });
+    promise['catch'](function() {
+        clearTimeout(timer);
+    });
+    return promise;
+};
+
+module.exports = ImageLoader;
+
+},{"./dummyimagecontainer":5,"./framecontainer":8,"./imagecontainer":10,"./lineargradientcontainer":12,"./log":13,"./proxyimagecontainer":17,"./svgcontainer":23,"./svgnodecontainer":24,"./utils":26,"./webkitgradientcontainer":27}],12:[function(_dereq_,module,exports){
+var GradientContainer = _dereq_('./gradientcontainer');
+var Color = _dereq_('./color');
+
+function LinearGradientContainer(imageData) {
+    GradientContainer.apply(this, arguments);
+    this.type = GradientContainer.TYPES.LINEAR;
+
+    var hasDirection = LinearGradientContainer.REGEXP_DIRECTION.test( imageData.args[0] ) ||
+        !GradientContainer.REGEXP_COLORSTOP.test( imageData.args[0] );
+
+    if (hasDirection) {
+        imageData.args[0].split(/\s+/).reverse().forEach(function(position, index) {
+            switch(position) {
+            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 y0 = this.y0;
+                var x0 = this.x0;
+                this.y0 = this.y1;
+                this.x0 = this.x1;
+                this.x1 = x0;
+                this.y1 = y0;
+                break;
+            case "center":
+                break; // centered by default
+            // Firefox internally converts position keywords to percentages:
+            // http://www.w3.org/TR/2010/WD-CSS2-20101207/colors.html#propdef-background-position
+            default: // percentage or absolute length
+                // TODO: support absolute start point positions (e.g., use bounds to convert px to a ratio)
+                var ratio = parseFloat(position, 10) * 1e-2;
+                if (isNaN(ratio)) { // invalid or unhandled value
+                    break;
+                }
+                if (index === 0) {
+                    this.y0 = ratio;
+                    this.y1 = 1 - this.y0;
+                } else {
+                    this.x0 = ratio;
+                    this.x1 = 1 - this.x0;
+                }
+                break;
+            }
+        }, this);
+    } else {
+        this.y0 = 0;
+        this.y1 = 1;
+    }
+
+    this.colorStops = imageData.args.slice(hasDirection ? 1 : 0).map(function(colorStop) {
+        var colorStopMatch = colorStop.match(GradientContainer.REGEXP_COLORSTOP);
+        var value = +colorStopMatch[2];
+        var unit = value === 0 ? "%" : colorStopMatch[3]; // treat "0" as "0%"
+        return {
+            color: new Color(colorStopMatch[1]),
+            // TODO: support absolute stop positions (e.g., compute gradient line length & convert px to ratio)
+            stop: unit === "%" ? value / 100 : null
+        };
+    });
+
+    if (this.colorStops[0].stop === null) {
+        this.colorStops[0].stop = 0;
+    }
+
+    if (this.colorStops[this.colorStops.length - 1].stop === null) {
+        this.colorStops[this.colorStops.length - 1].stop = 1;
+    }
+
+    // calculates and fills-in explicit stop positions when omitted from rule
+    this.colorStops.forEach(function(colorStop, index) {
+        if (colorStop.stop === null) {
+            this.colorStops.slice(index).some(function(find, count) {
+                if (find.stop !== null) {
+                    colorStop.stop = ((find.stop - this.colorStops[index - 1].stop) / (count + 1)) + this.colorStops[index - 1].stop;
+                    return true;
+                } else {
+                    return false;
+                }
+            }, this);
+        }
+    }, this);
+}
+
+LinearGradientContainer.prototype = Object.create(GradientContainer.prototype);
+
+// TODO: support <angle> (e.g. -?\d{1,3}(?:\.\d+)deg, etc. : https://developer.mozilla.org/docs/Web/CSS/angle )
+LinearGradientContainer.REGEXP_DIRECTION = /^\s*(?:to|left|right|top|bottom|center|\d{1,3}(?:\.\d+)?%?)(?:\s|$)/i;
+
+module.exports = LinearGradientContainer;
+
+},{"./color":3,"./gradientcontainer":9}],13:[function(_dereq_,module,exports){
+var logger = function() {
+    if (logger.options.logging && window.console && window.console.log) {
+        Function.prototype.bind.call(window.console.log, (window.console)).apply(window.console, [(Date.now() - logger.options.start) + "ms", "html2canvas:"].concat([].slice.call(arguments, 0)));
+    }
+};
+
+logger.options = {logging: false};
+module.exports = logger;
+
+},{}],14:[function(_dereq_,module,exports){
+var Color = _dereq_('./color');
+var utils = _dereq_('./utils');
+var getBounds = utils.getBounds;
+var parseBackgrounds = utils.parseBackgrounds;
+var offsetBounds = utils.offsetBounds;
+
+function NodeContainer(node, parent) {
+    this.node = node;
+    this.parent = parent;
+    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 = false;
+    this.opacity = null;
+}
+
+NodeContainer.prototype.cloneTo = function(stack) {
+    stack.visible = this.visible;
+    stack.borders = this.borders;
+    stack.bounds = this.bounds;
+    stack.clip = this.clip;
+    stack.backgroundClip = this.backgroundClip;
+    stack.computedStyles = this.computedStyles;
+    stack.styles = this.styles;
+    stack.backgroundImages = this.backgroundImages;
+    stack.opacity = this.opacity;
+};
+
+NodeContainer.prototype.getOpacity = function() {
+    return this.opacity === null ? (this.opacity = this.cssFloat('opacity')) : this.opacity;
+};
+
+NodeContainer.prototype.assignStack = function(stack) {
+    this.stack = stack;
+    stack.children.push(this);
+};
+
+NodeContainer.prototype.isElementVisible = function() {
+    return this.node.nodeType === Node.TEXT_NODE ? this.parent.visible : (
+        this.css('display') !== "none" &&
+        this.css('visibility') !== "hidden" &&
+        !this.node.hasAttribute("data-html2canvas-ignore") &&
+        (this.node.nodeName !== "INPUT" || this.node.getAttribute("type") !== "hidden")
+    );
+};
+
+NodeContainer.prototype.css = function(attribute) {
+    if (!this.computedStyles) {
+        this.computedStyles = this.isPseudoElement ? this.parent.computedStyle(this.before ? ":before" : ":after") : this.computedStyle(null);
+    }
+
+    return this.styles[attribute] || (this.styles[attribute] = this.computedStyles[attribute]);
+};
+
+NodeContainer.prototype.prefixedCss = function(attribute) {
+    var prefixes = ["webkit", "moz", "ms", "o"];
+    var value = this.css(attribute);
+    if (value === undefined) {
+        prefixes.some(function(prefix) {
+            value = this.css(prefix + attribute.substr(0, 1).toUpperCase() + attribute.substr(1));
+            return value !== undefined;
+        }, this);
+    }
+    return value === undefined ? null : value;
+};
+
+NodeContainer.prototype.computedStyle = function(type) {
+    return this.node.ownerDocument.defaultView.getComputedStyle(this.node, type);
+};
+
+NodeContainer.prototype.cssInt = function(attribute) {
+    var value = parseInt(this.css(attribute), 10);
+    return (isNaN(value)) ? 0 : value; // borders in old IE are throwing 'medium' for demo.html
+};
+
+NodeContainer.prototype.color = function(attribute) {
+    return this.colors[attribute] || (this.colors[attribute] = new Color(this.css(attribute)));
+};
+
+NodeContainer.prototype.cssFloat = function(attribute) {
+    var value = parseFloat(this.css(attribute));
+    return (isNaN(value)) ? 0 : value;
+};
+
+NodeContainer.prototype.fontWeight = function() {
+    var weight = this.css("fontWeight");
+    switch(parseInt(weight, 10)){
+    case 401:
+        weight = "bold";
+        break;
+    case 400:
+        weight = "normal";
+        break;
+    }
+    return weight;
+};
+
+NodeContainer.prototype.parseClip = function() {
+    var matches = this.css('clip').match(this.CLIP);
+    if (matches) {
+        return {
+            top: parseInt(matches[1], 10),
+            right: parseInt(matches[2], 10),
+            bottom: parseInt(matches[3], 10),
+            left: parseInt(matches[4], 10)
+        };
+    }
+    return null;
+};
+
+NodeContainer.prototype.parseBackgroundImages = function() {
+    return this.backgroundImages || (this.backgroundImages = parseBackgrounds(this.css("backgroundImage")));
+};
+
+NodeContainer.prototype.cssList = function(property, index) {
+    var value = (this.css(property) || '').split(',');
+    value = value[index || 0] || value[0] || 'auto';
+    value = value.trim().split(' ');
+    if (value.length === 1) {
+        value = [value[0], isPercentage(value[0]) ? 'auto' : value[0]];
+    }
+    return value;
+};
+
+NodeContainer.prototype.parseBackgroundSize = function(bounds, image, index) {
+    var size = this.cssList("backgroundSize", index);
+    var width, height;
+
+    if (isPercentage(size[0])) {
+        width = bounds.width * parseFloat(size[0]) / 100;
+    } else if (/contain|cover/.test(size[0])) {
+        var targetRatio = bounds.width / bounds.height, currentRatio = image.width / image.height;
+        return (targetRatio < currentRatio ^ size[0] === 'contain') ?  {width: bounds.height * currentRatio, height: bounds.height} : {width: bounds.width, height: bounds.width / currentRatio};
+    } else {
+        width = parseInt(size[0], 10);
+    }
+
+    if (size[0] === 'auto' && size[1] === 'auto') {
+        height = image.height;
+    } else if (size[1] === 'auto') {
+        height = width / image.width * image.height;
+    } else if (isPercentage(size[1])) {
+        height =  bounds.height * parseFloat(size[1]) / 100;
+    } else {
+        height = parseInt(size[1], 10);
+    }
+
+    if (size[0] === 'auto') {
+        width = height / image.height * image.width;
+    }
+
+    return {width: width, height: height};
+};
+
+NodeContainer.prototype.parseBackgroundPosition = function(bounds, image, index, backgroundSize) {
+    var position = this.cssList('backgroundPosition', index);
+    var left, top;
+
+    if (isPercentage(position[0])){
+        left = (bounds.width - (backgroundSize || image).width) * (parseFloat(position[0]) / 100);
+    } else {
+        left = parseInt(position[0], 10);
+    }
+
+    if (position[1] === 'auto') {
+        top = left / image.width * image.height;
+    } else if (isPercentage(position[1])){
+        top =  (bounds.height - (backgroundSize || image).height) * parseFloat(position[1]) / 100;
+    } else {
+        top = parseInt(position[1], 10);
+    }
+
+    if (position[0] === 'auto') {
+        left = top / image.height * image.width;
+    }
+
+    return {left: left, top: top};
+};
+
+NodeContainer.prototype.parseBackgroundRepeat = function(index) {
+    return this.cssList("backgroundRepeat", index)[0];
+};
+
+NodeContainer.prototype.parseTextShadows = function() {
+    var textShadow = this.css("textShadow");
+    var results = [];
+
+    if (textShadow && textShadow !== 'none') {
+        var shadows = textShadow.match(this.TEXT_SHADOW_PROPERTY);
+        for (var i = 0; shadows && (i < shadows.length); i++) {
+            var s = shadows[i].match(this.TEXT_SHADOW_VALUES);
+            results.push({
+                color: new Color(s[0]),
+                offsetX: s[1] ? parseFloat(s[1].replace('px', '')) : 0,
+                offsetY: s[2] ? parseFloat(s[2].replace('px', '')) : 0,
+                blur: s[3] ? s[3].replace('px', '') : 0
+            });
+        }
+    }
+    return results;
+};
+
+NodeContainer.prototype.parseTransform = function() {
+    if (!this.transformData) {
+        if (this.hasTransform()) {
+            var offset = this.parseBounds();
+            var origin = this.prefixedCss("transformOrigin").split(" ").map(removePx).map(asFloat);
+            origin[0] += offset.left;
+            origin[1] += offset.top;
+            this.transformData = {
+                origin: origin,
+                matrix: this.parseTransformMatrix()
+            };
+        } else {
+            this.transformData = {
+                origin: [0, 0],
+                matrix: [1, 0, 0, 1, 0, 0]
+            };
+        }
+    }
+    return this.transformData;
+};
+
+NodeContainer.prototype.parseTransformMatrix = function() {
+    if (!this.transformMatrix) {
+        var transform = this.prefixedCss("transform");
+        var matrix = transform ? parseMatrix(transform.match(this.MATRIX_PROPERTY)) : null;
+        this.transformMatrix = matrix ? matrix : [1, 0, 0, 1, 0, 0];
+    }
+    return this.transformMatrix;
+};
+
+NodeContainer.prototype.parseBounds = function() {
+    return this.bounds || (this.bounds = this.hasTransform() ? offsetBounds(this.node) : getBounds(this.node));
+};
+
+NodeContainer.prototype.hasTransform = function() {
+    return this.parseTransformMatrix().join(",") !== "1,0,0,1,0,0" || (this.parent && this.parent.hasTransform());
+};
+
+NodeContainer.prototype.getValue = function() {
+    var value = this.node.value || "";
+    if (this.node.tagName === "SELECT") {
+        value = selectionValue(this.node);
+    } else if (this.node.type === "password") {
+        value = Array(value.length + 1).join('\u2022'); // jshint ignore:line
+    }
+    return value.length === 0 ? (this.node.placeholder || "") : value;
+};
+
+NodeContainer.prototype.MATRIX_PROPERTY = /(matrix|matrix3d)\((.+)\)/;
+NodeContainer.prototype.TEXT_SHADOW_PROPERTY = /((rgba|rgb)\([^\)]+\)(\s-?\d+px){0,})/g;
+NodeContainer.prototype.TEXT_SHADOW_VALUES = /(-?\d+px)|(#.+)|(rgb\(.+\))|(rgba\(.+\))/g;
+NodeContainer.prototype.CLIP = /^rect\((\d+)px,? (\d+)px,? (\d+)px,? (\d+)px\)$/;
+
+function selectionValue(node) {
+    var option = node.options[node.selectedIndex || 0];
+    return option ? (option.text || "") : "";
+}
+
+function parseMatrix(match) {
+    if (match && match[1] === "matrix") {
+        return match[2].split(",").map(function(s) {
+            return parseFloat(s.trim());
+        });
+    } else if (match && match[1] === "matrix3d") {
+        var matrix3d = match[2].split(",").map(function(s) {
+          return parseFloat(s.trim());
+        });
+        return [matrix3d[0], matrix3d[1], matrix3d[4], matrix3d[5], matrix3d[12], matrix3d[13]];
+    }
+}
+
+function isPercentage(value) {
+    return value.toString().indexOf("%") !== -1;
+}
+
+function removePx(str) {
+    return str.replace("px", "");
+}
+
+function asFloat(str) {
+    return parseFloat(str);
+}
+
+module.exports = NodeContainer;
+
+},{"./color":3,"./utils":26}],15:[function(_dereq_,module,exports){
+var log = _dereq_('./log');
+var punycode = _dereq_('punycode');
+var NodeContainer = _dereq_('./nodecontainer');
+var TextContainer = _dereq_('./textcontainer');
+var PseudoElementContainer = _dereq_('./pseudoelementcontainer');
+var FontMetrics = _dereq_('./fontmetrics');
+var Color = _dereq_('./color');
+var StackingContext = _dereq_('./stackingcontext');
+var utils = _dereq_('./utils');
+var bind = utils.bind;
+var getBounds = utils.getBounds;
+var parseBackgrounds = utils.parseBackgrounds;
+var offsetBounds = utils.offsetBounds;
+
+function NodeParser(element, renderer, support, imageLoader, options) {
+    log("Starting NodeParser");
+    this.renderer = renderer;
+    this.options = options;
+    this.range = null;
+    this.support = support;
+    this.renderQueue = [];
+    this.stack = new StackingContext(true, 1, element.ownerDocument, null);
+    var parent = new NodeContainer(element, null);
+    if (options.background) {
+        renderer.rectangle(0, 0, renderer.width, renderer.height, new Color(options.background));
+    }
+    if (element === element.ownerDocument.documentElement) {
+        // http://www.w3.org/TR/css3-background/#special-backgrounds
+        var canvasBackground = new NodeContainer(parent.color('backgroundColor').isTransparent() ? element.ownerDocument.body : element.ownerDocument.documentElement, null);
+        renderer.rectangle(0, 0, renderer.width, renderer.height, canvasBackground.color('backgroundColor'));
+    }
+    parent.visibile = parent.isElementVisible();
+    this.createPseudoHideStyles(element.ownerDocument);
+    this.disableAnimations(element.ownerDocument);
+    this.nodes = flatten([parent].concat(this.getChildren(parent)).filter(function(container) {
+        return container.visible = container.isElementVisible();
+    }).map(this.getPseudoElements, this));
+    this.fontMetrics = new FontMetrics();
+    log("Fetched nodes, total:", this.nodes.length);
+    log("Calculate overflow clips");
+    this.calculateOverflowClips();
+    log("Start fetching images");
+    this.images = imageLoader.fetch(this.nodes.filter(isElement));
+    this.ready = this.images.ready.then(bind(function() {
+        log("Images loaded, starting parsing");
+        log("Creating stacking contexts");
+        this.createStackingContexts();
+        log("Sorting stacking contexts");
+        this.sortStackingContexts(this.stack);
+        this.parse(this.stack);
+        log("Render queue created with " + this.renderQueue.length + " items");
+        return new Promise(bind(function(resolve) {
+            if (!options.async) {
+                this.renderQueue.forEach(this.paint, this);
+                resolve();
+            } else if (typeof(options.async) === "function") {
+                options.async.call(this, this.renderQueue, resolve);
+            } else if (this.renderQueue.length > 0){
+                this.renderIndex = 0;
+                this.asyncRenderer(this.renderQueue, resolve);
+            } else {
+                resolve();
+            }
+        }, this));
+    }, this));
+}
+
+NodeParser.prototype.calculateOverflowClips = function() {
+    this.nodes.forEach(function(container) {
+        if (isElement(container)) {
+            if (isPseudoElement(container)) {
+                container.appendToDOM();
+            }
+            container.borders = this.parseBorders(container);
+            var clip = (container.css('overflow') === "hidden") ? [container.borders.clip] : [];
+            var cssClip = container.parseClip();
+            if (cssClip && ["absolute", "fixed"].indexOf(container.css('position')) !== -1) {
+                clip.push([["rect",
+                        container.bounds.left + cssClip.left,
+                        container.bounds.top + cssClip.top,
+                        cssClip.right - cssClip.left,
+                        cssClip.bottom - cssClip.top
+                ]]);
+            }
+            container.clip = hasParentClip(container) ? container.parent.clip.concat(clip) : clip;
+            container.backgroundClip = (container.css('overflow') !== "hidden") ? container.clip.concat([container.borders.clip]) : container.clip;
+            if (isPseudoElement(container)) {
+                container.cleanDOM();
+            }
+        } else if (isTextNode(container)) {
+            container.clip = hasParentClip(container) ? container.parent.clip : [];
+        }
+        if (!isPseudoElement(container)) {
+            container.bounds = null;
+        }
+    }, this);
+};
+
+function hasParentClip(container) {
+    return container.parent && container.parent.clip.length;
+}
+
+NodeParser.prototype.asyncRenderer = function(queue, resolve, asyncTimer) {
+    asyncTimer = asyncTimer || Date.now();
+    this.paint(queue[this.renderIndex++]);
+    if (queue.length === this.renderIndex) {
+        resolve();
+    } else if (asyncTimer + 20 > Date.now()) {
+        this.asyncRenderer(queue, resolve, asyncTimer);
+    } else {
+        setTimeout(bind(function() {
+            this.asyncRenderer(queue, resolve);
+        }, this), 0);
+    }
+};
+
+NodeParser.prototype.createPseudoHideStyles = function(document) {
+    this.createStyles(document, '.' + PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_BEFORE + ':before { content: "" !important; display: none !important; }' +
+        '.' + PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_AFTER + ':after { content: "" !important; display: none !important; }');
+};
+
+NodeParser.prototype.disableAnimations = function(document) {
+    this.createStyles(document, '* { -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;}');
+};
+
+NodeParser.prototype.createStyles = function(document, styles) {
+    var hidePseudoElements = document.createElement('style');
+    hidePseudoElements.innerHTML = styles;
+    document.body.appendChild(hidePseudoElements);
+};
+
+NodeParser.prototype.getPseudoElements = function(container) {
+    var nodes = [[container]];
+    if (container.node.nodeType === Node.ELEMENT_NODE) {
+        var before = this.getPseudoElement(container, ":before");
+        var after = this.getPseudoElement(container, ":after");
+
+        if (before) {
+            nodes.push(before);
+        }
+
+        if (after) {
+            nodes.push(after);
+        }
+    }
+    return flatten(nodes);
+};
+
+function toCamelCase(str) {
+    return str.replace(/(\-[a-z])/g, function(match){
+        return match.toUpperCase().replace('-','');
+    });
+}
+
+NodeParser.prototype.getPseudoElement = function(container, type) {
+    var style = container.computedStyle(type);
+    if(!style || !style.content || style.content === "none" || style.content === "-moz-alt-content" || style.display === "none") {
+        return null;
+    }
+
+    var content = stripQuotes(style.content);
+    var isImage = content.substr(0, 3) === 'url';
+    var pseudoNode = document.createElement(isImage ? 'img' : 'html2canvaspseudoelement');
+    var pseudoContainer = new PseudoElementContainer(pseudoNode, container, type);
+
+    for (var i = style.length-1; i >= 0; i--) {
+        var property = toCamelCase(style.item(i));
+        pseudoNode.style[property] = style[property];
+    }
+
+    pseudoNode.className = PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_BEFORE + " " + PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_AFTER;
+
+    if (isImage) {
+        pseudoNode.src = parseBackgrounds(content)[0].args[0];
+        return [pseudoContainer];
+    } else {
+        var text = document.createTextNode(content);
+        pseudoNode.appendChild(text);
+        return [pseudoContainer, new TextContainer(text, pseudoContainer)];
+    }
+};
+
+
+NodeParser.prototype.getChildren = function(parentContainer) {
+    return flatten([].filter.call(parentContainer.node.childNodes, renderableNode).map(function(node) {
+        var container = [node.nodeType === Node.TEXT_NODE ? new TextContainer(node, parentContainer) : new NodeContainer(node, parentContainer)].filter(nonIgnoredElement);
+        return node.nodeType === Node.ELEMENT_NODE && container.length && node.tagName !== "TEXTAREA" ? (container[0].isElementVisible() ? container.concat(this.getChildren(container[0])) : []) : container;
+    }, this));
+};
+
+NodeParser.prototype.newStackingContext = function(container, hasOwnStacking) {
+    var stack = new StackingContext(hasOwnStacking, container.getOpacity(), container.node, container.parent);
+    container.cloneTo(stack);
+    var parentStack = hasOwnStacking ? stack.getParentStack(this) : stack.parent.stack;
+    parentStack.contexts.push(stack);
+    container.stack = stack;
+};
+
+NodeParser.prototype.createStackingContexts = function() {
+    this.nodes.forEach(function(container) {
+        if (isElement(container) && (this.isRootElement(container) || hasOpacity(container) || isPositionedForStacking(container) || this.isBodyWithTransparentRoot(container) || container.hasTransform())) {
+            this.newStackingContext(container, true);
+        } else if (isElement(container) && ((isPositioned(container) && zIndex0(container)) || isInlineBlock(container) || isFloating(container))) {
+            this.newStackingContext(container, false);
+        } else {
+            container.assignStack(container.parent.stack);
+        }
+    }, this);
+};
+
+NodeParser.prototype.isBodyWithTransparentRoot = function(container) {
+    return container.node.nodeName === "BODY" && container.parent.color('backgroundColor').isTransparent();
+};
+
+NodeParser.prototype.isRootElement = function(container) {
+    return container.parent === null;
+};
+
+NodeParser.prototype.sortStackingContexts = function(stack) {
+    stack.contexts.sort(zIndexSort(stack.contexts.slice(0)));
+    stack.contexts.forEach(this.sortStackingContexts, this);
+};
+
+NodeParser.prototype.parseTextBounds = function(container) {
+    return function(text, index, textList) {
+        if (container.parent.css("textDecoration").substr(0, 4) !== "none" || text.trim().length !== 0) {
+            if (this.support.rangeBounds && !container.parent.hasTransform()) {
+                var offset = textList.slice(0, index).join("").length;
+                return this.getRangeBounds(container.node, offset, text.length);
+            } else if (container.node && typeof(container.node.data) === "string") {
+                var replacementNode = container.node.splitText(text.length);
+                var bounds = this.getWrapperBounds(container.node, container.parent.hasTransform());
+                container.node = replacementNode;
+                return bounds;
+            }
+        } else if(!this.support.rangeBounds || container.parent.hasTransform()){
+            container.node = container.node.splitText(text.length);
+        }
+        return {};
+    };
+};
+
+NodeParser.prototype.getWrapperBounds = function(node, transform) {
+    var wrapper = node.ownerDocument.createElement('html2canvaswrapper');
+    var parent = node.parentNode,
+        backupText = node.cloneNode(true);
+
+    wrapper.appendChild(node.cloneNode(true));
+    parent.replaceChild(wrapper, node);
+    var bounds = transform ? offsetBounds(wrapper) : getBounds(wrapper);
+    parent.replaceChild(backupText, wrapper);
+    return bounds;
+};
+
+NodeParser.prototype.getRangeBounds = function(node, offset, length) {
+    var range = this.range || (this.range = node.ownerDocument.createRange());
+    range.setStart(node, offset);
+    range.setEnd(node, offset + length);
+    return range.getBoundingClientRect();
+};
+
+function ClearTransform() {}
+
+NodeParser.prototype.parse = function(stack) {
+    // http://www.w3.org/TR/CSS21/visuren.html#z-index
+    var negativeZindex = stack.contexts.filter(negativeZIndex); // 2. the child stacking contexts with negative stack levels (most negative first).
+    var descendantElements = stack.children.filter(isElement);
+    var descendantNonFloats = descendantElements.filter(not(isFloating));
+    var nonInlineNonPositionedDescendants = descendantNonFloats.filter(not(isPositioned)).filter(not(inlineLevel)); // 3 the in-flow, non-inline-level, non-positioned descendants.
+    var nonPositionedFloats = descendantElements.filter(not(isPositioned)).filter(isFloating); // 4. the non-positioned floats.
+    var inFlow = descendantNonFloats.filter(not(isPositioned)).filter(inlineLevel); // 5. the in-flow, inline-level, non-positioned descendants, including inline tables and inline blocks.
+    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.
+    var text = stack.children.filter(isTextNode).filter(hasText);
+    var positiveZindex = stack.contexts.filter(positiveZIndex); // 7. the child stacking contexts with positive stack levels (least positive first).
+    negativeZindex.concat(nonInlineNonPositionedDescendants).concat(nonPositionedFloats)
+        .concat(inFlow).concat(stackLevel0).concat(text).concat(positiveZindex).forEach(function(container) {
+            this.renderQueue.push(container);
+            if (isStackingContext(container)) {
+                this.parse(container);
+                this.renderQueue.push(new ClearTransform());
+            }
+        }, this);
+};
+
+NodeParser.prototype.paint = function(container) {
+    try {
+        if (container instanceof ClearTransform) {
+            this.renderer.ctx.restore();
+        } else if (isTextNode(container)) {
+            if (isPseudoElement(container.parent)) {
+                container.parent.appendToDOM();
+            }
+            this.paintText(container);
+            if (isPseudoElement(container.parent)) {
+                container.parent.cleanDOM();
+            }
+        } else {
+            this.paintNode(container);
+        }
+    } catch(e) {
+        log(e);
+        if (this.options.strict) {
+            throw e;
+        }
+    }
+};
+
+NodeParser.prototype.paintNode = function(container) {
+    if (isStackingContext(container)) {
+        this.renderer.setOpacity(container.opacity);
+        this.renderer.ctx.save();
+        if (container.hasTransform()) {
+            this.renderer.setTransform(container.parseTransform());
+        }
+    }
+
+    if (container.node.nodeName === "INPUT" && container.node.type === "checkbox") {
+        this.paintCheckbox(container);
+    } else if (container.node.nodeName === "INPUT" && container.node.type === "radio") {
+        this.paintRadio(container);
+    } else {
+        this.paintElement(container);
+    }
+};
+
+NodeParser.prototype.paintElement = function(container) {
+    var bounds = container.parseBounds();
+    this.renderer.clip(container.backgroundClip, function() {
+        this.renderer.renderBackground(container, bounds, container.borders.borders.map(getWidth));
+    }, this);
+
+    this.renderer.clip(container.clip, function() {
+        this.renderer.renderBorders(container.borders.borders);
+    }, this);
+
+    this.renderer.clip(container.backgroundClip, function() {
+        switch (container.node.nodeName) {
+        case "svg":
+        case "IFRAME":
+            var imgContainer = this.images.get(container.node);
+            if (imgContainer) {
+                this.renderer.renderImage(container, bounds, container.borders, imgContainer);
+            } else {
+                log("Error loading <" + container.node.nodeName + ">", container.node);
+            }
+            break;
+        case "IMG":
+            var imageContainer = this.images.get(container.node.src);
+            if (imageContainer) {
+                this.renderer.renderImage(container, bounds, container.borders, imageContainer);
+            } else {
+                log("Error loading <img>", container.node.src);
+            }
+            break;
+        case "CANVAS":
+            this.renderer.renderImage(container, bounds, container.borders, {image: container.node});
+            break;
+        case "SELECT":
+        case "INPUT":
+        case "TEXTAREA":
+            this.paintFormValue(container);
+            break;
+        }
+    }, this);
+};
+
+NodeParser.prototype.paintCheckbox = function(container) {
+    var b = container.parseBounds();
+
+    var size = Math.min(b.width, b.height);
+    var bounds = {width: size - 1, height: size - 1, top: b.top, left: b.left};
+    var r = [3, 3];
+    var radius = [r, r, r, r];
+    var borders = [1,1,1,1].map(function(w) {
+        return {color: new Color('#A5A5A5'), width: w};
+    });
+
+    var borderPoints = calculateCurvePoints(bounds, radius, borders);
+
+    this.renderer.clip(container.backgroundClip, function() {
+        this.renderer.rectangle(bounds.left + 1, bounds.top + 1, bounds.width - 2, bounds.height - 2, new Color("#DEDEDE"));
+        this.renderer.renderBorders(calculateBorders(borders, bounds, borderPoints, radius));
+        if (container.node.checked) {
+            this.renderer.font(new Color('#424242'), 'normal', 'normal', 'bold', (size - 3) + "px", 'arial');
+            this.renderer.text("\u2714", bounds.left + size / 6, bounds.top + size - 1);
+        }
+    }, this);
+};
+
+NodeParser.prototype.paintRadio = function(container) {
+    var bounds = container.parseBounds();
+
+    var size = Math.min(bounds.width, bounds.height) - 2;
+
+    this.renderer.clip(container.backgroundClip, function() {
+        this.renderer.circleStroke(bounds.left + 1, bounds.top + 1, size, new Color('#DEDEDE'), 1, new Color('#A5A5A5'));
+        if (container.node.checked) {
+            this.renderer.circle(Math.ceil(bounds.left + size / 4) + 1, Math.ceil(bounds.top + size / 4) + 1, Math.floor(size / 2), new Color('#424242'));
+        }
+    }, this);
+};
+
+NodeParser.prototype.paintFormValue = function(container) {
+    var value = container.getValue();
+    if (value.length > 0) {
+        var document = container.node.ownerDocument;
+        var wrapper = document.createElement('html2canvaswrapper');
+        var properties = ['lineHeight', 'textAlign', 'fontFamily', 'fontWeight', 'fontSize', 'color',
+            'paddingLeft', 'paddingTop', 'paddingRight', 'paddingBottom',
+            'width', 'height', 'borderLeftStyle', 'borderTopStyle', 'borderLeftWidth', 'borderTopWidth',
+            'boxSizing', 'whiteSpace', 'wordWrap'];
+
+        properties.forEach(function(property) {
+            try {
+                wrapper.style[property] = container.css(property);
+            } catch(e) {
+                // Older IE has issues with "border"
+                log("html2canvas: Parse: Exception caught in renderFormValue: " + e.message);
+            }
+        });
+        var bounds = container.parseBounds();
+        wrapper.style.position = "fixed";
+        wrapper.style.left = bounds.left + "px";
+        wrapper.style.top = bounds.top + "px";
+        wrapper.textContent = value;
+        document.body.appendChild(wrapper);
+        this.paintText(new TextContainer(wrapper.firstChild, container));
+        document.body.removeChild(wrapper);
+    }
+};
+
+NodeParser.prototype.paintText = function(container) {
+    container.applyTextTransform();
+    var characters = punycode.ucs2.decode(container.node.data);
+    var textList = (!this.options.letterRendering || noLetterSpacing(container)) && !hasUnicode(container.node.data) ? getWords(characters) : characters.map(function(character) {
+        return punycode.ucs2.encode([character]);
+    });
+
+    var weight = container.parent.fontWeight();
+    var size = container.parent.css('fontSize');
+    var family = container.parent.css('fontFamily');
+    var shadows = container.parent.parseTextShadows();
+
+    this.renderer.font(container.parent.color('color'), container.parent.css('fontStyle'), container.parent.css('fontVariant'), weight, size, family);
+    if (shadows.length) {
+        // TODO: support multiple text shadows
+        this.renderer.fontShadow(shadows[0].color, shadows[0].offsetX, shadows[0].offsetY, shadows[0].blur);
+    } else {
+        this.renderer.clearShadow();
+    }
+
+    this.renderer.clip(container.parent.clip, function() {
+        textList.map(this.parseTextBounds(container), this).forEach(function(bounds, index) {
+            if (bounds) {
+                this.renderer.text(textList[index], bounds.left, bounds.bottom);
+                this.renderTextDecoration(container.parent, bounds, this.fontMetrics.getMetrics(family, size));
+            }
+        }, this);
+    }, this);
+};
+
+NodeParser.prototype.renderTextDecoration = function(container, bounds, metrics) {
+    switch(container.css("textDecoration").split(" ")[0]) {
+    case "underline":
+        // Draws a line at the baseline of the font
+        // 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
+        this.renderer.rectangle(bounds.left, Math.round(bounds.top + metrics.baseline + metrics.lineWidth), bounds.width, 1, container.color("color"));
+        break;
+    case "overline":
+        this.renderer.rectangle(bounds.left, Math.round(bounds.top), bounds.width, 1, container.color("color"));
+        break;
+    case "line-through":
+        // TODO try and find exact position for line-through
+        this.renderer.rectangle(bounds.left, Math.ceil(bounds.top + metrics.middle + metrics.lineWidth), bounds.width, 1, container.color("color"));
+        break;
+    }
+};
+
+var borderColorTransforms = {
+    inset: [
+        ["darken", 0.60],
+        ["darken", 0.10],
+        ["darken", 0.10],
+        ["darken", 0.60]
+    ]
+};
+
+NodeParser.prototype.parseBorders = function(container) {
+    var nodeBounds = container.parseBounds();
+    var radius = getBorderRadiusData(container);
+    var borders = ["Top", "Right", "Bottom", "Left"].map(function(side, index) {
+        var style = container.css('border' + side + 'Style');
+        var color = container.color('border' + side + 'Color');
+        if (style === "inset" && color.isBlack()) {
+            color = new Color([255, 255, 255, color.a]); // this is wrong, but
+        }
+        var colorTransform = borderColorTransforms[style] ? borderColorTransforms[style][index] : null;
+        return {
+            width: container.cssInt('border' + side + 'Width'),
+            color: colorTransform ? color[colorTransform[0]](colorTransform[1]) : color,
+            args: null
+        };
+    });
+    var borderPoints = calculateCurvePoints(nodeBounds, radius, borders);
+
+    return {
+        clip: this.parseBackgroundClip(container, borderPoints, borders, radius, nodeBounds),
+        borders: calculateBorders(borders, nodeBounds, borderPoints, radius)
+    };
+};
+
+function calculateBorders(borders, nodeBounds, borderPoints, radius) {
+    return borders.map(function(border, borderSide) {
+        if (border.width > 0) {
+            var bx = nodeBounds.left;
+            var by = nodeBounds.top;
+            var bw = nodeBounds.width;
+            var bh = nodeBounds.height - (borders[2].width);
+
+            switch(borderSide) {
+            case 0:
+                // top border
+                bh = borders[0].width;
+                border.args = drawSide({
+                        c1: [bx, by],
+                        c2: [bx + bw, by],
+                        c3: [bx + bw - borders[1].width, by + bh],
+                        c4: [bx + borders[3].width, by + bh]
+                    }, radius[0], radius[1],
+                    borderPoints.topLeftOuter, borderPoints.topLeftInner, borderPoints.topRightOuter, borderPoints.topRightInner);
+                break;
+            case 1:
+                // right border
+                bx = nodeBounds.left + nodeBounds.width - (borders[1].width);
+                bw = borders[1].width;
+
+                border.args = drawSide({
+                        c1: [bx + bw, by],
+                        c2: [bx + bw, by + bh + borders[2].width],
+                        c3: [bx, by + bh],
+                        c4: [bx, by + borders[0].width]
+                    }, radius[1], radius[2],
+                    borderPoints.topRightOuter, borderPoints.topRightInner, borderPoints.bottomRightOuter, borderPoints.bottomRightInner);
+                break;
+            case 2:
+                // bottom border
+                by = (by + nodeBounds.height) - (borders[2].width);
+                bh = borders[2].width;
+                border.args = drawSide({
+                        c1: [bx + bw, by + bh],
+                        c2: [bx, by + bh],
+                        c3: [bx + borders[3].width, by],
+                        c4: [bx + bw - borders[3].width, by]
+                    }, radius[2], radius[3],
+                    borderPoints.bottomRightOuter, borderPoints.bottomRightInner, borderPoints.bottomLeftOuter, borderPoints.bottomLeftInner);
+                break;
+            case 3:
+                // left border
+                bw = borders[3].width;
+                border.args = drawSide({
+                        c1: [bx, by + bh + borders[2].width],
+                        c2: [bx, by],
+                        c3: [bx + bw, by + borders[0].width],
+                        c4: [bx + bw, by + bh]
+                    }, radius[3], radius[0],
+                    borderPoints.bottomLeftOuter, borderPoints.bottomLeftInner, borderPoints.topLeftOuter, borderPoints.topLeftInner);
+                break;
+            }
+        }
+        return border;
+    });
+}
+
+NodeParser.prototype.parseBackgroundClip = function(container, borderPoints, borders, radius, bounds) {
+    var backgroundClip = container.css('backgroundClip'),
+        borderArgs = [];
+
+    switch(backgroundClip) {
+    case "content-box":
+    case "padding-box":
+        parseCorner(borderArgs, radius[0], radius[1], borderPoints.topLeftInner, borderPoints.topRightInner, bounds.left + borders[3].width, bounds.top + borders[0].width);
+        parseCorner(borderArgs, radius[1], radius[2], borderPoints.topRightInner, borderPoints.bottomRightInner, bounds.left + bounds.width - borders[1].width, bounds.top + borders[0].width);
+        parseCorner(borderArgs, radius[2], radius[3], borderPoints.bottomRightInner, borderPoints.bottomLeftInner, bounds.left + bounds.width - borders[1].width, bounds.top + bounds.height - borders[2].width);
+        parseCorner(borderArgs, radius[3], radius[0], borderPoints.bottomLeftInner, borderPoints.topLeftInner, bounds.left + borders[3].width, bounds.top + bounds.height - borders[2].width);
+        break;
+
+    default:
+        parseCorner(borderArgs, radius[0], radius[1], borderPoints.topLeftOuter, borderPoints.topRightOuter, bounds.left, bounds.top);
+        parseCorner(borderArgs, radius[1], radius[2], borderPoints.topRightOuter, borderPoints.bottomRightOuter, bounds.left + bounds.width, bounds.top);
+        parseCorner(borderArgs, radius[2], radius[3], borderPoints.bottomRightOuter, borderPoints.bottomLeftOuter, bounds.left + bounds.width, bounds.top + bounds.height);
+        parseCorner(borderArgs, radius[3], radius[0], borderPoints.bottomLeftOuter, borderPoints.topLeftOuter, bounds.left, bounds.top + bounds.height);
+        break;
+    }
+
+    return borderArgs;
+};
+
+function getCurvePoints(x, y, r1, r2) {
+    var kappa = 4 * ((Math.sqrt(2) - 1) / 3);
+    var ox = (r1) * kappa, // control point offset horizontal
+        oy = (r2) * kappa, // control point offset vertical
+        xm = x + r1, // x-middle
+        ym = y + r2; // y-middle
+    return {
+        topLeft: bezierCurve({x: x, y: ym}, {x: x, y: ym - oy}, {x: xm - ox, y: y}, {x: xm, y: y}),
+        topRight: bezierCurve({x: x, y: y}, {x: x + ox,y: y}, {x: xm, y: ym - oy}, {x: xm, y: ym}),
+        bottomRight: bezierCurve({x: xm, y: y}, {x: xm, y: y + oy}, {x: x + ox, y: ym}, {x: x, y: ym}),
+        bottomLeft: bezierCurve({x: xm, y: ym}, {x: xm - ox, y: ym}, {x: x, y: y + oy}, {x: x, y:y})
+    };
+}
+
+function calculateCurvePoints(bounds, borderRadius, borders) {
+    var x = bounds.left,
+        y = bounds.top,
+        width = bounds.width,
+        height = bounds.height,
+
+        tlh = borderRadius[0][0] < width / 2 ? borderRadius[0][0] : width / 2,
+        tlv = borderRadius[0][1] < height / 2 ? borderRadius[0][1] : height / 2,
+        trh = borderRadius[1][0] < width / 2 ? borderRadius[1][0] : width / 2,
+        trv = borderRadius[1][1] < height / 2 ? borderRadius[1][1] : height / 2,
+        brh = borderRadius[2][0] < width / 2 ? borderRadius[2][0] : width / 2,
+        brv = borderRadius[2][1] < height / 2 ? borderRadius[2][1] : height / 2,
+        blh = borderRadius[3][0] < width / 2 ? borderRadius[3][0] : width / 2,
+        blv = borderRadius[3][1] < height / 2 ? borderRadius[3][1] : height / 2;
+
+    var topWidth = width - trh,
+        rightHeight = height - brv,
+        bottomWidth = width - brh,
+        leftHeight = height - blv;
+
+    return {
+        topLeftOuter: getCurvePoints(x, y, tlh, tlv).topLeft.subdivide(0.5),
+        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),
+        topRightOuter: getCurvePoints(x + topWidth, y, trh, trv).topRight.subdivide(0.5),
+        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),
+        bottomRightOuter: getCurvePoints(x + bottomWidth, y + rightHeight, brh, brv).bottomRight.subdivide(0.5),
+        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),
+        bottomLeftOuter: getCurvePoints(x, y + leftHeight, blh, blv).bottomLeft.subdivide(0.5),
+        bottomLeftInner: getCurvePoints(x + borders[3].width, y + leftHeight, Math.max(0, blh - borders[3].width), blv - borders[2].width).bottomLeft.subdivide(0.5)
+    };
+}
+
+function bezierCurve(start, startControl, endControl, end) {
+    var lerp = function (a, b, t) {
+        return {
+            x: a.x + (b.x - a.x) * t,
+            y: a.y + (b.y - a.y) * t
+        };
+    };
+
+    return {
+        start: start,
+        startControl: startControl,
+        endControl: endControl,
+        end: end,
+        subdivide: function(t) {
+            var ab = lerp(start, startControl, t),
+                bc = lerp(startControl, endControl, t),
+                cd = lerp(endControl, end, t),
+                abbc = lerp(ab, bc, t),
+                bccd = lerp(bc, cd, t),
+                dest = lerp(abbc, bccd, t);
+            return [bezierCurve(start, ab, abbc, dest), bezierCurve(dest, bccd, cd, end)];
+        },
+        curveTo: function(borderArgs) {
+            borderArgs.push(["bezierCurve", startControl.x, startControl.y, endControl.x, endControl.y, end.x, end.y]);
+        },
+        curveToReversed: function(borderArgs) {
+            borderArgs.push(["bezierCurve", endControl.x, endControl.y, startControl.x, startControl.y, start.x, start.y]);
+        }
+    };
+}
+
+function drawSide(borderData, radius1, radius2, outer1, inner1, outer2, inner2) {
+    var borderArgs = [];
+
+    if (radius1[0] > 0 || radius1[1] > 0) {
+        borderArgs.push(["line", outer1[1].start.x, outer1[1].start.y]);
+        outer1[1].curveTo(borderArgs);
+    } else {
+        borderArgs.push([ "line", borderData.c1[0], borderData.c1[1]]);
+    }
+
+    if (radius2[0] > 0 || radius2[1] > 0) {
+        borderArgs.push(["line", outer2[0].start.x, outer2[0].start.y]);
+        outer2[0].curveTo(borderArgs);
+        borderArgs.push(["line", inner2[0].end.x, inner2[0].end.y]);
+        inner2[0].curveToReversed(borderArgs);
+    } else {
+        borderArgs.push(["line", borderData.c2[0], borderData.c2[1]]);
+        borderArgs.push(["line", borderData.c3[0], borderData.c3[1]]);
+    }
+
+    if (radius1[0] > 0 || radius1[1] > 0) {
+        borderArgs.push(["line", inner1[1].end.x, inner1[1].end.y]);
+        inner1[1].curveToReversed(borderArgs);
+    } else {
+        borderArgs.push(["line", borderData.c4[0], borderData.c4[1]]);
+    }
+
+    return borderArgs;
+}
+
+function parseCorner(borderArgs, radius1, radius2, corner1, corner2, x, y) {
+    if (radius1[0] > 0 || radius1[1] > 0) {
+        borderArgs.push(["line", corner1[0].start.x, corner1[0].start.y]);
+        corner1[0].curveTo(borderArgs);
+        corner1[1].curveTo(borderArgs);
+    } else {
+        borderArgs.push(["line", x, y]);
+    }
+
+    if (radius2[0] > 0 || radius2[1] > 0) {
+        borderArgs.push(["line", corner2[0].start.x, corner2[0].start.y]);
+    }
+}
+
+function negativeZIndex(container) {
+    return container.cssInt("zIndex") < 0;
+}
+
+function positiveZIndex(container) {
+    return container.cssInt("zIndex") > 0;
+}
+
+function zIndex0(container) {
+    return container.cssInt("zIndex") === 0;
+}
+
+function inlineLevel(container) {
+    return ["inline", "inline-block", "inline-table"].indexOf(container.css("display")) !== -1;
+}
+
+function isStackingContext(container) {
+    return (container instanceof StackingContext);
+}
+
+function hasText(container) {
+    return container.node.data.trim().length > 0;
+}
+
+function noLetterSpacing(container) {
+    return (/^(normal|none|0px)$/.test(container.parent.css("letterSpacing")));
+}
+
+function getBorderRadiusData(container) {
+    return ["TopLeft", "TopRight", "BottomRight", "BottomLeft"].map(function(side) {
+        var value = container.css('border' + side + 'Radius');
+        var arr = value.split(" ");
+        if (arr.length <= 1) {
+            arr[1] = arr[0];
+        }
+        return arr.map(asInt);
+    });
+}
+
+function renderableNode(node) {
+    return (node.nodeType === Node.TEXT_NODE || node.nodeType === Node.ELEMENT_NODE);
+}
+
+function isPositionedForStacking(container) {
+    var position = container.css("position");
+    var zIndex = (["absolute", "relative", "fixed"].indexOf(position) !== -1) ? container.css("zIndex") : "auto";
+    return zIndex !== "auto";
+}
+
+function isPositioned(container) {
+    return container.css("position") !== "static";
+}
+
+function isFloating(container) {
+    return container.css("float") !== "none";
+}
+
+function isInlineBlock(container) {
+    return ["inline-block", "inline-table"].indexOf(container.css("display")) !== -1;
+}
+
+function not(callback) {
+    var context = this;
+    return function() {
+        return !callback.apply(context, arguments);
+    };
+}
+
+function isElement(container) {
+    return container.node.nodeType === Node.ELEMENT_NODE;
+}
+
+function isPseudoElement(container) {
+    return container.isPseudoElement === true;
+}
+
+function isTextNode(container) {
+    return container.node.nodeType === Node.TEXT_NODE;
+}
+
+function zIndexSort(contexts) {
+    return function(a, b) {
+        return (a.cssInt("zIndex") + (contexts.indexOf(a) / contexts.length)) - (b.cssInt("zIndex") + (contexts.indexOf(b) / contexts.length));
+    };
+}
+
+function hasOpacity(container) {
+    return container.getOpacity() < 1;
+}
+
+function asInt(value) {
+    return parseInt(value, 10);
+}
+
+function getWidth(border) {
+    return border.width;
+}
+
+function nonIgnoredElement(nodeContainer) {
+    return (nodeContainer.node.nodeType !== Node.ELEMENT_NODE || ["SCRIPT", "HEAD", "TITLE", "OBJECT", "BR", "OPTION"].indexOf(nodeContainer.node.nodeName) === -1);
+}
+
+function flatten(arrays) {
+    return [].concat.apply([], arrays);
+}
+
+function stripQuotes(content) {
+    var first = content.substr(0, 1);
+    return (first === content.substr(content.length - 1) && first.match(/'|"/)) ? content.substr(1, content.length - 2) : content;
+}
+
+function getWords(characters) {
+    var words = [], i = 0, onWordBoundary = false, word;
+    while(characters.length) {
+        if (isWordBoundary(characters[i]) === onWordBoundary) {
+            word = characters.splice(0, i);
+            if (word.length) {
+                words.push(punycode.ucs2.encode(word));
+            }
+            onWordBoundary =! onWordBoundary;
+            i = 0;
+        } else {
+            i++;
+        }
+
+        if (i >= characters.length) {
+            word = characters.splice(0, i);
+            if (word.length) {
+                words.push(punycode.ucs2.encode(word));
+            }
+        }
+    }
+    return words;
+}
+
+function isWordBoundary(characterCode) {
+    return [
+        32, // <space>
+        13, // \r
+        10, // \n
+        9, // \t
+        45 // -
+    ].indexOf(characterCode) !== -1;
+}
+
+function hasUnicode(string) {
+    return (/[^\u0000-\u00ff]/).test(string);
+}
+
+module.exports = NodeParser;
+
+},{"./color":3,"./fontmetrics":7,"./log":13,"./nodecontainer":14,"./pseudoelementcontainer":18,"./stackingcontext":21,"./textcontainer":25,"./utils":26,"punycode":1}],16:[function(_dereq_,module,exports){
+var XHR = _dereq_('./xhr');
+var utils = _dereq_('./utils');
+var log = _dereq_('./log');
+var createWindowClone = _dereq_('./clone');
+var decode64 = utils.decode64;
+
+function Proxy(src, proxyUrl, document) {
+    var supportsCORS = ('withCredentials' in new XMLHttpRequest());
+    if (!proxyUrl) {
+        return Promise.reject("No proxy configured");
+    }
+    var callback = createCallback(supportsCORS);
+    var url = createProxyUrl(proxyUrl, src, callback);
+
+    return supportsCORS ? XHR(url) : (jsonp(document, url, callback).then(function(response) {
+        return decode64(response.content);
+    }));
+}
+var proxyCount = 0;
+
+function ProxyURL(src, proxyUrl, document) {
+    var supportsCORSImage = ('crossOrigin' in new Image());
+    var callback = createCallback(supportsCORSImage);
+    var url = createProxyUrl(proxyUrl, src, callback);
+    return (supportsCORSImage ? Promise.resolve(url) : jsonp(document, url, callback).then(function(response) {
+        return "data:" + response.type + ";base64," + response.content;
+    }));
+}
+
+function jsonp(document, url, callback) {
+    return new Promise(function(resolve, reject) {
+        var s = document.createElement("script");
+        var cleanup = function() {
+            delete window.html2canvas.proxy[callback];
+            document.body.removeChild(s);
+        };
+        window.html2canvas.proxy[callback] = function(response) {
+            cleanup();
+            resolve(response);
+        };
+        s.src = url;
+        s.onerror = function(e) {
+            cleanup();
+            reject(e);
+        };
+        document.body.appendChild(s);
+    });
+}
+
+function createCallback(useCORS) {
+    return !useCORS ? "html2canvas_" + Date.now() + "_" + (++proxyCount) + "_" + Math.round(Math.random() * 100000) : "";
+}
+
+function createProxyUrl(proxyUrl, src, callback) {
+    return proxyUrl + "?url=" + encodeURIComponent(src) + (callback.length ? "&callback=html2canvas.proxy." + callback : "");
+}
+
+function documentFromHTML(src) {
+    return function(html) {
+        var parser = new DOMParser(), doc;
+        try {
+            doc = parser.parseFromString(html, "text/html");
+        } catch(e) {
+            log("DOMParser not supported, falling back to createHTMLDocument");
+            doc = document.implementation.createHTMLDocument("");
+            try {
+                doc.open();
+                doc.write(html);
+                doc.close();
+            } catch(ee) {
+                log("createHTMLDocument write not supported, falling back to document.body.innerHTML");
+                doc.body.innerHTML = html; // ie9 doesnt support writing to documentElement
+            }
+        }
+
+        var b = doc.querySelector("base");
+        if (!b || !b.href.host) {
+            var base = doc.createElement("base");
+            base.href = src;
+            doc.head.insertBefore(base, doc.head.firstChild);
+        }
+
+        return doc;
+    };
+}
+
+function loadUrlDocument(src, proxy, document, width, height, options) {
+    return new Proxy(src, proxy, window.document).then(documentFromHTML(src)).then(function(doc) {
+        return createWindowClone(doc, document, width, height, options, 0, 0);
+    });
+}
+
+exports.Proxy = Proxy;
+exports.ProxyURL = ProxyURL;
+exports.loadUrlDocument = loadUrlDocument;
+
+},{"./clone":2,"./log":13,"./utils":26,"./xhr":28}],17:[function(_dereq_,module,exports){
+var ProxyURL = _dereq_('./proxy').ProxyURL;
+
+function ProxyImageContainer(src, proxy) {
+    var link = document.createElement("a");
+    link.href = src;
+    src = link.href;
+    this.src = src;
+    this.image = new Image();
+    var self = this;
+    this.promise = new Promise(function(resolve, reject) {
+        self.image.crossOrigin = "Anonymous";
+        self.image.onload = resolve;
+        self.image.onerror = reject;
+
+        new ProxyURL(src, proxy, document).then(function(url) {
+            self.image.src = url;
+        })['catch'](reject);
+    });
+}
+
+module.exports = ProxyImageContainer;
+
+},{"./proxy":16}],18:[function(_dereq_,module,exports){
+var NodeContainer = _dereq_('./nodecontainer');
+
+function PseudoElementContainer(node, parent, type) {
+    NodeContainer.call(this, node, parent);
+    this.isPseudoElement = true;
+    this.before = type === ":before";
+}
+
+PseudoElementContainer.prototype.cloneTo = function(stack) {
+    PseudoElementContainer.prototype.cloneTo.call(this, stack);
+    stack.isPseudoElement = true;
+    stack.before = this.before;
+};
+
+PseudoElementContainer.prototype = Object.create(NodeContainer.prototype);
+
+PseudoElementContainer.prototype.appendToDOM = function() {
+    if (this.before) {
+        this.parent.node.insertBefore(this.node, this.parent.node.firstChild);
+    } else {
+        this.parent.node.appendChild(this.node);
+    }
+    this.parent.node.className += " " + this.getHideClass();
+};
+
+PseudoElementContainer.prototype.cleanDOM = function() {
+    this.node.parentNode.removeChild(this.node);
+    this.parent.node.className = this.parent.node.className.replace(this.getHideClass(), "");
+};
+
+PseudoElementContainer.prototype.getHideClass = function() {
+    return this["PSEUDO_HIDE_ELEMENT_CLASS_" + (this.before ? "BEFORE" : "AFTER")];
+};
+
+PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_BEFORE = "___html2canvas___pseudoelement_before";
+PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_AFTER = "___html2canvas___pseudoelement_after";
+
+module.exports = PseudoElementContainer;
+
+},{"./nodecontainer":14}],19:[function(_dereq_,module,exports){
+var log = _dereq_('./log');
+
+function Renderer(width, height, images, options, document) {
+    this.width = width;
+    this.height = height;
+    this.images = images;
+    this.options = options;
+    this.document = document;
+}
+
+Renderer.prototype.renderImage = function(container, bounds, borderData, imageContainer) {
+    var paddingLeft = container.cssInt('paddingLeft'),
+        paddingTop = container.cssInt('paddingTop'),
+        paddingRight = container.cssInt('paddingRight'),
+        paddingBottom = container.cssInt('paddingBottom'),
+        borders = borderData.borders;
+
+    var width = bounds.width - (borders[1].width + borders[3].width + paddingLeft + paddingRight);
+    var height = bounds.height - (borders[0].width + borders[2].width + paddingTop + paddingBottom);
+    this.drawImage(
+        imageContainer,
+        0,
+        0,
+        imageContainer.image.width || width,
+        imageContainer.image.height || height,
+        bounds.left + paddingLeft + borders[3].width,
+        bounds.top + paddingTop + borders[0].width,
+        width,
+        height
+    );
+};
+
+Renderer.prototype.renderBackground = function(container, bounds, borderData) {
+    if (bounds.height > 0 && bounds.width > 0) {
+        this.renderBackgroundColor(container, bounds);
+        this.renderBackgroundImage(container, bounds, borderData);
+    }
+};
+
+Renderer.prototype.renderBackgroundColor = function(container, bounds) {
+    var color = container.color("backgroundColor");
+    if (!color.isTransparent()) {
+        this.rectangle(bounds.left, bounds.top, bounds.width, bounds.height, color);
+    }
+};
+
+Renderer.prototype.renderBorders = function(borders) {
+    borders.forEach(this.renderBorder, this);
+};
+
+Renderer.prototype.renderBorder = function(data) {
+    if (!data.color.isTransparent() && data.args !== null) {
+        this.drawShape(data.args, data.color);
+    }
+};
+
+Renderer.prototype.renderBackgroundImage = function(container, bounds, borderData) {
+    var backgroundImages = container.parseBackgroundImages();
+    backgroundImages.reverse().forEach(function(backgroundImage, index, arr) {
+        switch(backgroundImage.method) {
+        case "url":
+            var image = this.images.get(backgroundImage.args[0]);
+            if (image) {
+                this.renderBackgroundRepeating(container, bounds, image, arr.length - (index+1), borderData);
+            } else {
+                log("Error loading background-image", backgroundImage.args[0]);
+            }
+            break;
+        case "linear-gradient":
+        case "gradient":
+            var gradientImage = this.images.get(backgroundImage.value);
+            if (gradientImage) {
+                this.renderBackgroundGradient(gradientImage, bounds, borderData);
+            } else {
+                log("Error loading background-image", backgroundImage.args[0]);
+            }
+            break;
+        case "none":
+            break;
+        default:
+            log("Unknown background-image type", backgroundImage.args[0]);
+        }
+    }, this);
+};
+
+Renderer.prototype.renderBackgroundRepeating = function(container, bounds, imageContainer, index, borderData) {
+    var size = container.parseBackgroundSize(bounds, imageContainer.image, index);
+    var position = container.parseBackgroundPosition(bounds, imageContainer.image, index, size);
+    var repeat = container.parseBackgroundRepeat(index);
+    switch (repeat) {
+    case "repeat-x":
+    case "repeat no-repeat":
+        this.backgroundRepeatShape(imageContainer, position, size, bounds, bounds.left + borderData[3], bounds.top + position.top + borderData[0], 99999, size.height, borderData);
+        break;
+    case "repeat-y":
+    case "no-repeat repeat":
+        this.backgroundRepeatShape(imageContainer, position, size, bounds, bounds.left + position.left + borderData[3], bounds.top + borderData[0], size.width, 99999, borderData);
+        break;
+    case "no-repeat":
+        this.backgroundRepeatShape(imageContainer, position, size, bounds, bounds.left + position.left + borderData[3], bounds.top + position.top + borderData[0], size.width, size.height, borderData);
+        break;
+    default:
+        this.renderBackgroundRepeat(imageContainer, position, size, {top: bounds.top, left: bounds.left}, borderData[3], borderData[0]);
+        break;
+    }
+};
+
+module.exports = Renderer;
+
+},{"./log":13}],20:[function(_dereq_,module,exports){
+var Renderer = _dereq_('../renderer');
+var LinearGradientContainer = _dereq_('../lineargradientcontainer');
+var log = _dereq_('../log');
+
+function CanvasRenderer(width, height) {
+    Renderer.apply(this, arguments);
+    this.canvas = this.options.canvas || this.document.createElement("canvas");
+    if (!this.options.canvas) {
+        this.canvas.width = width;
+        this.canvas.height = height;
+    }
+    this.ctx = this.canvas.getContext("2d");
+    this.taintCtx = this.document.createElement("canvas").getContext("2d");
+    this.ctx.textBaseline = "bottom";
+    this.variables = {};
+    log("Initialized CanvasRenderer with size", width, "x", height);
+}
+
+CanvasRenderer.prototype = Object.create(Renderer.prototype);
+
+CanvasRenderer.prototype.setFillStyle = function(fillStyle) {
+    this.ctx.fillStyle = typeof(fillStyle) === "object" && !!fillStyle.isColor ? fillStyle.toString() : fillStyle;
+    return this.ctx;
+};
+
+CanvasRenderer.prototype.rectangle = function(left, top, width, height, color) {
+    this.setFillStyle(color).fillRect(left, top, width, height);
+};
+
+CanvasRenderer.prototype.circle = function(left, top, size, color) {
+    this.setFillStyle(color);
+    this.ctx.beginPath();
+    this.ctx.arc(left + size / 2, top + size / 2, size / 2, 0, Math.PI*2, true);
+    this.ctx.closePath();
+    this.ctx.fill();
+};
+
+CanvasRenderer.prototype.circleStroke = function(left, top, size, color, stroke, strokeColor) {
+    this.circle(left, top, size, color);
+    this.ctx.strokeStyle = strokeColor.toString();
+    this.ctx.stroke();
+};
+
+CanvasRenderer.prototype.drawShape = function(shape, color) {
+    this.shape(shape);
+    this.setFillStyle(color).fill();
+};
+
+CanvasRenderer.prototype.taints = function(imageContainer) {
+    if (imageContainer.tainted === null) {
+        this.taintCtx.drawImage(imageContainer.image, 0, 0);
+        try {
+            this.taintCtx.getImageData(0, 0, 1, 1);
+            imageContainer.tainted = false;
+        } catch(e) {
+            this.taintCtx = document.createElement("canvas").getContext("2d");
+            imageContainer.tainted = true;
+        }
+    }
+
+    return imageContainer.tainted;
+};
+
+CanvasRenderer.prototype.drawImage = function(imageContainer, sx, sy, sw, sh, dx, dy, dw, dh) {
+    if (!this.taints(imageContainer) || this.options.allowTaint) {
+        this.ctx.drawImage(imageContainer.image, sx, sy, sw, sh, dx, dy, dw, dh);
+    }
+};
+
+CanvasRenderer.prototype.clip = function(shapes, callback, context) {
+    this.ctx.save();
+    shapes.filter(hasEntries).forEach(function(shape) {
+        this.shape(shape).clip();
+    }, this);
+    callback.call(context);
+    this.ctx.restore();
+};
+
+CanvasRenderer.prototype.shape = function(shape) {
+    this.ctx.beginPath();
+    shape.forEach(function(point, index) {
+        if (point[0] === "rect") {
+            this.ctx.rect.apply(this.ctx, point.slice(1));
+        } else {
+            this.ctx[(index === 0) ? "moveTo" : point[0] + "To" ].apply(this.ctx, point.slice(1));
+        }
+    }, this);
+    this.ctx.closePath();
+    return this.ctx;
+};
+
+CanvasRenderer.prototype.font = function(color, style, variant, weight, size, family) {
+    this.setFillStyle(color).font = [style, variant, weight, size, family].join(" ").split(",")[0];
+};
+
+CanvasRenderer.prototype.fontShadow = function(color, offsetX, offsetY, blur) {
+    this.setVariable("shadowColor", color.toString())
+        .setVariable("shadowOffsetY", offsetX)
+        .setVariable("shadowOffsetX", offsetY)
+        .setVariable("shadowBlur", blur);
+};
+
+CanvasRenderer.prototype.clearShadow = function() {
+    this.setVariable("shadowColor", "rgba(0,0,0,0)");
+};
+
+CanvasRenderer.prototype.setOpacity = function(opacity) {
+    this.ctx.globalAlpha = opacity;
+};
+
+CanvasRenderer.prototype.setTransform = function(transform) {
+    this.ctx.translate(transform.origin[0], transform.origin[1]);
+    this.ctx.transform.apply(this.ctx, transform.matrix);
+    this.ctx.translate(-transform.origin[0], -transform.origin[1]);
+};
+
+CanvasRenderer.prototype.setVariable = function(property, value) {
+    if (this.variables[property] !== value) {
+        this.variables[property] = this.ctx[property] = value;
+    }
+
+    return this;
+};
+
+CanvasRenderer.prototype.text = function(text, left, bottom) {
+    this.ctx.fillText(text, left, bottom);
+};
+
+CanvasRenderer.prototype.backgroundRepeatShape = function(imageContainer, backgroundPosition, size, bounds, left, top, width, height, borderData) {
+    var shape = [
+        ["line", Math.round(left), Math.round(top)],
+        ["line", Math.round(left + width), Math.round(top)],
+        ["line", Math.round(left + width), Math.round(height + top)],
+        ["line", Math.round(left), Math.round(height + top)]
+    ];
+    this.clip([shape], function() {
+        this.renderBackgroundRepeat(imageContainer, backgroundPosition, size, bounds, borderData[3], borderData[0]);
+    }, this);
+};
+
+CanvasRenderer.prototype.renderBackgroundRepeat = function(imageContainer, backgroundPosition, size, bounds, borderLeft, borderTop) {
+    var offsetX = Math.round(bounds.left + backgroundPosition.left + borderLeft), offsetY = Math.round(bounds.top + backgroundPosition.top + borderTop);
+    this.setFillStyle(this.ctx.createPattern(this.resizeImage(imageContainer, size), "repeat"));
+    this.ctx.translate(offsetX, offsetY);
+    this.ctx.fill();
+    this.ctx.translate(-offsetX, -offsetY);
+};
+
+CanvasRenderer.prototype.renderBackgroundGradient = function(gradientImage, bounds) {
+    if (gradientImage instanceof LinearGradientContainer) {
+        var gradient = this.ctx.createLinearGradient(
+            bounds.left + bounds.width * gradientImage.x0,
+            bounds.top + bounds.height * gradientImage.y0,
+            bounds.left +  bounds.width * gradientImage.x1,
+            bounds.top +  bounds.height * gradientImage.y1);
+        gradientImage.colorStops.forEach(function(colorStop) {
+            gradient.addColorStop(colorStop.stop, colorStop.color.toString());
+        });
+        this.rectangle(bounds.left, bounds.top, bounds.width, bounds.height, gradient);
+    }
+};
+
+CanvasRenderer.prototype.resizeImage = function(imageContainer, size) {
+    var image = imageContainer.image;
+    if(image.width === size.width && image.height === size.height) {
+        return image;
+    }
+
+    var ctx, canvas = document.createElement('canvas');
+    canvas.width = size.width;
+    canvas.height = size.height;
+    ctx = canvas.getContext("2d");
+    ctx.drawImage(image, 0, 0, image.width, image.height, 0, 0, size.width, size.height );
+    return canvas;
+};
+
+function hasEntries(array) {
+    return array.length > 0;
+}
+
+module.exports = CanvasRenderer;
+
+},{"../lineargradientcontainer":12,"../log":13,"../renderer":19}],21:[function(_dereq_,module,exports){
+var NodeContainer = _dereq_('./nodecontainer');
+
+function StackingContext(hasOwnStacking, opacity, element, parent) {
+    NodeContainer.call(this, element, parent);
+    this.ownStacking = hasOwnStacking;
+    this.contexts = [];
+    this.children = [];
+    this.opacity = (this.parent ? this.parent.stack.opacity : 1) * opacity;
+}
+
+StackingContext.prototype = Object.create(NodeContainer.prototype);
+
+StackingContext.prototype.getParentStack = function(context) {
+    var parentStack = (this.parent) ? this.parent.stack : null;
+    return parentStack ? (parentStack.ownStacking ? parentStack : parentStack.getParentStack(context)) : context.stack;
+};
+
+module.exports = StackingContext;
+
+},{"./nodecontainer":14}],22:[function(_dereq_,module,exports){
+function Support(document) {
+    this.rangeBounds = this.testRangeBounds(document);
+    this.cors = this.testCORS();
+    this.svg = this.testSVG();
+}
+
+Support.prototype.testRangeBounds = function(document) {
+    var range, testElement, rangeBounds, rangeHeight, support = false;
+
+    if (document.createRange) {
+        range = document.createRange();
+        if (range.getBoundingClientRect) {
+            testElement = document.createElement('boundtest');
+            testElement.style.height = "123px";
+            testElement.style.display = "block";
+            document.body.appendChild(testElement);
+
+            range.selectNode(testElement);
+            rangeBounds = range.getBoundingClientRect();
+            rangeHeight = rangeBounds.height;
+
+            if (rangeHeight === 123) {
+                support = true;
+            }
+            document.body.removeChild(testElement);
+        }
+    }
+
+    return support;
+};
+
+Support.prototype.testCORS = function() {
+    return typeof((new Image()).crossOrigin) !== "undefined";
+};
+
+Support.prototype.testSVG = function() {
+    var img = new Image();
+    var canvas = document.createElement("canvas");
+    var ctx =  canvas.getContext("2d");
+    img.src = "data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg'></svg>";
+
+    try {
+        ctx.drawImage(img, 0, 0);
+        canvas.toDataURL();
+    } catch(e) {
+        return false;
+    }
+    return true;
+};
+
+module.exports = Support;
+
+},{}],23:[function(_dereq_,module,exports){
+var XHR = _dereq_('./xhr');
+var decode64 = _dereq_('./utils').decode64;
+
+function SVGContainer(src) {
+    this.src = src;
+    this.image = null;
+    var self = this;
+
+    this.promise = this.hasFabric().then(function() {
+        return (self.isInline(src) ? Promise.resolve(self.inlineFormatting(src)) : XHR(src));
+    }).then(function(svg) {
+        return new Promise(function(resolve) {
+            window.html2canvas.svg.fabric.loadSVGFromString(svg, self.createCanvas.call(self, resolve));
+        });
+    });
+}
+
+SVGContainer.prototype.hasFabric = function() {
+    return !window.html2canvas.svg || !window.html2canvas.svg.fabric ? Promise.reject(new Error("html2canvas.svg.js is not loaded, cannot render svg")) : Promise.resolve();
+};
+
+SVGContainer.prototype.inlineFormatting = function(src) {
+    return (/^data:image\/svg\+xml;base64,/.test(src)) ? this.decode64(this.removeContentType(src)) : this.removeContentType(src);
+};
+
+SVGContainer.prototype.removeContentType = function(src) {
+    return src.replace(/^data:image\/svg\+xml(;base64)?,/,'');
+};
+
+SVGContainer.prototype.isInline = function(src) {
+    return (/^data:image\/svg\+xml/i.test(src));
+};
+
+SVGContainer.prototype.createCanvas = function(resolve) {
+    var self = this;
+    return function (objects, options) {
+        var canvas = new window.html2canvas.svg.fabric.StaticCanvas('c');
+        self.image = canvas.lowerCanvasEl;
+        canvas
+            .setWidth(options.width)
+            .setHeight(options.height)
+            .add(window.html2canvas.svg.fabric.util.groupSVGElements(objects, options))
+            .renderAll();
+        resolve(canvas.lowerCanvasEl);
+    };
+};
+
+SVGContainer.prototype.decode64 = function(str) {
+    return (typeof(window.atob) === "function") ? window.atob(str) : decode64(str);
+};
+
+module.exports = SVGContainer;
+
+},{"./utils":26,"./xhr":28}],24:[function(_dereq_,module,exports){
+var SVGContainer = _dereq_('./svgcontainer');
+
+function SVGNodeContainer(node, _native) {
+    this.src = node;
+    this.image = null;
+    var self = this;
+
+    this.promise = _native ? new Promise(function(resolve, reject) {
+        self.image = new Image();
+        self.image.onload = resolve;
+        self.image.onerror = reject;
+        self.image.src = "data:image/svg+xml," + (new XMLSerializer()).serializeToString(node);
+        if (self.image.complete === true) {
+            resolve(self.image);
+        }
+    }) : this.hasFabric().then(function() {
+        return new Promise(function(resolve) {
+            window.html2canvas.svg.fabric.parseSVGDocument(node, self.createCanvas.call(self, resolve));
+        });
+    });
+}
+
+SVGNodeContainer.prototype = Object.create(SVGContainer.prototype);
+
+module.exports = SVGNodeContainer;
+
+},{"./svgcontainer":23}],25:[function(_dereq_,module,exports){
+var NodeContainer = _dereq_('./nodecontainer');
+
+function TextContainer(node, parent) {
+    NodeContainer.call(this, node, parent);
+}
+
+TextContainer.prototype = Object.create(NodeContainer.prototype);
+
+TextContainer.prototype.applyTextTransform = function() {
+    this.node.data = this.transform(this.parent.css("textTransform"));
+};
+
+TextContainer.prototype.transform = function(transform) {
+    var text = this.node.data;
+    switch(transform){
+        case "lowercase":
+            return text.toLowerCase();
+        case "capitalize":
+            return text.replace(/(^|\s|:|-|\(|\))([a-z])/g, capitalize);
+        case "uppercase":
+            return text.toUpperCase();
+        default:
+            return text;
+    }
+};
+
+function capitalize(m, p1, p2) {
+    if (m.length > 0) {
+        return p1 + p2.toUpperCase();
+    }
+}
+
+module.exports = TextContainer;
+
+},{"./nodecontainer":14}],26:[function(_dereq_,module,exports){
+exports.smallImage = function smallImage() {
+    return "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";
+};
+
+exports.bind = function(callback, context) {
+    return function() {
+        return callback.apply(context, arguments);
+    };
+};
+
+/*
+ * base64-arraybuffer
+ * https://github.com/niklasvh/base64-arraybuffer
+ *
+ * Copyright (c) 2012 Niklas von Hertzen
+ * Licensed under the MIT license.
+ */
+
+exports.decode64 = function(base64) {
+    var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+    var len = base64.length, i, encoded1, encoded2, encoded3, encoded4, byte1, byte2, byte3;
+
+    var output = "";
+
+    for (i = 0; i < len; i+=4) {
+        encoded1 = chars.indexOf(base64[i]);
+        encoded2 = chars.indexOf(base64[i+1]);
+        encoded3 = chars.indexOf(base64[i+2]);
+        encoded4 = chars.indexOf(base64[i+3]);
+
+        byte1 = (encoded1 << 2) | (encoded2 >> 4);
+        byte2 = ((encoded2 & 15) << 4) | (encoded3 >> 2);
+        byte3 = ((encoded3 & 3) << 6) | encoded4;
+        if (encoded3 === 64) {
+            output += String.fromCharCode(byte1);
+        } else if (encoded4 === 64 || encoded4 === -1) {
+            output += String.fromCharCode(byte1, byte2);
+        } else{
+            output += String.fromCharCode(byte1, byte2, byte3);
+        }
+    }
+
+    return output;
+};
+
+exports.getBounds = function(node) {
+    if (node.getBoundingClientRect) {
+        var clientRect = node.getBoundingClientRect();
+        var width = node.offsetWidth == null ? clientRect.width : node.offsetWidth;
+        return {
+            top: clientRect.top,
+            bottom: clientRect.bottom || (clientRect.top + clientRect.height),
+            right: clientRect.left + width,
+            left: clientRect.left,
+            width:  width,
+            height: node.offsetHeight == null ? clientRect.height : node.offsetHeight
+        };
+    }
+    return {};
+};
+
+exports.offsetBounds = function(node) {
+    var parent = node.offsetParent ? exports.offsetBounds(node.offsetParent) : {top: 0, left: 0};
+
+    return {
+        top: node.offsetTop + parent.top,
+        bottom: node.offsetTop + node.offsetHeight + parent.top,
+        right: node.offsetLeft + parent.left + node.offsetWidth,
+        left: node.offsetLeft + parent.left,
+        width: node.offsetWidth,
+        height: node.offsetHeight
+    };
+};
+
+exports.parseBackgrounds = function(backgroundImage) {
+    var whitespace = ' \r\n\t',
+        method, definition, prefix, prefix_i, block, results = [],
+        mode = 0, numParen = 0, quote, args;
+    var appendResult = function() {
+        if(method) {
+            if (definition.substr(0, 1) === '"') {
+                definition = definition.substr(1, definition.length - 2);
+            }
+            if (definition) {
+                args.push(definition);
+            }
+            if (method.substr(0, 1) === '-' && (prefix_i = method.indexOf('-', 1 ) + 1) > 0) {
+                prefix = method.substr(0, prefix_i);
+                method = method.substr(prefix_i);
+            }
+            results.push({
+                prefix: prefix,
+                method: method.toLowerCase(),
+                value: block,
+                args: args,
+                image: null
+            });
+        }
+        args = [];
+        method = prefix = definition = block = '';
+    };
+    args = [];
+    method = prefix = definition = block = '';
+    backgroundImage.split("").forEach(function(c) {
+        if (mode === 0 && whitespace.indexOf(c) > -1) {
+            return;
+        }
+        switch(c) {
+        case '"':
+            if(!quote) {
+                quote = c;
+            } else if(quote === c) {
+                quote = null;
+            }
+            break;
+        case '(':
+            if(quote) {
+                break;
+            } else if(mode === 0) {
+                mode = 1;
+                block += c;
+                return;
+            } else {
+                numParen++;
+            }
+            break;
+        case ')':
+            if (quote) {
+                break;
+            } else if(mode === 1) {
+                if(numParen === 0) {
+                    mode = 0;
+                    block += c;
+                    appendResult();
+                    return;
+                } else {
+                    numParen--;
+                }
+            }
+            break;
+
+        case ',':
+            if (quote) {
+                break;
+            } else if(mode === 0) {
+                appendResult();
+                return;
+            } else if (mode === 1) {
+                if (numParen === 0 && !method.match(/^url$/i)) {
+                    args.push(definition);
+                    definition = '';
+                    block += c;
+                    return;
+                }
+            }
+            break;
+        }
+
+        block += c;
+        if (mode === 0) {
+            method += c;
+        } else {
+            definition += c;
+        }
+    });
+
+    appendResult();
+    return results;
+};
+
+},{}],27:[function(_dereq_,module,exports){
+var GradientContainer = _dereq_('./gradientcontainer');
+
+function WebkitGradientContainer(imageData) {
+    GradientContainer.apply(this, arguments);
+    this.type = imageData.args[0] === "linear" ? GradientContainer.TYPES.LINEAR : GradientContainer.TYPES.RADIAL;
+}
+
+WebkitGradientContainer.prototype = Object.create(GradientContainer.prototype);
+
+module.exports = WebkitGradientContainer;
+
+},{"./gradientcontainer":9}],28:[function(_dereq_,module,exports){
+function XHR(url) {
+    return new Promise(function(resolve, reject) {
+        var xhr = new XMLHttpRequest();
+        xhr.open('GET', url);
+
+        xhr.onload = function() {
+            if (xhr.status === 200) {
+                resolve(xhr.responseText);
+            } else {
+                reject(new Error(xhr.statusText));
+            }
+        };
+
+        xhr.onerror = function() {
+            reject(new Error("Network Error"));
+        };
+
+        xhr.send();
+    });
+}
+
+module.exports = XHR;
+
+},{}]},{},[4])(4)
+});
+
+// Generated by CoffeeScript 1.4.0
+
+/*
+# PNG.js
+# Copyright (c) 2011 Devon Govett
+# MIT LICENSE
+# 
+# 
+*/
+
+
+(function(global) {
+  var PNG;
+
+  PNG = (function() {
+    var APNG_BLEND_OP_OVER, APNG_BLEND_OP_SOURCE, APNG_DISPOSE_OP_BACKGROUND, APNG_DISPOSE_OP_NONE, APNG_DISPOSE_OP_PREVIOUS, makeImage, scratchCanvas, scratchCtx;
+
+    PNG.load = function(url, canvas, callback) {
+      var xhr,
+        _this = this;
+      if (typeof canvas === 'function') {
+        callback = canvas;
+      }
+      xhr = new XMLHttpRequest;
+      xhr.open("GET", url, true);
+      xhr.responseType = "arraybuffer";
+      xhr.onload = function() {
+        var data, png;
+        data = new Uint8Array(xhr.response || xhr.mozResponseArrayBuffer);
+        png = new PNG(data);
+        if (typeof (canvas != null ? canvas.getContext : void 0) === 'function') {
+          png.render(canvas);
+        }
+        return typeof callback === "function" ? callback(png) : void 0;
+      };
+      return xhr.send(null);
+    };
+
+    APNG_DISPOSE_OP_NONE = 0;
+
+    APNG_DISPOSE_OP_BACKGROUND = 1;
+
+    APNG_DISPOSE_OP_PREVIOUS = 2;
+
+    APNG_BLEND_OP_SOURCE = 0;
+
+    APNG_BLEND_OP_OVER = 1;
+
+    function PNG(data) {
+      var chunkSize, colors, palLen, delayDen, delayNum, frame, i, index, key, section, palShort, text, _i, _j, _ref;
+      this.data = data;
+      this.pos = 8;
+      this.palette = [];
+      this.imgData = [];
+      this.transparency = {};
+      this.animation = null;
+      this.text = {};
+      frame = null;
+      while (true) {
+        chunkSize = this.readUInt32();
+        section = ((function() {
+          var _i, _results;
+          _results = [];
+          for (i = _i = 0; _i < 4; i = ++_i) {
+            _results.push(String.fromCharCode(this.data[this.pos++]));
+          }
+          return _results;
+        }).call(this)).join('');
+        switch (section) {
+          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() || Infinity,
+              frames: []
+            };
+            break;
+          case 'PLTE':
+            this.palette = this.read(chunkSize);
+            break;
+          case 'fcTL':
+            if (frame) {
+              this.animation.frames.push(frame);
+            }
+            this.pos += 4;
+            frame = {
+              width: this.readUInt32(),
+              height: this.readUInt32(),
+              xOffset: this.readUInt32(),
+              yOffset: this.readUInt32()
+            };
+            delayNum = this.readUInt16();
+            delayDen = this.readUInt16() || 100;
+            frame.delay = 1000 * delayNum / delayDen;
+            frame.disposeOp = this.data[this.pos++];
+            frame.blendOp = this.data[this.pos++];
+            frame.data = [];
+            break;
+          case 'IDAT':
+          case 'fdAT':
+            if (section === 'fdAT') {
+              this.pos += 4;
+              chunkSize -= 4;
+            }
+            data = (frame != null ? frame.data : void 0) || this.imgData;
+            for (i = _i = 0; 0 <= chunkSize ? _i < chunkSize : _i > chunkSize; i = 0 <= chunkSize ? ++_i : --_i) {
+              data.push(this.data[this.pos++]);
+            }
+            break;
+          case 'tRNS':
+            this.transparency = {};
+            switch (this.colorType) {
+              case 3:
+            	palLen = this.palette.length/3;
+                this.transparency.indexed = this.read(chunkSize);
+                if(this.transparency.indexed.length > palLen)
+                	throw new Error('More transparent colors than palette size');
+                /*
+                 * According to the PNG spec trns should be increased to the same size as palette if shorter
+                 */
+                //palShort = 255 - this.transparency.indexed.length;
+                palShort = palLen - this.transparency.indexed.length;
+                if (palShort > 0) {
+                  for (i = _j = 0; 0 <= palShort ? _j < palShort : _j > palShort; i = 0 <= palShort ? ++_j : --_j) {
+                    this.transparency.indexed.push(255);
+                  }
+                }
+                break;
+              case 0:
+                this.transparency.grayscale = this.read(chunkSize)[0];
+                break;
+              case 2:
+                this.transparency.rgb = this.read(chunkSize);
+            }
+            break;
+          case 'tEXt':
+            text = this.read(chunkSize);
+            index = text.indexOf(0);
+            key = String.fromCharCode.apply(String, text.slice(0, index));
+            this.text[key] = String.fromCharCode.apply(String, text.slice(index + 1));
+            break;
+          case 'IEND':
+            if (frame) {
+              this.animation.frames.push(frame);
+            }
+            this.colors = (function() {
+              switch (this.colorType) {
+                case 0:
+                case 3:
+                case 4:
+                  return 1;
+                case 2:
+                case 6:
+                  return 3;
+              }
+            }).call(this);
+            this.hasAlphaChannel = (_ref = this.colorType) === 4 || _ref === 6;
+            colors = this.colors + (this.hasAlphaChannel ? 1 : 0);
+            this.pixelBitlength = this.bits * colors;
+            this.colorSpace = (function() {
+              switch (this.colors) {
+                case 1:
+                  return 'DeviceGray';
+                case 3:
+                  return 'DeviceRGB';
+              }
+            }).call(this);
+            this.imgData = new Uint8Array(this.imgData);
+            return;
+          default:
+            this.pos += chunkSize;
+        }
+        this.pos += 4;
+        if (this.pos > this.data.length) {
+          throw new Error("Incomplete or corrupt PNG file");
+        }
+      }
+      return;
+    }
+
+    PNG.prototype.read = function(bytes) {
+      var i, _i, _results;
+      _results = [];
+      for (i = _i = 0; 0 <= bytes ? _i < bytes : _i > bytes; i = 0 <= bytes ? ++_i : --_i) {
+        _results.push(this.data[this.pos++]);
+      }
+      return _results;
+    };
+
+    PNG.prototype.readUInt32 = function() {
+      var b1, b2, b3, b4;
+      b1 = this.data[this.pos++] << 24;
+      b2 = this.data[this.pos++] << 16;
+      b3 = this.data[this.pos++] << 8;
+      b4 = this.data[this.pos++];
+      return b1 | b2 | b3 | b4;
+    };
+
+    PNG.prototype.readUInt16 = function() {
+      var b1, b2;
+      b1 = this.data[this.pos++] << 8;
+      b2 = this.data[this.pos++];
+      return b1 | b2;
+    };
+
+    PNG.prototype.decodePixels = function(data) {
+      var abyte, c, col, i, left, length, p, pa, paeth, pb, pc, pixelBytes, pixels, pos, row, scanlineLength, upper, upperLeft, _i, _j, _k, _l, _m;
+      if (data == null) {
+        data = this.imgData;
+      }
+      if (data.length === 0) {
+        return new Uint8Array(0);
+      }
+      data = new FlateStream(data);
+      data = data.getBytes();
+      pixelBytes = this.pixelBitlength / 8;
+      scanlineLength = pixelBytes * this.width;
+      pixels = new Uint8Array(scanlineLength * this.height);
+      length = data.length;
+      row = 0;
+      pos = 0;
+      c = 0;
+      while (pos < length) {
+        switch (data[pos++]) {
+          case 0:
+            for (i = _i = 0; _i < scanlineLength; i = _i += 1) {
+              pixels[c++] = data[pos++];
+            }
+            break;
+          case 1:
+            for (i = _j = 0; _j < scanlineLength; i = _j += 1) {
+              abyte = data[pos++];
+              left = i < pixelBytes ? 0 : pixels[c - pixelBytes];
+              pixels[c++] = (abyte + left) % 256;
+            }
+            break;
+          case 2:
+            for (i = _k = 0; _k < scanlineLength; i = _k += 1) {
+              abyte = data[pos++];
+              col = (i - (i % pixelBytes)) / pixelBytes;
+              upper = row && pixels[(row - 1) * scanlineLength + col * pixelBytes + (i % pixelBytes)];
+              pixels[c++] = (upper + abyte) % 256;
+            }
+            break;
+          case 3:
+            for (i = _l = 0; _l < scanlineLength; i = _l += 1) {
+              abyte = data[pos++];
+              col = (i - (i % pixelBytes)) / pixelBytes;
+              left = i < pixelBytes ? 0 : pixels[c - pixelBytes];
+              upper = row && pixels[(row - 1) * scanlineLength + col * pixelBytes + (i % pixelBytes)];
+              pixels[c++] = (abyte + Math.floor((left + upper) / 2)) % 256;
+            }
+            break;
+          case 4:
+            for (i = _m = 0; _m < scanlineLength; i = _m += 1) {
+              abyte = data[pos++];
+              col = (i - (i % pixelBytes)) / pixelBytes;
+              left = i < pixelBytes ? 0 : pixels[c - pixelBytes];
+              if (row === 0) {
+                upper = upperLeft = 0;
+              } else {
+                upper = pixels[(row - 1) * scanlineLength + col * pixelBytes + (i % pixelBytes)];
+                upperLeft = col && pixels[(row - 1) * scanlineLength + (col - 1) * pixelBytes + (i % pixelBytes)];
+              }
+              p = left + upper - upperLeft;
+              pa = Math.abs(p - left);
+              pb = Math.abs(p - upper);
+              pc = Math.abs(p - upperLeft);
+              if (pa <= pb && pa <= pc) {
+                paeth = left;
+              } else if (pb <= pc) {
+                paeth = upper;
+              } else {
+                paeth = upperLeft;
+              }
+              pixels[c++] = (abyte + paeth) % 256;
+            }
+            break;
+          default:
+            throw new Error("Invalid filter algorithm: " + data[pos - 1]);
+        }
+        row++;
+      }
+      return pixels;
+    };
+
+    PNG.prototype.decodePalette = function() {
+      var c, i, length, palette, pos, ret, transparency, _i, _ref, _ref1;
+      palette = this.palette;
+      transparency = this.transparency.indexed || [];
+      ret = new Uint8Array((transparency.length || 0) + palette.length);
+      pos = 0;
+      length = palette.length;
+      c = 0;
+      for (i = _i = 0, _ref = palette.length; _i < _ref; i = _i += 3) {
+        ret[pos++] = palette[i];
+        ret[pos++] = palette[i + 1];
+        ret[pos++] = palette[i + 2];
+        ret[pos++] = (_ref1 = transparency[c++]) != null ? _ref1 : 255;
+      }
+      return ret;
+    };
+
+    PNG.prototype.copyToImageData = function(imageData, pixels) {
+      var alpha, colors, data, i, input, j, k, length, palette, v, _ref;
+      colors = this.colors;
+      palette = null;
+      alpha = this.hasAlphaChannel;
+      if (this.palette.length) {
+        palette = (_ref = this._decodedPalette) != null ? _ref : this._decodedPalette = this.decodePalette();
+        colors = 4;
+        alpha = true;
+      }
+      data = imageData.data || imageData;
+      length = data.length;
+      input = palette || pixels;
+      i = j = 0;
+      if (colors === 1) {
+        while (i < length) {
+          k = palette ? pixels[i / 4] * 4 : j;
+          v = input[k++];
+          data[i++] = v;
+          data[i++] = v;
+          data[i++] = v;
+          data[i++] = alpha ? input[k++] : 255;
+          j = k;
+        }
+      } else {
+        while (i < length) {
+          k = palette ? pixels[i / 4] * 4 : j;
+          data[i++] = input[k++];
+          data[i++] = input[k++];
+          data[i++] = input[k++];
+          data[i++] = alpha ? input[k++] : 255;
+          j = k;
+        }
+      }
+    };
+
+    PNG.prototype.decode = function() {
+      var ret;
+      ret = new Uint8Array(this.width * this.height * 4);
+      this.copyToImageData(ret, this.decodePixels());
+      return ret;
+    };
+
+    try {
+        scratchCanvas = global.document.createElement('canvas');
+        scratchCtx = scratchCanvas.getContext('2d');
+    } catch(e) {
+        return -1;
+    }
+
+    makeImage = function(imageData) {
+      var img;
+      scratchCtx.width = imageData.width;
+      scratchCtx.height = imageData.height;
+      scratchCtx.clearRect(0, 0, imageData.width, imageData.height);
+      scratchCtx.putImageData(imageData, 0, 0);
+      img = new Image;
+      img.src = scratchCanvas.toDataURL();
+      return img;
+    };
+
+    PNG.prototype.decodeFrames = function(ctx) {
+      var frame, i, imageData, pixels, _i, _len, _ref, _results;
+      if (!this.animation) {
+        return;
+      }
+      _ref = this.animation.frames;
+      _results = [];
+      for (i = _i = 0, _len = _ref.length; _i < _len; i = ++_i) {
+        frame = _ref[i];
+        imageData = ctx.createImageData(frame.width, frame.height);
+        pixels = this.decodePixels(new Uint8Array(frame.data));
+        this.copyToImageData(imageData, pixels);
+        frame.imageData = imageData;
+        _results.push(frame.image = makeImage(imageData));
+      }
+      return _results;
+    };
+
+    PNG.prototype.renderFrame = function(ctx, number) {
+      var frame, frames, prev;
+      frames = this.animation.frames;
+      frame = frames[number];
+      prev = frames[number - 1];
+      if (number === 0) {
+        ctx.clearRect(0, 0, this.width, this.height);
+      }
+      if ((prev != null ? prev.disposeOp : void 0) === APNG_DISPOSE_OP_BACKGROUND) {
+        ctx.clearRect(prev.xOffset, prev.yOffset, prev.width, prev.height);
+      } else if ((prev != null ? prev.disposeOp : void 0) === APNG_DISPOSE_OP_PREVIOUS) {
+        ctx.putImageData(prev.imageData, prev.xOffset, prev.yOffset);
+      }
+      if (frame.blendOp === APNG_BLEND_OP_SOURCE) {
+        ctx.clearRect(frame.xOffset, frame.yOffset, frame.width, frame.height);
+      }
+      return ctx.drawImage(frame.image, frame.xOffset, frame.yOffset);
+    };
+
+    PNG.prototype.animate = function(ctx) {
+      var doFrame, frameNumber, frames, numFrames, numPlays, _ref,
+        _this = this;
+      frameNumber = 0;
+      _ref = this.animation, numFrames = _ref.numFrames, frames = _ref.frames, numPlays = _ref.numPlays;
+      return (doFrame = function() {
+        var f, frame;
+        f = frameNumber++ % numFrames;
+        frame = frames[f];
+        _this.renderFrame(ctx, f);
+        if (numFrames > 1 && frameNumber / numFrames < numPlays) {
+          return _this.animation._timeout = setTimeout(doFrame, frame.delay);
+        }
+      })();
+    };
+
+    PNG.prototype.stopAnimation = function() {
+      var _ref;
+      return clearTimeout((_ref = this.animation) != null ? _ref._timeout : void 0);
+    };
+
+    PNG.prototype.render = function(canvas) {
+      var ctx, data;
+      if (canvas._png) {
+        canvas._png.stopAnimation();
+      }
+      canvas._png = this;
+      canvas.width = this.width;
+      canvas.height = this.height;
+      ctx = canvas.getContext("2d");
+      if (this.animation) {
+        this.decodeFrames(ctx);
+        return this.animate(ctx);
+      } else {
+        data = ctx.createImageData(this.width, this.height);
+        this.copyToImageData(data, this.decodePixels());
+        return ctx.putImageData(data, 0, 0);
+      }
+    };
+
+    return PNG;
+
+  })();
+
+  global.PNG = PNG;
+
+})(typeof window !== "undefined" && window || undefined);
+
+/*
+ * Extracted from pdf.js
+ * https://github.com/andreasgal/pdf.js
+ *
+ * Copyright (c) 2011 Mozilla Foundation
+ *
+ * Contributors: Andreas Gal <gal@mozilla.com>
+ *               Chris G Jones <cjones@mozilla.com>
+ *               Shaon Barman <shaon.barman@gmail.com>
+ *               Vivien Nicolas <21@vingtetun.org>
+ *               Justin D'Arcangelo <justindarc@gmail.com>
+ *               Yury Delendik
+ *
+ * 
+ */
+
+var DecodeStream = (function() {
+  function constructor() {
+    this.pos = 0;
+    this.bufferLength = 0;
+    this.eof = false;
+    this.buffer = null;
+  }
+
+  constructor.prototype = {
+    ensureBuffer: function decodestream_ensureBuffer(requested) {
+      var buffer = this.buffer;
+      var current = buffer ? buffer.byteLength : 0;
+      if (requested < current)
+        return buffer;
+      var size = 512;
+      while (size < requested)
+        size <<= 1;
+      var buffer2 = new Uint8Array(size);
+      for (var i = 0; i < current; ++i)
+        buffer2[i] = buffer[i];
+      return this.buffer = buffer2;
+    },
+    getByte: function decodestream_getByte() {
+      var pos = this.pos;
+      while (this.bufferLength <= pos) {
+        if (this.eof)
+          return null;
+        this.readBlock();
+      }
+      return this.buffer[this.pos++];
+    },
+    getBytes: function decodestream_getBytes(length) {
+      var pos = this.pos;
+
+      if (length) {
+        this.ensureBuffer(pos + length);
+        var end = pos + length;
+
+        while (!this.eof && this.bufferLength < end)
+          this.readBlock();
+
+        var bufEnd = this.bufferLength;
+        if (end > bufEnd)
+          end = bufEnd;
+      } else {
+        while (!this.eof)
+          this.readBlock();
+
+        var end = this.bufferLength;
+      }
+
+      this.pos = end;
+      return this.buffer.subarray(pos, end);
+    },
+    lookChar: function decodestream_lookChar() {
+      var pos = this.pos;
+      while (this.bufferLength <= pos) {
+        if (this.eof)
+          return null;
+        this.readBlock();
+      }
+      return String.fromCharCode(this.buffer[this.pos]);
+    },
+    getChar: function decodestream_getChar() {
+      var pos = this.pos;
+      while (this.bufferLength <= pos) {
+        if (this.eof)
+          return null;
+        this.readBlock();
+      }
+      return String.fromCharCode(this.buffer[this.pos++]);
+    },
+    makeSubStream: function decodestream_makeSubstream(start, length, dict) {
+      var end = start + length;
+      while (this.bufferLength <= end && !this.eof)
+        this.readBlock();
+      return new Stream(this.buffer, start, length, dict);
+    },
+    skip: function decodestream_skip(n) {
+      if (!n)
+        n = 1;
+      this.pos += n;
+    },
+    reset: function decodestream_reset() {
+      this.pos = 0;
+    }
+  };
+
+  return constructor;
+})();
+
+var FlateStream = (function() {
+  if (typeof Uint32Array === 'undefined') {
+    return undefined;
+  }
+  var codeLenCodeMap = new Uint32Array([
+    16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15
+  ]);
+
+  var lengthDecode = new Uint32Array([
+    0x00003, 0x00004, 0x00005, 0x00006, 0x00007, 0x00008, 0x00009, 0x0000a,
+    0x1000b, 0x1000d, 0x1000f, 0x10011, 0x20013, 0x20017, 0x2001b, 0x2001f,
+    0x30023, 0x3002b, 0x30033, 0x3003b, 0x40043, 0x40053, 0x40063, 0x40073,
+    0x50083, 0x500a3, 0x500c3, 0x500e3, 0x00102, 0x00102, 0x00102
+  ]);
+
+  var distDecode = new Uint32Array([
+    0x00001, 0x00002, 0x00003, 0x00004, 0x10005, 0x10007, 0x20009, 0x2000d,
+    0x30011, 0x30019, 0x40021, 0x40031, 0x50041, 0x50061, 0x60081, 0x600c1,
+    0x70101, 0x70181, 0x80201, 0x80301, 0x90401, 0x90601, 0xa0801, 0xa0c01,
+    0xb1001, 0xb1801, 0xc2001, 0xc3001, 0xd4001, 0xd6001
+  ]);
+
+  var fixedLitCodeTab = [new Uint32Array([
+    0x70100, 0x80050, 0x80010, 0x80118, 0x70110, 0x80070, 0x80030, 0x900c0,
+    0x70108, 0x80060, 0x80020, 0x900a0, 0x80000, 0x80080, 0x80040, 0x900e0,
+    0x70104, 0x80058, 0x80018, 0x90090, 0x70114, 0x80078, 0x80038, 0x900d0,
+    0x7010c, 0x80068, 0x80028, 0x900b0, 0x80008, 0x80088, 0x80048, 0x900f0,
+    0x70102, 0x80054, 0x80014, 0x8011c, 0x70112, 0x80074, 0x80034, 0x900c8,
+    0x7010a, 0x80064, 0x80024, 0x900a8, 0x80004, 0x80084, 0x80044, 0x900e8,
+    0x70106, 0x8005c, 0x8001c, 0x90098, 0x70116, 0x8007c, 0x8003c, 0x900d8,
+    0x7010e, 0x8006c, 0x8002c, 0x900b8, 0x8000c, 0x8008c, 0x8004c, 0x900f8,
+    0x70101, 0x80052, 0x80012, 0x8011a, 0x70111, 0x80072, 0x80032, 0x900c4,
+    0x70109, 0x80062, 0x80022, 0x900a4, 0x80002, 0x80082, 0x80042, 0x900e4,
+    0x70105, 0x8005a, 0x8001a, 0x90094, 0x70115, 0x8007a, 0x8003a, 0x900d4,
+    0x7010d, 0x8006a, 0x8002a, 0x900b4, 0x8000a, 0x8008a, 0x8004a, 0x900f4,
+    0x70103, 0x80056, 0x80016, 0x8011e, 0x70113, 0x80076, 0x80036, 0x900cc,
+    0x7010b, 0x80066, 0x80026, 0x900ac, 0x80006, 0x80086, 0x80046, 0x900ec,
+    0x70107, 0x8005e, 0x8001e, 0x9009c, 0x70117, 0x8007e, 0x8003e, 0x900dc,
+    0x7010f, 0x8006e, 0x8002e, 0x900bc, 0x8000e, 0x8008e, 0x8004e, 0x900fc,
+    0x70100, 0x80051, 0x80011, 0x80119, 0x70110, 0x80071, 0x80031, 0x900c2,
+    0x70108, 0x80061, 0x80021, 0x900a2, 0x80001, 0x80081, 0x80041, 0x900e2,
+    0x70104, 0x80059, 0x80019, 0x90092, 0x70114, 0x80079, 0x80039, 0x900d2,
+    0x7010c, 0x80069, 0x80029, 0x900b2, 0x80009, 0x80089, 0x80049, 0x900f2,
+    0x70102, 0x80055, 0x80015, 0x8011d, 0x70112, 0x80075, 0x80035, 0x900ca,
+    0x7010a, 0x80065, 0x80025, 0x900aa, 0x80005, 0x80085, 0x80045, 0x900ea,
+    0x70106, 0x8005d, 0x8001d, 0x9009a, 0x70116, 0x8007d, 0x8003d, 0x900da,
+    0x7010e, 0x8006d, 0x8002d, 0x900ba, 0x8000d, 0x8008d, 0x8004d, 0x900fa,
+    0x70101, 0x80053, 0x80013, 0x8011b, 0x70111, 0x80073, 0x80033, 0x900c6,
+    0x70109, 0x80063, 0x80023, 0x900a6, 0x80003, 0x80083, 0x80043, 0x900e6,
+    0x70105, 0x8005b, 0x8001b, 0x90096, 0x70115, 0x8007b, 0x8003b, 0x900d6,
+    0x7010d, 0x8006b, 0x8002b, 0x900b6, 0x8000b, 0x8008b, 0x8004b, 0x900f6,
+    0x70103, 0x80057, 0x80017, 0x8011f, 0x70113, 0x80077, 0x80037, 0x900ce,
+    0x7010b, 0x80067, 0x80027, 0x900ae, 0x80007, 0x80087, 0x80047, 0x900ee,
+    0x70107, 0x8005f, 0x8001f, 0x9009e, 0x70117, 0x8007f, 0x8003f, 0x900de,
+    0x7010f, 0x8006f, 0x8002f, 0x900be, 0x8000f, 0x8008f, 0x8004f, 0x900fe,
+    0x70100, 0x80050, 0x80010, 0x80118, 0x70110, 0x80070, 0x80030, 0x900c1,
+    0x70108, 0x80060, 0x80020, 0x900a1, 0x80000, 0x80080, 0x80040, 0x900e1,
+    0x70104, 0x80058, 0x80018, 0x90091, 0x70114, 0x80078, 0x80038, 0x900d1,
+    0x7010c, 0x80068, 0x80028, 0x900b1, 0x80008, 0x80088, 0x80048, 0x900f1,
+    0x70102, 0x80054, 0x80014, 0x8011c, 0x70112, 0x80074, 0x80034, 0x900c9,
+    0x7010a, 0x80064, 0x80024, 0x900a9, 0x80004, 0x80084, 0x80044, 0x900e9,
+    0x70106, 0x8005c, 0x8001c, 0x90099, 0x70116, 0x8007c, 0x8003c, 0x900d9,
+    0x7010e, 0x8006c, 0x8002c, 0x900b9, 0x8000c, 0x8008c, 0x8004c, 0x900f9,
+    0x70101, 0x80052, 0x80012, 0x8011a, 0x70111, 0x80072, 0x80032, 0x900c5,
+    0x70109, 0x80062, 0x80022, 0x900a5, 0x80002, 0x80082, 0x80042, 0x900e5,
+    0x70105, 0x8005a, 0x8001a, 0x90095, 0x70115, 0x8007a, 0x8003a, 0x900d5,
+    0x7010d, 0x8006a, 0x8002a, 0x900b5, 0x8000a, 0x8008a, 0x8004a, 0x900f5,
+    0x70103, 0x80056, 0x80016, 0x8011e, 0x70113, 0x80076, 0x80036, 0x900cd,
+    0x7010b, 0x80066, 0x80026, 0x900ad, 0x80006, 0x80086, 0x80046, 0x900ed,
+    0x70107, 0x8005e, 0x8001e, 0x9009d, 0x70117, 0x8007e, 0x8003e, 0x900dd,
+    0x7010f, 0x8006e, 0x8002e, 0x900bd, 0x8000e, 0x8008e, 0x8004e, 0x900fd,
+    0x70100, 0x80051, 0x80011, 0x80119, 0x70110, 0x80071, 0x80031, 0x900c3,
+    0x70108, 0x80061, 0x80021, 0x900a3, 0x80001, 0x80081, 0x80041, 0x900e3,
+    0x70104, 0x80059, 0x80019, 0x90093, 0x70114, 0x80079, 0x80039, 0x900d3,
+    0x7010c, 0x80069, 0x80029, 0x900b3, 0x80009, 0x80089, 0x80049, 0x900f3,
+    0x70102, 0x80055, 0x80015, 0x8011d, 0x70112, 0x80075, 0x80035, 0x900cb,
+    0x7010a, 0x80065, 0x80025, 0x900ab, 0x80005, 0x80085, 0x80045, 0x900eb,
+    0x70106, 0x8005d, 0x8001d, 0x9009b, 0x70116, 0x8007d, 0x8003d, 0x900db,
+    0x7010e, 0x8006d, 0x8002d, 0x900bb, 0x8000d, 0x8008d, 0x8004d, 0x900fb,
+    0x70101, 0x80053, 0x80013, 0x8011b, 0x70111, 0x80073, 0x80033, 0x900c7,
+    0x70109, 0x80063, 0x80023, 0x900a7, 0x80003, 0x80083, 0x80043, 0x900e7,
+    0x70105, 0x8005b, 0x8001b, 0x90097, 0x70115, 0x8007b, 0x8003b, 0x900d7,
+    0x7010d, 0x8006b, 0x8002b, 0x900b7, 0x8000b, 0x8008b, 0x8004b, 0x900f7,
+    0x70103, 0x80057, 0x80017, 0x8011f, 0x70113, 0x80077, 0x80037, 0x900cf,
+    0x7010b, 0x80067, 0x80027, 0x900af, 0x80007, 0x80087, 0x80047, 0x900ef,
+    0x70107, 0x8005f, 0x8001f, 0x9009f, 0x70117, 0x8007f, 0x8003f, 0x900df,
+    0x7010f, 0x8006f, 0x8002f, 0x900bf, 0x8000f, 0x8008f, 0x8004f, 0x900ff
+  ]), 9];
+
+  var fixedDistCodeTab = [new Uint32Array([
+    0x50000, 0x50010, 0x50008, 0x50018, 0x50004, 0x50014, 0x5000c, 0x5001c,
+    0x50002, 0x50012, 0x5000a, 0x5001a, 0x50006, 0x50016, 0x5000e, 0x00000,
+    0x50001, 0x50011, 0x50009, 0x50019, 0x50005, 0x50015, 0x5000d, 0x5001d,
+    0x50003, 0x50013, 0x5000b, 0x5001b, 0x50007, 0x50017, 0x5000f, 0x00000
+  ]), 5];
+  
+  function error(e) {
+      throw new Error(e)
+  }
+
+  function constructor(bytes) {
+    //var bytes = stream.getBytes();
+    var bytesPos = 0;
+
+    var cmf = bytes[bytesPos++];
+    var flg = bytes[bytesPos++];
+    if (cmf == -1 || flg == -1)
+      error('Invalid header in flate stream');
+    if ((cmf & 0x0f) != 0x08)
+      error('Unknown compression method in flate stream');
+    if ((((cmf << 8) + flg) % 31) != 0)
+      error('Bad FCHECK in flate stream');
+    if (flg & 0x20)
+      error('FDICT bit set in flate stream');
+
+    this.bytes = bytes;
+    this.bytesPos = bytesPos;
+
+    this.codeSize = 0;
+    this.codeBuf = 0;
+
+    DecodeStream.call(this);
+  }
+
+  constructor.prototype = Object.create(DecodeStream.prototype);
+
+  constructor.prototype.getBits = function(bits) {
+    var codeSize = this.codeSize;
+    var codeBuf = this.codeBuf;
+    var bytes = this.bytes;
+    var bytesPos = this.bytesPos;
+
+    var b;
+    while (codeSize < bits) {
+      if (typeof (b = bytes[bytesPos++]) == 'undefined')
+        error('Bad encoding in flate stream');
+      codeBuf |= b << codeSize;
+      codeSize += 8;
+    }
+    b = codeBuf & ((1 << bits) - 1);
+    this.codeBuf = codeBuf >> bits;
+    this.codeSize = codeSize -= bits;
+    this.bytesPos = bytesPos;
+    return b;
+  };
+
+  constructor.prototype.getCode = function(table) {
+    var codes = table[0];
+    var maxLen = table[1];
+    var codeSize = this.codeSize;
+    var codeBuf = this.codeBuf;
+    var bytes = this.bytes;
+    var bytesPos = this.bytesPos;
+
+    while (codeSize < maxLen) {
+      var b;
+      if (typeof (b = bytes[bytesPos++]) == 'undefined')
+        error('Bad encoding in flate stream');
+      codeBuf |= (b << codeSize);
+      codeSize += 8;
+    }
+    var code = codes[codeBuf & ((1 << maxLen) - 1)];
+    var codeLen = code >> 16;
+    var codeVal = code & 0xffff;
+    if (codeSize == 0 || codeSize < codeLen || codeLen == 0)
+      error('Bad encoding in flate stream');
+    this.codeBuf = (codeBuf >> codeLen);
+    this.codeSize = (codeSize - codeLen);
+    this.bytesPos = bytesPos;
+    return codeVal;
+  };
+
+  constructor.prototype.generateHuffmanTable = function(lengths) {
+    var n = lengths.length;
+
+    // find max code length
+    var maxLen = 0;
+    for (var i = 0; i < n; ++i) {
+      if (lengths[i] > maxLen)
+        maxLen = lengths[i];
+    }
+
+    // build the table
+    var size = 1 << maxLen;
+    var codes = new Uint32Array(size);
+    for (var len = 1, code = 0, skip = 2;
+         len <= maxLen;
+         ++len, code <<= 1, skip <<= 1) {
+      for (var val = 0; val < n; ++val) {
+        if (lengths[val] == len) {
+          // bit-reverse the code
+          var code2 = 0;
+          var t = code;
+          for (var i = 0; i < len; ++i) {
+            code2 = (code2 << 1) | (t & 1);
+            t >>= 1;
+          }
+
+          // fill the table entries
+          for (var i = code2; i < size; i += skip)
+            codes[i] = (len << 16) | val;
+
+          ++code;
+        }
+      }
+    }
+
+    return [codes, maxLen];
+  };
+
+  constructor.prototype.readBlock = function() {
+    function repeat(stream, array, len, offset, what) {
+      var repeat = stream.getBits(len) + offset;
+      while (repeat-- > 0)
+        array[i++] = what;
+    }
+
+    // read block header
+    var hdr = this.getBits(3);
+    if (hdr & 1)
+      this.eof = true;
+    hdr >>= 1;
+
+    if (hdr == 0) { // uncompressed block
+      var bytes = this.bytes;
+      var bytesPos = this.bytesPos;
+      var b;
+
+      if (typeof (b = bytes[bytesPos++]) == 'undefined')
+        error('Bad block header in flate stream');
+      var blockLen = b;
+      if (typeof (b = bytes[bytesPos++]) == 'undefined')
+        error('Bad block header in flate stream');
+      blockLen |= (b << 8);
+      if (typeof (b = bytes[bytesPos++]) == 'undefined')
+        error('Bad block header in flate stream');
+      var check = b;
+      if (typeof (b = bytes[bytesPos++]) == 'undefined')
+        error('Bad block header in flate stream');
+      check |= (b << 8);
+      if (check != (~blockLen & 0xffff))
+        error('Bad uncompressed block length in flate stream');
+
+      this.codeBuf = 0;
+      this.codeSize = 0;
+
+      var bufferLength = this.bufferLength;
+      var buffer = this.ensureBuffer(bufferLength + blockLen);
+      var end = bufferLength + blockLen;
+      this.bufferLength = end;
+      for (var n = bufferLength; n < end; ++n) {
+        if (typeof (b = bytes[bytesPos++]) == 'undefined') {
+          this.eof = true;
+          break;
+        }
+        buffer[n] = b;
+      }
+      this.bytesPos = bytesPos;
+      return;
+    }
+
+    var litCodeTable;
+    var distCodeTable;
+    if (hdr == 1) { // compressed block, fixed codes
+      litCodeTable = fixedLitCodeTab;
+      distCodeTable = fixedDistCodeTab;
+    } else if (hdr == 2) { // compressed block, dynamic codes
+      var numLitCodes = this.getBits(5) + 257;
+      var numDistCodes = this.getBits(5) + 1;
+      var numCodeLenCodes = this.getBits(4) + 4;
+
+      // build the code lengths code table
+      var codeLenCodeLengths = Array(codeLenCodeMap.length);
+      var i = 0;
+      while (i < numCodeLenCodes)
+        codeLenCodeLengths[codeLenCodeMap[i++]] = this.getBits(3);
+      var codeLenCodeTab = this.generateHuffmanTable(codeLenCodeLengths);
+
+      // build the literal and distance code tables
+      var len = 0;
+      var i = 0;
+      var codes = numLitCodes + numDistCodes;
+      var codeLengths = new Array(codes);
+      while (i < codes) {
+        var code = this.getCode(codeLenCodeTab);
+        if (code == 16) {
+          repeat(this, codeLengths, 2, 3, len);
+        } else if (code == 17) {
+          repeat(this, codeLengths, 3, 3, len = 0);
+        } else if (code == 18) {
+          repeat(this, codeLengths, 7, 11, len = 0);
+        } else {
+          codeLengths[i++] = len = code;
+        }
+      }
+
+      litCodeTable =
+        this.generateHuffmanTable(codeLengths.slice(0, numLitCodes));
+      distCodeTable =
+        this.generateHuffmanTable(codeLengths.slice(numLitCodes, codes));
+    } else {
+      error('Unknown block type in flate stream');
+    }
+
+    var buffer = this.buffer;
+    var limit = buffer ? buffer.length : 0;
+    var pos = this.bufferLength;
+    while (true) {
+      var code1 = this.getCode(litCodeTable);
+      if (code1 < 256) {
+        if (pos + 1 >= limit) {
+          buffer = this.ensureBuffer(pos + 1);
+          limit = buffer.length;
+        }
+        buffer[pos++] = code1;
+        continue;
+      }
+      if (code1 == 256) {
+        this.bufferLength = pos;
+        return;
+      }
+      code1 -= 257;
+      code1 = lengthDecode[code1];
+      var code2 = code1 >> 16;
+      if (code2 > 0)
+        code2 = this.getBits(code2);
+      var len = (code1 & 0xffff) + code2;
+      code1 = this.getCode(distCodeTable);
+      code1 = distDecode[code1];
+      code2 = code1 >> 16;
+      if (code2 > 0)
+        code2 = this.getBits(code2);
+      var dist = (code1 & 0xffff) + code2;
+      if (pos + len >= limit) {
+        buffer = this.ensureBuffer(pos + len);
+        limit = buffer.length;
+      }
+      for (var k = 0; k < len; ++k, ++pos)
+        buffer[pos] = buffer[pos - dist];
+    }
+  };
+
+  return constructor;
+})();
+
+/**
+ * JavaScript Polyfill functions for jsPDF
+ * Collected from public resources by
+ * https://github.com/diegocr
+ */
+
+(function (global) {
+	var b64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
+
+	if (typeof global.btoa === 'undefined') {
+		global.btoa = function(data) {
+			//  discuss at: http://phpjs.org/functions/base64_encode/
+			// original by: Tyler Akins (http://rumkin.com)
+			// improved by: Bayron Guevara
+			// improved by: Thunder.m
+			// improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
+			// improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
+			// improved by: Rafal Kukawski (http://kukawski.pl)
+			// bugfixed by: Pellentesque Malesuada
+			//   example 1: base64_encode('Kevin van Zonneveld');
+			//   returns 1: 'S2V2aW4gdmFuIFpvbm5ldmVsZA=='
+
+			var o1,o2,o3,h1,h2,h3,h4,bits,i = 0,ac = 0,enc = '',tmp_arr = [];
+
+			if (!data) {
+				return data;
+			}
+
+			do { // pack three octets into four hexets
+				o1 = data.charCodeAt(i++);
+				o2 = data.charCodeAt(i++);
+				o3 = data.charCodeAt(i++);
+
+				bits = o1 << 16 | o2 << 8 | o3;
+
+				h1 = bits >> 18 & 0x3f;
+				h2 = bits >> 12 & 0x3f;
+				h3 = bits >> 6 & 0x3f;
+				h4 = bits & 0x3f;
+
+				// use hexets to index into b64, and append result to encoded string
+				tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
+			} while (i < data.length);
+
+			enc = tmp_arr.join('');
+
+			var r = data.length % 3;
+
+			return (r ? enc.slice(0, r - 3) : enc) + '==='.slice(r || 3);
+		};
+	}
+
+	if (typeof global.atob === 'undefined') {
+		global.atob = function(data) {
+			//  discuss at: http://phpjs.org/functions/base64_decode/
+			// original by: Tyler Akins (http://rumkin.com)
+			// improved by: Thunder.m
+			// improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
+			// improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
+			//    input by: Aman Gupta
+			//    input by: Brett Zamir (http://brett-zamir.me)
+			// bugfixed by: Onno Marsman
+			// bugfixed by: Pellentesque Malesuada
+			// bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
+			//   example 1: base64_decode('S2V2aW4gdmFuIFpvbm5ldmVsZA==');
+			//   returns 1: 'Kevin van Zonneveld'
+
+			var o1,o2,o3,h1,h2,h3,h4,bits,i = 0,ac = 0,dec = '',tmp_arr = [];
+
+			if (!data) {
+				return data;
+			}
+
+			data += '';
+
+			do { // unpack four hexets into three octets using index points in b64
+				h1 = b64.indexOf(data.charAt(i++));
+				h2 = b64.indexOf(data.charAt(i++));
+				h3 = b64.indexOf(data.charAt(i++));
+				h4 = b64.indexOf(data.charAt(i++));
+
+				bits = h1 << 18 | h2 << 12 | h3 << 6 | h4;
+
+				o1 = bits >> 16 & 0xff;
+				o2 = bits >> 8 & 0xff;
+				o3 = bits & 0xff;
+
+				if (h3 == 64) {
+					tmp_arr[ac++] = String.fromCharCode(o1);
+				} else if (h4 == 64) {
+					tmp_arr[ac++] = String.fromCharCode(o1, o2);
+				} else {
+					tmp_arr[ac++] = String.fromCharCode(o1, o2, o3);
+				}
+			} while (i < data.length);
+
+			dec = tmp_arr.join('');
+
+			return dec;
+		};
+	}
+
+	if (!Array.prototype.map) {
+		Array.prototype.map = function(fun /*, thisArg */) {
+			if (this === void 0 || this === null || typeof fun !== "function")
+				throw new TypeError();
+
+			var t = Object(this), len = t.length >>> 0, res = new Array(len);
+			var thisArg = arguments.length > 1 ? arguments[1] : void 0;
+			for (var i = 0; i < len; i++) {
+				// NOTE: Absolute correctness would demand Object.defineProperty
+				//       be used.  But this method is fairly new, and failure is
+				//       possible only if Object.prototype or Array.prototype
+				//       has a property |i| (very unlikely), so use a less-correct
+				//       but more portable alternative.
+				if (i in t)
+					res[i] = fun.call(thisArg, t[i], i, t);
+			}
+
+			return res;
+		};
+	}
+
+
+	if(!Array.isArray) {
+		Array.isArray = function(arg) {
+			return Object.prototype.toString.call(arg) === '[object Array]';
+		};
+	}
+
+	if (!Array.prototype.forEach) {
+		Array.prototype.forEach = function(fun, thisArg) {
+			"use strict";
+
+			if (this === void 0 || this === null || typeof fun !== "function")
+				throw new TypeError();
+
+			var t = Object(this), len = t.length >>> 0;
+			for (var i = 0; i < len; i++) {
+				if (i in t)
+					fun.call(thisArg, t[i], i, t);
+			}
+		};
+	}
+
+	if (!Object.keys) {
+		Object.keys = (function () {
+			'use strict';
+
+			var hasOwnProperty = Object.prototype.hasOwnProperty,
+				hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),
+				dontEnums = ['toString','toLocaleString','valueOf','hasOwnProperty',
+					'isPrototypeOf','propertyIsEnumerable','constructor'],
+				dontEnumsLength = dontEnums.length;
+
+			return function (obj) {
+				if (typeof obj !== 'object' && (typeof obj !== 'function' || obj === null)) {
+					throw new TypeError();
+				}
+				var result = [], prop, i;
+
+				for (prop in obj) {
+					if (hasOwnProperty.call(obj, prop)) {
+						result.push(prop);
+					}
+				}
+
+				if (hasDontEnumBug) {
+					for (i = 0; i < dontEnumsLength; i++) {
+						if (hasOwnProperty.call(obj, dontEnums[i])) {
+							result.push(dontEnums[i]);
+						}
+					}
+				}
+				return result;
+			};
+		}());
+	}
+
+	if (!String.prototype.trim) {
+		String.prototype.trim = function () {
+			return this.replace(/^\s+|\s+$/g, '');
+		};
+	}
+	if (!String.prototype.trimLeft) {
+		String.prototype.trimLeft = function() {
+			return this.replace(/^\s+/g, "");
+		};
+	}
+	if (!String.prototype.trimRight) {
+		String.prototype.trimRight = function() {
+			return this.replace(/\s+$/g, "");
+		};
+	}
+
+})(typeof self !== "undefined" && self || typeof window !== "undefined" && window || undefined);
+
+return jsPDF;
+
+})));

+ 4463 - 0
static/lib/moment/moment.js

@@ -0,0 +1,4463 @@
+//! moment.js
+//! version : 2.18.1
+//! authors : Tim Wood, Iskren Chernev, Moment.js contributors
+//! license : MIT
+//! momentjs.com
+
+;(function (global, factory) {
+    typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
+    typeof define === 'function' && define.amd ? define(factory) :
+    global.moment = factory()
+}(this, (function () { 'use strict';
+
+var hookCallback;
+
+function hooks () {
+    return hookCallback.apply(null, arguments);
+}
+
+// This is done to register the method called with moment()
+// without creating circular dependencies.
+function setHookCallback (callback) {
+    hookCallback = callback;
+}
+
+function isArray(input) {
+    return input instanceof Array || Object.prototype.toString.call(input) === '[object Array]';
+}
+
+function isObject(input) {
+    // IE8 will treat undefined and null as object if it wasn't for
+    // input != null
+    return input != null && Object.prototype.toString.call(input) === '[object Object]';
+}
+
+function isObjectEmpty(obj) {
+    var k;
+    for (k in obj) {
+        // even if its not own property I'd still call it non-empty
+        return false;
+    }
+    return true;
+}
+
+function isUndefined(input) {
+    return input === void 0;
+}
+
+function isNumber(input) {
+    return typeof input === 'number' || Object.prototype.toString.call(input) === '[object Number]';
+}
+
+function isDate(input) {
+    return input instanceof Date || Object.prototype.toString.call(input) === '[object Date]';
+}
+
+function map(arr, fn) {
+    var res = [], i;
+    for (i = 0; i < arr.length; ++i) {
+        res.push(fn(arr[i], i));
+    }
+    return res;
+}
+
+function hasOwnProp(a, b) {
+    return Object.prototype.hasOwnProperty.call(a, b);
+}
+
+function extend(a, b) {
+    for (var i in b) {
+        if (hasOwnProp(b, i)) {
+            a[i] = b[i];
+        }
+    }
+
+    if (hasOwnProp(b, 'toString')) {
+        a.toString = b.toString;
+    }
+
+    if (hasOwnProp(b, 'valueOf')) {
+        a.valueOf = b.valueOf;
+    }
+
+    return a;
+}
+
+function createUTC (input, format, locale, strict) {
+    return createLocalOrUTC(input, format, locale, strict, true).utc();
+}
+
+function defaultParsingFlags() {
+    // We need to deep clone this object.
+    return {
+        empty           : false,
+        unusedTokens    : [],
+        unusedInput     : [],
+        overflow        : -2,
+        charsLeftOver   : 0,
+        nullInput       : false,
+        invalidMonth    : null,
+        invalidFormat   : false,
+        userInvalidated : false,
+        iso             : false,
+        parsedDateParts : [],
+        meridiem        : null,
+        rfc2822         : false,
+        weekdayMismatch : false
+    };
+}
+
+function getParsingFlags(m) {
+    if (m._pf == null) {
+        m._pf = defaultParsingFlags();
+    }
+    return m._pf;
+}
+
+var some;
+if (Array.prototype.some) {
+    some = Array.prototype.some;
+} else {
+    some = function (fun) {
+        var t = Object(this);
+        var len = t.length >>> 0;
+
+        for (var i = 0; i < len; i++) {
+            if (i in t && fun.call(this, t[i], i, t)) {
+                return true;
+            }
+        }
+
+        return false;
+    };
+}
+
+var some$1 = some;
+
+function isValid(m) {
+    if (m._isValid == null) {
+        var flags = getParsingFlags(m);
+        var parsedParts = some$1.call(flags.parsedDateParts, function (i) {
+            return i != null;
+        });
+        var isNowValid = !isNaN(m._d.getTime()) &&
+            flags.overflow < 0 &&
+            !flags.empty &&
+            !flags.invalidMonth &&
+            !flags.invalidWeekday &&
+            !flags.nullInput &&
+            !flags.invalidFormat &&
+            !flags.userInvalidated &&
+            (!flags.meridiem || (flags.meridiem && parsedParts));
+
+        if (m._strict) {
+            isNowValid = isNowValid &&
+                flags.charsLeftOver === 0 &&
+                flags.unusedTokens.length === 0 &&
+                flags.bigHour === undefined;
+        }
+
+        if (Object.isFrozen == null || !Object.isFrozen(m)) {
+            m._isValid = isNowValid;
+        }
+        else {
+            return isNowValid;
+        }
+    }
+    return m._isValid;
+}
+
+function createInvalid (flags) {
+    var m = createUTC(NaN);
+    if (flags != null) {
+        extend(getParsingFlags(m), flags);
+    }
+    else {
+        getParsingFlags(m).userInvalidated = true;
+    }
+
+    return m;
+}
+
+// Plugins that add properties should also add the key here (null value),
+// so we can properly clone ourselves.
+var momentProperties = hooks.momentProperties = [];
+
+function copyConfig(to, from) {
+    var i, prop, val;
+
+    if (!isUndefined(from._isAMomentObject)) {
+        to._isAMomentObject = from._isAMomentObject;
+    }
+    if (!isUndefined(from._i)) {
+        to._i = from._i;
+    }
+    if (!isUndefined(from._f)) {
+        to._f = from._f;
+    }
+    if (!isUndefined(from._l)) {
+        to._l = from._l;
+    }
+    if (!isUndefined(from._strict)) {
+        to._strict = from._strict;
+    }
+    if (!isUndefined(from._tzm)) {
+        to._tzm = from._tzm;
+    }
+    if (!isUndefined(from._isUTC)) {
+        to._isUTC = from._isUTC;
+    }
+    if (!isUndefined(from._offset)) {
+        to._offset = from._offset;
+    }
+    if (!isUndefined(from._pf)) {
+        to._pf = getParsingFlags(from);
+    }
+    if (!isUndefined(from._locale)) {
+        to._locale = from._locale;
+    }
+
+    if (momentProperties.length > 0) {
+        for (i = 0; i < momentProperties.length; i++) {
+            prop = momentProperties[i];
+            val = from[prop];
+            if (!isUndefined(val)) {
+                to[prop] = val;
+            }
+        }
+    }
+
+    return to;
+}
+
+var updateInProgress = false;
+
+// Moment prototype object
+function Moment(config) {
+    copyConfig(this, config);
+    this._d = new Date(config._d != null ? config._d.getTime() : NaN);
+    if (!this.isValid()) {
+        this._d = new Date(NaN);
+    }
+    // Prevent infinite loop in case updateOffset creates new moment
+    // objects.
+    if (updateInProgress === false) {
+        updateInProgress = true;
+        hooks.updateOffset(this);
+        updateInProgress = false;
+    }
+}
+
+function isMoment (obj) {
+    return obj instanceof Moment || (obj != null && obj._isAMomentObject != null);
+}
+
+function absFloor (number) {
+    if (number < 0) {
+        // -0 -> 0
+        return Math.ceil(number) || 0;
+    } else {
+        return Math.floor(number);
+    }
+}
+
+function toInt(argumentForCoercion) {
+    var coercedNumber = +argumentForCoercion,
+        value = 0;
+
+    if (coercedNumber !== 0 && isFinite(coercedNumber)) {
+        value = absFloor(coercedNumber);
+    }
+
+    return value;
+}
+
+// compare two arrays, return the number of differences
+function compareArrays(array1, array2, dontConvert) {
+    var len = Math.min(array1.length, array2.length),
+        lengthDiff = Math.abs(array1.length - array2.length),
+        diffs = 0,
+        i;
+    for (i = 0; i < len; i++) {
+        if ((dontConvert && array1[i] !== array2[i]) ||
+            (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) {
+            diffs++;
+        }
+    }
+    return diffs + lengthDiff;
+}
+
+function warn(msg) {
+    if (hooks.suppressDeprecationWarnings === false &&
+            (typeof console !==  'undefined') && console.warn) {
+        console.warn('Deprecation warning: ' + msg);
+    }
+}
+
+function deprecate(msg, fn) {
+    var firstTime = true;
+
+    return extend(function () {
+        if (hooks.deprecationHandler != null) {
+            hooks.deprecationHandler(null, msg);
+        }
+        if (firstTime) {
+            var args = [];
+            var arg;
+            for (var i = 0; i < arguments.length; i++) {
+                arg = '';
+                if (typeof arguments[i] === 'object') {
+                    arg += '\n[' + i + '] ';
+                    for (var key in arguments[0]) {
+                        arg += key + ': ' + arguments[0][key] + ', ';
+                    }
+                    arg = arg.slice(0, -2); // Remove trailing comma and space
+                } else {
+                    arg = arguments[i];
+                }
+                args.push(arg);
+            }
+            warn(msg + '\nArguments: ' + Array.prototype.slice.call(args).join('') + '\n' + (new Error()).stack);
+            firstTime = false;
+        }
+        return fn.apply(this, arguments);
+    }, fn);
+}
+
+var deprecations = {};
+
+function deprecateSimple(name, msg) {
+    if (hooks.deprecationHandler != null) {
+        hooks.deprecationHandler(name, msg);
+    }
+    if (!deprecations[name]) {
+        warn(msg);
+        deprecations[name] = true;
+    }
+}
+
+hooks.suppressDeprecationWarnings = false;
+hooks.deprecationHandler = null;
+
+function isFunction(input) {
+    return input instanceof Function || Object.prototype.toString.call(input) === '[object Function]';
+}
+
+function set (config) {
+    var prop, i;
+    for (i in config) {
+        prop = config[i];
+        if (isFunction(prop)) {
+            this[i] = prop;
+        } else {
+            this['_' + i] = prop;
+        }
+    }
+    this._config = config;
+    // Lenient ordinal parsing accepts just a number in addition to
+    // number + (possibly) stuff coming from _dayOfMonthOrdinalParse.
+    // TODO: Remove "ordinalParse" fallback in next major release.
+    this._dayOfMonthOrdinalParseLenient = new RegExp(
+        (this._dayOfMonthOrdinalParse.source || this._ordinalParse.source) +
+            '|' + (/\d{1,2}/).source);
+}
+
+function mergeConfigs(parentConfig, childConfig) {
+    var res = extend({}, parentConfig), prop;
+    for (prop in childConfig) {
+        if (hasOwnProp(childConfig, prop)) {
+            if (isObject(parentConfig[prop]) && isObject(childConfig[prop])) {
+                res[prop] = {};
+                extend(res[prop], parentConfig[prop]);
+                extend(res[prop], childConfig[prop]);
+            } else if (childConfig[prop] != null) {
+                res[prop] = childConfig[prop];
+            } else {
+                delete res[prop];
+            }
+        }
+    }
+    for (prop in parentConfig) {
+        if (hasOwnProp(parentConfig, prop) &&
+                !hasOwnProp(childConfig, prop) &&
+                isObject(parentConfig[prop])) {
+            // make sure changes to properties don't modify parent config
+            res[prop] = extend({}, res[prop]);
+        }
+    }
+    return res;
+}
+
+function Locale(config) {
+    if (config != null) {
+        this.set(config);
+    }
+}
+
+var keys;
+
+if (Object.keys) {
+    keys = Object.keys;
+} else {
+    keys = function (obj) {
+        var i, res = [];
+        for (i in obj) {
+            if (hasOwnProp(obj, i)) {
+                res.push(i);
+            }
+        }
+        return res;
+    };
+}
+
+var keys$1 = keys;
+
+var defaultCalendar = {
+    sameDay : '[Today at] LT',
+    nextDay : '[Tomorrow at] LT',
+    nextWeek : 'dddd [at] LT',
+    lastDay : '[Yesterday at] LT',
+    lastWeek : '[Last] dddd [at] LT',
+    sameElse : 'L'
+};
+
+function calendar (key, mom, now) {
+    var output = this._calendar[key] || this._calendar['sameElse'];
+    return isFunction(output) ? output.call(mom, now) : output;
+}
+
+var defaultLongDateFormat = {
+    LTS  : 'h:mm:ss A',
+    LT   : 'h:mm A',
+    L    : 'MM/DD/YYYY',
+    LL   : 'MMMM D, YYYY',
+    LLL  : 'MMMM D, YYYY h:mm A',
+    LLLL : 'dddd, MMMM D, YYYY h:mm A'
+};
+
+function longDateFormat (key) {
+    var format = this._longDateFormat[key],
+        formatUpper = this._longDateFormat[key.toUpperCase()];
+
+    if (format || !formatUpper) {
+        return format;
+    }
+
+    this._longDateFormat[key] = formatUpper.replace(/MMMM|MM|DD|dddd/g, function (val) {
+        return val.slice(1);
+    });
+
+    return this._longDateFormat[key];
+}
+
+var defaultInvalidDate = 'Invalid date';
+
+function invalidDate () {
+    return this._invalidDate;
+}
+
+var defaultOrdinal = '%d';
+var defaultDayOfMonthOrdinalParse = /\d{1,2}/;
+
+function ordinal (number) {
+    return this._ordinal.replace('%d', number);
+}
+
+var defaultRelativeTime = {
+    future : 'in %s',
+    past   : '%s ago',
+    s  : 'a few seconds',
+    ss : '%d seconds',
+    m  : 'a minute',
+    mm : '%d minutes',
+    h  : 'an hour',
+    hh : '%d hours',
+    d  : 'a day',
+    dd : '%d days',
+    M  : 'a month',
+    MM : '%d months',
+    y  : 'a year',
+    yy : '%d years'
+};
+
+function relativeTime (number, withoutSuffix, string, isFuture) {
+    var output = this._relativeTime[string];
+    return (isFunction(output)) ?
+        output(number, withoutSuffix, string, isFuture) :
+        output.replace(/%d/i, number);
+}
+
+function pastFuture (diff, output) {
+    var format = this._relativeTime[diff > 0 ? 'future' : 'past'];
+    return isFunction(format) ? format(output) : format.replace(/%s/i, output);
+}
+
+var aliases = {};
+
+function addUnitAlias (unit, shorthand) {
+    var lowerCase = unit.toLowerCase();
+    aliases[lowerCase] = aliases[lowerCase + 's'] = aliases[shorthand] = unit;
+}
+
+function normalizeUnits(units) {
+    return typeof units === 'string' ? aliases[units] || aliases[units.toLowerCase()] : undefined;
+}
+
+function normalizeObjectUnits(inputObject) {
+    var normalizedInput = {},
+        normalizedProp,
+        prop;
+
+    for (prop in inputObject) {
+        if (hasOwnProp(inputObject, prop)) {
+            normalizedProp = normalizeUnits(prop);
+            if (normalizedProp) {
+                normalizedInput[normalizedProp] = inputObject[prop];
+            }
+        }
+    }
+
+    return normalizedInput;
+}
+
+var priorities = {};
+
+function addUnitPriority(unit, priority) {
+    priorities[unit] = priority;
+}
+
+function getPrioritizedUnits(unitsObj) {
+    var units = [];
+    for (var u in unitsObj) {
+        units.push({unit: u, priority: priorities[u]});
+    }
+    units.sort(function (a, b) {
+        return a.priority - b.priority;
+    });
+    return units;
+}
+
+function makeGetSet (unit, keepTime) {
+    return function (value) {
+        if (value != null) {
+            set$1(this, unit, value);
+            hooks.updateOffset(this, keepTime);
+            return this;
+        } else {
+            return get(this, unit);
+        }
+    };
+}
+
+function get (mom, unit) {
+    return mom.isValid() ?
+        mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit]() : NaN;
+}
+
+function set$1 (mom, unit, value) {
+    if (mom.isValid()) {
+        mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value);
+    }
+}
+
+// MOMENTS
+
+function stringGet (units) {
+    units = normalizeUnits(units);
+    if (isFunction(this[units])) {
+        return this[units]();
+    }
+    return this;
+}
+
+
+function stringSet (units, value) {
+    if (typeof units === 'object') {
+        units = normalizeObjectUnits(units);
+        var prioritized = getPrioritizedUnits(units);
+        for (var i = 0; i < prioritized.length; i++) {
+            this[prioritized[i].unit](units[prioritized[i].unit]);
+        }
+    } else {
+        units = normalizeUnits(units);
+        if (isFunction(this[units])) {
+            return this[units](value);
+        }
+    }
+    return this;
+}
+
+function zeroFill(number, targetLength, forceSign) {
+    var absNumber = '' + Math.abs(number),
+        zerosToFill = targetLength - absNumber.length,
+        sign = number >= 0;
+    return (sign ? (forceSign ? '+' : '') : '-') +
+        Math.pow(10, Math.max(0, zerosToFill)).toString().substr(1) + absNumber;
+}
+
+var formattingTokens = /(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g;
+
+var localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g;
+
+var formatFunctions = {};
+
+var formatTokenFunctions = {};
+
+// token:    'M'
+// padded:   ['MM', 2]
+// ordinal:  'Mo'
+// callback: function () { this.month() + 1 }
+function addFormatToken (token, padded, ordinal, callback) {
+    var func = callback;
+    if (typeof callback === 'string') {
+        func = function () {
+            return this[callback]();
+        };
+    }
+    if (token) {
+        formatTokenFunctions[token] = func;
+    }
+    if (padded) {
+        formatTokenFunctions[padded[0]] = function () {
+            return zeroFill(func.apply(this, arguments), padded[1], padded[2]);
+        };
+    }
+    if (ordinal) {
+        formatTokenFunctions[ordinal] = function () {
+            return this.localeData().ordinal(func.apply(this, arguments), token);
+        };
+    }
+}
+
+function removeFormattingTokens(input) {
+    if (input.match(/\[[\s\S]/)) {
+        return input.replace(/^\[|\]$/g, '');
+    }
+    return input.replace(/\\/g, '');
+}
+
+function makeFormatFunction(format) {
+    var array = format.match(formattingTokens), i, length;
+
+    for (i = 0, length = array.length; i < length; i++) {
+        if (formatTokenFunctions[array[i]]) {
+            array[i] = formatTokenFunctions[array[i]];
+        } else {
+            array[i] = removeFormattingTokens(array[i]);
+        }
+    }
+
+    return function (mom) {
+        var output = '', i;
+        for (i = 0; i < length; i++) {
+            output += isFunction(array[i]) ? array[i].call(mom, format) : array[i];
+        }
+        return output;
+    };
+}
+
+// format date using native date object
+function formatMoment(m, format) {
+    if (!m.isValid()) {
+        return m.localeData().invalidDate();
+    }
+
+    format = expandFormat(format, m.localeData());
+    formatFunctions[format] = formatFunctions[format] || makeFormatFunction(format);
+
+    return formatFunctions[format](m);
+}
+
+function expandFormat(format, locale) {
+    var i = 5;
+
+    function replaceLongDateFormatTokens(input) {
+        return locale.longDateFormat(input) || input;
+    }
+
+    localFormattingTokens.lastIndex = 0;
+    while (i >= 0 && localFormattingTokens.test(format)) {
+        format = format.replace(localFormattingTokens, replaceLongDateFormatTokens);
+        localFormattingTokens.lastIndex = 0;
+        i -= 1;
+    }
+
+    return format;
+}
+
+var match1         = /\d/;            //       0 - 9
+var match2         = /\d\d/;          //      00 - 99
+var match3         = /\d{3}/;         //     000 - 999
+var match4         = /\d{4}/;         //    0000 - 9999
+var match6         = /[+-]?\d{6}/;    // -999999 - 999999
+var match1to2      = /\d\d?/;         //       0 - 99
+var match3to4      = /\d\d\d\d?/;     //     999 - 9999
+var match5to6      = /\d\d\d\d\d\d?/; //   99999 - 999999
+var match1to3      = /\d{1,3}/;       //       0 - 999
+var match1to4      = /\d{1,4}/;       //       0 - 9999
+var match1to6      = /[+-]?\d{1,6}/;  // -999999 - 999999
+
+var matchUnsigned  = /\d+/;           //       0 - inf
+var matchSigned    = /[+-]?\d+/;      //    -inf - inf
+
+var matchOffset    = /Z|[+-]\d\d:?\d\d/gi; // +00:00 -00:00 +0000 -0000 or Z
+var matchShortOffset = /Z|[+-]\d\d(?::?\d\d)?/gi; // +00 -00 +00:00 -00:00 +0000 -0000 or Z
+
+var matchTimestamp = /[+-]?\d+(\.\d{1,3})?/; // 123456789 123456789.123
+
+// any word (or two) characters or numbers including two/three word month in arabic.
+// includes scottish gaelic two word and hyphenated months
+var matchWord = /[0-9]*['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+|[\u0600-\u06FF\/]+(\s*?[\u0600-\u06FF]+){1,2}/i;
+
+
+var regexes = {};
+
+function addRegexToken (token, regex, strictRegex) {
+    regexes[token] = isFunction(regex) ? regex : function (isStrict, localeData) {
+        return (isStrict && strictRegex) ? strictRegex : regex;
+    };
+}
+
+function getParseRegexForToken (token, config) {
+    if (!hasOwnProp(regexes, token)) {
+        return new RegExp(unescapeFormat(token));
+    }
+
+    return regexes[token](config._strict, config._locale);
+}
+
+// Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
+function unescapeFormat(s) {
+    return regexEscape(s.replace('\\', '').replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) {
+        return p1 || p2 || p3 || p4;
+    }));
+}
+
+function regexEscape(s) {
+    return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
+}
+
+var tokens = {};
+
+function addParseToken (token, callback) {
+    var i, func = callback;
+    if (typeof token === 'string') {
+        token = [token];
+    }
+    if (isNumber(callback)) {
+        func = function (input, array) {
+            array[callback] = toInt(input);
+        };
+    }
+    for (i = 0; i < token.length; i++) {
+        tokens[token[i]] = func;
+    }
+}
+
+function addWeekParseToken (token, callback) {
+    addParseToken(token, function (input, array, config, token) {
+        config._w = config._w || {};
+        callback(input, config._w, config, token);
+    });
+}
+
+function addTimeToArrayFromToken(token, input, config) {
+    if (input != null && hasOwnProp(tokens, token)) {
+        tokens[token](input, config._a, config, token);
+    }
+}
+
+var YEAR = 0;
+var MONTH = 1;
+var DATE = 2;
+var HOUR = 3;
+var MINUTE = 4;
+var SECOND = 5;
+var MILLISECOND = 6;
+var WEEK = 7;
+var WEEKDAY = 8;
+
+var indexOf;
+
+if (Array.prototype.indexOf) {
+    indexOf = Array.prototype.indexOf;
+} else {
+    indexOf = function (o) {
+        // I know
+        var i;
+        for (i = 0; i < this.length; ++i) {
+            if (this[i] === o) {
+                return i;
+            }
+        }
+        return -1;
+    };
+}
+
+var indexOf$1 = indexOf;
+
+function daysInMonth(year, month) {
+    return new Date(Date.UTC(year, month + 1, 0)).getUTCDate();
+}
+
+// FORMATTING
+
+addFormatToken('M', ['MM', 2], 'Mo', function () {
+    return this.month() + 1;
+});
+
+addFormatToken('MMM', 0, 0, function (format) {
+    return this.localeData().monthsShort(this, format);
+});
+
+addFormatToken('MMMM', 0, 0, function (format) {
+    return this.localeData().months(this, format);
+});
+
+// ALIASES
+
+addUnitAlias('month', 'M');
+
+// PRIORITY
+
+addUnitPriority('month', 8);
+
+// PARSING
+
+addRegexToken('M',    match1to2);
+addRegexToken('MM',   match1to2, match2);
+addRegexToken('MMM',  function (isStrict, locale) {
+    return locale.monthsShortRegex(isStrict);
+});
+addRegexToken('MMMM', function (isStrict, locale) {
+    return locale.monthsRegex(isStrict);
+});
+
+addParseToken(['M', 'MM'], function (input, array) {
+    array[MONTH] = toInt(input) - 1;
+});
+
+addParseToken(['MMM', 'MMMM'], function (input, array, config, token) {
+    var month = config._locale.monthsParse(input, token, config._strict);
+    // if we didn't find a month name, mark the date as invalid.
+    if (month != null) {
+        array[MONTH] = month;
+    } else {
+        getParsingFlags(config).invalidMonth = input;
+    }
+});
+
+// LOCALES
+
+var MONTHS_IN_FORMAT = /D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/;
+var defaultLocaleMonths = 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_');
+function localeMonths (m, format) {
+    if (!m) {
+        return isArray(this._months) ? this._months :
+            this._months['standalone'];
+    }
+    return isArray(this._months) ? this._months[m.month()] :
+        this._months[(this._months.isFormat || MONTHS_IN_FORMAT).test(format) ? 'format' : 'standalone'][m.month()];
+}
+
+var defaultLocaleMonthsShort = 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_');
+function localeMonthsShort (m, format) {
+    if (!m) {
+        return isArray(this._monthsShort) ? this._monthsShort :
+            this._monthsShort['standalone'];
+    }
+    return isArray(this._monthsShort) ? this._monthsShort[m.month()] :
+        this._monthsShort[MONTHS_IN_FORMAT.test(format) ? 'format' : 'standalone'][m.month()];
+}
+
+function handleStrictParse(monthName, format, strict) {
+    var i, ii, mom, llc = monthName.toLocaleLowerCase();
+    if (!this._monthsParse) {
+        // this is not used
+        this._monthsParse = [];
+        this._longMonthsParse = [];
+        this._shortMonthsParse = [];
+        for (i = 0; i < 12; ++i) {
+            mom = createUTC([2000, i]);
+            this._shortMonthsParse[i] = this.monthsShort(mom, '').toLocaleLowerCase();
+            this._longMonthsParse[i] = this.months(mom, '').toLocaleLowerCase();
+        }
+    }
+
+    if (strict) {
+        if (format === 'MMM') {
+            ii = indexOf$1.call(this._shortMonthsParse, llc);
+            return ii !== -1 ? ii : null;
+        } else {
+            ii = indexOf$1.call(this._longMonthsParse, llc);
+            return ii !== -1 ? ii : null;
+        }
+    } else {
+        if (format === 'MMM') {
+            ii = indexOf$1.call(this._shortMonthsParse, llc);
+            if (ii !== -1) {
+                return ii;
+            }
+            ii = indexOf$1.call(this._longMonthsParse, llc);
+            return ii !== -1 ? ii : null;
+        } else {
+            ii = indexOf$1.call(this._longMonthsParse, llc);
+            if (ii !== -1) {
+                return ii;
+            }
+            ii = indexOf$1.call(this._shortMonthsParse, llc);
+            return ii !== -1 ? ii : null;
+        }
+    }
+}
+
+function localeMonthsParse (monthName, format, strict) {
+    var i, mom, regex;
+
+    if (this._monthsParseExact) {
+        return handleStrictParse.call(this, monthName, format, strict);
+    }
+
+    if (!this._monthsParse) {
+        this._monthsParse = [];
+        this._longMonthsParse = [];
+        this._shortMonthsParse = [];
+    }
+
+    // TODO: add sorting
+    // Sorting makes sure if one month (or abbr) is a prefix of another
+    // see sorting in computeMonthsParse
+    for (i = 0; i < 12; i++) {
+        // make the regex if we don't have it already
+        mom = createUTC([2000, i]);
+        if (strict && !this._longMonthsParse[i]) {
+            this._longMonthsParse[i] = new RegExp('^' + this.months(mom, '').replace('.', '') + '$', 'i');
+            this._shortMonthsParse[i] = new RegExp('^' + this.monthsShort(mom, '').replace('.', '') + '$', 'i');
+        }
+        if (!strict && !this._monthsParse[i]) {
+            regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, '');
+            this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i');
+        }
+        // test the regex
+        if (strict && format === 'MMMM' && this._longMonthsParse[i].test(monthName)) {
+            return i;
+        } else if (strict && format === 'MMM' && this._shortMonthsParse[i].test(monthName)) {
+            return i;
+        } else if (!strict && this._monthsParse[i].test(monthName)) {
+            return i;
+        }
+    }
+}
+
+// MOMENTS
+
+function setMonth (mom, value) {
+    var dayOfMonth;
+
+    if (!mom.isValid()) {
+        // No op
+        return mom;
+    }
+
+    if (typeof value === 'string') {
+        if (/^\d+$/.test(value)) {
+            value = toInt(value);
+        } else {
+            value = mom.localeData().monthsParse(value);
+            // TODO: Another silent failure?
+            if (!isNumber(value)) {
+                return mom;
+            }
+        }
+    }
+
+    dayOfMonth = Math.min(mom.date(), daysInMonth(mom.year(), value));
+    mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth);
+    return mom;
+}
+
+function getSetMonth (value) {
+    if (value != null) {
+        setMonth(this, value);
+        hooks.updateOffset(this, true);
+        return this;
+    } else {
+        return get(this, 'Month');
+    }
+}
+
+function getDaysInMonth () {
+    return daysInMonth(this.year(), this.month());
+}
+
+var defaultMonthsShortRegex = matchWord;
+function monthsShortRegex (isStrict) {
+    if (this._monthsParseExact) {
+        if (!hasOwnProp(this, '_monthsRegex')) {
+            computeMonthsParse.call(this);
+        }
+        if (isStrict) {
+            return this._monthsShortStrictRegex;
+        } else {
+            return this._monthsShortRegex;
+        }
+    } else {
+        if (!hasOwnProp(this, '_monthsShortRegex')) {
+            this._monthsShortRegex = defaultMonthsShortRegex;
+        }
+        return this._monthsShortStrictRegex && isStrict ?
+            this._monthsShortStrictRegex : this._monthsShortRegex;
+    }
+}
+
+var defaultMonthsRegex = matchWord;
+function monthsRegex (isStrict) {
+    if (this._monthsParseExact) {
+        if (!hasOwnProp(this, '_monthsRegex')) {
+            computeMonthsParse.call(this);
+        }
+        if (isStrict) {
+            return this._monthsStrictRegex;
+        } else {
+            return this._monthsRegex;
+        }
+    } else {
+        if (!hasOwnProp(this, '_monthsRegex')) {
+            this._monthsRegex = defaultMonthsRegex;
+        }
+        return this._monthsStrictRegex && isStrict ?
+            this._monthsStrictRegex : this._monthsRegex;
+    }
+}
+
+function computeMonthsParse () {
+    function cmpLenRev(a, b) {
+        return b.length - a.length;
+    }
+
+    var shortPieces = [], longPieces = [], mixedPieces = [],
+        i, mom;
+    for (i = 0; i < 12; i++) {
+        // make the regex if we don't have it already
+        mom = createUTC([2000, i]);
+        shortPieces.push(this.monthsShort(mom, ''));
+        longPieces.push(this.months(mom, ''));
+        mixedPieces.push(this.months(mom, ''));
+        mixedPieces.push(this.monthsShort(mom, ''));
+    }
+    // Sorting makes sure if one month (or abbr) is a prefix of another it
+    // will match the longer piece.
+    shortPieces.sort(cmpLenRev);
+    longPieces.sort(cmpLenRev);
+    mixedPieces.sort(cmpLenRev);
+    for (i = 0; i < 12; i++) {
+        shortPieces[i] = regexEscape(shortPieces[i]);
+        longPieces[i] = regexEscape(longPieces[i]);
+    }
+    for (i = 0; i < 24; i++) {
+        mixedPieces[i] = regexEscape(mixedPieces[i]);
+    }
+
+    this._monthsRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
+    this._monthsShortRegex = this._monthsRegex;
+    this._monthsStrictRegex = new RegExp('^(' + longPieces.join('|') + ')', 'i');
+    this._monthsShortStrictRegex = new RegExp('^(' + shortPieces.join('|') + ')', 'i');
+}
+
+// FORMATTING
+
+addFormatToken('Y', 0, 0, function () {
+    var y = this.year();
+    return y <= 9999 ? '' + y : '+' + y;
+});
+
+addFormatToken(0, ['YY', 2], 0, function () {
+    return this.year() % 100;
+});
+
+addFormatToken(0, ['YYYY',   4],       0, 'year');
+addFormatToken(0, ['YYYYY',  5],       0, 'year');
+addFormatToken(0, ['YYYYYY', 6, true], 0, 'year');
+
+// ALIASES
+
+addUnitAlias('year', 'y');
+
+// PRIORITIES
+
+addUnitPriority('year', 1);
+
+// PARSING
+
+addRegexToken('Y',      matchSigned);
+addRegexToken('YY',     match1to2, match2);
+addRegexToken('YYYY',   match1to4, match4);
+addRegexToken('YYYYY',  match1to6, match6);
+addRegexToken('YYYYYY', match1to6, match6);
+
+addParseToken(['YYYYY', 'YYYYYY'], YEAR);
+addParseToken('YYYY', function (input, array) {
+    array[YEAR] = input.length === 2 ? hooks.parseTwoDigitYear(input) : toInt(input);
+});
+addParseToken('YY', function (input, array) {
+    array[YEAR] = hooks.parseTwoDigitYear(input);
+});
+addParseToken('Y', function (input, array) {
+    array[YEAR] = parseInt(input, 10);
+});
+
+// HELPERS
+
+function daysInYear(year) {
+    return isLeapYear(year) ? 366 : 365;
+}
+
+function isLeapYear(year) {
+    return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
+}
+
+// HOOKS
+
+hooks.parseTwoDigitYear = function (input) {
+    return toInt(input) + (toInt(input) > 68 ? 1900 : 2000);
+};
+
+// MOMENTS
+
+var getSetYear = makeGetSet('FullYear', true);
+
+function getIsLeapYear () {
+    return isLeapYear(this.year());
+}
+
+function createDate (y, m, d, h, M, s, ms) {
+    // can't just apply() to create a date:
+    // https://stackoverflow.com/q/181348
+    var date = new Date(y, m, d, h, M, s, ms);
+
+    // the date constructor remaps years 0-99 to 1900-1999
+    if (y < 100 && y >= 0 && isFinite(date.getFullYear())) {
+        date.setFullYear(y);
+    }
+    return date;
+}
+
+function createUTCDate (y) {
+    var date = new Date(Date.UTC.apply(null, arguments));
+
+    // the Date.UTC function remaps years 0-99 to 1900-1999
+    if (y < 100 && y >= 0 && isFinite(date.getUTCFullYear())) {
+        date.setUTCFullYear(y);
+    }
+    return date;
+}
+
+// start-of-first-week - start-of-year
+function firstWeekOffset(year, dow, doy) {
+    var // first-week day -- which january is always in the first week (4 for iso, 1 for other)
+        fwd = 7 + dow - doy,
+        // first-week day local weekday -- which local weekday is fwd
+        fwdlw = (7 + createUTCDate(year, 0, fwd).getUTCDay() - dow) % 7;
+
+    return -fwdlw + fwd - 1;
+}
+
+// https://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday
+function dayOfYearFromWeeks(year, week, weekday, dow, doy) {
+    var localWeekday = (7 + weekday - dow) % 7,
+        weekOffset = firstWeekOffset(year, dow, doy),
+        dayOfYear = 1 + 7 * (week - 1) + localWeekday + weekOffset,
+        resYear, resDayOfYear;
+
+    if (dayOfYear <= 0) {
+        resYear = year - 1;
+        resDayOfYear = daysInYear(resYear) + dayOfYear;
+    } else if (dayOfYear > daysInYear(year)) {
+        resYear = year + 1;
+        resDayOfYear = dayOfYear - daysInYear(year);
+    } else {
+        resYear = year;
+        resDayOfYear = dayOfYear;
+    }
+
+    return {
+        year: resYear,
+        dayOfYear: resDayOfYear
+    };
+}
+
+function weekOfYear(mom, dow, doy) {
+    var weekOffset = firstWeekOffset(mom.year(), dow, doy),
+        week = Math.floor((mom.dayOfYear() - weekOffset - 1) / 7) + 1,
+        resWeek, resYear;
+
+    if (week < 1) {
+        resYear = mom.year() - 1;
+        resWeek = week + weeksInYear(resYear, dow, doy);
+    } else if (week > weeksInYear(mom.year(), dow, doy)) {
+        resWeek = week - weeksInYear(mom.year(), dow, doy);
+        resYear = mom.year() + 1;
+    } else {
+        resYear = mom.year();
+        resWeek = week;
+    }
+
+    return {
+        week: resWeek,
+        year: resYear
+    };
+}
+
+function weeksInYear(year, dow, doy) {
+    var weekOffset = firstWeekOffset(year, dow, doy),
+        weekOffsetNext = firstWeekOffset(year + 1, dow, doy);
+    return (daysInYear(year) - weekOffset + weekOffsetNext) / 7;
+}
+
+// FORMATTING
+
+addFormatToken('w', ['ww', 2], 'wo', 'week');
+addFormatToken('W', ['WW', 2], 'Wo', 'isoWeek');
+
+// ALIASES
+
+addUnitAlias('week', 'w');
+addUnitAlias('isoWeek', 'W');
+
+// PRIORITIES
+
+addUnitPriority('week', 5);
+addUnitPriority('isoWeek', 5);
+
+// PARSING
+
+addRegexToken('w',  match1to2);
+addRegexToken('ww', match1to2, match2);
+addRegexToken('W',  match1to2);
+addRegexToken('WW', match1to2, match2);
+
+addWeekParseToken(['w', 'ww', 'W', 'WW'], function (input, week, config, token) {
+    week[token.substr(0, 1)] = toInt(input);
+});
+
+// HELPERS
+
+// LOCALES
+
+function localeWeek (mom) {
+    return weekOfYear(mom, this._week.dow, this._week.doy).week;
+}
+
+var defaultLocaleWeek = {
+    dow : 0, // Sunday is the first day of the week.
+    doy : 6  // The week that contains Jan 1st is the first week of the year.
+};
+
+function localeFirstDayOfWeek () {
+    return this._week.dow;
+}
+
+function localeFirstDayOfYear () {
+    return this._week.doy;
+}
+
+// MOMENTS
+
+function getSetWeek (input) {
+    var week = this.localeData().week(this);
+    return input == null ? week : this.add((input - week) * 7, 'd');
+}
+
+function getSetISOWeek (input) {
+    var week = weekOfYear(this, 1, 4).week;
+    return input == null ? week : this.add((input - week) * 7, 'd');
+}
+
+// FORMATTING
+
+addFormatToken('d', 0, 'do', 'day');
+
+addFormatToken('dd', 0, 0, function (format) {
+    return this.localeData().weekdaysMin(this, format);
+});
+
+addFormatToken('ddd', 0, 0, function (format) {
+    return this.localeData().weekdaysShort(this, format);
+});
+
+addFormatToken('dddd', 0, 0, function (format) {
+    return this.localeData().weekdays(this, format);
+});
+
+addFormatToken('e', 0, 0, 'weekday');
+addFormatToken('E', 0, 0, 'isoWeekday');
+
+// ALIASES
+
+addUnitAlias('day', 'd');
+addUnitAlias('weekday', 'e');
+addUnitAlias('isoWeekday', 'E');
+
+// PRIORITY
+addUnitPriority('day', 11);
+addUnitPriority('weekday', 11);
+addUnitPriority('isoWeekday', 11);
+
+// PARSING
+
+addRegexToken('d',    match1to2);
+addRegexToken('e',    match1to2);
+addRegexToken('E',    match1to2);
+addRegexToken('dd',   function (isStrict, locale) {
+    return locale.weekdaysMinRegex(isStrict);
+});
+addRegexToken('ddd',   function (isStrict, locale) {
+    return locale.weekdaysShortRegex(isStrict);
+});
+addRegexToken('dddd',   function (isStrict, locale) {
+    return locale.weekdaysRegex(isStrict);
+});
+
+addWeekParseToken(['dd', 'ddd', 'dddd'], function (input, week, config, token) {
+    var weekday = config._locale.weekdaysParse(input, token, config._strict);
+    // if we didn't get a weekday name, mark the date as invalid
+    if (weekday != null) {
+        week.d = weekday;
+    } else {
+        getParsingFlags(config).invalidWeekday = input;
+    }
+});
+
+addWeekParseToken(['d', 'e', 'E'], function (input, week, config, token) {
+    week[token] = toInt(input);
+});
+
+// HELPERS
+
+function parseWeekday(input, locale) {
+    if (typeof input !== 'string') {
+        return input;
+    }
+
+    if (!isNaN(input)) {
+        return parseInt(input, 10);
+    }
+
+    input = locale.weekdaysParse(input);
+    if (typeof input === 'number') {
+        return input;
+    }
+
+    return null;
+}
+
+function parseIsoWeekday(input, locale) {
+    if (typeof input === 'string') {
+        return locale.weekdaysParse(input) % 7 || 7;
+    }
+    return isNaN(input) ? null : input;
+}
+
+// LOCALES
+
+var defaultLocaleWeekdays = 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_');
+function localeWeekdays (m, format) {
+    if (!m) {
+        return isArray(this._weekdays) ? this._weekdays :
+            this._weekdays['standalone'];
+    }
+    return isArray(this._weekdays) ? this._weekdays[m.day()] :
+        this._weekdays[this._weekdays.isFormat.test(format) ? 'format' : 'standalone'][m.day()];
+}
+
+var defaultLocaleWeekdaysShort = 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_');
+function localeWeekdaysShort (m) {
+    return (m) ? this._weekdaysShort[m.day()] : this._weekdaysShort;
+}
+
+var defaultLocaleWeekdaysMin = 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_');
+function localeWeekdaysMin (m) {
+    return (m) ? this._weekdaysMin[m.day()] : this._weekdaysMin;
+}
+
+function handleStrictParse$1(weekdayName, format, strict) {
+    var i, ii, mom, llc = weekdayName.toLocaleLowerCase();
+    if (!this._weekdaysParse) {
+        this._weekdaysParse = [];
+        this._shortWeekdaysParse = [];
+        this._minWeekdaysParse = [];
+
+        for (i = 0; i < 7; ++i) {
+            mom = createUTC([2000, 1]).day(i);
+            this._minWeekdaysParse[i] = this.weekdaysMin(mom, '').toLocaleLowerCase();
+            this._shortWeekdaysParse[i] = this.weekdaysShort(mom, '').toLocaleLowerCase();
+            this._weekdaysParse[i] = this.weekdays(mom, '').toLocaleLowerCase();
+        }
+    }
+
+    if (strict) {
+        if (format === 'dddd') {
+            ii = indexOf$1.call(this._weekdaysParse, llc);
+            return ii !== -1 ? ii : null;
+        } else if (format === 'ddd') {
+            ii = indexOf$1.call(this._shortWeekdaysParse, llc);
+            return ii !== -1 ? ii : null;
+        } else {
+            ii = indexOf$1.call(this._minWeekdaysParse, llc);
+            return ii !== -1 ? ii : null;
+        }
+    } else {
+        if (format === 'dddd') {
+            ii = indexOf$1.call(this._weekdaysParse, llc);
+            if (ii !== -1) {
+                return ii;
+            }
+            ii = indexOf$1.call(this._shortWeekdaysParse, llc);
+            if (ii !== -1) {
+                return ii;
+            }
+            ii = indexOf$1.call(this._minWeekdaysParse, llc);
+            return ii !== -1 ? ii : null;
+        } else if (format === 'ddd') {
+            ii = indexOf$1.call(this._shortWeekdaysParse, llc);
+            if (ii !== -1) {
+                return ii;
+            }
+            ii = indexOf$1.call(this._weekdaysParse, llc);
+            if (ii !== -1) {
+                return ii;
+            }
+            ii = indexOf$1.call(this._minWeekdaysParse, llc);
+            return ii !== -1 ? ii : null;
+        } else {
+            ii = indexOf$1.call(this._minWeekdaysParse, llc);
+            if (ii !== -1) {
+                return ii;
+            }
+            ii = indexOf$1.call(this._weekdaysParse, llc);
+            if (ii !== -1) {
+                return ii;
+            }
+            ii = indexOf$1.call(this._shortWeekdaysParse, llc);
+            return ii !== -1 ? ii : null;
+        }
+    }
+}
+
+function localeWeekdaysParse (weekdayName, format, strict) {
+    var i, mom, regex;
+
+    if (this._weekdaysParseExact) {
+        return handleStrictParse$1.call(this, weekdayName, format, strict);
+    }
+
+    if (!this._weekdaysParse) {
+        this._weekdaysParse = [];
+        this._minWeekdaysParse = [];
+        this._shortWeekdaysParse = [];
+        this._fullWeekdaysParse = [];
+    }
+
+    for (i = 0; i < 7; i++) {
+        // make the regex if we don't have it already
+
+        mom = createUTC([2000, 1]).day(i);
+        if (strict && !this._fullWeekdaysParse[i]) {
+            this._fullWeekdaysParse[i] = new RegExp('^' + this.weekdays(mom, '').replace('.', '\.?') + '$', 'i');
+            this._shortWeekdaysParse[i] = new RegExp('^' + this.weekdaysShort(mom, '').replace('.', '\.?') + '$', 'i');
+            this._minWeekdaysParse[i] = new RegExp('^' + this.weekdaysMin(mom, '').replace('.', '\.?') + '$', 'i');
+        }
+        if (!this._weekdaysParse[i]) {
+            regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, '');
+            this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i');
+        }
+        // test the regex
+        if (strict && format === 'dddd' && this._fullWeekdaysParse[i].test(weekdayName)) {
+            return i;
+        } else if (strict && format === 'ddd' && this._shortWeekdaysParse[i].test(weekdayName)) {
+            return i;
+        } else if (strict && format === 'dd' && this._minWeekdaysParse[i].test(weekdayName)) {
+            return i;
+        } else if (!strict && this._weekdaysParse[i].test(weekdayName)) {
+            return i;
+        }
+    }
+}
+
+// MOMENTS
+
+function getSetDayOfWeek (input) {
+    if (!this.isValid()) {
+        return input != null ? this : NaN;
+    }
+    var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
+    if (input != null) {
+        input = parseWeekday(input, this.localeData());
+        return this.add(input - day, 'd');
+    } else {
+        return day;
+    }
+}
+
+function getSetLocaleDayOfWeek (input) {
+    if (!this.isValid()) {
+        return input != null ? this : NaN;
+    }
+    var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7;
+    return input == null ? weekday : this.add(input - weekday, 'd');
+}
+
+function getSetISODayOfWeek (input) {
+    if (!this.isValid()) {
+        return input != null ? this : NaN;
+    }
+
+    // behaves the same as moment#day except
+    // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6)
+    // as a setter, sunday should belong to the previous week.
+
+    if (input != null) {
+        var weekday = parseIsoWeekday(input, this.localeData());
+        return this.day(this.day() % 7 ? weekday : weekday - 7);
+    } else {
+        return this.day() || 7;
+    }
+}
+
+var defaultWeekdaysRegex = matchWord;
+function weekdaysRegex (isStrict) {
+    if (this._weekdaysParseExact) {
+        if (!hasOwnProp(this, '_weekdaysRegex')) {
+            computeWeekdaysParse.call(this);
+        }
+        if (isStrict) {
+            return this._weekdaysStrictRegex;
+        } else {
+            return this._weekdaysRegex;
+        }
+    } else {
+        if (!hasOwnProp(this, '_weekdaysRegex')) {
+            this._weekdaysRegex = defaultWeekdaysRegex;
+        }
+        return this._weekdaysStrictRegex && isStrict ?
+            this._weekdaysStrictRegex : this._weekdaysRegex;
+    }
+}
+
+var defaultWeekdaysShortRegex = matchWord;
+function weekdaysShortRegex (isStrict) {
+    if (this._weekdaysParseExact) {
+        if (!hasOwnProp(this, '_weekdaysRegex')) {
+            computeWeekdaysParse.call(this);
+        }
+        if (isStrict) {
+            return this._weekdaysShortStrictRegex;
+        } else {
+            return this._weekdaysShortRegex;
+        }
+    } else {
+        if (!hasOwnProp(this, '_weekdaysShortRegex')) {
+            this._weekdaysShortRegex = defaultWeekdaysShortRegex;
+        }
+        return this._weekdaysShortStrictRegex && isStrict ?
+            this._weekdaysShortStrictRegex : this._weekdaysShortRegex;
+    }
+}
+
+var defaultWeekdaysMinRegex = matchWord;
+function weekdaysMinRegex (isStrict) {
+    if (this._weekdaysParseExact) {
+        if (!hasOwnProp(this, '_weekdaysRegex')) {
+            computeWeekdaysParse.call(this);
+        }
+        if (isStrict) {
+            return this._weekdaysMinStrictRegex;
+        } else {
+            return this._weekdaysMinRegex;
+        }
+    } else {
+        if (!hasOwnProp(this, '_weekdaysMinRegex')) {
+            this._weekdaysMinRegex = defaultWeekdaysMinRegex;
+        }
+        return this._weekdaysMinStrictRegex && isStrict ?
+            this._weekdaysMinStrictRegex : this._weekdaysMinRegex;
+    }
+}
+
+
+function computeWeekdaysParse () {
+    function cmpLenRev(a, b) {
+        return b.length - a.length;
+    }
+
+    var minPieces = [], shortPieces = [], longPieces = [], mixedPieces = [],
+        i, mom, minp, shortp, longp;
+    for (i = 0; i < 7; i++) {
+        // make the regex if we don't have it already
+        mom = createUTC([2000, 1]).day(i);
+        minp = this.weekdaysMin(mom, '');
+        shortp = this.weekdaysShort(mom, '');
+        longp = this.weekdays(mom, '');
+        minPieces.push(minp);
+        shortPieces.push(shortp);
+        longPieces.push(longp);
+        mixedPieces.push(minp);
+        mixedPieces.push(shortp);
+        mixedPieces.push(longp);
+    }
+    // Sorting makes sure if one weekday (or abbr) is a prefix of another it
+    // will match the longer piece.
+    minPieces.sort(cmpLenRev);
+    shortPieces.sort(cmpLenRev);
+    longPieces.sort(cmpLenRev);
+    mixedPieces.sort(cmpLenRev);
+    for (i = 0; i < 7; i++) {
+        shortPieces[i] = regexEscape(shortPieces[i]);
+        longPieces[i] = regexEscape(longPieces[i]);
+        mixedPieces[i] = regexEscape(mixedPieces[i]);
+    }
+
+    this._weekdaysRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
+    this._weekdaysShortRegex = this._weekdaysRegex;
+    this._weekdaysMinRegex = this._weekdaysRegex;
+
+    this._weekdaysStrictRegex = new RegExp('^(' + longPieces.join('|') + ')', 'i');
+    this._weekdaysShortStrictRegex = new RegExp('^(' + shortPieces.join('|') + ')', 'i');
+    this._weekdaysMinStrictRegex = new RegExp('^(' + minPieces.join('|') + ')', 'i');
+}
+
+// FORMATTING
+
+function hFormat() {
+    return this.hours() % 12 || 12;
+}
+
+function kFormat() {
+    return this.hours() || 24;
+}
+
+addFormatToken('H', ['HH', 2], 0, 'hour');
+addFormatToken('h', ['hh', 2], 0, hFormat);
+addFormatToken('k', ['kk', 2], 0, kFormat);
+
+addFormatToken('hmm', 0, 0, function () {
+    return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2);
+});
+
+addFormatToken('hmmss', 0, 0, function () {
+    return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2) +
+        zeroFill(this.seconds(), 2);
+});
+
+addFormatToken('Hmm', 0, 0, function () {
+    return '' + this.hours() + zeroFill(this.minutes(), 2);
+});
+
+addFormatToken('Hmmss', 0, 0, function () {
+    return '' + this.hours() + zeroFill(this.minutes(), 2) +
+        zeroFill(this.seconds(), 2);
+});
+
+function meridiem (token, lowercase) {
+    addFormatToken(token, 0, 0, function () {
+        return this.localeData().meridiem(this.hours(), this.minutes(), lowercase);
+    });
+}
+
+meridiem('a', true);
+meridiem('A', false);
+
+// ALIASES
+
+addUnitAlias('hour', 'h');
+
+// PRIORITY
+addUnitPriority('hour', 13);
+
+// PARSING
+
+function matchMeridiem (isStrict, locale) {
+    return locale._meridiemParse;
+}
+
+addRegexToken('a',  matchMeridiem);
+addRegexToken('A',  matchMeridiem);
+addRegexToken('H',  match1to2);
+addRegexToken('h',  match1to2);
+addRegexToken('k',  match1to2);
+addRegexToken('HH', match1to2, match2);
+addRegexToken('hh', match1to2, match2);
+addRegexToken('kk', match1to2, match2);
+
+addRegexToken('hmm', match3to4);
+addRegexToken('hmmss', match5to6);
+addRegexToken('Hmm', match3to4);
+addRegexToken('Hmmss', match5to6);
+
+addParseToken(['H', 'HH'], HOUR);
+addParseToken(['k', 'kk'], function (input, array, config) {
+    var kInput = toInt(input);
+    array[HOUR] = kInput === 24 ? 0 : kInput;
+});
+addParseToken(['a', 'A'], function (input, array, config) {
+    config._isPm = config._locale.isPM(input);
+    config._meridiem = input;
+});
+addParseToken(['h', 'hh'], function (input, array, config) {
+    array[HOUR] = toInt(input);
+    getParsingFlags(config).bigHour = true;
+});
+addParseToken('hmm', function (input, array, config) {
+    var pos = input.length - 2;
+    array[HOUR] = toInt(input.substr(0, pos));
+    array[MINUTE] = toInt(input.substr(pos));
+    getParsingFlags(config).bigHour = true;
+});
+addParseToken('hmmss', function (input, array, config) {
+    var pos1 = input.length - 4;
+    var pos2 = input.length - 2;
+    array[HOUR] = toInt(input.substr(0, pos1));
+    array[MINUTE] = toInt(input.substr(pos1, 2));
+    array[SECOND] = toInt(input.substr(pos2));
+    getParsingFlags(config).bigHour = true;
+});
+addParseToken('Hmm', function (input, array, config) {
+    var pos = input.length - 2;
+    array[HOUR] = toInt(input.substr(0, pos));
+    array[MINUTE] = toInt(input.substr(pos));
+});
+addParseToken('Hmmss', function (input, array, config) {
+    var pos1 = input.length - 4;
+    var pos2 = input.length - 2;
+    array[HOUR] = toInt(input.substr(0, pos1));
+    array[MINUTE] = toInt(input.substr(pos1, 2));
+    array[SECOND] = toInt(input.substr(pos2));
+});
+
+// LOCALES
+
+function localeIsPM (input) {
+    // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays
+    // Using charAt should be more compatible.
+    return ((input + '').toLowerCase().charAt(0) === 'p');
+}
+
+var defaultLocaleMeridiemParse = /[ap]\.?m?\.?/i;
+function localeMeridiem (hours, minutes, isLower) {
+    if (hours > 11) {
+        return isLower ? 'pm' : 'PM';
+    } else {
+        return isLower ? 'am' : 'AM';
+    }
+}
+
+
+// MOMENTS
+
+// Setting the hour should keep the time, because the user explicitly
+// specified which hour he wants. So trying to maintain the same hour (in
+// a new timezone) makes sense. Adding/subtracting hours does not follow
+// this rule.
+var getSetHour = makeGetSet('Hours', true);
+
+// months
+// week
+// weekdays
+// meridiem
+var baseConfig = {
+    calendar: defaultCalendar,
+    longDateFormat: defaultLongDateFormat,
+    invalidDate: defaultInvalidDate,
+    ordinal: defaultOrdinal,
+    dayOfMonthOrdinalParse: defaultDayOfMonthOrdinalParse,
+    relativeTime: defaultRelativeTime,
+
+    months: defaultLocaleMonths,
+    monthsShort: defaultLocaleMonthsShort,
+
+    week: defaultLocaleWeek,
+
+    weekdays: defaultLocaleWeekdays,
+    weekdaysMin: defaultLocaleWeekdaysMin,
+    weekdaysShort: defaultLocaleWeekdaysShort,
+
+    meridiemParse: defaultLocaleMeridiemParse
+};
+
+// internal storage for locale config files
+var locales = {};
+var localeFamilies = {};
+var globalLocale;
+
+function normalizeLocale(key) {
+    return key ? key.toLowerCase().replace('_', '-') : key;
+}
+
+// pick the locale from the array
+// try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each
+// substring from most specific to least, but move to the next array item if it's a more specific variant than the current root
+function chooseLocale(names) {
+    var i = 0, j, next, locale, split;
+
+    while (i < names.length) {
+        split = normalizeLocale(names[i]).split('-');
+        j = split.length;
+        next = normalizeLocale(names[i + 1]);
+        next = next ? next.split('-') : null;
+        while (j > 0) {
+            locale = loadLocale(split.slice(0, j).join('-'));
+            if (locale) {
+                return locale;
+            }
+            if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) {
+                //the next array item is better than a shallower substring of this one
+                break;
+            }
+            j--;
+        }
+        i++;
+    }
+    return null;
+}
+
+function loadLocale(name) {
+    var oldLocale = null;
+    // TODO: Find a better way to register and load all the locales in Node
+    if (!locales[name] && (typeof module !== 'undefined') &&
+            module && module.exports) {
+        try {
+            oldLocale = globalLocale._abbr;
+            require('./locale/' + name);
+            // because defineLocale currently also sets the global locale, we
+            // want to undo that for lazy loaded locales
+            getSetGlobalLocale(oldLocale);
+        } catch (e) { }
+    }
+    return locales[name];
+}
+
+// This function will load locale and then set the global locale.  If
+// no arguments are passed in, it will simply return the current global
+// locale key.
+function getSetGlobalLocale (key, values) {
+    var data;
+    if (key) {
+        if (isUndefined(values)) {
+            data = getLocale(key);
+        }
+        else {
+            data = defineLocale(key, values);
+        }
+
+        if (data) {
+            // moment.duration._locale = moment._locale = data;
+            globalLocale = data;
+        }
+    }
+
+    return globalLocale._abbr;
+}
+
+function defineLocale (name, config) {
+    if (config !== null) {
+        var parentConfig = baseConfig;
+        config.abbr = name;
+        if (locales[name] != null) {
+            deprecateSimple('defineLocaleOverride',
+                    'use moment.updateLocale(localeName, config) to change ' +
+                    'an existing locale. moment.defineLocale(localeName, ' +
+                    'config) should only be used for creating a new locale ' +
+                    'See http://momentjs.com/guides/#/warnings/define-locale/ for more info.');
+            parentConfig = locales[name]._config;
+        } else if (config.parentLocale != null) {
+            if (locales[config.parentLocale] != null) {
+                parentConfig = locales[config.parentLocale]._config;
+            } else {
+                if (!localeFamilies[config.parentLocale]) {
+                    localeFamilies[config.parentLocale] = [];
+                }
+                localeFamilies[config.parentLocale].push({
+                    name: name,
+                    config: config
+                });
+                return null;
+            }
+        }
+        locales[name] = new Locale(mergeConfigs(parentConfig, config));
+
+        if (localeFamilies[name]) {
+            localeFamilies[name].forEach(function (x) {
+                defineLocale(x.name, x.config);
+            });
+        }
+
+        // backwards compat for now: also set the locale
+        // make sure we set the locale AFTER all child locales have been
+        // created, so we won't end up with the child locale set.
+        getSetGlobalLocale(name);
+
+
+        return locales[name];
+    } else {
+        // useful for testing
+        delete locales[name];
+        return null;
+    }
+}
+
+function updateLocale(name, config) {
+    if (config != null) {
+        var locale, parentConfig = baseConfig;
+        // MERGE
+        if (locales[name] != null) {
+            parentConfig = locales[name]._config;
+        }
+        config = mergeConfigs(parentConfig, config);
+        locale = new Locale(config);
+        locale.parentLocale = locales[name];
+        locales[name] = locale;
+
+        // backwards compat for now: also set the locale
+        getSetGlobalLocale(name);
+    } else {
+        // pass null for config to unupdate, useful for tests
+        if (locales[name] != null) {
+            if (locales[name].parentLocale != null) {
+                locales[name] = locales[name].parentLocale;
+            } else if (locales[name] != null) {
+                delete locales[name];
+            }
+        }
+    }
+    return locales[name];
+}
+
+// returns locale data
+function getLocale (key) {
+    var locale;
+
+    if (key && key._locale && key._locale._abbr) {
+        key = key._locale._abbr;
+    }
+
+    if (!key) {
+        return globalLocale;
+    }
+
+    if (!isArray(key)) {
+        //short-circuit everything else
+        locale = loadLocale(key);
+        if (locale) {
+            return locale;
+        }
+        key = [key];
+    }
+
+    return chooseLocale(key);
+}
+
+function listLocales() {
+    return keys$1(locales);
+}
+
+function checkOverflow (m) {
+    var overflow;
+    var a = m._a;
+
+    if (a && getParsingFlags(m).overflow === -2) {
+        overflow =
+            a[MONTH]       < 0 || a[MONTH]       > 11  ? MONTH :
+            a[DATE]        < 1 || a[DATE]        > daysInMonth(a[YEAR], a[MONTH]) ? DATE :
+            a[HOUR]        < 0 || a[HOUR]        > 24 || (a[HOUR] === 24 && (a[MINUTE] !== 0 || a[SECOND] !== 0 || a[MILLISECOND] !== 0)) ? HOUR :
+            a[MINUTE]      < 0 || a[MINUTE]      > 59  ? MINUTE :
+            a[SECOND]      < 0 || a[SECOND]      > 59  ? SECOND :
+            a[MILLISECOND] < 0 || a[MILLISECOND] > 999 ? MILLISECOND :
+            -1;
+
+        if (getParsingFlags(m)._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) {
+            overflow = DATE;
+        }
+        if (getParsingFlags(m)._overflowWeeks && overflow === -1) {
+            overflow = WEEK;
+        }
+        if (getParsingFlags(m)._overflowWeekday && overflow === -1) {
+            overflow = WEEKDAY;
+        }
+
+        getParsingFlags(m).overflow = overflow;
+    }
+
+    return m;
+}
+
+// iso 8601 regex
+// 0000-00-00 0000-W00 or 0000-W00-0 + T + 00 or 00:00 or 00:00:00 or 00:00:00.000 + +00:00 or +0000 or +00)
+var extendedIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/;
+var basicIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/;
+
+var tzRegex = /Z|[+-]\d\d(?::?\d\d)?/;
+
+var isoDates = [
+    ['YYYYYY-MM-DD', /[+-]\d{6}-\d\d-\d\d/],
+    ['YYYY-MM-DD', /\d{4}-\d\d-\d\d/],
+    ['GGGG-[W]WW-E', /\d{4}-W\d\d-\d/],
+    ['GGGG-[W]WW', /\d{4}-W\d\d/, false],
+    ['YYYY-DDD', /\d{4}-\d{3}/],
+    ['YYYY-MM', /\d{4}-\d\d/, false],
+    ['YYYYYYMMDD', /[+-]\d{10}/],
+    ['YYYYMMDD', /\d{8}/],
+    // YYYYMM is NOT allowed by the standard
+    ['GGGG[W]WWE', /\d{4}W\d{3}/],
+    ['GGGG[W]WW', /\d{4}W\d{2}/, false],
+    ['YYYYDDD', /\d{7}/]
+];
+
+// iso time formats and regexes
+var isoTimes = [
+    ['HH:mm:ss.SSSS', /\d\d:\d\d:\d\d\.\d+/],
+    ['HH:mm:ss,SSSS', /\d\d:\d\d:\d\d,\d+/],
+    ['HH:mm:ss', /\d\d:\d\d:\d\d/],
+    ['HH:mm', /\d\d:\d\d/],
+    ['HHmmss.SSSS', /\d\d\d\d\d\d\.\d+/],
+    ['HHmmss,SSSS', /\d\d\d\d\d\d,\d+/],
+    ['HHmmss', /\d\d\d\d\d\d/],
+    ['HHmm', /\d\d\d\d/],
+    ['HH', /\d\d/]
+];
+
+var aspNetJsonRegex = /^\/?Date\((\-?\d+)/i;
+
+// date from iso format
+function configFromISO(config) {
+    var i, l,
+        string = config._i,
+        match = extendedIsoRegex.exec(string) || basicIsoRegex.exec(string),
+        allowTime, dateFormat, timeFormat, tzFormat;
+
+    if (match) {
+        getParsingFlags(config).iso = true;
+
+        for (i = 0, l = isoDates.length; i < l; i++) {
+            if (isoDates[i][1].exec(match[1])) {
+                dateFormat = isoDates[i][0];
+                allowTime = isoDates[i][2] !== false;
+                break;
+            }
+        }
+        if (dateFormat == null) {
+            config._isValid = false;
+            return;
+        }
+        if (match[3]) {
+            for (i = 0, l = isoTimes.length; i < l; i++) {
+                if (isoTimes[i][1].exec(match[3])) {
+                    // match[2] should be 'T' or space
+                    timeFormat = (match[2] || ' ') + isoTimes[i][0];
+                    break;
+                }
+            }
+            if (timeFormat == null) {
+                config._isValid = false;
+                return;
+            }
+        }
+        if (!allowTime && timeFormat != null) {
+            config._isValid = false;
+            return;
+        }
+        if (match[4]) {
+            if (tzRegex.exec(match[4])) {
+                tzFormat = 'Z';
+            } else {
+                config._isValid = false;
+                return;
+            }
+        }
+        config._f = dateFormat + (timeFormat || '') + (tzFormat || '');
+        configFromStringAndFormat(config);
+    } else {
+        config._isValid = false;
+    }
+}
+
+// RFC 2822 regex: For details see https://tools.ietf.org/html/rfc2822#section-3.3
+var basicRfcRegex = /^((?:Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s)?(\d?\d\s(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(?:\d\d)?\d\d\s)(\d\d:\d\d)(\:\d\d)?(\s(?:UT|GMT|[ECMP][SD]T|[A-IK-Za-ik-z]|[+-]\d{4}))$/;
+
+// date and time from ref 2822 format
+function configFromRFC2822(config) {
+    var string, match, dayFormat,
+        dateFormat, timeFormat, tzFormat;
+    var timezones = {
+        ' GMT': ' +0000',
+        ' EDT': ' -0400',
+        ' EST': ' -0500',
+        ' CDT': ' -0500',
+        ' CST': ' -0600',
+        ' MDT': ' -0600',
+        ' MST': ' -0700',
+        ' PDT': ' -0700',
+        ' PST': ' -0800'
+    };
+    var military = 'YXWVUTSRQPONZABCDEFGHIKLM';
+    var timezone, timezoneIndex;
+
+    string = config._i
+        .replace(/\([^\)]*\)|[\n\t]/g, ' ') // Remove comments and folding whitespace
+        .replace(/(\s\s+)/g, ' ') // Replace multiple-spaces with a single space
+        .replace(/^\s|\s$/g, ''); // Remove leading and trailing spaces
+    match = basicRfcRegex.exec(string);
+
+    if (match) {
+        dayFormat = match[1] ? 'ddd' + ((match[1].length === 5) ? ', ' : ' ') : '';
+        dateFormat = 'D MMM ' + ((match[2].length > 10) ? 'YYYY ' : 'YY ');
+        timeFormat = 'HH:mm' + (match[4] ? ':ss' : '');
+
+        // TODO: Replace the vanilla JS Date object with an indepentent day-of-week check.
+        if (match[1]) { // day of week given
+            var momentDate = new Date(match[2]);
+            var momentDay = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'][momentDate.getDay()];
+
+            if (match[1].substr(0,3) !== momentDay) {
+                getParsingFlags(config).weekdayMismatch = true;
+                config._isValid = false;
+                return;
+            }
+        }
+
+        switch (match[5].length) {
+            case 2: // military
+                if (timezoneIndex === 0) {
+                    timezone = ' +0000';
+                } else {
+                    timezoneIndex = military.indexOf(match[5][1].toUpperCase()) - 12;
+                    timezone = ((timezoneIndex < 0) ? ' -' : ' +') +
+                        (('' + timezoneIndex).replace(/^-?/, '0')).match(/..$/)[0] + '00';
+                }
+                break;
+            case 4: // Zone
+                timezone = timezones[match[5]];
+                break;
+            default: // UT or +/-9999
+                timezone = timezones[' GMT'];
+        }
+        match[5] = timezone;
+        config._i = match.splice(1).join('');
+        tzFormat = ' ZZ';
+        config._f = dayFormat + dateFormat + timeFormat + tzFormat;
+        configFromStringAndFormat(config);
+        getParsingFlags(config).rfc2822 = true;
+    } else {
+        config._isValid = false;
+    }
+}
+
+// date from iso format or fallback
+function configFromString(config) {
+    var matched = aspNetJsonRegex.exec(config._i);
+
+    if (matched !== null) {
+        config._d = new Date(+matched[1]);
+        return;
+    }
+
+    configFromISO(config);
+    if (config._isValid === false) {
+        delete config._isValid;
+    } else {
+        return;
+    }
+
+    configFromRFC2822(config);
+    if (config._isValid === false) {
+        delete config._isValid;
+    } else {
+        return;
+    }
+
+    // Final attempt, use Input Fallback
+    hooks.createFromInputFallback(config);
+}
+
+hooks.createFromInputFallback = deprecate(
+    'value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), ' +
+    'which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are ' +
+    'discouraged and will be removed in an upcoming major release. Please refer to ' +
+    'http://momentjs.com/guides/#/warnings/js-date/ for more info.',
+    function (config) {
+        config._d = new Date(config._i + (config._useUTC ? ' UTC' : ''));
+    }
+);
+
+// Pick the first defined of two or three arguments.
+function defaults(a, b, c) {
+    if (a != null) {
+        return a;
+    }
+    if (b != null) {
+        return b;
+    }
+    return c;
+}
+
+function currentDateArray(config) {
+    // hooks is actually the exported moment object
+    var nowValue = new Date(hooks.now());
+    if (config._useUTC) {
+        return [nowValue.getUTCFullYear(), nowValue.getUTCMonth(), nowValue.getUTCDate()];
+    }
+    return [nowValue.getFullYear(), nowValue.getMonth(), nowValue.getDate()];
+}
+
+// convert an array to a date.
+// the array should mirror the parameters below
+// note: all values past the year are optional and will default to the lowest possible value.
+// [year, month, day , hour, minute, second, millisecond]
+function configFromArray (config) {
+    var i, date, input = [], currentDate, yearToUse;
+
+    if (config._d) {
+        return;
+    }
+
+    currentDate = currentDateArray(config);
+
+    //compute day of the year from weeks and weekdays
+    if (config._w && config._a[DATE] == null && config._a[MONTH] == null) {
+        dayOfYearFromWeekInfo(config);
+    }
+
+    //if the day of the year is set, figure out what it is
+    if (config._dayOfYear != null) {
+        yearToUse = defaults(config._a[YEAR], currentDate[YEAR]);
+
+        if (config._dayOfYear > daysInYear(yearToUse) || config._dayOfYear === 0) {
+            getParsingFlags(config)._overflowDayOfYear = true;
+        }
+
+        date = createUTCDate(yearToUse, 0, config._dayOfYear);
+        config._a[MONTH] = date.getUTCMonth();
+        config._a[DATE] = date.getUTCDate();
+    }
+
+    // Default to current date.
+    // * if no year, month, day of month are given, default to today
+    // * if day of month is given, default month and year
+    // * if month is given, default only year
+    // * if year is given, don't default anything
+    for (i = 0; i < 3 && config._a[i] == null; ++i) {
+        config._a[i] = input[i] = currentDate[i];
+    }
+
+    // Zero out whatever was not defaulted, including time
+    for (; i < 7; i++) {
+        config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i];
+    }
+
+    // Check for 24:00:00.000
+    if (config._a[HOUR] === 24 &&
+            config._a[MINUTE] === 0 &&
+            config._a[SECOND] === 0 &&
+            config._a[MILLISECOND] === 0) {
+        config._nextDay = true;
+        config._a[HOUR] = 0;
+    }
+
+    config._d = (config._useUTC ? createUTCDate : createDate).apply(null, input);
+    // Apply timezone offset from input. The actual utcOffset can be changed
+    // with parseZone.
+    if (config._tzm != null) {
+        config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm);
+    }
+
+    if (config._nextDay) {
+        config._a[HOUR] = 24;
+    }
+}
+
+function dayOfYearFromWeekInfo(config) {
+    var w, weekYear, week, weekday, dow, doy, temp, weekdayOverflow;
+
+    w = config._w;
+    if (w.GG != null || w.W != null || w.E != null) {
+        dow = 1;
+        doy = 4;
+
+        // TODO: We need to take the current isoWeekYear, but that depends on
+        // how we interpret now (local, utc, fixed offset). So create
+        // a now version of current config (take local/utc/offset flags, and
+        // create now).
+        weekYear = defaults(w.GG, config._a[YEAR], weekOfYear(createLocal(), 1, 4).year);
+        week = defaults(w.W, 1);
+        weekday = defaults(w.E, 1);
+        if (weekday < 1 || weekday > 7) {
+            weekdayOverflow = true;
+        }
+    } else {
+        dow = config._locale._week.dow;
+        doy = config._locale._week.doy;
+
+        var curWeek = weekOfYear(createLocal(), dow, doy);
+
+        weekYear = defaults(w.gg, config._a[YEAR], curWeek.year);
+
+        // Default to current week.
+        week = defaults(w.w, curWeek.week);
+
+        if (w.d != null) {
+            // weekday -- low day numbers are considered next week
+            weekday = w.d;
+            if (weekday < 0 || weekday > 6) {
+                weekdayOverflow = true;
+            }
+        } else if (w.e != null) {
+            // local weekday -- counting starts from begining of week
+            weekday = w.e + dow;
+            if (w.e < 0 || w.e > 6) {
+                weekdayOverflow = true;
+            }
+        } else {
+            // default to begining of week
+            weekday = dow;
+        }
+    }
+    if (week < 1 || week > weeksInYear(weekYear, dow, doy)) {
+        getParsingFlags(config)._overflowWeeks = true;
+    } else if (weekdayOverflow != null) {
+        getParsingFlags(config)._overflowWeekday = true;
+    } else {
+        temp = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy);
+        config._a[YEAR] = temp.year;
+        config._dayOfYear = temp.dayOfYear;
+    }
+}
+
+// constant that refers to the ISO standard
+hooks.ISO_8601 = function () {};
+
+// constant that refers to the RFC 2822 form
+hooks.RFC_2822 = function () {};
+
+// date from string and format string
+function configFromStringAndFormat(config) {
+    // TODO: Move this to another part of the creation flow to prevent circular deps
+    if (config._f === hooks.ISO_8601) {
+        configFromISO(config);
+        return;
+    }
+    if (config._f === hooks.RFC_2822) {
+        configFromRFC2822(config);
+        return;
+    }
+    config._a = [];
+    getParsingFlags(config).empty = true;
+
+    // This array is used to make a Date, either with `new Date` or `Date.UTC`
+    var string = '' + config._i,
+        i, parsedInput, tokens, token, skipped,
+        stringLength = string.length,
+        totalParsedInputLength = 0;
+
+    tokens = expandFormat(config._f, config._locale).match(formattingTokens) || [];
+
+    for (i = 0; i < tokens.length; i++) {
+        token = tokens[i];
+        parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0];
+        // console.log('token', token, 'parsedInput', parsedInput,
+        //         'regex', getParseRegexForToken(token, config));
+        if (parsedInput) {
+            skipped = string.substr(0, string.indexOf(parsedInput));
+            if (skipped.length > 0) {
+                getParsingFlags(config).unusedInput.push(skipped);
+            }
+            string = string.slice(string.indexOf(parsedInput) + parsedInput.length);
+            totalParsedInputLength += parsedInput.length;
+        }
+        // don't parse if it's not a known token
+        if (formatTokenFunctions[token]) {
+            if (parsedInput) {
+                getParsingFlags(config).empty = false;
+            }
+            else {
+                getParsingFlags(config).unusedTokens.push(token);
+            }
+            addTimeToArrayFromToken(token, parsedInput, config);
+        }
+        else if (config._strict && !parsedInput) {
+            getParsingFlags(config).unusedTokens.push(token);
+        }
+    }
+
+    // add remaining unparsed input length to the string
+    getParsingFlags(config).charsLeftOver = stringLength - totalParsedInputLength;
+    if (string.length > 0) {
+        getParsingFlags(config).unusedInput.push(string);
+    }
+
+    // clear _12h flag if hour is <= 12
+    if (config._a[HOUR] <= 12 &&
+        getParsingFlags(config).bigHour === true &&
+        config._a[HOUR] > 0) {
+        getParsingFlags(config).bigHour = undefined;
+    }
+
+    getParsingFlags(config).parsedDateParts = config._a.slice(0);
+    getParsingFlags(config).meridiem = config._meridiem;
+    // handle meridiem
+    config._a[HOUR] = meridiemFixWrap(config._locale, config._a[HOUR], config._meridiem);
+
+    configFromArray(config);
+    checkOverflow(config);
+}
+
+
+function meridiemFixWrap (locale, hour, meridiem) {
+    var isPm;
+
+    if (meridiem == null) {
+        // nothing to do
+        return hour;
+    }
+    if (locale.meridiemHour != null) {
+        return locale.meridiemHour(hour, meridiem);
+    } else if (locale.isPM != null) {
+        // Fallback
+        isPm = locale.isPM(meridiem);
+        if (isPm && hour < 12) {
+            hour += 12;
+        }
+        if (!isPm && hour === 12) {
+            hour = 0;
+        }
+        return hour;
+    } else {
+        // this is not supposed to happen
+        return hour;
+    }
+}
+
+// date from string and array of format strings
+function configFromStringAndArray(config) {
+    var tempConfig,
+        bestMoment,
+
+        scoreToBeat,
+        i,
+        currentScore;
+
+    if (config._f.length === 0) {
+        getParsingFlags(config).invalidFormat = true;
+        config._d = new Date(NaN);
+        return;
+    }
+
+    for (i = 0; i < config._f.length; i++) {
+        currentScore = 0;
+        tempConfig = copyConfig({}, config);
+        if (config._useUTC != null) {
+            tempConfig._useUTC = config._useUTC;
+        }
+        tempConfig._f = config._f[i];
+        configFromStringAndFormat(tempConfig);
+
+        if (!isValid(tempConfig)) {
+            continue;
+        }
+
+        // if there is any input that was not parsed add a penalty for that format
+        currentScore += getParsingFlags(tempConfig).charsLeftOver;
+
+        //or tokens
+        currentScore += getParsingFlags(tempConfig).unusedTokens.length * 10;
+
+        getParsingFlags(tempConfig).score = currentScore;
+
+        if (scoreToBeat == null || currentScore < scoreToBeat) {
+            scoreToBeat = currentScore;
+            bestMoment = tempConfig;
+        }
+    }
+
+    extend(config, bestMoment || tempConfig);
+}
+
+function configFromObject(config) {
+    if (config._d) {
+        return;
+    }
+
+    var i = normalizeObjectUnits(config._i);
+    config._a = map([i.year, i.month, i.day || i.date, i.hour, i.minute, i.second, i.millisecond], function (obj) {
+        return obj && parseInt(obj, 10);
+    });
+
+    configFromArray(config);
+}
+
+function createFromConfig (config) {
+    var res = new Moment(checkOverflow(prepareConfig(config)));
+    if (res._nextDay) {
+        // Adding is smart enough around DST
+        res.add(1, 'd');
+        res._nextDay = undefined;
+    }
+
+    return res;
+}
+
+function prepareConfig (config) {
+    var input = config._i,
+        format = config._f;
+
+    config._locale = config._locale || getLocale(config._l);
+
+    if (input === null || (format === undefined && input === '')) {
+        return createInvalid({nullInput: true});
+    }
+
+    if (typeof input === 'string') {
+        config._i = input = config._locale.preparse(input);
+    }
+
+    if (isMoment(input)) {
+        return new Moment(checkOverflow(input));
+    } else if (isDate(input)) {
+        config._d = input;
+    } else if (isArray(format)) {
+        configFromStringAndArray(config);
+    } else if (format) {
+        configFromStringAndFormat(config);
+    }  else {
+        configFromInput(config);
+    }
+
+    if (!isValid(config)) {
+        config._d = null;
+    }
+
+    return config;
+}
+
+function configFromInput(config) {
+    var input = config._i;
+    if (isUndefined(input)) {
+        config._d = new Date(hooks.now());
+    } else if (isDate(input)) {
+        config._d = new Date(input.valueOf());
+    } else if (typeof input === 'string') {
+        configFromString(config);
+    } else if (isArray(input)) {
+        config._a = map(input.slice(0), function (obj) {
+            return parseInt(obj, 10);
+        });
+        configFromArray(config);
+    } else if (isObject(input)) {
+        configFromObject(config);
+    } else if (isNumber(input)) {
+        // from milliseconds
+        config._d = new Date(input);
+    } else {
+        hooks.createFromInputFallback(config);
+    }
+}
+
+function createLocalOrUTC (input, format, locale, strict, isUTC) {
+    var c = {};
+
+    if (locale === true || locale === false) {
+        strict = locale;
+        locale = undefined;
+    }
+
+    if ((isObject(input) && isObjectEmpty(input)) ||
+            (isArray(input) && input.length === 0)) {
+        input = undefined;
+    }
+    // object construction must be done this way.
+    // https://github.com/moment/moment/issues/1423
+    c._isAMomentObject = true;
+    c._useUTC = c._isUTC = isUTC;
+    c._l = locale;
+    c._i = input;
+    c._f = format;
+    c._strict = strict;
+
+    return createFromConfig(c);
+}
+
+function createLocal (input, format, locale, strict) {
+    return createLocalOrUTC(input, format, locale, strict, false);
+}
+
+var prototypeMin = deprecate(
+    'moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/',
+    function () {
+        var other = createLocal.apply(null, arguments);
+        if (this.isValid() && other.isValid()) {
+            return other < this ? this : other;
+        } else {
+            return createInvalid();
+        }
+    }
+);
+
+var prototypeMax = deprecate(
+    'moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/',
+    function () {
+        var other = createLocal.apply(null, arguments);
+        if (this.isValid() && other.isValid()) {
+            return other > this ? this : other;
+        } else {
+            return createInvalid();
+        }
+    }
+);
+
+// Pick a moment m from moments so that m[fn](other) is true for all
+// other. This relies on the function fn to be transitive.
+//
+// moments should either be an array of moment objects or an array, whose
+// first element is an array of moment objects.
+function pickBy(fn, moments) {
+    var res, i;
+    if (moments.length === 1 && isArray(moments[0])) {
+        moments = moments[0];
+    }
+    if (!moments.length) {
+        return createLocal();
+    }
+    res = moments[0];
+    for (i = 1; i < moments.length; ++i) {
+        if (!moments[i].isValid() || moments[i][fn](res)) {
+            res = moments[i];
+        }
+    }
+    return res;
+}
+
+// TODO: Use [].sort instead?
+function min () {
+    var args = [].slice.call(arguments, 0);
+
+    return pickBy('isBefore', args);
+}
+
+function max () {
+    var args = [].slice.call(arguments, 0);
+
+    return pickBy('isAfter', args);
+}
+
+var now = function () {
+    return Date.now ? Date.now() : +(new Date());
+};
+
+var ordering = ['year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', 'millisecond'];
+
+function isDurationValid(m) {
+    for (var key in m) {
+        if (!(ordering.indexOf(key) !== -1 && (m[key] == null || !isNaN(m[key])))) {
+            return false;
+        }
+    }
+
+    var unitHasDecimal = false;
+    for (var i = 0; i < ordering.length; ++i) {
+        if (m[ordering[i]]) {
+            if (unitHasDecimal) {
+                return false; // only allow non-integers for smallest unit
+            }
+            if (parseFloat(m[ordering[i]]) !== toInt(m[ordering[i]])) {
+                unitHasDecimal = true;
+            }
+        }
+    }
+
+    return true;
+}
+
+function isValid$1() {
+    return this._isValid;
+}
+
+function createInvalid$1() {
+    return createDuration(NaN);
+}
+
+function Duration (duration) {
+    var normalizedInput = normalizeObjectUnits(duration),
+        years = normalizedInput.year || 0,
+        quarters = normalizedInput.quarter || 0,
+        months = normalizedInput.month || 0,
+        weeks = normalizedInput.week || 0,
+        days = normalizedInput.day || 0,
+        hours = normalizedInput.hour || 0,
+        minutes = normalizedInput.minute || 0,
+        seconds = normalizedInput.second || 0,
+        milliseconds = normalizedInput.millisecond || 0;
+
+    this._isValid = isDurationValid(normalizedInput);
+
+    // representation for dateAddRemove
+    this._milliseconds = +milliseconds +
+        seconds * 1e3 + // 1000
+        minutes * 6e4 + // 1000 * 60
+        hours * 1000 * 60 * 60; //using 1000 * 60 * 60 instead of 36e5 to avoid floating point rounding errors https://github.com/moment/moment/issues/2978
+    // Because of dateAddRemove treats 24 hours as different from a
+    // day when working around DST, we need to store them separately
+    this._days = +days +
+        weeks * 7;
+    // It is impossible translate months into days without knowing
+    // which months you are are talking about, so we have to store
+    // it separately.
+    this._months = +months +
+        quarters * 3 +
+        years * 12;
+
+    this._data = {};
+
+    this._locale = getLocale();
+
+    this._bubble();
+}
+
+function isDuration (obj) {
+    return obj instanceof Duration;
+}
+
+function absRound (number) {
+    if (number < 0) {
+        return Math.round(-1 * number) * -1;
+    } else {
+        return Math.round(number);
+    }
+}
+
+// FORMATTING
+
+function offset (token, separator) {
+    addFormatToken(token, 0, 0, function () {
+        var offset = this.utcOffset();
+        var sign = '+';
+        if (offset < 0) {
+            offset = -offset;
+            sign = '-';
+        }
+        return sign + zeroFill(~~(offset / 60), 2) + separator + zeroFill(~~(offset) % 60, 2);
+    });
+}
+
+offset('Z', ':');
+offset('ZZ', '');
+
+// PARSING
+
+addRegexToken('Z',  matchShortOffset);
+addRegexToken('ZZ', matchShortOffset);
+addParseToken(['Z', 'ZZ'], function (input, array, config) {
+    config._useUTC = true;
+    config._tzm = offsetFromString(matchShortOffset, input);
+});
+
+// HELPERS
+
+// timezone chunker
+// '+10:00' > ['10',  '00']
+// '-1530'  > ['-15', '30']
+var chunkOffset = /([\+\-]|\d\d)/gi;
+
+function offsetFromString(matcher, string) {
+    var matches = (string || '').match(matcher);
+
+    if (matches === null) {
+        return null;
+    }
+
+    var chunk   = matches[matches.length - 1] || [];
+    var parts   = (chunk + '').match(chunkOffset) || ['-', 0, 0];
+    var minutes = +(parts[1] * 60) + toInt(parts[2]);
+
+    return minutes === 0 ?
+      0 :
+      parts[0] === '+' ? minutes : -minutes;
+}
+
+// Return a moment from input, that is local/utc/zone equivalent to model.
+function cloneWithOffset(input, model) {
+    var res, diff;
+    if (model._isUTC) {
+        res = model.clone();
+        diff = (isMoment(input) || isDate(input) ? input.valueOf() : createLocal(input).valueOf()) - res.valueOf();
+        // Use low-level api, because this fn is low-level api.
+        res._d.setTime(res._d.valueOf() + diff);
+        hooks.updateOffset(res, false);
+        return res;
+    } else {
+        return createLocal(input).local();
+    }
+}
+
+function getDateOffset (m) {
+    // On Firefox.24 Date#getTimezoneOffset returns a floating point.
+    // https://github.com/moment/moment/pull/1871
+    return -Math.round(m._d.getTimezoneOffset() / 15) * 15;
+}
+
+// HOOKS
+
+// This function will be called whenever a moment is mutated.
+// It is intended to keep the offset in sync with the timezone.
+hooks.updateOffset = function () {};
+
+// MOMENTS
+
+// keepLocalTime = true means only change the timezone, without
+// affecting the local hour. So 5:31:26 +0300 --[utcOffset(2, true)]-->
+// 5:31:26 +0200 It is possible that 5:31:26 doesn't exist with offset
+// +0200, so we adjust the time as needed, to be valid.
+//
+// Keeping the time actually adds/subtracts (one hour)
+// from the actual represented time. That is why we call updateOffset
+// a second time. In case it wants us to change the offset again
+// _changeInProgress == true case, then we have to adjust, because
+// there is no such time in the given timezone.
+function getSetOffset (input, keepLocalTime, keepMinutes) {
+    var offset = this._offset || 0,
+        localAdjust;
+    if (!this.isValid()) {
+        return input != null ? this : NaN;
+    }
+    if (input != null) {
+        if (typeof input === 'string') {
+            input = offsetFromString(matchShortOffset, input);
+            if (input === null) {
+                return this;
+            }
+        } else if (Math.abs(input) < 16 && !keepMinutes) {
+            input = input * 60;
+        }
+        if (!this._isUTC && keepLocalTime) {
+            localAdjust = getDateOffset(this);
+        }
+        this._offset = input;
+        this._isUTC = true;
+        if (localAdjust != null) {
+            this.add(localAdjust, 'm');
+        }
+        if (offset !== input) {
+            if (!keepLocalTime || this._changeInProgress) {
+                addSubtract(this, createDuration(input - offset, 'm'), 1, false);
+            } else if (!this._changeInProgress) {
+                this._changeInProgress = true;
+                hooks.updateOffset(this, true);
+                this._changeInProgress = null;
+            }
+        }
+        return this;
+    } else {
+        return this._isUTC ? offset : getDateOffset(this);
+    }
+}
+
+function getSetZone (input, keepLocalTime) {
+    if (input != null) {
+        if (typeof input !== 'string') {
+            input = -input;
+        }
+
+        this.utcOffset(input, keepLocalTime);
+
+        return this;
+    } else {
+        return -this.utcOffset();
+    }
+}
+
+function setOffsetToUTC (keepLocalTime) {
+    return this.utcOffset(0, keepLocalTime);
+}
+
+function setOffsetToLocal (keepLocalTime) {
+    if (this._isUTC) {
+        this.utcOffset(0, keepLocalTime);
+        this._isUTC = false;
+
+        if (keepLocalTime) {
+            this.subtract(getDateOffset(this), 'm');
+        }
+    }
+    return this;
+}
+
+function setOffsetToParsedOffset () {
+    if (this._tzm != null) {
+        this.utcOffset(this._tzm, false, true);
+    } else if (typeof this._i === 'string') {
+        var tZone = offsetFromString(matchOffset, this._i);
+        if (tZone != null) {
+            this.utcOffset(tZone);
+        }
+        else {
+            this.utcOffset(0, true);
+        }
+    }
+    return this;
+}
+
+function hasAlignedHourOffset (input) {
+    if (!this.isValid()) {
+        return false;
+    }
+    input = input ? createLocal(input).utcOffset() : 0;
+
+    return (this.utcOffset() - input) % 60 === 0;
+}
+
+function isDaylightSavingTime () {
+    return (
+        this.utcOffset() > this.clone().month(0).utcOffset() ||
+        this.utcOffset() > this.clone().month(5).utcOffset()
+    );
+}
+
+function isDaylightSavingTimeShifted () {
+    if (!isUndefined(this._isDSTShifted)) {
+        return this._isDSTShifted;
+    }
+
+    var c = {};
+
+    copyConfig(c, this);
+    c = prepareConfig(c);
+
+    if (c._a) {
+        var other = c._isUTC ? createUTC(c._a) : createLocal(c._a);
+        this._isDSTShifted = this.isValid() &&
+            compareArrays(c._a, other.toArray()) > 0;
+    } else {
+        this._isDSTShifted = false;
+    }
+
+    return this._isDSTShifted;
+}
+
+function isLocal () {
+    return this.isValid() ? !this._isUTC : false;
+}
+
+function isUtcOffset () {
+    return this.isValid() ? this._isUTC : false;
+}
+
+function isUtc () {
+    return this.isValid() ? this._isUTC && this._offset === 0 : false;
+}
+
+// ASP.NET json date format regex
+var aspNetRegex = /^(\-)?(?:(\d*)[. ])?(\d+)\:(\d+)(?:\:(\d+)(\.\d*)?)?$/;
+
+// from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html
+// somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere
+// and further modified to allow for strings containing both week and day
+var isoRegex = /^(-)?P(?:(-?[0-9,.]*)Y)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)W)?(?:(-?[0-9,.]*)D)?(?:T(?:(-?[0-9,.]*)H)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)S)?)?$/;
+
+function createDuration (input, key) {
+    var duration = input,
+        // matching against regexp is expensive, do it on demand
+        match = null,
+        sign,
+        ret,
+        diffRes;
+
+    if (isDuration(input)) {
+        duration = {
+            ms : input._milliseconds,
+            d  : input._days,
+            M  : input._months
+        };
+    } else if (isNumber(input)) {
+        duration = {};
+        if (key) {
+            duration[key] = input;
+        } else {
+            duration.milliseconds = input;
+        }
+    } else if (!!(match = aspNetRegex.exec(input))) {
+        sign = (match[1] === '-') ? -1 : 1;
+        duration = {
+            y  : 0,
+            d  : toInt(match[DATE])                         * sign,
+            h  : toInt(match[HOUR])                         * sign,
+            m  : toInt(match[MINUTE])                       * sign,
+            s  : toInt(match[SECOND])                       * sign,
+            ms : toInt(absRound(match[MILLISECOND] * 1000)) * sign // the millisecond decimal point is included in the match
+        };
+    } else if (!!(match = isoRegex.exec(input))) {
+        sign = (match[1] === '-') ? -1 : 1;
+        duration = {
+            y : parseIso(match[2], sign),
+            M : parseIso(match[3], sign),
+            w : parseIso(match[4], sign),
+            d : parseIso(match[5], sign),
+            h : parseIso(match[6], sign),
+            m : parseIso(match[7], sign),
+            s : parseIso(match[8], sign)
+        };
+    } else if (duration == null) {// checks for null or undefined
+        duration = {};
+    } else if (typeof duration === 'object' && ('from' in duration || 'to' in duration)) {
+        diffRes = momentsDifference(createLocal(duration.from), createLocal(duration.to));
+
+        duration = {};
+        duration.ms = diffRes.milliseconds;
+        duration.M = diffRes.months;
+    }
+
+    ret = new Duration(duration);
+
+    if (isDuration(input) && hasOwnProp(input, '_locale')) {
+        ret._locale = input._locale;
+    }
+
+    return ret;
+}
+
+createDuration.fn = Duration.prototype;
+createDuration.invalid = createInvalid$1;
+
+function parseIso (inp, sign) {
+    // We'd normally use ~~inp for this, but unfortunately it also
+    // converts floats to ints.
+    // inp may be undefined, so careful calling replace on it.
+    var res = inp && parseFloat(inp.replace(',', '.'));
+    // apply sign while we're at it
+    return (isNaN(res) ? 0 : res) * sign;
+}
+
+function positiveMomentsDifference(base, other) {
+    var res = {milliseconds: 0, months: 0};
+
+    res.months = other.month() - base.month() +
+        (other.year() - base.year()) * 12;
+    if (base.clone().add(res.months, 'M').isAfter(other)) {
+        --res.months;
+    }
+
+    res.milliseconds = +other - +(base.clone().add(res.months, 'M'));
+
+    return res;
+}
+
+function momentsDifference(base, other) {
+    var res;
+    if (!(base.isValid() && other.isValid())) {
+        return {milliseconds: 0, months: 0};
+    }
+
+    other = cloneWithOffset(other, base);
+    if (base.isBefore(other)) {
+        res = positiveMomentsDifference(base, other);
+    } else {
+        res = positiveMomentsDifference(other, base);
+        res.milliseconds = -res.milliseconds;
+        res.months = -res.months;
+    }
+
+    return res;
+}
+
+// TODO: remove 'name' arg after deprecation is removed
+function createAdder(direction, name) {
+    return function (val, period) {
+        var dur, tmp;
+        //invert the arguments, but complain about it
+        if (period !== null && !isNaN(+period)) {
+            deprecateSimple(name, 'moment().' + name  + '(period, number) is deprecated. Please use moment().' + name + '(number, period). ' +
+            'See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info.');
+            tmp = val; val = period; period = tmp;
+        }
+
+        val = typeof val === 'string' ? +val : val;
+        dur = createDuration(val, period);
+        addSubtract(this, dur, direction);
+        return this;
+    };
+}
+
+function addSubtract (mom, duration, isAdding, updateOffset) {
+    var milliseconds = duration._milliseconds,
+        days = absRound(duration._days),
+        months = absRound(duration._months);
+
+    if (!mom.isValid()) {
+        // No op
+        return;
+    }
+
+    updateOffset = updateOffset == null ? true : updateOffset;
+
+    if (milliseconds) {
+        mom._d.setTime(mom._d.valueOf() + milliseconds * isAdding);
+    }
+    if (days) {
+        set$1(mom, 'Date', get(mom, 'Date') + days * isAdding);
+    }
+    if (months) {
+        setMonth(mom, get(mom, 'Month') + months * isAdding);
+    }
+    if (updateOffset) {
+        hooks.updateOffset(mom, days || months);
+    }
+}
+
+var add      = createAdder(1, 'add');
+var subtract = createAdder(-1, 'subtract');
+
+function getCalendarFormat(myMoment, now) {
+    var diff = myMoment.diff(now, 'days', true);
+    return diff < -6 ? 'sameElse' :
+            diff < -1 ? 'lastWeek' :
+            diff < 0 ? 'lastDay' :
+            diff < 1 ? 'sameDay' :
+            diff < 2 ? 'nextDay' :
+            diff < 7 ? 'nextWeek' : 'sameElse';
+}
+
+function calendar$1 (time, formats) {
+    // We want to compare the start of today, vs this.
+    // Getting start-of-today depends on whether we're local/utc/offset or not.
+    var now = time || createLocal(),
+        sod = cloneWithOffset(now, this).startOf('day'),
+        format = hooks.calendarFormat(this, sod) || 'sameElse';
+
+    var output = formats && (isFunction(formats[format]) ? formats[format].call(this, now) : formats[format]);
+
+    return this.format(output || this.localeData().calendar(format, this, createLocal(now)));
+}
+
+function clone () {
+    return new Moment(this);
+}
+
+function isAfter (input, units) {
+    var localInput = isMoment(input) ? input : createLocal(input);
+    if (!(this.isValid() && localInput.isValid())) {
+        return false;
+    }
+    units = normalizeUnits(!isUndefined(units) ? units : 'millisecond');
+    if (units === 'millisecond') {
+        return this.valueOf() > localInput.valueOf();
+    } else {
+        return localInput.valueOf() < this.clone().startOf(units).valueOf();
+    }
+}
+
+function isBefore (input, units) {
+    var localInput = isMoment(input) ? input : createLocal(input);
+    if (!(this.isValid() && localInput.isValid())) {
+        return false;
+    }
+    units = normalizeUnits(!isUndefined(units) ? units : 'millisecond');
+    if (units === 'millisecond') {
+        return this.valueOf() < localInput.valueOf();
+    } else {
+        return this.clone().endOf(units).valueOf() < localInput.valueOf();
+    }
+}
+
+function isBetween (from, to, units, inclusivity) {
+    inclusivity = inclusivity || '()';
+    return (inclusivity[0] === '(' ? this.isAfter(from, units) : !this.isBefore(from, units)) &&
+        (inclusivity[1] === ')' ? this.isBefore(to, units) : !this.isAfter(to, units));
+}
+
+function isSame (input, units) {
+    var localInput = isMoment(input) ? input : createLocal(input),
+        inputMs;
+    if (!(this.isValid() && localInput.isValid())) {
+        return false;
+    }
+    units = normalizeUnits(units || 'millisecond');
+    if (units === 'millisecond') {
+        return this.valueOf() === localInput.valueOf();
+    } else {
+        inputMs = localInput.valueOf();
+        return this.clone().startOf(units).valueOf() <= inputMs && inputMs <= this.clone().endOf(units).valueOf();
+    }
+}
+
+function isSameOrAfter (input, units) {
+    return this.isSame(input, units) || this.isAfter(input,units);
+}
+
+function isSameOrBefore (input, units) {
+    return this.isSame(input, units) || this.isBefore(input,units);
+}
+
+function diff (input, units, asFloat) {
+    var that,
+        zoneDelta,
+        delta, output;
+
+    if (!this.isValid()) {
+        return NaN;
+    }
+
+    that = cloneWithOffset(input, this);
+
+    if (!that.isValid()) {
+        return NaN;
+    }
+
+    zoneDelta = (that.utcOffset() - this.utcOffset()) * 6e4;
+
+    units = normalizeUnits(units);
+
+    if (units === 'year' || units === 'month' || units === 'quarter') {
+        output = monthDiff(this, that);
+        if (units === 'quarter') {
+            output = output / 3;
+        } else if (units === 'year') {
+            output = output / 12;
+        }
+    } else {
+        delta = this - that;
+        output = units === 'second' ? delta / 1e3 : // 1000
+            units === 'minute' ? delta / 6e4 : // 1000 * 60
+            units === 'hour' ? delta / 36e5 : // 1000 * 60 * 60
+            units === 'day' ? (delta - zoneDelta) / 864e5 : // 1000 * 60 * 60 * 24, negate dst
+            units === 'week' ? (delta - zoneDelta) / 6048e5 : // 1000 * 60 * 60 * 24 * 7, negate dst
+            delta;
+    }
+    return asFloat ? output : absFloor(output);
+}
+
+function monthDiff (a, b) {
+    // difference in months
+    var wholeMonthDiff = ((b.year() - a.year()) * 12) + (b.month() - a.month()),
+        // b is in (anchor - 1 month, anchor + 1 month)
+        anchor = a.clone().add(wholeMonthDiff, 'months'),
+        anchor2, adjust;
+
+    if (b - anchor < 0) {
+        anchor2 = a.clone().add(wholeMonthDiff - 1, 'months');
+        // linear across the month
+        adjust = (b - anchor) / (anchor - anchor2);
+    } else {
+        anchor2 = a.clone().add(wholeMonthDiff + 1, 'months');
+        // linear across the month
+        adjust = (b - anchor) / (anchor2 - anchor);
+    }
+
+    //check for negative zero, return zero if negative zero
+    return -(wholeMonthDiff + adjust) || 0;
+}
+
+hooks.defaultFormat = 'YYYY-MM-DDTHH:mm:ssZ';
+hooks.defaultFormatUtc = 'YYYY-MM-DDTHH:mm:ss[Z]';
+
+function toString () {
+    return this.clone().locale('en').format('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ');
+}
+
+function toISOString() {
+    if (!this.isValid()) {
+        return null;
+    }
+    var m = this.clone().utc();
+    if (m.year() < 0 || m.year() > 9999) {
+        return formatMoment(m, 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
+    }
+    if (isFunction(Date.prototype.toISOString)) {
+        // native implementation is ~50x faster, use it when we can
+        return this.toDate().toISOString();
+    }
+    return formatMoment(m, 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
+}
+
+/**
+ * Return a human readable representation of a moment that can
+ * also be evaluated to get a new moment which is the same
+ *
+ * @link https://nodejs.org/dist/latest/docs/api/util.html#util_custom_inspect_function_on_objects
+ */
+function inspect () {
+    if (!this.isValid()) {
+        return 'moment.invalid(/* ' + this._i + ' */)';
+    }
+    var func = 'moment';
+    var zone = '';
+    if (!this.isLocal()) {
+        func = this.utcOffset() === 0 ? 'moment.utc' : 'moment.parseZone';
+        zone = 'Z';
+    }
+    var prefix = '[' + func + '("]';
+    var year = (0 <= this.year() && this.year() <= 9999) ? 'YYYY' : 'YYYYYY';
+    var datetime = '-MM-DD[T]HH:mm:ss.SSS';
+    var suffix = zone + '[")]';
+
+    return this.format(prefix + year + datetime + suffix);
+}
+
+function format (inputString) {
+    if (!inputString) {
+        inputString = this.isUtc() ? hooks.defaultFormatUtc : hooks.defaultFormat;
+    }
+    var output = formatMoment(this, inputString);
+    return this.localeData().postformat(output);
+}
+
+function from (time, withoutSuffix) {
+    if (this.isValid() &&
+            ((isMoment(time) && time.isValid()) ||
+             createLocal(time).isValid())) {
+        return createDuration({to: this, from: time}).locale(this.locale()).humanize(!withoutSuffix);
+    } else {
+        return this.localeData().invalidDate();
+    }
+}
+
+function fromNow (withoutSuffix) {
+    return this.from(createLocal(), withoutSuffix);
+}
+
+function to (time, withoutSuffix) {
+    if (this.isValid() &&
+            ((isMoment(time) && time.isValid()) ||
+             createLocal(time).isValid())) {
+        return createDuration({from: this, to: time}).locale(this.locale()).humanize(!withoutSuffix);
+    } else {
+        return this.localeData().invalidDate();
+    }
+}
+
+function toNow (withoutSuffix) {
+    return this.to(createLocal(), withoutSuffix);
+}
+
+// If passed a locale key, it will set the locale for this
+// instance.  Otherwise, it will return the locale configuration
+// variables for this instance.
+function locale (key) {
+    var newLocaleData;
+
+    if (key === undefined) {
+        return this._locale._abbr;
+    } else {
+        newLocaleData = getLocale(key);
+        if (newLocaleData != null) {
+            this._locale = newLocaleData;
+        }
+        return this;
+    }
+}
+
+var lang = deprecate(
+    'moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.',
+    function (key) {
+        if (key === undefined) {
+            return this.localeData();
+        } else {
+            return this.locale(key);
+        }
+    }
+);
+
+function localeData () {
+    return this._locale;
+}
+
+function startOf (units) {
+    units = normalizeUnits(units);
+    // the following switch intentionally omits break keywords
+    // to utilize falling through the cases.
+    switch (units) {
+        case 'year':
+            this.month(0);
+            /* falls through */
+        case 'quarter':
+        case 'month':
+            this.date(1);
+            /* falls through */
+        case 'week':
+        case 'isoWeek':
+        case 'day':
+        case 'date':
+            this.hours(0);
+            /* falls through */
+        case 'hour':
+            this.minutes(0);
+            /* falls through */
+        case 'minute':
+            this.seconds(0);
+            /* falls through */
+        case 'second':
+            this.milliseconds(0);
+    }
+
+    // weeks are a special case
+    if (units === 'week') {
+        this.weekday(0);
+    }
+    if (units === 'isoWeek') {
+        this.isoWeekday(1);
+    }
+
+    // quarters are also special
+    if (units === 'quarter') {
+        this.month(Math.floor(this.month() / 3) * 3);
+    }
+
+    return this;
+}
+
+function endOf (units) {
+    units = normalizeUnits(units);
+    if (units === undefined || units === 'millisecond') {
+        return this;
+    }
+
+    // 'date' is an alias for 'day', so it should be considered as such.
+    if (units === 'date') {
+        units = 'day';
+    }
+
+    return this.startOf(units).add(1, (units === 'isoWeek' ? 'week' : units)).subtract(1, 'ms');
+}
+
+function valueOf () {
+    return this._d.valueOf() - ((this._offset || 0) * 60000);
+}
+
+function unix () {
+    return Math.floor(this.valueOf() / 1000);
+}
+
+function toDate () {
+    return new Date(this.valueOf());
+}
+
+function toArray () {
+    var m = this;
+    return [m.year(), m.month(), m.date(), m.hour(), m.minute(), m.second(), m.millisecond()];
+}
+
+function toObject () {
+    var m = this;
+    return {
+        years: m.year(),
+        months: m.month(),
+        date: m.date(),
+        hours: m.hours(),
+        minutes: m.minutes(),
+        seconds: m.seconds(),
+        milliseconds: m.milliseconds()
+    };
+}
+
+function toJSON () {
+    // new Date(NaN).toJSON() === null
+    return this.isValid() ? this.toISOString() : null;
+}
+
+function isValid$2 () {
+    return isValid(this);
+}
+
+function parsingFlags () {
+    return extend({}, getParsingFlags(this));
+}
+
+function invalidAt () {
+    return getParsingFlags(this).overflow;
+}
+
+function creationData() {
+    return {
+        input: this._i,
+        format: this._f,
+        locale: this._locale,
+        isUTC: this._isUTC,
+        strict: this._strict
+    };
+}
+
+// FORMATTING
+
+addFormatToken(0, ['gg', 2], 0, function () {
+    return this.weekYear() % 100;
+});
+
+addFormatToken(0, ['GG', 2], 0, function () {
+    return this.isoWeekYear() % 100;
+});
+
+function addWeekYearFormatToken (token, getter) {
+    addFormatToken(0, [token, token.length], 0, getter);
+}
+
+addWeekYearFormatToken('gggg',     'weekYear');
+addWeekYearFormatToken('ggggg',    'weekYear');
+addWeekYearFormatToken('GGGG',  'isoWeekYear');
+addWeekYearFormatToken('GGGGG', 'isoWeekYear');
+
+// ALIASES
+
+addUnitAlias('weekYear', 'gg');
+addUnitAlias('isoWeekYear', 'GG');
+
+// PRIORITY
+
+addUnitPriority('weekYear', 1);
+addUnitPriority('isoWeekYear', 1);
+
+
+// PARSING
+
+addRegexToken('G',      matchSigned);
+addRegexToken('g',      matchSigned);
+addRegexToken('GG',     match1to2, match2);
+addRegexToken('gg',     match1to2, match2);
+addRegexToken('GGGG',   match1to4, match4);
+addRegexToken('gggg',   match1to4, match4);
+addRegexToken('GGGGG',  match1to6, match6);
+addRegexToken('ggggg',  match1to6, match6);
+
+addWeekParseToken(['gggg', 'ggggg', 'GGGG', 'GGGGG'], function (input, week, config, token) {
+    week[token.substr(0, 2)] = toInt(input);
+});
+
+addWeekParseToken(['gg', 'GG'], function (input, week, config, token) {
+    week[token] = hooks.parseTwoDigitYear(input);
+});
+
+// MOMENTS
+
+function getSetWeekYear (input) {
+    return getSetWeekYearHelper.call(this,
+            input,
+            this.week(),
+            this.weekday(),
+            this.localeData()._week.dow,
+            this.localeData()._week.doy);
+}
+
+function getSetISOWeekYear (input) {
+    return getSetWeekYearHelper.call(this,
+            input, this.isoWeek(), this.isoWeekday(), 1, 4);
+}
+
+function getISOWeeksInYear () {
+    return weeksInYear(this.year(), 1, 4);
+}
+
+function getWeeksInYear () {
+    var weekInfo = this.localeData()._week;
+    return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy);
+}
+
+function getSetWeekYearHelper(input, week, weekday, dow, doy) {
+    var weeksTarget;
+    if (input == null) {
+        return weekOfYear(this, dow, doy).year;
+    } else {
+        weeksTarget = weeksInYear(input, dow, doy);
+        if (week > weeksTarget) {
+            week = weeksTarget;
+        }
+        return setWeekAll.call(this, input, week, weekday, dow, doy);
+    }
+}
+
+function setWeekAll(weekYear, week, weekday, dow, doy) {
+    var dayOfYearData = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy),
+        date = createUTCDate(dayOfYearData.year, 0, dayOfYearData.dayOfYear);
+
+    this.year(date.getUTCFullYear());
+    this.month(date.getUTCMonth());
+    this.date(date.getUTCDate());
+    return this;
+}
+
+// FORMATTING
+
+addFormatToken('Q', 0, 'Qo', 'quarter');
+
+// ALIASES
+
+addUnitAlias('quarter', 'Q');
+
+// PRIORITY
+
+addUnitPriority('quarter', 7);
+
+// PARSING
+
+addRegexToken('Q', match1);
+addParseToken('Q', function (input, array) {
+    array[MONTH] = (toInt(input) - 1) * 3;
+});
+
+// MOMENTS
+
+function getSetQuarter (input) {
+    return input == null ? Math.ceil((this.month() + 1) / 3) : this.month((input - 1) * 3 + this.month() % 3);
+}
+
+// FORMATTING
+
+addFormatToken('D', ['DD', 2], 'Do', 'date');
+
+// ALIASES
+
+addUnitAlias('date', 'D');
+
+// PRIOROITY
+addUnitPriority('date', 9);
+
+// PARSING
+
+addRegexToken('D',  match1to2);
+addRegexToken('DD', match1to2, match2);
+addRegexToken('Do', function (isStrict, locale) {
+    // TODO: Remove "ordinalParse" fallback in next major release.
+    return isStrict ?
+      (locale._dayOfMonthOrdinalParse || locale._ordinalParse) :
+      locale._dayOfMonthOrdinalParseLenient;
+});
+
+addParseToken(['D', 'DD'], DATE);
+addParseToken('Do', function (input, array) {
+    array[DATE] = toInt(input.match(match1to2)[0], 10);
+});
+
+// MOMENTS
+
+var getSetDayOfMonth = makeGetSet('Date', true);
+
+// FORMATTING
+
+addFormatToken('DDD', ['DDDD', 3], 'DDDo', 'dayOfYear');
+
+// ALIASES
+
+addUnitAlias('dayOfYear', 'DDD');
+
+// PRIORITY
+addUnitPriority('dayOfYear', 4);
+
+// PARSING
+
+addRegexToken('DDD',  match1to3);
+addRegexToken('DDDD', match3);
+addParseToken(['DDD', 'DDDD'], function (input, array, config) {
+    config._dayOfYear = toInt(input);
+});
+
+// HELPERS
+
+// MOMENTS
+
+function getSetDayOfYear (input) {
+    var dayOfYear = Math.round((this.clone().startOf('day') - this.clone().startOf('year')) / 864e5) + 1;
+    return input == null ? dayOfYear : this.add((input - dayOfYear), 'd');
+}
+
+// FORMATTING
+
+addFormatToken('m', ['mm', 2], 0, 'minute');
+
+// ALIASES
+
+addUnitAlias('minute', 'm');
+
+// PRIORITY
+
+addUnitPriority('minute', 14);
+
+// PARSING
+
+addRegexToken('m',  match1to2);
+addRegexToken('mm', match1to2, match2);
+addParseToken(['m', 'mm'], MINUTE);
+
+// MOMENTS
+
+var getSetMinute = makeGetSet('Minutes', false);
+
+// FORMATTING
+
+addFormatToken('s', ['ss', 2], 0, 'second');
+
+// ALIASES
+
+addUnitAlias('second', 's');
+
+// PRIORITY
+
+addUnitPriority('second', 15);
+
+// PARSING
+
+addRegexToken('s',  match1to2);
+addRegexToken('ss', match1to2, match2);
+addParseToken(['s', 'ss'], SECOND);
+
+// MOMENTS
+
+var getSetSecond = makeGetSet('Seconds', false);
+
+// FORMATTING
+
+addFormatToken('S', 0, 0, function () {
+    return ~~(this.millisecond() / 100);
+});
+
+addFormatToken(0, ['SS', 2], 0, function () {
+    return ~~(this.millisecond() / 10);
+});
+
+addFormatToken(0, ['SSS', 3], 0, 'millisecond');
+addFormatToken(0, ['SSSS', 4], 0, function () {
+    return this.millisecond() * 10;
+});
+addFormatToken(0, ['SSSSS', 5], 0, function () {
+    return this.millisecond() * 100;
+});
+addFormatToken(0, ['SSSSSS', 6], 0, function () {
+    return this.millisecond() * 1000;
+});
+addFormatToken(0, ['SSSSSSS', 7], 0, function () {
+    return this.millisecond() * 10000;
+});
+addFormatToken(0, ['SSSSSSSS', 8], 0, function () {
+    return this.millisecond() * 100000;
+});
+addFormatToken(0, ['SSSSSSSSS', 9], 0, function () {
+    return this.millisecond() * 1000000;
+});
+
+
+// ALIASES
+
+addUnitAlias('millisecond', 'ms');
+
+// PRIORITY
+
+addUnitPriority('millisecond', 16);
+
+// PARSING
+
+addRegexToken('S',    match1to3, match1);
+addRegexToken('SS',   match1to3, match2);
+addRegexToken('SSS',  match1to3, match3);
+
+var token;
+for (token = 'SSSS'; token.length <= 9; token += 'S') {
+    addRegexToken(token, matchUnsigned);
+}
+
+function parseMs(input, array) {
+    array[MILLISECOND] = toInt(('0.' + input) * 1000);
+}
+
+for (token = 'S'; token.length <= 9; token += 'S') {
+    addParseToken(token, parseMs);
+}
+// MOMENTS
+
+var getSetMillisecond = makeGetSet('Milliseconds', false);
+
+// FORMATTING
+
+addFormatToken('z',  0, 0, 'zoneAbbr');
+addFormatToken('zz', 0, 0, 'zoneName');
+
+// MOMENTS
+
+function getZoneAbbr () {
+    return this._isUTC ? 'UTC' : '';
+}
+
+function getZoneName () {
+    return this._isUTC ? 'Coordinated Universal Time' : '';
+}
+
+var proto = Moment.prototype;
+
+proto.add               = add;
+proto.calendar          = calendar$1;
+proto.clone             = clone;
+proto.diff              = diff;
+proto.endOf             = endOf;
+proto.format            = format;
+proto.from              = from;
+proto.fromNow           = fromNow;
+proto.to                = to;
+proto.toNow             = toNow;
+proto.get               = stringGet;
+proto.invalidAt         = invalidAt;
+proto.isAfter           = isAfter;
+proto.isBefore          = isBefore;
+proto.isBetween         = isBetween;
+proto.isSame            = isSame;
+proto.isSameOrAfter     = isSameOrAfter;
+proto.isSameOrBefore    = isSameOrBefore;
+proto.isValid           = isValid$2;
+proto.lang              = lang;
+proto.locale            = locale;
+proto.localeData        = localeData;
+proto.max               = prototypeMax;
+proto.min               = prototypeMin;
+proto.parsingFlags      = parsingFlags;
+proto.set               = stringSet;
+proto.startOf           = startOf;
+proto.subtract          = subtract;
+proto.toArray           = toArray;
+proto.toObject          = toObject;
+proto.toDate            = toDate;
+proto.toISOString       = toISOString;
+proto.inspect           = inspect;
+proto.toJSON            = toJSON;
+proto.toString          = toString;
+proto.unix              = unix;
+proto.valueOf           = valueOf;
+proto.creationData      = creationData;
+
+// Year
+proto.year       = getSetYear;
+proto.isLeapYear = getIsLeapYear;
+
+// Week Year
+proto.weekYear    = getSetWeekYear;
+proto.isoWeekYear = getSetISOWeekYear;
+
+// Quarter
+proto.quarter = proto.quarters = getSetQuarter;
+
+// Month
+proto.month       = getSetMonth;
+proto.daysInMonth = getDaysInMonth;
+
+// Week
+proto.week           = proto.weeks        = getSetWeek;
+proto.isoWeek        = proto.isoWeeks     = getSetISOWeek;
+proto.weeksInYear    = getWeeksInYear;
+proto.isoWeeksInYear = getISOWeeksInYear;
+
+// Day
+proto.date       = getSetDayOfMonth;
+proto.day        = proto.days             = getSetDayOfWeek;
+proto.weekday    = getSetLocaleDayOfWeek;
+proto.isoWeekday = getSetISODayOfWeek;
+proto.dayOfYear  = getSetDayOfYear;
+
+// Hour
+proto.hour = proto.hours = getSetHour;
+
+// Minute
+proto.minute = proto.minutes = getSetMinute;
+
+// Second
+proto.second = proto.seconds = getSetSecond;
+
+// Millisecond
+proto.millisecond = proto.milliseconds = getSetMillisecond;
+
+// Offset
+proto.utcOffset            = getSetOffset;
+proto.utc                  = setOffsetToUTC;
+proto.local                = setOffsetToLocal;
+proto.parseZone            = setOffsetToParsedOffset;
+proto.hasAlignedHourOffset = hasAlignedHourOffset;
+proto.isDST                = isDaylightSavingTime;
+proto.isLocal              = isLocal;
+proto.isUtcOffset          = isUtcOffset;
+proto.isUtc                = isUtc;
+proto.isUTC                = isUtc;
+
+// Timezone
+proto.zoneAbbr = getZoneAbbr;
+proto.zoneName = getZoneName;
+
+// Deprecations
+proto.dates  = deprecate('dates accessor is deprecated. Use date instead.', getSetDayOfMonth);
+proto.months = deprecate('months accessor is deprecated. Use month instead', getSetMonth);
+proto.years  = deprecate('years accessor is deprecated. Use year instead', getSetYear);
+proto.zone   = deprecate('moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/', getSetZone);
+proto.isDSTShifted = deprecate('isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information', isDaylightSavingTimeShifted);
+
+function createUnix (input) {
+    return createLocal(input * 1000);
+}
+
+function createInZone () {
+    return createLocal.apply(null, arguments).parseZone();
+}
+
+function preParsePostFormat (string) {
+    return string;
+}
+
+var proto$1 = Locale.prototype;
+
+proto$1.calendar        = calendar;
+proto$1.longDateFormat  = longDateFormat;
+proto$1.invalidDate     = invalidDate;
+proto$1.ordinal         = ordinal;
+proto$1.preparse        = preParsePostFormat;
+proto$1.postformat      = preParsePostFormat;
+proto$1.relativeTime    = relativeTime;
+proto$1.pastFuture      = pastFuture;
+proto$1.set             = set;
+
+// Month
+proto$1.months            =        localeMonths;
+proto$1.monthsShort       =        localeMonthsShort;
+proto$1.monthsParse       =        localeMonthsParse;
+proto$1.monthsRegex       = monthsRegex;
+proto$1.monthsShortRegex  = monthsShortRegex;
+
+// Week
+proto$1.week = localeWeek;
+proto$1.firstDayOfYear = localeFirstDayOfYear;
+proto$1.firstDayOfWeek = localeFirstDayOfWeek;
+
+// Day of Week
+proto$1.weekdays       =        localeWeekdays;
+proto$1.weekdaysMin    =        localeWeekdaysMin;
+proto$1.weekdaysShort  =        localeWeekdaysShort;
+proto$1.weekdaysParse  =        localeWeekdaysParse;
+
+proto$1.weekdaysRegex       =        weekdaysRegex;
+proto$1.weekdaysShortRegex  =        weekdaysShortRegex;
+proto$1.weekdaysMinRegex    =        weekdaysMinRegex;
+
+// Hours
+proto$1.isPM = localeIsPM;
+proto$1.meridiem = localeMeridiem;
+
+function get$1 (format, index, field, setter) {
+    var locale = getLocale();
+    var utc = createUTC().set(setter, index);
+    return locale[field](utc, format);
+}
+
+function listMonthsImpl (format, index, field) {
+    if (isNumber(format)) {
+        index = format;
+        format = undefined;
+    }
+
+    format = format || '';
+
+    if (index != null) {
+        return get$1(format, index, field, 'month');
+    }
+
+    var i;
+    var out = [];
+    for (i = 0; i < 12; i++) {
+        out[i] = get$1(format, i, field, 'month');
+    }
+    return out;
+}
+
+// ()
+// (5)
+// (fmt, 5)
+// (fmt)
+// (true)
+// (true, 5)
+// (true, fmt, 5)
+// (true, fmt)
+function listWeekdaysImpl (localeSorted, format, index, field) {
+    if (typeof localeSorted === 'boolean') {
+        if (isNumber(format)) {
+            index = format;
+            format = undefined;
+        }
+
+        format = format || '';
+    } else {
+        format = localeSorted;
+        index = format;
+        localeSorted = false;
+
+        if (isNumber(format)) {
+            index = format;
+            format = undefined;
+        }
+
+        format = format || '';
+    }
+
+    var locale = getLocale(),
+        shift = localeSorted ? locale._week.dow : 0;
+
+    if (index != null) {
+        return get$1(format, (index + shift) % 7, field, 'day');
+    }
+
+    var i;
+    var out = [];
+    for (i = 0; i < 7; i++) {
+        out[i] = get$1(format, (i + shift) % 7, field, 'day');
+    }
+    return out;
+}
+
+function listMonths (format, index) {
+    return listMonthsImpl(format, index, 'months');
+}
+
+function listMonthsShort (format, index) {
+    return listMonthsImpl(format, index, 'monthsShort');
+}
+
+function listWeekdays (localeSorted, format, index) {
+    return listWeekdaysImpl(localeSorted, format, index, 'weekdays');
+}
+
+function listWeekdaysShort (localeSorted, format, index) {
+    return listWeekdaysImpl(localeSorted, format, index, 'weekdaysShort');
+}
+
+function listWeekdaysMin (localeSorted, format, index) {
+    return listWeekdaysImpl(localeSorted, format, index, 'weekdaysMin');
+}
+
+getSetGlobalLocale('en', {
+    dayOfMonthOrdinalParse: /\d{1,2}(th|st|nd|rd)/,
+    ordinal : function (number) {
+        var b = number % 10,
+            output = (toInt(number % 100 / 10) === 1) ? 'th' :
+            (b === 1) ? 'st' :
+            (b === 2) ? 'nd' :
+            (b === 3) ? 'rd' : 'th';
+        return number + output;
+    }
+});
+
+// Side effect imports
+hooks.lang = deprecate('moment.lang is deprecated. Use moment.locale instead.', getSetGlobalLocale);
+hooks.langData = deprecate('moment.langData is deprecated. Use moment.localeData instead.', getLocale);
+
+var mathAbs = Math.abs;
+
+function abs () {
+    var data           = this._data;
+
+    this._milliseconds = mathAbs(this._milliseconds);
+    this._days         = mathAbs(this._days);
+    this._months       = mathAbs(this._months);
+
+    data.milliseconds  = mathAbs(data.milliseconds);
+    data.seconds       = mathAbs(data.seconds);
+    data.minutes       = mathAbs(data.minutes);
+    data.hours         = mathAbs(data.hours);
+    data.months        = mathAbs(data.months);
+    data.years         = mathAbs(data.years);
+
+    return this;
+}
+
+function addSubtract$1 (duration, input, value, direction) {
+    var other = createDuration(input, value);
+
+    duration._milliseconds += direction * other._milliseconds;
+    duration._days         += direction * other._days;
+    duration._months       += direction * other._months;
+
+    return duration._bubble();
+}
+
+// supports only 2.0-style add(1, 's') or add(duration)
+function add$1 (input, value) {
+    return addSubtract$1(this, input, value, 1);
+}
+
+// supports only 2.0-style subtract(1, 's') or subtract(duration)
+function subtract$1 (input, value) {
+    return addSubtract$1(this, input, value, -1);
+}
+
+function absCeil (number) {
+    if (number < 0) {
+        return Math.floor(number);
+    } else {
+        return Math.ceil(number);
+    }
+}
+
+function bubble () {
+    var milliseconds = this._milliseconds;
+    var days         = this._days;
+    var months       = this._months;
+    var data         = this._data;
+    var seconds, minutes, hours, years, monthsFromDays;
+
+    // if we have a mix of positive and negative values, bubble down first
+    // check: https://github.com/moment/moment/issues/2166
+    if (!((milliseconds >= 0 && days >= 0 && months >= 0) ||
+            (milliseconds <= 0 && days <= 0 && months <= 0))) {
+        milliseconds += absCeil(monthsToDays(months) + days) * 864e5;
+        days = 0;
+        months = 0;
+    }
+
+    // The following code bubbles up values, see the tests for
+    // examples of what that means.
+    data.milliseconds = milliseconds % 1000;
+
+    seconds           = absFloor(milliseconds / 1000);
+    data.seconds      = seconds % 60;
+
+    minutes           = absFloor(seconds / 60);
+    data.minutes      = minutes % 60;
+
+    hours             = absFloor(minutes / 60);
+    data.hours        = hours % 24;
+
+    days += absFloor(hours / 24);
+
+    // convert days to months
+    monthsFromDays = absFloor(daysToMonths(days));
+    months += monthsFromDays;
+    days -= absCeil(monthsToDays(monthsFromDays));
+
+    // 12 months -> 1 year
+    years = absFloor(months / 12);
+    months %= 12;
+
+    data.days   = days;
+    data.months = months;
+    data.years  = years;
+
+    return this;
+}
+
+function daysToMonths (days) {
+    // 400 years have 146097 days (taking into account leap year rules)
+    // 400 years have 12 months === 4800
+    return days * 4800 / 146097;
+}
+
+function monthsToDays (months) {
+    // the reverse of daysToMonths
+    return months * 146097 / 4800;
+}
+
+function as (units) {
+    if (!this.isValid()) {
+        return NaN;
+    }
+    var days;
+    var months;
+    var milliseconds = this._milliseconds;
+
+    units = normalizeUnits(units);
+
+    if (units === 'month' || units === 'year') {
+        days   = this._days   + milliseconds / 864e5;
+        months = this._months + daysToMonths(days);
+        return units === 'month' ? months : months / 12;
+    } else {
+        // handle milliseconds separately because of floating point math errors (issue #1867)
+        days = this._days + Math.round(monthsToDays(this._months));
+        switch (units) {
+            case 'week'   : return days / 7     + milliseconds / 6048e5;
+            case 'day'    : return days         + milliseconds / 864e5;
+            case 'hour'   : return days * 24    + milliseconds / 36e5;
+            case 'minute' : return days * 1440  + milliseconds / 6e4;
+            case 'second' : return days * 86400 + milliseconds / 1000;
+            // Math.floor prevents floating point math errors here
+            case 'millisecond': return Math.floor(days * 864e5) + milliseconds;
+            default: throw new Error('Unknown unit ' + units);
+        }
+    }
+}
+
+// TODO: Use this.as('ms')?
+function valueOf$1 () {
+    if (!this.isValid()) {
+        return NaN;
+    }
+    return (
+        this._milliseconds +
+        this._days * 864e5 +
+        (this._months % 12) * 2592e6 +
+        toInt(this._months / 12) * 31536e6
+    );
+}
+
+function makeAs (alias) {
+    return function () {
+        return this.as(alias);
+    };
+}
+
+var asMilliseconds = makeAs('ms');
+var asSeconds      = makeAs('s');
+var asMinutes      = makeAs('m');
+var asHours        = makeAs('h');
+var asDays         = makeAs('d');
+var asWeeks        = makeAs('w');
+var asMonths       = makeAs('M');
+var asYears        = makeAs('y');
+
+function get$2 (units) {
+    units = normalizeUnits(units);
+    return this.isValid() ? this[units + 's']() : NaN;
+}
+
+function makeGetter(name) {
+    return function () {
+        return this.isValid() ? this._data[name] : NaN;
+    };
+}
+
+var milliseconds = makeGetter('milliseconds');
+var seconds      = makeGetter('seconds');
+var minutes      = makeGetter('minutes');
+var hours        = makeGetter('hours');
+var days         = makeGetter('days');
+var months       = makeGetter('months');
+var years        = makeGetter('years');
+
+function weeks () {
+    return absFloor(this.days() / 7);
+}
+
+var round = Math.round;
+var thresholds = {
+    ss: 44,         // a few seconds to seconds
+    s : 45,         // seconds to minute
+    m : 45,         // minutes to hour
+    h : 22,         // hours to day
+    d : 26,         // days to month
+    M : 11          // months to year
+};
+
+// helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize
+function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale) {
+    return locale.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
+}
+
+function relativeTime$1 (posNegDuration, withoutSuffix, locale) {
+    var duration = createDuration(posNegDuration).abs();
+    var seconds  = round(duration.as('s'));
+    var minutes  = round(duration.as('m'));
+    var hours    = round(duration.as('h'));
+    var days     = round(duration.as('d'));
+    var months   = round(duration.as('M'));
+    var years    = round(duration.as('y'));
+
+    var a = seconds <= thresholds.ss && ['s', seconds]  ||
+            seconds < thresholds.s   && ['ss', seconds] ||
+            minutes <= 1             && ['m']           ||
+            minutes < thresholds.m   && ['mm', minutes] ||
+            hours   <= 1             && ['h']           ||
+            hours   < thresholds.h   && ['hh', hours]   ||
+            days    <= 1             && ['d']           ||
+            days    < thresholds.d   && ['dd', days]    ||
+            months  <= 1             && ['M']           ||
+            months  < thresholds.M   && ['MM', months]  ||
+            years   <= 1             && ['y']           || ['yy', years];
+
+    a[2] = withoutSuffix;
+    a[3] = +posNegDuration > 0;
+    a[4] = locale;
+    return substituteTimeAgo.apply(null, a);
+}
+
+// This function allows you to set the rounding function for relative time strings
+function getSetRelativeTimeRounding (roundingFunction) {
+    if (roundingFunction === undefined) {
+        return round;
+    }
+    if (typeof(roundingFunction) === 'function') {
+        round = roundingFunction;
+        return true;
+    }
+    return false;
+}
+
+// This function allows you to set a threshold for relative time strings
+function getSetRelativeTimeThreshold (threshold, limit) {
+    if (thresholds[threshold] === undefined) {
+        return false;
+    }
+    if (limit === undefined) {
+        return thresholds[threshold];
+    }
+    thresholds[threshold] = limit;
+    if (threshold === 's') {
+        thresholds.ss = limit - 1;
+    }
+    return true;
+}
+
+function humanize (withSuffix) {
+    if (!this.isValid()) {
+        return this.localeData().invalidDate();
+    }
+
+    var locale = this.localeData();
+    var output = relativeTime$1(this, !withSuffix, locale);
+
+    if (withSuffix) {
+        output = locale.pastFuture(+this, output);
+    }
+
+    return locale.postformat(output);
+}
+
+var abs$1 = Math.abs;
+
+function toISOString$1() {
+    // for ISO strings we do not use the normal bubbling rules:
+    //  * milliseconds bubble up until they become hours
+    //  * days do not bubble at all
+    //  * months bubble up until they become years
+    // This is because there is no context-free conversion between hours and days
+    // (think of clock changes)
+    // and also not between days and months (28-31 days per month)
+    if (!this.isValid()) {
+        return this.localeData().invalidDate();
+    }
+
+    var seconds = abs$1(this._milliseconds) / 1000;
+    var days         = abs$1(this._days);
+    var months       = abs$1(this._months);
+    var minutes, hours, years;
+
+    // 3600 seconds -> 60 minutes -> 1 hour
+    minutes           = absFloor(seconds / 60);
+    hours             = absFloor(minutes / 60);
+    seconds %= 60;
+    minutes %= 60;
+
+    // 12 months -> 1 year
+    years  = absFloor(months / 12);
+    months %= 12;
+
+
+    // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js
+    var Y = years;
+    var M = months;
+    var D = days;
+    var h = hours;
+    var m = minutes;
+    var s = seconds;
+    var total = this.asSeconds();
+
+    if (!total) {
+        // this is the same as C#'s (Noda) and python (isodate)...
+        // but not other JS (goog.date)
+        return 'P0D';
+    }
+
+    return (total < 0 ? '-' : '') +
+        'P' +
+        (Y ? Y + 'Y' : '') +
+        (M ? M + 'M' : '') +
+        (D ? D + 'D' : '') +
+        ((h || m || s) ? 'T' : '') +
+        (h ? h + 'H' : '') +
+        (m ? m + 'M' : '') +
+        (s ? s + 'S' : '');
+}
+
+var proto$2 = Duration.prototype;
+
+proto$2.isValid        = isValid$1;
+proto$2.abs            = abs;
+proto$2.add            = add$1;
+proto$2.subtract       = subtract$1;
+proto$2.as             = as;
+proto$2.asMilliseconds = asMilliseconds;
+proto$2.asSeconds      = asSeconds;
+proto$2.asMinutes      = asMinutes;
+proto$2.asHours        = asHours;
+proto$2.asDays         = asDays;
+proto$2.asWeeks        = asWeeks;
+proto$2.asMonths       = asMonths;
+proto$2.asYears        = asYears;
+proto$2.valueOf        = valueOf$1;
+proto$2._bubble        = bubble;
+proto$2.get            = get$2;
+proto$2.milliseconds   = milliseconds;
+proto$2.seconds        = seconds;
+proto$2.minutes        = minutes;
+proto$2.hours          = hours;
+proto$2.days           = days;
+proto$2.weeks          = weeks;
+proto$2.months         = months;
+proto$2.years          = years;
+proto$2.humanize       = humanize;
+proto$2.toISOString    = toISOString$1;
+proto$2.toString       = toISOString$1;
+proto$2.toJSON         = toISOString$1;
+proto$2.locale         = locale;
+proto$2.localeData     = localeData;
+
+// Deprecations
+proto$2.toIsoString = deprecate('toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)', toISOString$1);
+proto$2.lang = lang;
+
+// Side effect imports
+
+// FORMATTING
+
+addFormatToken('X', 0, 0, 'unix');
+addFormatToken('x', 0, 0, 'valueOf');
+
+// PARSING
+
+addRegexToken('x', matchSigned);
+addRegexToken('X', matchTimestamp);
+addParseToken('X', function (input, array, config) {
+    config._d = new Date(parseFloat(input, 10) * 1000);
+});
+addParseToken('x', function (input, array, config) {
+    config._d = new Date(toInt(input));
+});
+
+// Side effect imports
+
+
+hooks.version = '2.18.1';
+
+setHookCallback(createLocal);
+
+hooks.fn                    = proto;
+hooks.min                   = min;
+hooks.max                   = max;
+hooks.now                   = now;
+hooks.utc                   = createUTC;
+hooks.unix                  = createUnix;
+hooks.months                = listMonths;
+hooks.isDate                = isDate;
+hooks.locale                = getSetGlobalLocale;
+hooks.invalid               = createInvalid;
+hooks.duration              = createDuration;
+hooks.isMoment              = isMoment;
+hooks.weekdays              = listWeekdays;
+hooks.parseZone             = createInZone;
+hooks.localeData            = getLocale;
+hooks.isDuration            = isDuration;
+hooks.monthsShort           = listMonthsShort;
+hooks.weekdaysMin           = listWeekdaysMin;
+hooks.defineLocale          = defineLocale;
+hooks.updateLocale          = updateLocale;
+hooks.locales               = listLocales;
+hooks.weekdaysShort         = listWeekdaysShort;
+hooks.normalizeUnits        = normalizeUnits;
+hooks.relativeTimeRounding = getSetRelativeTimeRounding;
+hooks.relativeTimeThreshold = getSetRelativeTimeThreshold;
+hooks.calendarFormat        = getCalendarFormat;
+hooks.prototype             = proto;
+
+return hooks;
+
+})));

+ 41 - 0
templates.xml

@@ -0,0 +1,41 @@
+<openerp>
+    <data>
+        <template id="web.assets_eiru" name="Eiru Assets" inherit_id="web.assets_backend">
+            <xpath expr="." position="inside">
+                <!-- Accounting JS -->
+                <script type="text/javascript" src="/eiru_assets/static/lib/accounting/accounting.js" />
+
+                <!-- Boostrap Table -->
+                <link rel="stylesheet" href="/eiru_assets/static/lib/bootstrap-table/bootstrap-table.css" />
+                <script type="text/javascript" src="/eiru_assets/static/lib/bootstrap-table/bootstrap-table.js" />
+                <script type="text/javascript" src="/eiru_assets/static/lib/bootstrap-table/bootstrap-table-es-PY.js" />
+                <script type="text/javascript" src="/eiru_assets/static/lib/bootstrap-table/bootstrap-table-toolbar.js" />
+                <script type="text/javascript" src="/eiru_assets/static/lib/bootstrap-table/bootstrap-table-reorder-columns.js" />
+                <script type="text/javascript" src="/eiru_assets/static/lib/bootstrap-table/bootstrap-table-export.js" />
+                <script type="text/javascript" src="/eiru_assets/static/lib/bootstrap-table/tableExport.js" />
+
+                <!-- Chartjs -->
+                <script type="text/javascript" src="/eiru_assets/static/lib/chartjs/Chart.js" />
+
+                <!-- Gridstack -->
+                <link rel="stylesheet" href="/eiru_assets/static/lib/gridstack/gridstack.css" />
+                <link rel="stylesheet" href="/eiru_assets/static/lib/gridstack/gridstack-extra.css" />
+                <script type="text/javascript" src="/eiru_assets/static/lib/gridstack/gridstack.js" />
+                <script type="text/javascript" src="/eiru_assets/static/lib/gridstack/gridstack.jQueryUI.js" />
+
+                <!-- jQuery addons -->
+                <link rel="stylesheet" href="/eiru_assets/static/lib/jquery/jquery.dragtable.css" />
+                <script type="text/javascript" src="/eiru_assets/static/lib/jquery/jquery.dragtable.js" />
+                <script type="text/javascript" src="/eiru_assets/static/lib/jquery/jquery.base64.js" />
+                <script type="text/javascript" src="/eiru_assets/static/lib/jquery/jquery.serializejson.js" />
+
+                <!-- jsPdf -->
+                <script type="text/javascript" src="/eiru_assets/static/lib/jspdf/jspdf.js" />
+                <script type="text/javascript" src="/eiru_assets/static/lib/jspdf/jspdf.autotable.js" />
+
+                <!-- Moment -->
+                <script type="text/javascript" src="/eiru_assets/static/lib/moment/moment.js" />
+            </xpath>
+        </template>
+    </data>
+</openerp>