function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }

function createPngDataTable() {
  /* Table of CRCs of all 8-bit messages. */
  var crcTable = new Int32Array(256);
  for (var n = 0; n < 256; n++) {
    var c = n;
    for (var k = 0; k < 8; k++) {
      c = c & 1 ? 0xedb88320 ^ c >>> 1 : c >>> 1;
    }
    crcTable[n] = c;
  }
  return crcTable;
}

function calcCrc(buf) {
  var c = -1;
  if (!pngDataTable) pngDataTable = createPngDataTable();
  for (var n = 0; n < buf.length; n++) {
    c = pngDataTable[(c ^ buf[n]) & 0xFF] ^ c >>> 8;
  }
  return c ^ -1;
}

var pngDataTable = void 0;

var PNG = 'image/png';
var JPEG = 'image/jpeg';

// those are 3 possible signature of the physBlock in base64.
// the pHYs signature block is preceed by the 4 bytes of lenght. The length of
// the block is always 9 bytes. So a phys block has always this signature:
// 0 0 0 9 p H Y s.
// However the data64 encoding aligns we will always find one of those 3 strings.
// this allow us to find this particular occurence of the pHYs block without
// converting from b64 back to string
var b64PhysSignature1 = 'AAlwSFlz';
var b64PhysSignature2 = 'AAAJcEhZ';
var b64PhysSignature3 = 'AAAACXBI';

var _P = 'p'.charCodeAt(0);
var _H = 'H'.charCodeAt(0);
var _Y = 'Y'.charCodeAt(0);
var _S = 's'.charCodeAt(0);

function changeDpiBlob(blob, dpi) {
  // 33 bytes are ok for pngs and jpegs
  // to contain the information.
  var headerChunk = blob.slice(0, 33);
  return new Promise(function (resolve, reject) {
    var fileReader = new FileReader();
    fileReader.onload = function () {
      var dataArray = new Uint8Array(fileReader.result);
      var tail = blob.slice(33);
      var changedArray = changeDpiOnArray(dataArray, dpi, blob.type);
      resolve(new Blob([changedArray, tail], { type: blob.type }));
    };
    fileReader.readAsArrayBuffer(headerChunk);
  });
}

function changeDpiDataUrl(base64Image, dpi) {
  var dataSplitted = base64Image.split(',');
  var format = dataSplitted[0];
  var body = dataSplitted[1];
  var type = void 0;
  var headerLength = void 0;
  var overwritepHYs = false;
  if (format.indexOf(PNG) !== -1) {
    type = PNG;
    var b64Index = detectPhysChunkFromDataUrl(body);
    // 28 bytes in dataUrl are 21bytes, length of phys chunk with everything inside.
    if (b64Index >= 0) {
      headerLength = Math.ceil((b64Index + 28) / 3) * 4;
      overwritepHYs = true;
    } else {
      headerLength = 33 / 3 * 4;
    }
  }
  if (format.indexOf(JPEG) !== -1) {
    type = JPEG;
    headerLength = 18 / 3 * 4;
  }
  // 33 bytes are ok for pngs and jpegs
  // to contain the information.
  var stringHeader = body.substring(0, headerLength);
  var restOfData = body.substring(headerLength);
  var headerBytes = atob(stringHeader);
  var dataArray = new Uint8Array(headerBytes.length);
  for (var i = 0; i < dataArray.length; i++) {
    dataArray[i] = headerBytes.charCodeAt(i);
  }
  var finalArray = changeDpiOnArray(dataArray, dpi, type, overwritepHYs);
  var base64Header = btoa(String.fromCharCode.apply(String, _toConsumableArray(finalArray)));
  return [format, ',', base64Header, restOfData].join('');
}

function detectPhysChunkFromDataUrl(data) {
  var b64index = data.indexOf(b64PhysSignature1);
  if (b64index === -1) {
    b64index = data.indexOf(b64PhysSignature2);
  }
  if (b64index === -1) {
    b64index = data.indexOf(b64PhysSignature3);
  }
  // if b64index === -1 chunk is not found
  return b64index;
}

function searchStartOfPhys(data) {
  var length = data.length - 1;
  // we check from the end since we cut the string in proximity of the header
  // the header is within 21 bytes from the end.
  for (var i = length; i >= 4; i--) {
    if (data[i - 4] === 9 && data[i - 3] === _P && data[i - 2] === _H && data[i - 1] === _Y && data[i] === _S) {
      return i - 3;
    }
  }
}

function changeDpiOnArray(dataArray, dpi, format, overwritepHYs) {
  if (format === JPEG) {
    dataArray[13] = 1; // 1 pixel per inch or 2 pixel per cm
    dataArray[14] = dpi >> 8; // dpiX high byte
    dataArray[15] = dpi & 0xff; // dpiX low byte
    dataArray[16] = dpi >> 8; // dpiY high byte
    dataArray[17] = dpi & 0xff; // dpiY low byte
    return dataArray;
  }
  if (format === PNG) {
    var physChunk = new Uint8Array(13);
    // chunk header pHYs
    // 9 bytes of data
    // 4 bytes of crc
    // this multiplication is because the standard is dpi per meter.
    dpi *= 39.3701;
    physChunk[0] = _P;
    physChunk[1] = _H;
    physChunk[2] = _Y;
    physChunk[3] = _S;
    physChunk[4] = dpi >>> 24; // dpiX highest byte
    physChunk[5] = dpi >>> 16; // dpiX veryhigh byte
    physChunk[6] = dpi >>> 8; // dpiX high byte
    physChunk[7] = dpi & 0xff; // dpiX low byte
    physChunk[8] = physChunk[4]; // dpiY highest byte
    physChunk[9] = physChunk[5]; // dpiY veryhigh byte
    physChunk[10] = physChunk[6]; // dpiY high byte
    physChunk[11] = physChunk[7]; // dpiY low byte
    physChunk[12] = 1; // dot per meter....

    var crc = calcCrc(physChunk);

    var crcChunk = new Uint8Array(4);
    crcChunk[0] = crc >>> 24;
    crcChunk[1] = crc >>> 16;
    crcChunk[2] = crc >>> 8;
    crcChunk[3] = crc & 0xff;

    if (overwritepHYs) {
      var startingIndex = searchStartOfPhys(dataArray);
      dataArray.set(physChunk, startingIndex);
      dataArray.set(crcChunk, startingIndex + 13);
      return dataArray;
    } else {
      // i need to give back an array of data that is divisible by 3 so that
      // dataurl encoding gives me integers, for luck this chunk is 17 + 4 = 21
      // if it was we could add a text chunk contaning some info, untill desired
      // length is met.

      // chunk structur 4 bytes for length is 9
      var chunkLength = new Uint8Array(4);
      chunkLength[0] = 0;
      chunkLength[1] = 0;
      chunkLength[2] = 0;
      chunkLength[3] = 9;

      var finalHeader = new Uint8Array(54);
      finalHeader.set(dataArray, 0);
      finalHeader.set(chunkLength, 33);
      finalHeader.set(physChunk, 37);
      finalHeader.set(crcChunk, 50);
      return finalHeader;
    }
  }
}

/* @preserve
 * The MIT License (MIT)
 *
 * Copyright (c) 2013-2015 Petka Antonov
 *
 * 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.
 *
 */
/**
 * bluebird build version 3.3.5
 * Features enabled: core, race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, using, timers, filter, any, each
*/
!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var e;"undefined"!=typeof window?e=window:"undefined"!=typeof global?e=global:"undefined"!=typeof self&&(e=self),e.Promise=t()}}(function(){var t,e,n;return function r(t,e,n){function i(s,a){if(!e[s]){if(!t[s]){var c="function"==typeof _dereq_&&_dereq_;if(!a&&c)return c(s,!0);if(o)return o(s,!0);var l=new Error("Cannot find module '"+s+"'");throw l.code="MODULE_NOT_FOUND",l}var u=e[s]={exports:{}};t[s][0].call(u.exports,function(e){var n=t[s][1][e];return i(n?n:e)},u,u.exports,r,t,e,n)}return e[s].exports}for(var o="function"==typeof _dereq_&&_dereq_,s=0;s<n.length;s++)i(n[s]);return i}({1:[function(t,e,n){"use strict";e.exports=function(t){function e(t){var e=new n(t),r=e.promise();return e.setHowMany(1),e.setUnwrap(),e.init(),r}var n=t._SomePromiseArray;t.any=function(t){return e(t)},t.prototype.any=function(){return e(this)}}},{}],2:[function(t,e,n){"use strict";function r(){this._customScheduler=!1,this._isTickUsed=!1,this._lateQueue=new u(16),this._normalQueue=new u(16),this._haveDrainedQueues=!1,this._trampolineEnabled=!0;var t=this;this.drainQueues=function(){t._drainQueues()},this._schedule=l}function i(t,e,n){this._lateQueue.push(t,e,n),this._queueTick()}function o(t,e,n){this._normalQueue.push(t,e,n),this._queueTick()}function s(t){this._normalQueue._pushOne(t),this._queueTick()}var a;try{throw new Error}catch(c){a=c}var l=t("./schedule"),u=t("./queue"),p=t("./util");r.prototype.setScheduler=function(t){var e=this._schedule;return this._schedule=t,this._customScheduler=!0,e},r.prototype.hasCustomScheduler=function(){return this._customScheduler},r.prototype.enableTrampoline=function(){this._trampolineEnabled=!0},r.prototype.disableTrampolineIfNecessary=function(){p.hasDevTools&&(this._trampolineEnabled=!1)},r.prototype.haveItemsQueued=function(){return this._isTickUsed||this._haveDrainedQueues},r.prototype.fatalError=function(t,e){e?(process.stderr.write("Fatal "+(t instanceof Error?t.stack:t)+"\n"),process.exit(2)):this.throwLater(t)},r.prototype.throwLater=function(t,e){if(1===arguments.length&&(e=t,t=function(){throw e}),"undefined"!=typeof setTimeout)setTimeout(function(){t(e)},0);else try{this._schedule(function(){t(e)})}catch(n){throw new Error("No async scheduler available\n\n    See http://goo.gl/MqrFmX\n")}},p.hasDevTools?(r.prototype.invokeLater=function(t,e,n){this._trampolineEnabled?i.call(this,t,e,n):this._schedule(function(){setTimeout(function(){t.call(e,n)},100)})},r.prototype.invoke=function(t,e,n){this._trampolineEnabled?o.call(this,t,e,n):this._schedule(function(){t.call(e,n)})},r.prototype.settlePromises=function(t){this._trampolineEnabled?s.call(this,t):this._schedule(function(){t._settlePromises()})}):(r.prototype.invokeLater=i,r.prototype.invoke=o,r.prototype.settlePromises=s),r.prototype.invokeFirst=function(t,e,n){this._normalQueue.unshift(t,e,n),this._queueTick()},r.prototype._drainQueue=function(t){for(;t.length()>0;){var e=t.shift();if("function"==typeof e){var n=t.shift(),r=t.shift();e.call(n,r)}else e._settlePromises()}},r.prototype._drainQueues=function(){this._drainQueue(this._normalQueue),this._reset(),this._haveDrainedQueues=!0,this._drainQueue(this._lateQueue)},r.prototype._queueTick=function(){this._isTickUsed||(this._isTickUsed=!0,this._schedule(this.drainQueues))},r.prototype._reset=function(){this._isTickUsed=!1},e.exports=r,e.exports.firstLineError=a},{"./queue":26,"./schedule":29,"./util":36}],3:[function(t,e,n){"use strict";e.exports=function(t,e,n,r){var i=!1,o=function(t,e){this._reject(e)},s=function(t,e){e.promiseRejectionQueued=!0,e.bindingPromise._then(o,o,null,this,t)},a=function(t,e){0===(50397184&this._bitField)&&this._resolveCallback(e.target)},c=function(t,e){e.promiseRejectionQueued||this._reject(t)};t.prototype.bind=function(o){i||(i=!0,t.prototype._propagateFrom=r.propagateFromFunction(),t.prototype._boundValue=r.boundValueFunction());var l=n(o),u=new t(e);u._propagateFrom(this,1);var p=this._target();if(u._setBoundTo(l),l instanceof t){var h={promiseRejectionQueued:!1,promise:u,target:p,bindingPromise:l};p._then(e,s,void 0,u,h),l._then(a,c,void 0,u,h),u._setOnCancel(l)}else u._resolveCallback(p);return u},t.prototype._setBoundTo=function(t){void 0!==t?(this._bitField=2097152|this._bitField,this._boundTo=t):this._bitField=-2097153&this._bitField},t.prototype._isBound=function(){return 2097152===(2097152&this._bitField)},t.bind=function(e,n){return t.resolve(n).bind(e)}}},{}],4:[function(t,e,n){"use strict";function r(){try{Promise===o&&(Promise=i)}catch(t){}return o}var i;"undefined"!=typeof Promise&&(i=Promise);var o=t("./promise")();o.noConflict=r,e.exports=o},{"./promise":22}],5:[function(t,e,n){"use strict";var r=Object.create;if(r){var i=r(null),o=r(null);i[" size"]=o[" size"]=0}e.exports=function(e){function n(t,n){var r;if(null!=t&&(r=t[n]),"function"!=typeof r){var i="Object "+a.classString(t)+" has no method '"+a.toString(n)+"'";throw new e.TypeError(i)}return r}function r(t){var e=this.pop(),r=n(t,e);return r.apply(t,this)}function i(t){return t[this]}function o(t){var e=+this;return 0>e&&(e=Math.max(0,e+t.length)),t[e]}var s,a=t("./util"),c=a.canEvaluate;a.isIdentifier;e.prototype.call=function(t){var e=[].slice.call(arguments,1);return e.push(t),this._then(r,void 0,void 0,e,void 0)},e.prototype.get=function(t){var e,n="number"==typeof t;if(n)e=o;else if(c){var r=s(t);e=null!==r?r:i}else e=i;return this._then(e,void 0,void 0,t,void 0)}}},{"./util":36}],6:[function(t,e,n){"use strict";e.exports=function(e,n,r,i){var o=t("./util"),s=o.tryCatch,a=o.errorObj,c=e._async;e.prototype["break"]=e.prototype.cancel=function(){if(!i.cancellation())return this._warn("cancellation is disabled");for(var t=this,e=t;t.isCancellable();){if(!t._cancelBy(e)){e._isFollowing()?e._followee().cancel():e._cancelBranched();break}var n=t._cancellationParent;if(null==n||!n.isCancellable()){t._isFollowing()?t._followee().cancel():t._cancelBranched();break}t._isFollowing()&&t._followee().cancel(),e=t,t=n}},e.prototype._branchHasCancelled=function(){this._branchesRemainingToCancel--},e.prototype._enoughBranchesHaveCancelled=function(){return void 0===this._branchesRemainingToCancel||this._branchesRemainingToCancel<=0},e.prototype._cancelBy=function(t){return t===this?(this._branchesRemainingToCancel=0,this._invokeOnCancel(),!0):(this._branchHasCancelled(),this._enoughBranchesHaveCancelled()?(this._invokeOnCancel(),!0):!1)},e.prototype._cancelBranched=function(){this._enoughBranchesHaveCancelled()&&this._cancel()},e.prototype._cancel=function(){this.isCancellable()&&(this._setCancelled(),c.invoke(this._cancelPromises,this,void 0))},e.prototype._cancelPromises=function(){this._length()>0&&this._settlePromises()},e.prototype._unsetOnCancel=function(){this._onCancelField=void 0},e.prototype.isCancellable=function(){return this.isPending()&&!this.isCancelled()},e.prototype._doInvokeOnCancel=function(t,e){if(o.isArray(t))for(var n=0;n<t.length;++n)this._doInvokeOnCancel(t[n],e);else if(void 0!==t)if("function"==typeof t){if(!e){var r=s(t).call(this._boundValue());r===a&&(this._attachExtraTrace(r.e),c.throwLater(r.e))}}else t._resultCancelled(this)},e.prototype._invokeOnCancel=function(){var t=this._onCancel();this._unsetOnCancel(),c.invoke(this._doInvokeOnCancel,this,t)},e.prototype._invokeInternalOnCancel=function(){this.isCancellable()&&(this._doInvokeOnCancel(this._onCancel(),!0),this._unsetOnCancel())},e.prototype._resultCancelled=function(){this.cancel()}}},{"./util":36}],7:[function(t,e,n){"use strict";e.exports=function(e){function n(t,n,a){return function(c){var l=a._boundValue();t:for(var u=0;u<t.length;++u){var p=t[u];if(p===Error||null!=p&&p.prototype instanceof Error){if(c instanceof p)return o(n).call(l,c)}else if("function"==typeof p){var h=o(p).call(l,c);if(h===s)return h;if(h)return o(n).call(l,c)}else if(r.isObject(c)){for(var f=i(p),_=0;_<f.length;++_){var d=f[_];if(p[d]!=c[d])continue t}return o(n).call(l,c)}}return e}}var r=t("./util"),i=t("./es5").keys,o=r.tryCatch,s=r.errorObj;return n}},{"./es5":13,"./util":36}],8:[function(t,e,n){"use strict";e.exports=function(t){function e(){this._trace=new e.CapturedTrace(r())}function n(){return i?new e:void 0}function r(){var t=o.length-1;return t>=0?o[t]:void 0}var i=!1,o=[];return t.prototype._promiseCreated=function(){},t.prototype._pushContext=function(){},t.prototype._popContext=function(){return null},t._peekContext=t.prototype._peekContext=function(){},e.prototype._pushContext=function(){void 0!==this._trace&&(this._trace._promiseCreated=null,o.push(this._trace))},e.prototype._popContext=function(){if(void 0!==this._trace){var t=o.pop(),e=t._promiseCreated;return t._promiseCreated=null,e}return null},e.CapturedTrace=null,e.create=n,e.deactivateLongStackTraces=function(){},e.activateLongStackTraces=function(){var n=t.prototype._pushContext,o=t.prototype._popContext,s=t._peekContext,a=t.prototype._peekContext,c=t.prototype._promiseCreated;e.deactivateLongStackTraces=function(){t.prototype._pushContext=n,t.prototype._popContext=o,t._peekContext=s,t.prototype._peekContext=a,t.prototype._promiseCreated=c,i=!1},i=!0,t.prototype._pushContext=e.prototype._pushContext,t.prototype._popContext=e.prototype._popContext,t._peekContext=t.prototype._peekContext=r,t.prototype._promiseCreated=function(){var t=this._peekContext();t&&null==t._promiseCreated&&(t._promiseCreated=this)}},e}},{}],9:[function(t,e,n){"use strict";e.exports=function(e,n){function r(t,e){return{promise:e}}function i(){return!1}function o(t,e,n){var r=this;try{t(e,n,function(t){if("function"!=typeof t)throw new TypeError("onCancel must be a function, got: "+H.toString(t));r._attachCancellationCallback(t)})}catch(i){return i}}function s(t){if(!this.isCancellable())return this;var e=this._onCancel();void 0!==e?H.isArray(e)?e.push(t):this._setOnCancel([e,t]):this._setOnCancel(t)}function a(){return this._onCancelField}function c(t){this._onCancelField=t}function l(){this._cancellationParent=void 0,this._onCancelField=void 0}function u(t,e){if(0!==(1&e)){this._cancellationParent=t;var n=t._branchesRemainingToCancel;void 0===n&&(n=0),t._branchesRemainingToCancel=n+1}0!==(2&e)&&t._isBound()&&this._setBoundTo(t._boundTo)}function p(t,e){0!==(2&e)&&t._isBound()&&this._setBoundTo(t._boundTo)}function h(){var t=this._boundTo;return void 0!==t&&t instanceof e?t.isFulfilled()?t.value():void 0:t}function f(){this._trace=new S(this._peekContext())}function _(t,e){if(N(t)){var n=this._trace;if(void 0!==n&&e&&(n=n._parent),void 0!==n)n.attachExtraTrace(t);else if(!t.__stackCleaned__){var r=j(t);H.notEnumerableProp(t,"stack",r.message+"\n"+r.stack.join("\n")),H.notEnumerableProp(t,"__stackCleaned__",!0)}}}function d(t,e,n,r,i){if(void 0===t&&null!==e&&z){if(void 0!==i&&i._returnedNonUndefined())return;if(0===(65535&r._bitField))return;n&&(n+=" ");var o="a promise was created in a "+n+"handler but was not returned from it";r._warn(o,!0,e)}}function v(t,e){var n=t+" is deprecated and will be removed in a future version.";return e&&(n+=" Use "+e+" instead."),y(n)}function y(t,n,r){if(rt.warnings){var i,o=new L(t);if(n)r._attachExtraTrace(o);else if(rt.longStackTraces&&(i=e._peekContext()))i.attachExtraTrace(o);else{var s=j(o);o.stack=s.message+"\n"+s.stack.join("\n")}Y("warning",o)||k(o,"",!0)}}function m(t,e){for(var n=0;n<e.length-1;++n)e[n].push("From previous event:"),e[n]=e[n].join("\n");return n<e.length&&(e[n]=e[n].join("\n")),t+"\n"+e.join("\n")}function g(t){for(var e=0;e<t.length;++e)(0===t[e].length||e+1<t.length&&t[e][0]===t[e+1][0])&&(t.splice(e,1),e--)}function b(t){for(var e=t[0],n=1;n<t.length;++n){for(var r=t[n],i=e.length-1,o=e[i],s=-1,a=r.length-1;a>=0;--a)if(r[a]===o){s=a;break}for(var a=s;a>=0;--a){var c=r[a];if(e[i]!==c)break;e.pop(),i--}e=r}}function w(t){for(var e=[],n=0;n<t.length;++n){var r=t[n],i="    (No stack trace)"===r||B.test(r),o=i&&tt(r);i&&!o&&(q&&" "!==r.charAt(0)&&(r="    "+r),e.push(r))}return e}function C(t){for(var e=t.stack.replace(/\s+$/g,"").split("\n"),n=0;n<e.length;++n){var r=e[n];if("    (No stack trace)"===r||B.test(r))break}return n>0&&(e=e.slice(n)),e}function j(t){var e=t.stack,n=t.toString();return e="string"==typeof e&&e.length>0?C(t):["    (No stack trace)"],{message:n,stack:w(e)}}function k(t,e,n){if("undefined"!=typeof console){var r;if(H.isObject(t)){var i=t.stack;r=e+M(i,t)}else r=e+String(t);"function"==typeof D?D(r,n):("function"==typeof console.log||"object"==typeof console.log)&&console.log(r)}}function E(t,e,n,r){var i=!1;try{"function"==typeof e&&(i=!0,"rejectionHandled"===t?e(r):e(n,r))}catch(o){I.throwLater(o)}"unhandledRejection"===t?Y(t,n,r)||i||k(n,"Unhandled rejection "):Y(t,r)}function F(t){var e;if("function"==typeof t)e="[function "+(t.name||"anonymous")+"]";else{e=t&&"function"==typeof t.toString?t.toString():H.toString(t);var n=/\[object [a-zA-Z0-9$_]+\]/;if(n.test(e))try{var r=JSON.stringify(t);e=r}catch(i){}0===e.length&&(e="(empty array)")}return"(<"+x(e)+">, no stack trace)"}function x(t){var e=41;return t.length<e?t:t.substr(0,e-3)+"..."}function T(){return"function"==typeof nt}function P(t){var e=t.match(et);return e?{fileName:e[1],line:parseInt(e[2],10)}:void 0}function R(t,e){if(T()){for(var n,r,i=t.stack.split("\n"),o=e.stack.split("\n"),s=-1,a=-1,c=0;c<i.length;++c){var l=P(i[c]);if(l){n=l.fileName,s=l.line;break}}for(var c=0;c<o.length;++c){var l=P(o[c]);if(l){r=l.fileName,a=l.line;break}}0>s||0>a||!n||!r||n!==r||s>=a||(tt=function(t){if(U.test(t))return!0;var e=P(t);return e&&e.fileName===n&&s<=e.line&&e.line<=a?!0:!1})}}function S(t){this._parent=t,this._promisesCreated=0;var e=this._length=1+(void 0===t?0:t._length);nt(this,S),e>32&&this.uncycle()}var O,A,D,V=e._getDomain,I=e._async,L=t("./errors").Warning,H=t("./util"),N=H.canAttachTrace,U=/[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/,B=null,M=null,q=!1,Q=!(0==H.env("BLUEBIRD_DEBUG")||!H.env("BLUEBIRD_DEBUG")&&"development"!==H.env("NODE_ENV")),$=!(0==H.env("BLUEBIRD_WARNINGS")||!Q&&!H.env("BLUEBIRD_WARNINGS")),G=!(0==H.env("BLUEBIRD_LONG_STACK_TRACES")||!Q&&!H.env("BLUEBIRD_LONG_STACK_TRACES")),z=0!=H.env("BLUEBIRD_W_FORGOTTEN_RETURN")&&($||!!H.env("BLUEBIRD_W_FORGOTTEN_RETURN"));e.prototype.suppressUnhandledRejections=function(){var t=this._target();t._bitField=-1048577&t._bitField|524288},e.prototype._ensurePossibleRejectionHandled=function(){0===(524288&this._bitField)&&(this._setRejectionIsUnhandled(),I.invokeLater(this._notifyUnhandledRejection,this,void 0))},e.prototype._notifyUnhandledRejectionIsHandled=function(){E("rejectionHandled",O,void 0,this)},e.prototype._setReturnedNonUndefined=function(){this._bitField=268435456|this._bitField},e.prototype._returnedNonUndefined=function(){return 0!==(268435456&this._bitField)},e.prototype._notifyUnhandledRejection=function(){if(this._isRejectionUnhandled()){var t=this._settledValue();this._setUnhandledRejectionIsNotified(),E("unhandledRejection",A,t,this)}},e.prototype._setUnhandledRejectionIsNotified=function(){this._bitField=262144|this._bitField},e.prototype._unsetUnhandledRejectionIsNotified=function(){this._bitField=-262145&this._bitField},e.prototype._isUnhandledRejectionNotified=function(){return(262144&this._bitField)>0},e.prototype._setRejectionIsUnhandled=function(){this._bitField=1048576|this._bitField},e.prototype._unsetRejectionIsUnhandled=function(){this._bitField=-1048577&this._bitField,this._isUnhandledRejectionNotified()&&(this._unsetUnhandledRejectionIsNotified(),this._notifyUnhandledRejectionIsHandled())},e.prototype._isRejectionUnhandled=function(){return(1048576&this._bitField)>0},e.prototype._warn=function(t,e,n){return y(t,e,n||this)},e.onPossiblyUnhandledRejection=function(t){var e=V();A="function"==typeof t?null===e?t:e.bind(t):void 0},e.onUnhandledRejectionHandled=function(t){var e=V();O="function"==typeof t?null===e?t:e.bind(t):void 0};var X=function(){};e.longStackTraces=function(){if(I.haveItemsQueued()&&!rt.longStackTraces)throw new Error("cannot enable long stack traces after promises have been created\n\n    See http://goo.gl/MqrFmX\n");if(!rt.longStackTraces&&T()){var t=e.prototype._captureStackTrace,r=e.prototype._attachExtraTrace;rt.longStackTraces=!0,X=function(){if(I.haveItemsQueued()&&!rt.longStackTraces)throw new Error("cannot enable long stack traces after promises have been created\n\n    See http://goo.gl/MqrFmX\n");e.prototype._captureStackTrace=t,e.prototype._attachExtraTrace=r,n.deactivateLongStackTraces(),I.enableTrampoline(),rt.longStackTraces=!1},e.prototype._captureStackTrace=f,e.prototype._attachExtraTrace=_,n.activateLongStackTraces(),I.disableTrampolineIfNecessary()}},e.hasLongStackTraces=function(){return rt.longStackTraces&&T()};var W=function(){try{var t=document.createEvent("CustomEvent");return t.initCustomEvent("testingtheevent",!1,!0,{}),H.global.dispatchEvent(t),function(t,e){var n=document.createEvent("CustomEvent");return n.initCustomEvent(t.toLowerCase(),!1,!0,e),!H.global.dispatchEvent(n)}}catch(e){}return function(){return!1}}(),K=function(){return H.isNode?function(){return process.emit.apply(process,arguments)}:H.global?function(t){var e="on"+t.toLowerCase(),n=H.global[e];return n?(n.apply(H.global,[].slice.call(arguments,1)),!0):!1}:function(){return!1}}(),J={promiseCreated:r,promiseFulfilled:r,promiseRejected:r,promiseResolved:r,promiseCancelled:r,promiseChained:function(t,e,n){return{promise:e,child:n}},warning:function(t,e){return{warning:e}},unhandledRejection:function(t,e,n){return{reason:e,promise:n}},rejectionHandled:r},Y=function(t){var e=!1;try{e=K.apply(null,arguments)}catch(n){I.throwLater(n),e=!0}var r=!1;try{r=W(t,J[t].apply(null,arguments))}catch(n){I.throwLater(n),r=!0}return r||e};e.config=function(t){if(t=Object(t),"longStackTraces"in t&&(t.longStackTraces?e.longStackTraces():!t.longStackTraces&&e.hasLongStackTraces()&&X()),"warnings"in t){var n=t.warnings;rt.warnings=!!n,z=rt.warnings,H.isObject(n)&&"wForgottenReturn"in n&&(z=!!n.wForgottenReturn)}if("cancellation"in t&&t.cancellation&&!rt.cancellation){if(I.haveItemsQueued())throw new Error("cannot enable cancellation after promises are in use");e.prototype._clearCancellationData=l,e.prototype._propagateFrom=u,e.prototype._onCancel=a,e.prototype._setOnCancel=c,e.prototype._attachCancellationCallback=s,e.prototype._execute=o,Z=u,rt.cancellation=!0}"monitoring"in t&&(t.monitoring&&!rt.monitoring?(rt.monitoring=!0,e.prototype._fireEvent=Y):!t.monitoring&&rt.monitoring&&(rt.monitoring=!1,e.prototype._fireEvent=i))},e.prototype._fireEvent=i,e.prototype._execute=function(t,e,n){try{t(e,n)}catch(r){return r}},e.prototype._onCancel=function(){},e.prototype._setOnCancel=function(t){},e.prototype._attachCancellationCallback=function(t){},e.prototype._captureStackTrace=function(){},e.prototype._attachExtraTrace=function(){},e.prototype._clearCancellationData=function(){},e.prototype._propagateFrom=function(t,e){};var Z=p,tt=function(){return!1},et=/[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;H.inherits(S,Error),n.CapturedTrace=S,S.prototype.uncycle=function(){var t=this._length;if(!(2>t)){for(var e=[],n={},r=0,i=this;void 0!==i;++r)e.push(i),i=i._parent;t=this._length=r;for(var r=t-1;r>=0;--r){var o=e[r].stack;void 0===n[o]&&(n[o]=r)}for(var r=0;t>r;++r){var s=e[r].stack,a=n[s];if(void 0!==a&&a!==r){a>0&&(e[a-1]._parent=void 0,e[a-1]._length=1),e[r]._parent=void 0,e[r]._length=1;var c=r>0?e[r-1]:this;t-1>a?(c._parent=e[a+1],c._parent.uncycle(),c._length=c._parent._length+1):(c._parent=void 0,c._length=1);for(var l=c._length+1,u=r-2;u>=0;--u)e[u]._length=l,l++;return}}}},S.prototype.attachExtraTrace=function(t){if(!t.__stackCleaned__){this.uncycle();for(var e=j(t),n=e.message,r=[e.stack],i=this;void 0!==i;)r.push(w(i.stack.split("\n"))),i=i._parent;b(r),g(r),H.notEnumerableProp(t,"stack",m(n,r)),H.notEnumerableProp(t,"__stackCleaned__",!0)}};var nt=function(){var t=/^\s*at\s*/,e=function(t,e){return"string"==typeof t?t:void 0!==e.name&&void 0!==e.message?e.toString():F(e)};if("number"==typeof Error.stackTraceLimit&&"function"==typeof Error.captureStackTrace){Error.stackTraceLimit+=6,B=t,M=e;var n=Error.captureStackTrace;return tt=function(t){return U.test(t)},function(t,e){Error.stackTraceLimit+=6,n(t,e),Error.stackTraceLimit-=6}}var r=new Error;if("string"==typeof r.stack&&r.stack.split("\n")[0].indexOf("stackDetection@")>=0)return B=/@/,M=e,q=!0,function(t){t.stack=(new Error).stack};var i;try{throw new Error}catch(o){i="stack"in o}return"stack"in r||!i||"number"!=typeof Error.stackTraceLimit?(M=function(t,e){return"string"==typeof t?t:"object"!=typeof e&&"function"!=typeof e||void 0===e.name||void 0===e.message?F(e):e.toString()},null):(B=t,M=e,function(t){Error.stackTraceLimit+=6;try{throw new Error}catch(e){t.stack=e.stack}Error.stackTraceLimit-=6})}([]);"undefined"!=typeof console&&"undefined"!=typeof console.warn&&(D=function(t){console.warn(t)},H.isNode&&process.stderr.isTTY?D=function(t,e){var n=e?"[33m":"[31m";console.warn(n+t+"[0m\n")}:H.isNode||"string"!=typeof(new Error).stack||(D=function(t,e){console.warn("%c"+t,e?"color: darkorange":"color: red")}));var rt={warnings:$,longStackTraces:!1,cancellation:!1,monitoring:!1};return G&&e.longStackTraces(),{longStackTraces:function(){return rt.longStackTraces},warnings:function(){return rt.warnings},cancellation:function(){return rt.cancellation},monitoring:function(){return rt.monitoring},propagateFromFunction:function(){return Z},boundValueFunction:function(){return h},checkForgottenReturns:d,setBounds:R,warn:y,deprecated:v,CapturedTrace:S,fireDomEvent:W,fireGlobalEvent:K}}},{"./errors":12,"./util":36}],10:[function(t,e,n){"use strict";e.exports=function(t){function e(){return this.value}function n(){throw this.reason}t.prototype["return"]=t.prototype.thenReturn=function(n){return n instanceof t&&n.suppressUnhandledRejections(),this._then(e,void 0,void 0,{value:n},void 0)},t.prototype["throw"]=t.prototype.thenThrow=function(t){return this._then(n,void 0,void 0,{reason:t},void 0)},t.prototype.catchThrow=function(t){if(arguments.length<=1)return this._then(void 0,n,void 0,{reason:t},void 0);var e=arguments[1],r=function(){throw e};return this.caught(t,r)},t.prototype.catchReturn=function(n){if(arguments.length<=1)return n instanceof t&&n.suppressUnhandledRejections(),this._then(void 0,e,void 0,{value:n},void 0);var r=arguments[1];r instanceof t&&r.suppressUnhandledRejections();var i=function(){return r};return this.caught(n,i)}}},{}],11:[function(t,e,n){"use strict";e.exports=function(t,e){function n(){return o(this)}function r(t,n){return i(t,n,e,e)}var i=t.reduce,o=t.all;t.prototype.each=function(t){return this.mapSeries(t)._then(n,void 0,void 0,this,void 0)},t.prototype.mapSeries=function(t){return i(this,t,e,e)},t.each=function(t,e){return r(t,e)._then(n,void 0,void 0,t,void 0)},t.mapSeries=r}},{}],12:[function(t,e,n){"use strict";function r(t,e){function n(r){return this instanceof n?(p(this,"message","string"==typeof r?r:e),p(this,"name",t),void(Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):Error.call(this))):new n(r)}return u(n,Error),n}function i(t){return this instanceof i?(p(this,"name","OperationalError"),p(this,"message",t),this.cause=t,this.isOperational=!0,void(t instanceof Error?(p(this,"message",t.message),p(this,"stack",t.stack)):Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor))):new i(t)}var o,s,a=t("./es5"),c=a.freeze,l=t("./util"),u=l.inherits,p=l.notEnumerableProp,h=r("Warning","warning"),f=r("CancellationError","cancellation error"),_=r("TimeoutError","timeout error"),d=r("AggregateError","aggregate error");try{o=TypeError,s=RangeError}catch(v){o=r("TypeError","type error"),s=r("RangeError","range error")}for(var y="join pop push shift unshift slice filter forEach some every map indexOf lastIndexOf reduce reduceRight sort reverse".split(" "),m=0;m<y.length;++m)"function"==typeof Array.prototype[y[m]]&&(d.prototype[y[m]]=Array.prototype[y[m]]);a.defineProperty(d.prototype,"length",{value:0,configurable:!1,writable:!0,enumerable:!0}),d.prototype.isOperational=!0;var g=0;d.prototype.toString=function(){var t=Array(4*g+1).join(" "),e="\n"+t+"AggregateError of:\n";g++,t=Array(4*g+1).join(" ");for(var n=0;n<this.length;++n){for(var r=this[n]===this?"[Circular AggregateError]":this[n]+"",i=r.split("\n"),o=0;o<i.length;++o)i[o]=t+i[o];r=i.join("\n"),e+=r+"\n"}return g--,e},u(i,Error);var b=Error.__BluebirdErrorTypes__;b||(b=c({CancellationError:f,TimeoutError:_,OperationalError:i,RejectionError:i,AggregateError:d}),a.defineProperty(Error,"__BluebirdErrorTypes__",{value:b,writable:!1,enumerable:!1,configurable:!1})),e.exports={Error:Error,TypeError:o,RangeError:s,CancellationError:b.CancellationError,OperationalError:b.OperationalError,TimeoutError:b.TimeoutError,AggregateError:b.AggregateError,Warning:h}},{"./es5":13,"./util":36}],13:[function(t,e,n){var r=function(){"use strict";return void 0===this}();if(r)e.exports={freeze:Object.freeze,defineProperty:Object.defineProperty,getDescriptor:Object.getOwnPropertyDescriptor,keys:Object.keys,names:Object.getOwnPropertyNames,getPrototypeOf:Object.getPrototypeOf,isArray:Array.isArray,isES5:r,propertyIsWritable:function(t,e){var n=Object.getOwnPropertyDescriptor(t,e);return!(n&&!n.writable&&!n.set)}};else{var i={}.hasOwnProperty,o={}.toString,s={}.constructor.prototype,a=function(t){var e=[];for(var n in t)i.call(t,n)&&e.push(n);return e},c=function(t,e){return{value:t[e]}},l=function(t,e,n){return t[e]=n.value,t},u=function(t){return t},p=function(t){try{return Object(t).constructor.prototype}catch(e){return s}},h=function(t){try{return"[object Array]"===o.call(t)}catch(e){return!1}};e.exports={isArray:h,keys:a,names:a,defineProperty:l,getDescriptor:c,freeze:u,getPrototypeOf:p,isES5:r,propertyIsWritable:function(){return!0}}}},{}],14:[function(t,e,n){"use strict";e.exports=function(t,e){var n=t.map;t.prototype.filter=function(t,r){return n(this,t,r,e)},t.filter=function(t,r,i){return n(t,r,i,e)}}},{}],15:[function(t,e,n){"use strict";e.exports=function(e,n){function r(t,e,n){this.promise=t,this.type=e,this.handler=n,this.called=!1,this.cancelPromise=null}function i(t){this.finallyHandler=t}function o(t,e){return null!=t.cancelPromise?(arguments.length>1?t.cancelPromise._reject(e):t.cancelPromise._cancel(),t.cancelPromise=null,!0):!1}function s(){return c.call(this,this.promise._target()._settledValue())}function a(t){return o(this,t)?void 0:(p.e=t,p)}function c(t){var r=this.promise,c=this.handler;if(!this.called){this.called=!0;var l=this.isFinallyHandler()?c.call(r._boundValue()):c.call(r._boundValue(),t);if(void 0!==l){r._setReturnedNonUndefined();var h=n(l,r);if(h instanceof e){if(null!=this.cancelPromise){if(h.isCancelled()){var f=new u("late cancellation observer");return r._attachExtraTrace(f),p.e=f,p}h.isPending()&&h._attachCancellationCallback(new i(this))}return h._then(s,a,void 0,this,void 0)}}}return r.isRejected()?(o(this),p.e=t,p):(o(this),t)}var l=t("./util"),u=e.CancellationError,p=l.errorObj;return r.prototype.isFinallyHandler=function(){return 0===this.type},i.prototype._resultCancelled=function(){o(this.finallyHandler)},e.prototype._passThrough=function(t,e,n,i){return"function"!=typeof t?this.then():this._then(n,i,void 0,new r(this,e,t),void 0)},e.prototype.lastly=e.prototype["finally"]=function(t){return this._passThrough(t,0,c,c)},e.prototype.tap=function(t){return this._passThrough(t,1,c)},r}},{"./util":36}],16:[function(t,e,n){"use strict";e.exports=function(e,n,r,i,o,s){function a(t,n,r){for(var o=0;o<n.length;++o){r._pushContext();var s=f(n[o])(t);if(r._popContext(),s===h){r._pushContext();var a=e.reject(h.e);return r._popContext(),a}var c=i(s,r);if(c instanceof e)return c}return null}function c(t,n,i,o){if(s.cancellation()){var a=new e(r),c=this._finallyPromise=new e(r);this._promise=a.lastly(function(){return c}),a._captureStackTrace(),a._setOnCancel(this)}else{var l=this._promise=new e(r);l._captureStackTrace()}this._stack=o,this._generatorFunction=t,this._receiver=n,this._generator=void 0,this._yieldHandlers="function"==typeof i?[i].concat(_):_,this._yieldedPromise=null,this._cancellationPhase=!1}var l=t("./errors"),u=l.TypeError,p=t("./util"),h=p.errorObj,f=p.tryCatch,_=[];p.inherits(c,o),c.prototype._isResolved=function(){return null===this._promise},c.prototype._cleanup=function(){this._promise=this._generator=null,s.cancellation()&&null!==this._finallyPromise&&(this._finallyPromise._fulfill(),this._finallyPromise=null)},c.prototype._promiseCancelled=function(){if(!this._isResolved()){var t,n="undefined"!=typeof this._generator["return"];if(n)this._promise._pushContext(),t=f(this._generator["return"]).call(this._generator,void 0),this._promise._popContext();else{var r=new e.CancellationError("generator .return() sentinel");e.coroutine.returnSentinel=r,this._promise._attachExtraTrace(r),this._promise._pushContext(),t=f(this._generator["throw"]).call(this._generator,r),this._promise._popContext()}this._cancellationPhase=!0,this._yieldedPromise=null,this._continue(t)}},c.prototype._promiseFulfilled=function(t){this._yieldedPromise=null,this._promise._pushContext();var e=f(this._generator.next).call(this._generator,t);this._promise._popContext(),this._continue(e)},c.prototype._promiseRejected=function(t){this._yieldedPromise=null,this._promise._attachExtraTrace(t),this._promise._pushContext();var e=f(this._generator["throw"]).call(this._generator,t);this._promise._popContext(),this._continue(e)},c.prototype._resultCancelled=function(){if(this._yieldedPromise instanceof e){var t=this._yieldedPromise;this._yieldedPromise=null,t.cancel()}},c.prototype.promise=function(){return this._promise},c.prototype._run=function(){this._generator=this._generatorFunction.call(this._receiver),this._receiver=this._generatorFunction=void 0,this._promiseFulfilled(void 0)},c.prototype._continue=function(t){var n=this._promise;if(t===h)return this._cleanup(),this._cancellationPhase?n.cancel():n._rejectCallback(t.e,!1);var r=t.value;if(t.done===!0)return this._cleanup(),this._cancellationPhase?n.cancel():n._resolveCallback(r);var o=i(r,this._promise);if(!(o instanceof e)&&(o=a(o,this._yieldHandlers,this._promise),null===o))return void this._promiseRejected(new u("A value %s was yielded that could not be treated as a promise\n\n    See http://goo.gl/MqrFmX\n\n".replace("%s",r)+"From coroutine:\n"+this._stack.split("\n").slice(1,-7).join("\n")));o=o._target();var s=o._bitField;0===(50397184&s)?(this._yieldedPromise=o,o._proxy(this,null)):0!==(33554432&s)?this._promiseFulfilled(o._value()):0!==(16777216&s)?this._promiseRejected(o._reason()):this._promiseCancelled()},e.coroutine=function(t,e){if("function"!=typeof t)throw new u("generatorFunction must be a function\n\n    See http://goo.gl/MqrFmX\n");var n=Object(e).yieldHandler,r=c,i=(new Error).stack;return function(){var e=t.apply(this,arguments),o=new r(void 0,void 0,n,i),s=o.promise();return o._generator=e,o._promiseFulfilled(void 0),s}},e.coroutine.addYieldHandler=function(t){if("function"!=typeof t)throw new u("expecting a function but got "+p.classString(t));_.push(t)},e.spawn=function(t){if(s.deprecated("Promise.spawn()","Promise.coroutine()"),"function"!=typeof t)return n("generatorFunction must be a function\n\n    See http://goo.gl/MqrFmX\n");var r=new c(t,this),i=r.promise();return r._run(e.spawn),i}}},{"./errors":12,"./util":36}],17:[function(t,e,n){"use strict";e.exports=function(e,n,r,i){var o=t("./util");o.canEvaluate,o.tryCatch,o.errorObj;e.join=function(){var t,e=arguments.length-1;if(e>0&&"function"==typeof arguments[e]){t=arguments[e];var r}var i=[].slice.call(arguments);t&&i.pop();var r=new n(i).promise();return void 0!==t?r.spread(t):r}}},{"./util":36}],18:[function(t,e,n){"use strict";e.exports=function(e,n,r,i,o,s){function a(t,e,n,r){this.constructor$(t),this._promise._captureStackTrace();var i=l();this._callback=null===i?e:i.bind(e),
this._preservedValues=r===o?new Array(this.length()):null,this._limit=n,this._inFlight=0,this._queue=n>=1?[]:f,this._init$(void 0,-2)}function c(t,e,n,i){if("function"!=typeof e)return r("expecting a function but got "+u.classString(e));var o="object"==typeof n&&null!==n?n.concurrency:0;return o="number"==typeof o&&isFinite(o)&&o>=1?o:0,new a(t,e,o,i).promise()}var l=e._getDomain,u=t("./util"),p=u.tryCatch,h=u.errorObj,f=[];u.inherits(a,n),a.prototype._init=function(){},a.prototype._promiseFulfilled=function(t,n){var r=this._values,o=this.length(),a=this._preservedValues,c=this._limit;if(0>n){if(n=-1*n-1,r[n]=t,c>=1&&(this._inFlight--,this._drainQueue(),this._isResolved()))return!0}else{if(c>=1&&this._inFlight>=c)return r[n]=t,this._queue.push(n),!1;null!==a&&(a[n]=t);var l=this._promise,u=this._callback,f=l._boundValue();l._pushContext();var _=p(u).call(f,t,n,o),d=l._popContext();if(s.checkForgottenReturns(_,d,null!==a?"Promise.filter":"Promise.map",l),_===h)return this._reject(_.e),!0;var v=i(_,this._promise);if(v instanceof e){v=v._target();var y=v._bitField;if(0===(50397184&y))return c>=1&&this._inFlight++,r[n]=v,v._proxy(this,-1*(n+1)),!1;if(0===(33554432&y))return 0!==(16777216&y)?(this._reject(v._reason()),!0):(this._cancel(),!0);_=v._value()}r[n]=_}var m=++this._totalResolved;return m>=o?(null!==a?this._filter(r,a):this._resolve(r),!0):!1},a.prototype._drainQueue=function(){for(var t=this._queue,e=this._limit,n=this._values;t.length>0&&this._inFlight<e;){if(this._isResolved())return;var r=t.pop();this._promiseFulfilled(n[r],r)}},a.prototype._filter=function(t,e){for(var n=e.length,r=new Array(n),i=0,o=0;n>o;++o)t[o]&&(r[i++]=e[o]);r.length=i,this._resolve(r)},a.prototype.preservedValues=function(){return this._preservedValues},e.prototype.map=function(t,e){return c(this,t,e,null)},e.map=function(t,e,n,r){return c(t,e,n,r)}}},{"./util":36}],19:[function(t,e,n){"use strict";e.exports=function(e,n,r,i,o){var s=t("./util"),a=s.tryCatch;e.method=function(t){if("function"!=typeof t)throw new e.TypeError("expecting a function but got "+s.classString(t));return function(){var r=new e(n);r._captureStackTrace(),r._pushContext();var i=a(t).apply(this,arguments),s=r._popContext();return o.checkForgottenReturns(i,s,"Promise.method",r),r._resolveFromSyncValue(i),r}},e.attempt=e["try"]=function(t){if("function"!=typeof t)return i("expecting a function but got "+s.classString(t));var r=new e(n);r._captureStackTrace(),r._pushContext();var c;if(arguments.length>1){o.deprecated("calling Promise.try with more than 1 argument");var l=arguments[1],u=arguments[2];c=s.isArray(l)?a(t).apply(u,l):a(t).call(u,l)}else c=a(t)();var p=r._popContext();return o.checkForgottenReturns(c,p,"Promise.try",r),r._resolveFromSyncValue(c),r},e.prototype._resolveFromSyncValue=function(t){t===s.errorObj?this._rejectCallback(t.e,!1):this._resolveCallback(t,!0)}}},{"./util":36}],20:[function(t,e,n){"use strict";function r(t){return t instanceof Error&&u.getPrototypeOf(t)===Error.prototype}function i(t){var e;if(r(t)){e=new l(t),e.name=t.name,e.message=t.message,e.stack=t.stack;for(var n=u.keys(t),i=0;i<n.length;++i){var o=n[i];p.test(o)||(e[o]=t[o])}return e}return s.markAsOriginatingFromRejection(t),t}function o(t,e){return function(n,r){if(null!==t){if(n){var o=i(a(n));t._attachExtraTrace(o),t._reject(o)}else if(e){var s=[].slice.call(arguments,1);t._fulfill(s)}else t._fulfill(r);t=null}}}var s=t("./util"),a=s.maybeWrapAsError,c=t("./errors"),l=c.OperationalError,u=t("./es5"),p=/^(?:name|message|stack|cause)$/;e.exports=o},{"./errors":12,"./es5":13,"./util":36}],21:[function(t,e,n){"use strict";e.exports=function(e){function n(t,e){var n=this;if(!o.isArray(t))return r.call(n,t,e);var i=a(e).apply(n._boundValue(),[null].concat(t));i===c&&s.throwLater(i.e)}function r(t,e){var n=this,r=n._boundValue(),i=void 0===t?a(e).call(r,null):a(e).call(r,null,t);i===c&&s.throwLater(i.e)}function i(t,e){var n=this;if(!t){var r=new Error(t+"");r.cause=t,t=r}var i=a(e).call(n._boundValue(),t);i===c&&s.throwLater(i.e)}var o=t("./util"),s=e._async,a=o.tryCatch,c=o.errorObj;e.prototype.asCallback=e.prototype.nodeify=function(t,e){if("function"==typeof t){var o=r;void 0!==e&&Object(e).spread&&(o=n),this._then(o,i,void 0,this,t)}return this}}},{"./util":36}],22:[function(t,e,n){"use strict";e.exports=function(){function e(){}function n(t,e){if("function"!=typeof e)throw new y("expecting a function but got "+h.classString(e));if(t.constructor!==r)throw new y("the promise constructor cannot be invoked directly\n\n    See http://goo.gl/MqrFmX\n")}function r(t){this._bitField=0,this._fulfillmentHandler0=void 0,this._rejectionHandler0=void 0,this._promise0=void 0,this._receiver0=void 0,t!==g&&(n(this,t),this._resolveFromExecutor(t)),this._promiseCreated(),this._fireEvent("promiseCreated",this)}function i(t){this.promise._resolveCallback(t)}function o(t){this.promise._rejectCallback(t,!1)}function s(t){var e=new r(g);e._fulfillmentHandler0=t,e._rejectionHandler0=t,e._promise0=t,e._receiver0=t}var a,c=function(){return new y("circular promise resolution chain\n\n    See http://goo.gl/MqrFmX\n")},l=function(){return new r.PromiseInspection(this._target())},u=function(t){return r.reject(new y(t))},p={},h=t("./util");a=h.isNode?function(){var t=process.domain;return void 0===t&&(t=null),t}:function(){return null},h.notEnumerableProp(r,"_getDomain",a);var f=t("./es5"),_=t("./async"),d=new _;f.defineProperty(r,"_async",{value:d});var v=t("./errors"),y=r.TypeError=v.TypeError;r.RangeError=v.RangeError;var m=r.CancellationError=v.CancellationError;r.TimeoutError=v.TimeoutError,r.OperationalError=v.OperationalError,r.RejectionError=v.OperationalError,r.AggregateError=v.AggregateError;var g=function(){},b={},w={},C=t("./thenables")(r,g),j=t("./promise_array")(r,g,C,u,e),k=t("./context")(r),E=k.create,F=t("./debuggability")(r,k),x=(F.CapturedTrace,t("./finally")(r,C)),T=t("./catch_filter")(w),P=t("./nodeback"),R=h.errorObj,S=h.tryCatch;return r.prototype.toString=function(){return"[object Promise]"},r.prototype.caught=r.prototype["catch"]=function(t){var e=arguments.length;if(e>1){var n,r=new Array(e-1),i=0;for(n=0;e-1>n;++n){var o=arguments[n];if(!h.isObject(o))return u("expecting an object but got "+h.classString(o));r[i++]=o}return r.length=i,t=arguments[n],this.then(void 0,T(r,t,this))}return this.then(void 0,t)},r.prototype.reflect=function(){return this._then(l,l,void 0,this,void 0)},r.prototype.then=function(t,e){if(F.warnings()&&arguments.length>0&&"function"!=typeof t&&"function"!=typeof e){var n=".then() only accepts functions but was passed: "+h.classString(t);arguments.length>1&&(n+=", "+h.classString(e)),this._warn(n)}return this._then(t,e,void 0,void 0,void 0)},r.prototype.done=function(t,e){var n=this._then(t,e,void 0,void 0,void 0);n._setIsFinal()},r.prototype.spread=function(t){return"function"!=typeof t?u("expecting a function but got "+h.classString(t)):this.all()._then(t,void 0,void 0,b,void 0)},r.prototype.toJSON=function(){var t={isFulfilled:!1,isRejected:!1,fulfillmentValue:void 0,rejectionReason:void 0};return this.isFulfilled()?(t.fulfillmentValue=this.value(),t.isFulfilled=!0):this.isRejected()&&(t.rejectionReason=this.reason(),t.isRejected=!0),t},r.prototype.all=function(){return arguments.length>0&&this._warn(".all() was passed arguments but it does not take any"),new j(this).promise()},r.prototype.error=function(t){return this.caught(h.originatesFromRejection,t)},r.is=function(t){return t instanceof r},r.fromNode=r.fromCallback=function(t){var e=new r(g);e._captureStackTrace();var n=arguments.length>1?!!Object(arguments[1]).multiArgs:!1,i=S(t)(P(e,n));return i===R&&e._rejectCallback(i.e,!0),e._isFateSealed()||e._setAsyncGuaranteed(),e},r.all=function(t){return new j(t).promise()},r.cast=function(t){var e=C(t);return e instanceof r||(e=new r(g),e._captureStackTrace(),e._setFulfilled(),e._rejectionHandler0=t),e},r.resolve=r.fulfilled=r.cast,r.reject=r.rejected=function(t){var e=new r(g);return e._captureStackTrace(),e._rejectCallback(t,!0),e},r.setScheduler=function(t){if("function"!=typeof t)throw new y("expecting a function but got "+h.classString(t));return d.setScheduler(t)},r.prototype._then=function(t,e,n,i,o){var s=void 0!==o,c=s?o:new r(g),l=this._target(),u=l._bitField;s||(c._propagateFrom(this,3),c._captureStackTrace(),void 0===i&&0!==(2097152&this._bitField)&&(i=0!==(50397184&u)?this._boundValue():l===this?void 0:this._boundTo),this._fireEvent("promiseChained",this,c));var p=a();if(0!==(50397184&u)){var h,f,_=l._settlePromiseCtx;0!==(33554432&u)?(f=l._rejectionHandler0,h=t):0!==(16777216&u)?(f=l._fulfillmentHandler0,h=e,l._unsetRejectionIsUnhandled()):(_=l._settlePromiseLateCancellationObserver,f=new m("late cancellation observer"),l._attachExtraTrace(f),h=e),d.invoke(_,l,{handler:null===p?h:"function"==typeof h&&p.bind(h),promise:c,receiver:i,value:f})}else l._addCallbacks(t,e,c,i,p);return c},r.prototype._length=function(){return 65535&this._bitField},r.prototype._isFateSealed=function(){return 0!==(117506048&this._bitField)},r.prototype._isFollowing=function(){return 67108864===(67108864&this._bitField)},r.prototype._setLength=function(t){this._bitField=-65536&this._bitField|65535&t},r.prototype._setFulfilled=function(){this._bitField=33554432|this._bitField,this._fireEvent("promiseFulfilled",this)},r.prototype._setRejected=function(){this._bitField=16777216|this._bitField,this._fireEvent("promiseRejected",this)},r.prototype._setFollowing=function(){this._bitField=67108864|this._bitField,this._fireEvent("promiseResolved",this)},r.prototype._setIsFinal=function(){this._bitField=4194304|this._bitField},r.prototype._isFinal=function(){return(4194304&this._bitField)>0},r.prototype._unsetCancelled=function(){this._bitField=-65537&this._bitField},r.prototype._setCancelled=function(){this._bitField=65536|this._bitField,this._fireEvent("promiseCancelled",this)},r.prototype._setAsyncGuaranteed=function(){d.hasCustomScheduler()||(this._bitField=134217728|this._bitField)},r.prototype._receiverAt=function(t){var e=0===t?this._receiver0:this[4*t-4+3];return e===p?void 0:void 0===e&&this._isBound()?this._boundValue():e},r.prototype._promiseAt=function(t){return this[4*t-4+2]},r.prototype._fulfillmentHandlerAt=function(t){return this[4*t-4+0]},r.prototype._rejectionHandlerAt=function(t){return this[4*t-4+1]},r.prototype._boundValue=function(){},r.prototype._migrateCallback0=function(t){var e=(t._bitField,t._fulfillmentHandler0),n=t._rejectionHandler0,r=t._promise0,i=t._receiverAt(0);void 0===i&&(i=p),this._addCallbacks(e,n,r,i,null)},r.prototype._migrateCallbackAt=function(t,e){var n=t._fulfillmentHandlerAt(e),r=t._rejectionHandlerAt(e),i=t._promiseAt(e),o=t._receiverAt(e);void 0===o&&(o=p),this._addCallbacks(n,r,i,o,null)},r.prototype._addCallbacks=function(t,e,n,r,i){var o=this._length();if(o>=65531&&(o=0,this._setLength(0)),0===o)this._promise0=n,this._receiver0=r,"function"==typeof t&&(this._fulfillmentHandler0=null===i?t:i.bind(t)),"function"==typeof e&&(this._rejectionHandler0=null===i?e:i.bind(e));else{var s=4*o-4;this[s+2]=n,this[s+3]=r,"function"==typeof t&&(this[s+0]=null===i?t:i.bind(t)),"function"==typeof e&&(this[s+1]=null===i?e:i.bind(e))}return this._setLength(o+1),o},r.prototype._proxy=function(t,e){this._addCallbacks(void 0,void 0,e,t,null)},r.prototype._resolveCallback=function(t,e){if(0===(117506048&this._bitField)){if(t===this)return this._rejectCallback(c(),!1);var n=C(t,this);if(!(n instanceof r))return this._fulfill(t);e&&this._propagateFrom(n,2);var i=n._target();if(i===this)return void this._reject(c());var o=i._bitField;if(0===(50397184&o)){var s=this._length();s>0&&i._migrateCallback0(this);for(var a=1;s>a;++a)i._migrateCallbackAt(this,a);this._setFollowing(),this._setLength(0),this._setFollowee(i)}else if(0!==(33554432&o))this._fulfill(i._value());else if(0!==(16777216&o))this._reject(i._reason());else{var l=new m("late cancellation observer");i._attachExtraTrace(l),this._reject(l)}}},r.prototype._rejectCallback=function(t,e,n){var r=h.ensureErrorObject(t),i=r===t;if(!i&&!n&&F.warnings()){var o="a promise was rejected with a non-error: "+h.classString(t);this._warn(o,!0)}this._attachExtraTrace(r,e?i:!1),this._reject(t)},r.prototype._resolveFromExecutor=function(t){var e=this;this._captureStackTrace(),this._pushContext();var n=!0,r=this._execute(t,function(t){e._resolveCallback(t)},function(t){e._rejectCallback(t,n)});n=!1,this._popContext(),void 0!==r&&e._rejectCallback(r,!0)},r.prototype._settlePromiseFromHandler=function(t,e,n,r){var i=r._bitField;if(0===(65536&i)){r._pushContext();var o;e===b?n&&"number"==typeof n.length?o=S(t).apply(this._boundValue(),n):(o=R,o.e=new y("cannot .spread() a non-array: "+h.classString(n))):o=S(t).call(e,n);var s=r._popContext();i=r._bitField,0===(65536&i)&&(o===w?r._reject(n):o===R?r._rejectCallback(o.e,!1):(F.checkForgottenReturns(o,s,"",r,this),r._resolveCallback(o)))}},r.prototype._target=function(){for(var t=this;t._isFollowing();)t=t._followee();return t},r.prototype._followee=function(){return this._rejectionHandler0},r.prototype._setFollowee=function(t){this._rejectionHandler0=t},r.prototype._settlePromise=function(t,n,i,o){var s=t instanceof r,a=this._bitField,c=0!==(134217728&a);0!==(65536&a)?(s&&t._invokeInternalOnCancel(),i instanceof x&&i.isFinallyHandler()?(i.cancelPromise=t,S(n).call(i,o)===R&&t._reject(R.e)):n===l?t._fulfill(l.call(i)):i instanceof e?i._promiseCancelled(t):s||t instanceof j?t._cancel():i.cancel()):"function"==typeof n?s?(c&&t._setAsyncGuaranteed(),this._settlePromiseFromHandler(n,i,o,t)):n.call(i,o,t):i instanceof e?i._isResolved()||(0!==(33554432&a)?i._promiseFulfilled(o,t):i._promiseRejected(o,t)):s&&(c&&t._setAsyncGuaranteed(),0!==(33554432&a)?t._fulfill(o):t._reject(o))},r.prototype._settlePromiseLateCancellationObserver=function(t){var e=t.handler,n=t.promise,i=t.receiver,o=t.value;"function"==typeof e?n instanceof r?this._settlePromiseFromHandler(e,i,o,n):e.call(i,o,n):n instanceof r&&n._reject(o)},r.prototype._settlePromiseCtx=function(t){this._settlePromise(t.promise,t.handler,t.receiver,t.value)},r.prototype._settlePromise0=function(t,e,n){var r=this._promise0,i=this._receiverAt(0);this._promise0=void 0,this._receiver0=void 0,this._settlePromise(r,t,i,e)},r.prototype._clearCallbackDataAtIndex=function(t){var e=4*t-4;this[e+2]=this[e+3]=this[e+0]=this[e+1]=void 0},r.prototype._fulfill=function(t){var e=this._bitField;if(!((117506048&e)>>>16)){if(t===this){var n=c();return this._attachExtraTrace(n),this._reject(n)}this._setFulfilled(),this._rejectionHandler0=t,(65535&e)>0&&(0!==(134217728&e)?this._settlePromises():d.settlePromises(this))}},r.prototype._reject=function(t){var e=this._bitField;if(!((117506048&e)>>>16))return this._setRejected(),this._fulfillmentHandler0=t,this._isFinal()?d.fatalError(t,h.isNode):void((65535&e)>0?d.settlePromises(this):this._ensurePossibleRejectionHandled())},r.prototype._fulfillPromises=function(t,e){for(var n=1;t>n;n++){var r=this._fulfillmentHandlerAt(n),i=this._promiseAt(n),o=this._receiverAt(n);this._clearCallbackDataAtIndex(n),this._settlePromise(i,r,o,e)}},r.prototype._rejectPromises=function(t,e){for(var n=1;t>n;n++){var r=this._rejectionHandlerAt(n),i=this._promiseAt(n),o=this._receiverAt(n);this._clearCallbackDataAtIndex(n),this._settlePromise(i,r,o,e)}},r.prototype._settlePromises=function(){var t=this._bitField,e=65535&t;if(e>0){if(0!==(16842752&t)){var n=this._fulfillmentHandler0;this._settlePromise0(this._rejectionHandler0,n,t),this._rejectPromises(e,n)}else{var r=this._rejectionHandler0;this._settlePromise0(this._fulfillmentHandler0,r,t),this._fulfillPromises(e,r)}this._setLength(0)}this._clearCancellationData()},r.prototype._settledValue=function(){var t=this._bitField;return 0!==(33554432&t)?this._rejectionHandler0:0!==(16777216&t)?this._fulfillmentHandler0:void 0},r.defer=r.pending=function(){F.deprecated("Promise.defer","new Promise");var t=new r(g);return{promise:t,resolve:i,reject:o}},h.notEnumerableProp(r,"_makeSelfResolutionError",c),t("./method")(r,g,C,u,F),t("./bind")(r,g,C,F),t("./cancel")(r,j,u,F),t("./direct_resolve")(r),t("./synchronous_inspection")(r),t("./join")(r,j,C,g,F),r.Promise=r,t("./map.js")(r,j,u,C,g,F),t("./call_get.js")(r),t("./using.js")(r,u,C,E,g,F),t("./timers.js")(r,g,F),t("./generators.js")(r,u,g,C,e,F),t("./nodeify.js")(r),t("./promisify.js")(r,g),t("./props.js")(r,j,C,u),t("./race.js")(r,g,C,u),t("./reduce.js")(r,j,u,C,g,F),t("./settle.js")(r,j,F),t("./some.js")(r,j,u),t("./filter.js")(r,g),t("./each.js")(r,g),t("./any.js")(r),h.toFastProperties(r),h.toFastProperties(r.prototype),s({a:1}),s({b:2}),s({c:3}),s(1),s(function(){}),s(void 0),s(!1),s(new r(g)),F.setBounds(_.firstLineError,h.lastLineError),r}},{"./any.js":1,"./async":2,"./bind":3,"./call_get.js":5,"./cancel":6,"./catch_filter":7,"./context":8,"./debuggability":9,"./direct_resolve":10,"./each.js":11,"./errors":12,"./es5":13,"./filter.js":14,"./finally":15,"./generators.js":16,"./join":17,"./map.js":18,"./method":19,"./nodeback":20,"./nodeify.js":21,"./promise_array":23,"./promisify.js":24,"./props.js":25,"./race.js":27,"./reduce.js":28,"./settle.js":30,"./some.js":31,"./synchronous_inspection":32,"./thenables":33,"./timers.js":34,"./using.js":35,"./util":36}],23:[function(t,e,n){"use strict";e.exports=function(e,n,r,i,o){function s(t){switch(t){case-2:return[];case-3:return{}}}function a(t){var r=this._promise=new e(n);t instanceof e&&r._propagateFrom(t,3),r._setOnCancel(this),this._values=t,this._length=0,this._totalResolved=0,this._init(void 0,-2)}var c=t("./util");c.isArray;return c.inherits(a,o),a.prototype.length=function(){return this._length},a.prototype.promise=function(){return this._promise},a.prototype._init=function l(t,n){var o=r(this._values,this._promise);if(o instanceof e){o=o._target();var a=o._bitField;if(this._values=o,0===(50397184&a))return this._promise._setAsyncGuaranteed(),o._then(l,this._reject,void 0,this,n);if(0===(33554432&a))return 0!==(16777216&a)?this._reject(o._reason()):this._cancel();o=o._value()}if(o=c.asArray(o),null===o){var u=i("expecting an array or an iterable object but got "+c.classString(o)).reason();return void this._promise._rejectCallback(u,!1)}return 0===o.length?void(-5===n?this._resolveEmptyArray():this._resolve(s(n))):void this._iterate(o)},a.prototype._iterate=function(t){var n=this.getActualLength(t.length);this._length=n,this._values=this.shouldCopyValues()?new Array(n):this._values;for(var i=this._promise,o=!1,s=null,a=0;n>a;++a){var c=r(t[a],i);c instanceof e?(c=c._target(),s=c._bitField):s=null,o?null!==s&&c.suppressUnhandledRejections():null!==s?0===(50397184&s)?(c._proxy(this,a),this._values[a]=c):o=0!==(33554432&s)?this._promiseFulfilled(c._value(),a):0!==(16777216&s)?this._promiseRejected(c._reason(),a):this._promiseCancelled(a):o=this._promiseFulfilled(c,a)}o||i._setAsyncGuaranteed()},a.prototype._isResolved=function(){return null===this._values},a.prototype._resolve=function(t){this._values=null,this._promise._fulfill(t)},a.prototype._cancel=function(){!this._isResolved()&&this._promise.isCancellable()&&(this._values=null,this._promise._cancel())},a.prototype._reject=function(t){this._values=null,this._promise._rejectCallback(t,!1)},a.prototype._promiseFulfilled=function(t,e){this._values[e]=t;var n=++this._totalResolved;return n>=this._length?(this._resolve(this._values),!0):!1},a.prototype._promiseCancelled=function(){return this._cancel(),!0},a.prototype._promiseRejected=function(t){return this._totalResolved++,this._reject(t),!0},a.prototype._resultCancelled=function(){if(!this._isResolved()){var t=this._values;if(this._cancel(),t instanceof e)t.cancel();else for(var n=0;n<t.length;++n)t[n]instanceof e&&t[n].cancel()}},a.prototype.shouldCopyValues=function(){return!0},a.prototype.getActualLength=function(t){return t},a}},{"./util":36}],24:[function(t,e,n){"use strict";e.exports=function(e,n){function r(t){return!C.test(t)}function i(t){try{return t.__isPromisified__===!0}catch(e){return!1}}function o(t,e,n){var r=f.getDataPropertyOrDefault(t,e+n,b);return r?i(r):!1}function s(t,e,n){for(var r=0;r<t.length;r+=2){var i=t[r];if(n.test(i))for(var o=i.replace(n,""),s=0;s<t.length;s+=2)if(t[s]===o)throw new m("Cannot promisify an API that has normal methods with '%s'-suffix\n\n    See http://goo.gl/MqrFmX\n".replace("%s",e))}}function a(t,e,n,r){for(var a=f.inheritedDataKeys(t),c=[],l=0;l<a.length;++l){var u=a[l],p=t[u],h=r===j?!0:j(u,p,t);"function"!=typeof p||i(p)||o(t,u,e)||!r(u,p,t,h)||c.push(u,p)}return s(c,e,n),c}function c(t,r,i,o,s,a){function c(){var i=r;r===h&&(i=this);var o=new e(n);o._captureStackTrace();var s="string"==typeof u&&this!==l?this[u]:t,c=_(o,a);try{s.apply(i,d(arguments,c))}catch(p){o._rejectCallback(v(p),!0,!0)}return o._isFateSealed()||o._setAsyncGuaranteed(),o}var l=function(){return this}(),u=t;return"string"==typeof u&&(t=o),f.notEnumerableProp(c,"__isPromisified__",!0),c}function l(t,e,n,r,i){for(var o=new RegExp(k(e)+"$"),s=a(t,e,o,n),c=0,l=s.length;l>c;c+=2){var u=s[c],p=s[c+1],_=u+e;if(r===E)t[_]=E(u,h,u,p,e,i);else{var d=r(p,function(){return E(u,h,u,p,e,i)});f.notEnumerableProp(d,"__isPromisified__",!0),t[_]=d}}return f.toFastProperties(t),t}function u(t,e,n){return E(t,e,void 0,t,null,n)}var p,h={},f=t("./util"),_=t("./nodeback"),d=f.withAppended,v=f.maybeWrapAsError,y=f.canEvaluate,m=t("./errors").TypeError,g="Async",b={__isPromisified__:!0},w=["arity","length","name","arguments","caller","callee","prototype","__isPromisified__"],C=new RegExp("^(?:"+w.join("|")+")$"),j=function(t){return f.isIdentifier(t)&&"_"!==t.charAt(0)&&"constructor"!==t},k=function(t){return t.replace(/([$])/,"\\$")},E=y?p:c;e.promisify=function(t,e){if("function"!=typeof t)throw new m("expecting a function but got "+f.classString(t));if(i(t))return t;e=Object(e);var n=void 0===e.context?h:e.context,o=!!e.multiArgs,s=u(t,n,o);return f.copyDescriptors(t,s,r),s},e.promisifyAll=function(t,e){if("function"!=typeof t&&"object"!=typeof t)throw new m("the target of promisifyAll must be an object or a function\n\n    See http://goo.gl/MqrFmX\n");e=Object(e);var n=!!e.multiArgs,r=e.suffix;"string"!=typeof r&&(r=g);var i=e.filter;"function"!=typeof i&&(i=j);var o=e.promisifier;if("function"!=typeof o&&(o=E),!f.isIdentifier(r))throw new RangeError("suffix must be a valid identifier\n\n    See http://goo.gl/MqrFmX\n");for(var s=f.inheritedDataKeys(t),a=0;a<s.length;++a){var c=t[s[a]];"constructor"!==s[a]&&f.isClass(c)&&(l(c.prototype,r,i,o,n),l(c,r,i,o,n))}return l(t,r,i,o,n)}}},{"./errors":12,"./nodeback":20,"./util":36}],25:[function(t,e,n){"use strict";e.exports=function(e,n,r,i){function o(t){var e,n=!1;if(void 0!==a&&t instanceof a)e=p(t),n=!0;else{var r=u.keys(t),i=r.length;e=new Array(2*i);for(var o=0;i>o;++o){var s=r[o];e[o]=t[s],e[o+i]=s}}this.constructor$(e),this._isMap=n,this._init$(void 0,-3)}function s(t){var n,s=r(t);return l(s)?(n=s instanceof e?s._then(e.props,void 0,void 0,void 0,void 0):new o(s).promise(),s instanceof e&&n._propagateFrom(s,2),n):i("cannot await properties of a non-object\n\n    See http://goo.gl/MqrFmX\n")}var a,c=t("./util"),l=c.isObject,u=t("./es5");"function"==typeof Map&&(a=Map);var p=function(){function t(t,r){this[e]=t,this[e+n]=r,e++}var e=0,n=0;return function(r){n=r.size,e=0;var i=new Array(2*r.size);return r.forEach(t,i),i}}(),h=function(t){for(var e=new a,n=t.length/2|0,r=0;n>r;++r){var i=t[n+r],o=t[r];e.set(i,o)}return e};c.inherits(o,n),o.prototype._init=function(){},o.prototype._promiseFulfilled=function(t,e){this._values[e]=t;var n=++this._totalResolved;if(n>=this._length){var r;if(this._isMap)r=h(this._values);else{r={};for(var i=this.length(),o=0,s=this.length();s>o;++o)r[this._values[o+i]]=this._values[o]}return this._resolve(r),!0}return!1},o.prototype.shouldCopyValues=function(){return!1},o.prototype.getActualLength=function(t){return t>>1},e.prototype.props=function(){return s(this)},e.props=function(t){return s(t)}}},{"./es5":13,"./util":36}],26:[function(t,e,n){"use strict";function r(t,e,n,r,i){for(var o=0;i>o;++o)n[o+r]=t[o+e],t[o+e]=void 0}function i(t){this._capacity=t,this._length=0,this._front=0}i.prototype._willBeOverCapacity=function(t){return this._capacity<t},i.prototype._pushOne=function(t){var e=this.length();this._checkCapacity(e+1);var n=this._front+e&this._capacity-1;this[n]=t,this._length=e+1},i.prototype._unshiftOne=function(t){var e=this._capacity;this._checkCapacity(this.length()+1);var n=this._front,r=(n-1&e-1^e)-e;this[r]=t,this._front=r,this._length=this.length()+1},i.prototype.unshift=function(t,e,n){this._unshiftOne(n),this._unshiftOne(e),this._unshiftOne(t)},i.prototype.push=function(t,e,n){var r=this.length()+3;if(this._willBeOverCapacity(r))return this._pushOne(t),this._pushOne(e),void this._pushOne(n);var i=this._front+r-3;this._checkCapacity(r);var o=this._capacity-1;this[i+0&o]=t,this[i+1&o]=e,this[i+2&o]=n,this._length=r},i.prototype.shift=function(){var t=this._front,e=this[t];return this[t]=void 0,this._front=t+1&this._capacity-1,this._length--,e},i.prototype.length=function(){return this._length},i.prototype._checkCapacity=function(t){this._capacity<t&&this._resizeTo(this._capacity<<1)},i.prototype._resizeTo=function(t){var e=this._capacity;this._capacity=t;var n=this._front,i=this._length,o=n+i&e-1;r(this,0,this,e,o)},e.exports=i},{}],27:[function(t,e,n){"use strict";e.exports=function(e,n,r,i){function o(t,o){var c=r(t);if(c instanceof e)return a(c);if(t=s.asArray(t),null===t)return i("expecting an array or an iterable object but got "+s.classString(t));var l=new e(n);void 0!==o&&l._propagateFrom(o,3);for(var u=l._fulfill,p=l._reject,h=0,f=t.length;f>h;++h){var _=t[h];(void 0!==_||h in t)&&e.cast(_)._then(u,p,void 0,l,null)}return l}var s=t("./util"),a=function(t){return t.then(function(e){return o(e,t)})};e.race=function(t){return o(t,void 0)},e.prototype.race=function(){return o(this,void 0)}}},{"./util":36}],28:[function(t,e,n){"use strict";e.exports=function(e,n,r,i,o,s){function a(t,n,r,i){this.constructor$(t);var s=h();this._fn=null===s?n:s.bind(n),void 0!==r&&(r=e.resolve(r),r._attachCancellationCallback(this)),this._initialValue=r,this._currentCancellable=null,this._eachValues=i===o?[]:void 0,this._promise._captureStackTrace(),this._init$(void 0,-5)}function c(t,e){this.isFulfilled()?e._resolve(t):e._reject(t)}function l(t,e,n,i){if("function"!=typeof e)return r("expecting a function but got "+f.classString(e));var o=new a(t,e,n,i);return o.promise()}function u(t){this.accum=t,this.array._gotAccum(t);var n=i(this.value,this.array._promise);return n instanceof e?(this.array._currentCancellable=n,n._then(p,void 0,void 0,this,void 0)):p.call(this,n)}function p(t){var n=this.array,r=n._promise,i=_(n._fn);r._pushContext();var o;o=void 0!==n._eachValues?i.call(r._boundValue(),t,this.index,this.length):i.call(r._boundValue(),this.accum,t,this.index,this.length),o instanceof e&&(n._currentCancellable=o);var a=r._popContext();return s.checkForgottenReturns(o,a,void 0!==n._eachValues?"Promise.each":"Promise.reduce",r),o}var h=e._getDomain,f=t("./util"),_=f.tryCatch;f.inherits(a,n),a.prototype._gotAccum=function(t){void 0!==this._eachValues&&t!==o&&this._eachValues.push(t)},a.prototype._eachComplete=function(t){return this._eachValues.push(t),this._eachValues},a.prototype._init=function(){},a.prototype._resolveEmptyArray=function(){this._resolve(void 0!==this._eachValues?this._eachValues:this._initialValue)},a.prototype.shouldCopyValues=function(){return!1},a.prototype._resolve=function(t){this._promise._resolveCallback(t),this._values=null},a.prototype._resultCancelled=function(t){return t===this._initialValue?this._cancel():void(this._isResolved()||(this._resultCancelled$(),this._currentCancellable instanceof e&&this._currentCancellable.cancel(),this._initialValue instanceof e&&this._initialValue.cancel()))},a.prototype._iterate=function(t){this._values=t;var n,r,i=t.length;if(void 0!==this._initialValue?(n=this._initialValue,r=0):(n=e.resolve(t[0]),r=1),this._currentCancellable=n,!n.isRejected())for(;i>r;++r){var o={accum:null,value:t[r],index:r,length:i,array:this};n=n._then(u,void 0,void 0,o,void 0)}void 0!==this._eachValues&&(n=n._then(this._eachComplete,void 0,void 0,this,void 0)),n._then(c,c,void 0,n,this)},e.prototype.reduce=function(t,e){return l(this,t,e,null)},e.reduce=function(t,e,n,r){return l(t,e,n,r)}}},{"./util":36}],29:[function(t,e,n){"use strict";var r,i=t("./util"),o=function(){throw new Error("No async scheduler available\n\n    See http://goo.gl/MqrFmX\n")},s=i.getNativePromise();if(i.isNode&&"undefined"==typeof MutationObserver){var a=global.setImmediate,c=process.nextTick;r=i.isRecentNode?function(t){a.call(global,t)}:function(t){c.call(process,t)}}else if("function"==typeof s){var l=s.resolve();r=function(t){l.then(t)}}else r="undefined"==typeof MutationObserver||"undefined"!=typeof window&&window.navigator&&window.navigator.standalone?"undefined"!=typeof setImmediate?function(t){setImmediate(t)}:"undefined"!=typeof setTimeout?function(t){setTimeout(t,0)}:o:function(){var t=document.createElement("div"),e={attributes:!0},n=!1,r=document.createElement("div"),i=new MutationObserver(function(){t.classList.toggle("foo"),n=!1});i.observe(r,e);var o=function(){n||(n=!0,r.classList.toggle("foo"))};return function(n){var r=new MutationObserver(function(){r.disconnect(),n()});r.observe(t,e),o()}}();e.exports=r},{"./util":36}],30:[function(t,e,n){"use strict";e.exports=function(e,n,r){function i(t){this.constructor$(t)}var o=e.PromiseInspection,s=t("./util");s.inherits(i,n),i.prototype._promiseResolved=function(t,e){this._values[t]=e;var n=++this._totalResolved;return n>=this._length?(this._resolve(this._values),!0):!1},i.prototype._promiseFulfilled=function(t,e){var n=new o;return n._bitField=33554432,n._settledValueField=t,this._promiseResolved(e,n)},i.prototype._promiseRejected=function(t,e){var n=new o;return n._bitField=16777216,n._settledValueField=t,this._promiseResolved(e,n)},e.settle=function(t){return r.deprecated(".settle()",".reflect()"),new i(t).promise()},e.prototype.settle=function(){return e.settle(this)}}},{"./util":36}],31:[function(t,e,n){"use strict";e.exports=function(e,n,r){function i(t){this.constructor$(t),this._howMany=0,this._unwrap=!1,this._initialized=!1}function o(t,e){if((0|e)!==e||0>e)return r("expecting a positive integer\n\n    See http://goo.gl/MqrFmX\n");var n=new i(t),o=n.promise();return n.setHowMany(e),n.init(),o}var s=t("./util"),a=t("./errors").RangeError,c=t("./errors").AggregateError,l=s.isArray,u={};s.inherits(i,n),i.prototype._init=function(){if(this._initialized){if(0===this._howMany)return void this._resolve([]);this._init$(void 0,-5);var t=l(this._values);!this._isResolved()&&t&&this._howMany>this._canPossiblyFulfill()&&this._reject(this._getRangeError(this.length()))}},i.prototype.init=function(){this._initialized=!0,this._init()},i.prototype.setUnwrap=function(){this._unwrap=!0},i.prototype.howMany=function(){return this._howMany},i.prototype.setHowMany=function(t){this._howMany=t},i.prototype._promiseFulfilled=function(t){return this._addFulfilled(t),this._fulfilled()===this.howMany()?(this._values.length=this.howMany(),1===this.howMany()&&this._unwrap?this._resolve(this._values[0]):this._resolve(this._values),!0):!1},i.prototype._promiseRejected=function(t){return this._addRejected(t),this._checkOutcome()},i.prototype._promiseCancelled=function(){return this._values instanceof e||null==this._values?this._cancel():(this._addRejected(u),this._checkOutcome())},i.prototype._checkOutcome=function(){if(this.howMany()>this._canPossiblyFulfill()){for(var t=new c,e=this.length();e<this._values.length;++e)this._values[e]!==u&&t.push(this._values[e]);return t.length>0?this._reject(t):this._cancel(),!0}return!1},i.prototype._fulfilled=function(){return this._totalResolved},i.prototype._rejected=function(){return this._values.length-this.length()},i.prototype._addRejected=function(t){this._values.push(t);
},i.prototype._addFulfilled=function(t){this._values[this._totalResolved++]=t},i.prototype._canPossiblyFulfill=function(){return this.length()-this._rejected()},i.prototype._getRangeError=function(t){var e="Input array must contain at least "+this._howMany+" items but contains only "+t+" items";return new a(e)},i.prototype._resolveEmptyArray=function(){this._reject(this._getRangeError(0))},e.some=function(t,e){return o(t,e)},e.prototype.some=function(t){return o(this,t)},e._SomePromiseArray=i}},{"./errors":12,"./util":36}],32:[function(t,e,n){"use strict";e.exports=function(t){function e(t){void 0!==t?(t=t._target(),this._bitField=t._bitField,this._settledValueField=t._isFateSealed()?t._settledValue():void 0):(this._bitField=0,this._settledValueField=void 0)}e.prototype._settledValue=function(){return this._settledValueField};var n=e.prototype.value=function(){if(!this.isFulfilled())throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\n\n    See http://goo.gl/MqrFmX\n");return this._settledValue()},r=e.prototype.error=e.prototype.reason=function(){if(!this.isRejected())throw new TypeError("cannot get rejection reason of a non-rejected promise\n\n    See http://goo.gl/MqrFmX\n");return this._settledValue()},i=e.prototype.isFulfilled=function(){return 0!==(33554432&this._bitField)},o=e.prototype.isRejected=function(){return 0!==(16777216&this._bitField)},s=e.prototype.isPending=function(){return 0===(50397184&this._bitField)},a=e.prototype.isResolved=function(){return 0!==(50331648&this._bitField)};e.prototype.isCancelled=t.prototype._isCancelled=function(){return 65536===(65536&this._bitField)},t.prototype.isCancelled=function(){return this._target()._isCancelled()},t.prototype.isPending=function(){return s.call(this._target())},t.prototype.isRejected=function(){return o.call(this._target())},t.prototype.isFulfilled=function(){return i.call(this._target())},t.prototype.isResolved=function(){return a.call(this._target())},t.prototype.value=function(){return n.call(this._target())},t.prototype.reason=function(){var t=this._target();return t._unsetRejectionIsUnhandled(),r.call(t)},t.prototype._value=function(){return this._settledValue()},t.prototype._reason=function(){return this._unsetRejectionIsUnhandled(),this._settledValue()},t.PromiseInspection=e}},{}],33:[function(t,e,n){"use strict";e.exports=function(e,n){function r(t,r){if(u(t)){if(t instanceof e)return t;var i=o(t);if(i===l){r&&r._pushContext();var c=e.reject(i.e);return r&&r._popContext(),c}if("function"==typeof i){if(s(t)){var c=new e(n);return t._then(c._fulfill,c._reject,void 0,c,null),c}return a(t,i,r)}}return t}function i(t){return t.then}function o(t){try{return i(t)}catch(e){return l.e=e,l}}function s(t){return p.call(t,"_promise0")}function a(t,r,i){function o(t){a&&(a._resolveCallback(t),a=null)}function s(t){a&&(a._rejectCallback(t,p,!0),a=null)}var a=new e(n),u=a;i&&i._pushContext(),a._captureStackTrace(),i&&i._popContext();var p=!0,h=c.tryCatch(r).call(t,o,s);return p=!1,a&&h===l&&(a._rejectCallback(h.e,!0,!0),a=null),u}var c=t("./util"),l=c.errorObj,u=c.isObject,p={}.hasOwnProperty;return r}},{"./util":36}],34:[function(t,e,n){"use strict";e.exports=function(e,n,r){function i(t){this.handle=t}function o(t){return clearTimeout(this.handle),t}function s(t){throw clearTimeout(this.handle),t}var a=t("./util"),c=e.TimeoutError;i.prototype._resultCancelled=function(){clearTimeout(this.handle)};var l=function(t){return u(+this).thenReturn(t)},u=e.delay=function(t,o){var s,a;return void 0!==o?(s=e.resolve(o)._then(l,null,null,t,void 0),r.cancellation()&&o instanceof e&&s._setOnCancel(o)):(s=new e(n),a=setTimeout(function(){s._fulfill()},+t),r.cancellation()&&s._setOnCancel(new i(a))),s._setAsyncGuaranteed(),s};e.prototype.delay=function(t){return u(t,this)};var p=function(t,e,n){var r;r="string"!=typeof e?e instanceof Error?e:new c("operation timed out"):new c(e),a.markAsOriginatingFromRejection(r),t._attachExtraTrace(r),t._reject(r),null!=n&&n.cancel()};e.prototype.timeout=function(t,e){t=+t;var n,a,c=new i(setTimeout(function(){n.isPending()&&p(n,e,a)},t));return r.cancellation()?(a=this.then(),n=a._then(o,s,void 0,c,void 0),n._setOnCancel(c)):n=this._then(o,s,void 0,c,void 0),n}}},{"./util":36}],35:[function(t,e,n){"use strict";e.exports=function(e,n,r,i,o,s){function a(t){setTimeout(function(){throw t},0)}function c(t){var e=r(t);return e!==t&&"function"==typeof t._isDisposable&&"function"==typeof t._getDisposer&&t._isDisposable()&&e._setDisposable(t._getDisposer()),e}function l(t,n){function i(){if(s>=l)return u._fulfill();var o=c(t[s++]);if(o instanceof e&&o._isDisposable()){try{o=r(o._getDisposer().tryDispose(n),t.promise)}catch(p){return a(p)}if(o instanceof e)return o._then(i,a,null,null,null)}i()}var s=0,l=t.length,u=new e(o);return i(),u}function u(t,e,n){this._data=t,this._promise=e,this._context=n}function p(t,e,n){this.constructor$(t,e,n)}function h(t){return u.isDisposer(t)?(this.resources[this.index]._setDisposable(t),t.promise()):t}function f(t){this.length=t,this.promise=null,this[t-1]=null}var _=t("./util"),d=t("./errors").TypeError,v=t("./util").inherits,y=_.errorObj,m=_.tryCatch;u.prototype.data=function(){return this._data},u.prototype.promise=function(){return this._promise},u.prototype.resource=function(){return this.promise().isFulfilled()?this.promise().value():null},u.prototype.tryDispose=function(t){var e=this.resource(),n=this._context;void 0!==n&&n._pushContext();var r=null!==e?this.doDispose(e,t):null;return void 0!==n&&n._popContext(),this._promise._unsetDisposable(),this._data=null,r},u.isDisposer=function(t){return null!=t&&"function"==typeof t.resource&&"function"==typeof t.tryDispose},v(p,u),p.prototype.doDispose=function(t,e){var n=this.data();return n.call(t,t,e)},f.prototype._resultCancelled=function(){for(var t=this.length,n=0;t>n;++n){var r=this[n];r instanceof e&&r.cancel()}},e.using=function(){var t=arguments.length;if(2>t)return n("you must pass at least 2 arguments to Promise.using");var i=arguments[t-1];if("function"!=typeof i)return n("expecting a function but got "+_.classString(i));var o,a=!0;2===t&&Array.isArray(arguments[0])?(o=arguments[0],t=o.length,a=!1):(o=arguments,t--);for(var c=new f(t),p=0;t>p;++p){var d=o[p];if(u.isDisposer(d)){var v=d;d=d.promise(),d._setDisposable(v)}else{var g=r(d);g instanceof e&&(d=g._then(h,null,null,{resources:c,index:p},void 0))}c[p]=d}for(var b=new Array(c.length),p=0;p<b.length;++p)b[p]=e.resolve(c[p]).reflect();var w=e.all(b).then(function(t){for(var e=0;e<t.length;++e){var n=t[e];if(n.isRejected())return y.e=n.error(),y;if(!n.isFulfilled())return void w.cancel();t[e]=n.value()}C._pushContext(),i=m(i);var r=a?i.apply(void 0,t):i(t),o=C._popContext();return s.checkForgottenReturns(r,o,"Promise.using",C),r}),C=w.lastly(function(){var t=new e.PromiseInspection(w);return l(c,t)});return c.promise=C,C._setOnCancel(c),C},e.prototype._setDisposable=function(t){this._bitField=131072|this._bitField,this._disposer=t},e.prototype._isDisposable=function(){return(131072&this._bitField)>0},e.prototype._getDisposer=function(){return this._disposer},e.prototype._unsetDisposable=function(){this._bitField=-131073&this._bitField,this._disposer=void 0},e.prototype.disposer=function(t){if("function"==typeof t)return new p(t,this,i());throw new d}}},{"./errors":12,"./util":36}],36:[function(t,e,n){"use strict";function r(){try{var t=T;return T=null,t.apply(this,arguments)}catch(e){return x.e=e,x}}function i(t){return T=t,r}function o(t){return null==t||t===!0||t===!1||"string"==typeof t||"number"==typeof t}function s(t){return"function"==typeof t||"object"==typeof t&&null!==t}function a(t){return o(t)?new Error(v(t)):t}function c(t,e){var n,r=t.length,i=new Array(r+1);for(n=0;r>n;++n)i[n]=t[n];return i[n]=e,i}function l(t,e,n){if(!E.isES5)return{}.hasOwnProperty.call(t,e)?t[e]:void 0;var r=Object.getOwnPropertyDescriptor(t,e);return null!=r?null==r.get&&null==r.set?r.value:n:void 0}function u(t,e,n){if(o(t))return t;var r={value:n,configurable:!0,enumerable:!1,writable:!0};return E.defineProperty(t,e,r),t}function p(t){throw t}function h(t){try{if("function"==typeof t){var e=E.names(t.prototype),n=E.isES5&&e.length>1,r=e.length>0&&!(1===e.length&&"constructor"===e[0]),i=O.test(t+"")&&E.names(t).length>0;if(n||r||i)return!0}return!1}catch(o){return!1}}function f(t){function e(){}e.prototype=t;for(var n=8;n--;)new e;return t}function _(t){return A.test(t)}function d(t,e,n){for(var r=new Array(t),i=0;t>i;++i)r[i]=e+i+n;return r}function v(t){try{return t+""}catch(e){return"[no string representation]"}}function y(t){return null!==t&&"object"==typeof t&&"string"==typeof t.message&&"string"==typeof t.name}function m(t){try{u(t,"isOperational",!0)}catch(e){}}function g(t){return null==t?!1:t instanceof Error.__BluebirdErrorTypes__.OperationalError||t.isOperational===!0}function b(t){return y(t)&&E.propertyIsWritable(t,"stack")}function w(t){return{}.toString.call(t)}function C(t,e,n){for(var r=E.names(t),i=0;i<r.length;++i){var o=r[i];if(n(o))try{E.defineProperty(e,o,E.getDescriptor(t,o))}catch(s){}}}function j(t,e){return L?process.env[t]:e}function k(){if("function"==typeof Promise)try{var t=new Promise(function(){});if("[object Promise]"==={}.toString.call(t))return Promise}catch(e){}}var E=t("./es5"),F="undefined"==typeof navigator,x={e:{}},T,P="undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:void 0!==this?this:null,R=function(t,e){function n(){this.constructor=t,this.constructor$=e;for(var n in e.prototype)r.call(e.prototype,n)&&"$"!==n.charAt(n.length-1)&&(this[n+"$"]=e.prototype[n])}var r={}.hasOwnProperty;return n.prototype=e.prototype,t.prototype=new n,t.prototype},S=function(){var t=[Array.prototype,Object.prototype,Function.prototype],e=function(e){for(var n=0;n<t.length;++n)if(t[n]===e)return!0;return!1};if(E.isES5){var n=Object.getOwnPropertyNames;return function(t){for(var r=[],i=Object.create(null);null!=t&&!e(t);){var o;try{o=n(t)}catch(s){return r}for(var a=0;a<o.length;++a){var c=o[a];if(!i[c]){i[c]=!0;var l=Object.getOwnPropertyDescriptor(t,c);null!=l&&null==l.get&&null==l.set&&r.push(c)}}t=E.getPrototypeOf(t)}return r}}var r={}.hasOwnProperty;return function(n){if(e(n))return[];var i=[];t:for(var o in n)if(r.call(n,o))i.push(o);else{for(var s=0;s<t.length;++s)if(r.call(t[s],o))continue t;i.push(o)}return i}}(),O=/this\s*\.\s*\S+\s*=/,A=/^[a-z$_][a-z$_0-9]*$/i,D=function(){return"stack"in new Error?function(t){return b(t)?t:new Error(v(t))}:function(t){if(b(t))return t;try{throw new Error(v(t))}catch(e){return e}}}(),V=function(t){return E.isArray(t)?t:null};if("undefined"!=typeof Symbol&&Symbol.iterator){var I="function"==typeof Array.from?function(t){return Array.from(t)}:function(t){for(var e,n=[],r=t[Symbol.iterator]();!(e=r.next()).done;)n.push(e.value);return n};V=function(t){return E.isArray(t)?t:null!=t&&"function"==typeof t[Symbol.iterator]?I(t):null}}var L="undefined"!=typeof process&&"[object process]"===w(process).toLowerCase(),H={isClass:h,isIdentifier:_,inheritedDataKeys:S,getDataPropertyOrDefault:l,thrower:p,isArray:E.isArray,asArray:V,notEnumerableProp:u,isPrimitive:o,isObject:s,isError:y,canEvaluate:F,errorObj:x,tryCatch:i,inherits:R,withAppended:c,maybeWrapAsError:a,toFastProperties:f,filledRange:d,toString:v,canAttachTrace:b,ensureErrorObject:D,originatesFromRejection:g,markAsOriginatingFromRejection:m,classString:w,copyDescriptors:C,hasDevTools:"undefined"!=typeof chrome&&chrome&&"function"==typeof chrome.loadTimes,isNode:L,env:j,global:P,getNativePromise:k};H.isRecentNode=H.isNode&&function(){var t=process.versions.node.split(".").map(Number);return 0===t[0]&&t[1]>10||t[0]>0}(),H.isNode&&H.toFastProperties(process);try{throw new Error}catch(N){H.lastLineError=N}e.exports=H},{"./es5":13}]},{},[4])(4)}),"undefined"!=typeof window&&null!==window?window.P=window.Promise:"undefined"!=typeof self&&null!==self&&(self.P=self.Promise);

//download.js v4.2, by dandavis; 2008-2016. [CCBY2] see http://danml.com/download.html for tests/usage
// v1 landed a FF+Chrome compat way of downloading strings to local un-named files, upgraded to use a hidden frame and optional mime
// v2 added named files via a[download], msSaveBlob, IE (10+) support, and window.URL support for larger+faster saves than dataURLs
// v3 added dataURL and Blob Input, bind-toggle arity, and legacy dataURL fallback was improved with force-download mime and base64 support. 3.1 improved safari handling.
// v4 adds AMD/UMD, commonJS, and plain browser support
// v4.1 adds url download capability via solo URL argument (same domain/CORS only)
// v4.2 adds semantic variable names, long (over 2MB) dataURL support, and hidden by default temp anchors
// https://github.com/rndme/download

(function (root, factory) {
	if (typeof define === 'function' && define.amd) {
		// AMD. Register as an anonymous module.
		define([], factory);
	} else if (typeof exports === 'object') {
		// Node. Does not work with strict CommonJS, but
		// only CommonJS-like environments that support module.exports,
		// like Node.
		module.exports = factory();
	} else {
		// Browser globals (root is window)
		root.download = factory();
  }
}(this, function () {

	return function download(data, strFileName, strMimeType) {

		var self = window, // this script is only for browsers anyway...
			defaultMime = "application/octet-stream", // this default mime also triggers iframe downloads
			mimeType = strMimeType || defaultMime,
			payload = data,
			url = !strFileName && !strMimeType && payload,
			anchor = document.createElement("a"),
			toString = function(a){return String(a);},
			myBlob = (self.Blob || self.MozBlob || self.WebKitBlob || toString),
			fileName = strFileName || "download",
			blob,
			reader;
			myBlob= myBlob.call ? myBlob.bind(self) : Blob ;
	  
		if(String(this)==="true"){ //reverse arguments, allowing download.bind(true, "text/xml", "export.xml") to act as a callback
			payload=[payload, mimeType];
			mimeType=payload[0];
			payload=payload[1];
		}


		if(url && url.length< 2048){ // if no filename and no mime, assume a url was passed as the only argument
			fileName = url.split("/").pop().split("?")[0];
			anchor.href = url; // assign href prop to temp anchor
		  	if(anchor.href.indexOf(url) !== -1){ // if the browser determines that it's a potentially valid url path:
        		var ajax=new XMLHttpRequest();
        		ajax.open( "GET", url, true);
        		ajax.responseType = 'blob';
        		ajax.onload= function(e){ 
				  download(e.target.response, fileName, defaultMime);
				};
        		setTimeout(function(){ ajax.send();}, 0); // allows setting custom ajax headers using the return:
			    return ajax;
			} // end if valid url?
		} // end if url?


		//go ahead and download dataURLs right away
		if(/^data\:[\w+\-]+\/[\w+\-]+[,;]/.test(payload)){
		
			if(payload.length > (1024*1024*1.999) && myBlob !== toString ){
				payload=dataUrlToBlob(payload);
				mimeType=payload.type || defaultMime;
			}else{			
				return navigator.msSaveBlob ?  // IE10 can't do a[download], only Blobs:
					navigator.msSaveBlob(dataUrlToBlob(payload), fileName) :
					saver(payload) ; // everyone else can save dataURLs un-processed
			}
			
		}//end if dataURL passed?

		blob = payload instanceof myBlob ?
			payload :
			new myBlob([payload], {type: mimeType}) ;


		function dataUrlToBlob(strUrl) {
			var parts= strUrl.split(/[:;,]/),
			type= parts[1],
			decoder= parts[2] == "base64" ? atob : decodeURIComponent,
			binData= decoder( parts.pop() ),
			mx= binData.length,
			i= 0,
			uiArr= new Uint8Array(mx);

			for(i;i<mx;++i) uiArr[i]= binData.charCodeAt(i);

			return new myBlob([uiArr], {type: type});
		 }

		function saver(url, winMode){

			if ('download' in anchor) { //html5 A[download]
				anchor.href = url;
				anchor.setAttribute("download", fileName);
				anchor.className = "download-js-link";
				anchor.innerHTML = "downloading...";
				anchor.style.display = "none";
				document.body.appendChild(anchor);
				setTimeout(function() {
					anchor.click();
					document.body.removeChild(anchor);
					if(winMode===true){setTimeout(function(){ self.URL.revokeObjectURL(anchor.href);}, 250 );}
				}, 66);
				return true;
			}

			// handle non-a[download] safari as best we can:
			if(/(Version)\/(\d+)\.(\d+)(?:\.(\d+))?.*Safari\//.test(navigator.userAgent)) {
				url=url.replace(/^data:([\w\/\-\+]+)/, defaultMime);
				if(!window.open(url)){ // popup blocked, offer direct download:
					if(confirm("Displaying New Document\n\nUse Save As... to download, then click back to return to this page.")){ location.href=url; }
				}
				return true;
			}

			//do iframe dataURL download (old ch+FF):
			var f = document.createElement("iframe");
			document.body.appendChild(f);

			if(!winMode){ // force a mime that will download:
				url="data:"+url.replace(/^data:([\w\/\-\+]+)/, defaultMime);
			}
			f.src=url;
			setTimeout(function(){ document.body.removeChild(f); }, 333);

		}//end saver




		if (navigator.msSaveBlob) { // IE10+ : (has Blob, but not a[download] or URL)
			return navigator.msSaveBlob(blob, fileName);
		}

		if(self.URL){ // simple fast and modern way using Blob and URL:
			saver(self.URL.createObjectURL(blob), true);
		}else{
			// handle non-Blob()+non-URL browsers:
			if(typeof blob === "string" || blob.constructor===toString ){
				try{
					return saver( "data:" +  mimeType   + ";base64,"  +  self.btoa(blob)  );
				}catch(y){
					return saver( "data:" +  mimeType   + "," + encodeURIComponent(blob)  );
				}
			}

			// Blob but not URL support:
			reader=new FileReader();
			reader.onload=function(e){
				saver(this.result);
			};
			reader.readAsDataURL(blob);
		}
		return true;
	}; /* end download() */
}));

(function (global){

  "use strict";

  var fabric=global.fabric||(global.fabric={}),
    extend=fabric.util.object.extend,
    clone=fabric.util.object.clone;

  if(fabric.CurvedText){
    fabric.warn('fabric.CurvedText is already defined');
    return;
  }
  var stateProperties=fabric.Text.prototype.stateProperties.concat();
  stateProperties.push(
    'radius',
    'spacing',
    'reverse',
    'effect',
    'range',
    'largeFont',
    'smallFont'
  );
  var _dimensionAffectingProps=fabric.Text.prototype._dimensionAffectingProps
    .concat(['radius','spacing','reverse','fill','effect','width','height','range','fontSize','shadow','largeFont','smallFont']);


  var letterProperties = ['backgroundColor','textBackgroundColor','textDecoration','stroke','strokeWidth','shadow','fontWeight','fontStyle','strokeWidth','textAlign'];

  /**
   * Group class
   * @class fabric.CurvedText
   * @extends fabric.Text
   * @mixes fabric.Collection
   */
  fabric.CurvedText=fabric.util.createClass(fabric.Text, fabric.Collection, /** @lends fabric.CurvedText.prototype */ {
    /**
     * Type of an object
     * @type String
     * @default
     */
    type: 'curvedText',
    /**
     * The radius of the curved Text
     * @type Number
     * @default 50
     */
    radius: 50,
    /**
     * Special Effects, Thanks to fahadnabbasi
     * https://github.com/EffEPi/fabric.curvedText/issues/9
     */
    range: 5,
    smallFont: 10,
    largeFont: 30,
    effect: 'curved',
    /**
     * Spacing between the letters
     * @type fabricNumber
     * @default 20
     */
    spacing: 20,
//		letters: null,

    /**
     * Reversing the radius (position of the original point)
     * @type Boolean
     * @default false
     */
    reverse: false,
    /**
     * List of properties to consider when checking if state of an object is changed ({@link fabric.Object#hasStateChanged})
     * as well as for history (undo/redo) purposes
     * @type Array
     */
    stateProperties: stateProperties,
    /**
     * Properties that are delegated to group objects when reading/writing
     * @param {Object} delegatedProperties
     */
    // delegatedProperties: delegatedProperties,
    /**
     * Properties which when set cause object to change dimensions
     * @type Object
     * @private
     */
    _dimensionAffectingProps: _dimensionAffectingProps,
    /**
     *
     * Rendering, is we are rendering and another rendering call is passed, then stop rendering the old and
     * rendering the new (trying to speed things up)
     */
    _isRendering: 0,
    /**
     * Added complexity
     */
    complexity: function (){
      this.callSuper('complexity');
    },
    initialize: function (text, options){
      options||(options={});
      this.__skipDimension=true;
      delete options.text;
      this.setOptions(options);
      this.__skipDimension=false;

      if(parseFloat(fabric.version) >= 2) {
        this.callSuper('initialize', text, options);
      }

      this.letters=new fabric.Group([], {
        selectable: false,
        padding: 0
      });
      this.setText(text);
      // this.render(this.ctx,true);
    },
    setText: function (text){
      if(this.letters){
        while(this.letters.size()){
          this.letters.remove(this.letters.item(0));
        }
        for(var i=0; i<text.length; i++){
          //I need to pass the options from the main options
          if(this.letters.item(i)===undefined){
            this.letters.add(new fabric.Text(text[i]));
          }else{
            this.letters.item(i).text = text[i];
          }
        }
      }
      this.text = text;

      var i = this.letters.size();
      while(i--){
        var letter = this.letters.item(i);
        letter.set({
          objectCaching: false,
          fill: this.fill,
          stroke: this.stroke,
          strokeWidth: this.strokeWidth,
          fontFamily: this.fontFamily,
          fontSize: this.fontSize,
          fontStyle: this.fontStyle,
          fontWeight: this.fontWeight,
          underline: this.underline,
          overline:  this.overline,
          linethrough: this.linethrough,
          lineHeight: this.lineHeight
        });
      }

      this._updateLetters();

      this.canvas && this.canvas.renderAll();
    },
    _initDimensions: function (ctx){
      // from fabric.Text.prototype._initDimensions
      // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
      if(this.__skipDimension){
        return;
      }
      if(!ctx){
        ctx=fabric.util.createCanvasElement().getContext('2d');
        this._setTextStyles(ctx);
      }
      this._textLines=this.text.split(this._reNewline);
      this._clearCache();
      var currentTextAlign=this.textAlign;
      this.textAlign='left';
      this.width=this.get('width');
      this.textAlign=currentTextAlign;
      this.height=this.get('height');
      // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
      this._updateLetters();
    },
    _updateLetters: function (){
      var renderingCode=fabric.util.getRandomInt(100, 999);
      this._isRendering=renderingCode;
      if(this.letters && this.text){
        var curAngle=0,
          curAngleRotation=0,
          angleRadians=0,
          align=0,
          textWidth=0,
          space=parseInt(this.spacing),
          fixedLetterAngle=0;

        //get text width
        if(this.effect==='curved'){
          for(var i=0, len=this.text.length; i<len; i++){
            textWidth+=this.letters.item(i).width+space;
          }
          textWidth-=space;
        }else if(this.effect==='arc'){
          fixedLetterAngle=((this.letters.item(0).fontSize+space)/this.radius)/(Math.PI/180);
          textWidth=((this.text.length+1)*(this.letters.item(0).fontSize+space));
        }
        // Text align
        if(this.get('textAlign')==='right'){
          curAngle=90-(((textWidth/2)/this.radius)/(Math.PI/180));
        }else if(this.get('textAlign')==='left'){
          curAngle=-90-(((textWidth/2)/this.radius)/(Math.PI/180));
        }else{
          curAngle=-(((textWidth/2)/this.radius)/(Math.PI/180));
        }
        if(this.reverse)
          curAngle=-curAngle;

        var width=0,
          multiplier=this.reverse?-1:1,
          thisLetterAngle=0,
          lastLetterAngle=0;

        for(var i=0, len=this.text.length; i<len; i++){
          if(renderingCode!==this._isRendering)
            return;

          for(var key in letterProperties){
            this.letters.item(i).set(key, this.get(key));
          }

          this.letters.item(i).set('left', (width));
          this.letters.item(i).set('top', (0));
          this.letters.item(i).set('angle',0);
          this.letters.item(i).set('padding', 0);

          if(this.effect==='curved'){
            thisLetterAngle=((this.letters.item(i).width+space)/this.radius)/(Math.PI/180);
            curAngle=multiplier*((multiplier*curAngle)+lastLetterAngle);
            angleRadians=curAngle*(Math.PI/180);
            lastLetterAngle=thisLetterAngle;

            this.letters.item(i).set('angle',curAngle);
            this.letters.item(i).set('top', multiplier*-1*(Math.cos(angleRadians)*this.radius));
            this.letters.item(i).set('left', multiplier*(Math.sin(angleRadians)*this.radius));
            this.letters.item(i).set('padding', 0);
            this.letters.item(i).set('selectable', false);

          }else if(this.effect==='arc'){//arc
            curAngle=multiplier*((multiplier*curAngle)+fixedLetterAngle);
            angleRadians=curAngle*(Math.PI/180);

            this.letters.item(i).set('top', multiplier*-1*(Math.cos(angleRadians)*this.radius));
            this.letters.item(i).set('left', multiplier*(Math.sin(angleRadians)*this.radius));
            this.letters.item(i).set('padding', 0);
            this.letters.item(i).set('selectable', false);
          }else if(this.effect==='STRAIGHT'){//STRAIGHT
            //var newfont=(i*5)+15;
            //this.letters.item(i).set('fontSize',(newfont));
            this.letters.item(i).set('left', (width));
            this.letters.item(i).set('top', (0));
            this.letters.item(i).set('angle',0);
            width+=this.letters.item(i).get('width');
            this.letters.item(i).set('padding', 0);
            this.letters.item(i).set({
              borderColor: 'red',
              cornerColor: 'green',
              cornerSize: 6,
              transparentCorners: false
            });
            this.letters.item(i).set('selectable', false);
          }else if(this.effect==='smallToLarge'){//smallToLarge
            var small=parseInt(this.smallFont);
            var large=parseInt(this.largeFont);
            //var small = 20;
            //var large = 75;
            var difference=large-small;
            var center=Math.ceil(this.text.length/2);
            var step=difference/(this.text.length);
            var newfont=small+(i*step);

            //var newfont=(i*this.smallFont)+15;

            this.letters.item(i).set('fontSize', (newfont));

            this.letters.item(i).set('left', (width));
            width+=this.letters.item(i).get('width');
            //this.letters.item(i).set('padding', 0);
            /*this.letters.item(i).set({
                         borderColor: 'red',
                         cornerColor: 'green',
                         cornerSize: 6,
                         transparentCorners: false
                         });*/
            this.letters.item(i).set('padding', 0);
            this.letters.item(i).set('selectable', false);
            this.letters.item(i).set('top', -1*this.letters.item(i).get('fontSize')+i);
            //this.letters.width=width;
            //this.letters.height=this.letters.item(i).get('height');

          }else if(this.effect==='largeToSmallTop'){//largeToSmallTop
            var small=parseInt(this.largeFont);
            var large=parseInt(this.smallFont);
            //var small = 20;
            //var large = 75;
            var difference=large-small;
            var center=Math.ceil(this.text.length/2);
            var step=difference/(this.text.length);
            var newfont=small+(i*step);
            //var newfont=((this.text.length-i)*this.smallFont)+12;
            this.letters.item(i).set('fontSize', (newfont));
            this.letters.item(i).set('left', (width));
            width+=this.letters.item(i).get('width');
            this.letters.item(i).set('padding', 0);
            this.letters.item(i).set({
              borderColor: 'red',
              cornerColor: 'green',
              cornerSize: 6,
              transparentCorners: false
            });
            this.letters.item(i).set('padding', 0);
            this.letters.item(i).set('selectable', false);
            this.letters.item(i).top=-1*this.letters.item(i).get('fontSize')+(i/this.text.length);

          }else if(this.effect==='largeToSmallBottom'){
            var small=parseInt(this.largeFont);
            var large=parseInt(this.smallFont);
            //var small = 20;
            //var large = 75;
            var difference=large-small;
            var center=Math.ceil(this.text.length/2);
            var step=difference/(this.text.length);
            var newfont=small+(i*step);
            //var newfont=((this.text.length-i)*this.smallFont)+12;
            this.letters.item(i).set('fontSize', (newfont));
            this.letters.item(i).set('left', (width));
            width+=this.letters.item(i).get('width');
            this.letters.item(i).set('padding', 0);
            this.letters.item(i).set({
              borderColor: 'red',
              cornerColor: 'green',
              cornerSize: 6,
              transparentCorners: false
            });
            this.letters.item(i).set('padding', 0);
            this.letters.item(i).set('selectable', false);
            //this.letters.item(i).top =-1* this.letters.item(i).get('fontSize')+newfont-((this.text.length-i))-((this.text.length-i));
            this.letters.item(i).top=-1*this.letters.item(i).get('fontSize')-i;

          }else if(this.effect==='bulge'){//bulge
            var small=parseInt(this.smallFont);
            var large=parseInt(this.largeFont);
            //var small = 20;
            //var large = 75;
            var difference=large-small;
            var center=Math.ceil(this.text.length/2);
            var step=difference/(this.text.length-center);
            if(i<center)
              var newfont=small+(i*step);
            else
              var newfont=large-((i-center+1)*step);
            this.letters.item(i).set('fontSize', (newfont));

            this.letters.item(i).set('left', (width));
            width+=this.letters.item(i).get('width');

            this.letters.item(i).set('padding', 0);
            this.letters.item(i).set('selectable', false);

            this.letters.item(i).set('top', -1*this.letters.item(i).get('height')/2);
          }
        }

        var scaleX=this.letters.get('scaleX');
        var scaleY=this.letters.get('scaleY');
        var angle=this.letters.get('angle');

        this.letters.set('scaleX', 1);
        this.letters.set('scaleY', 1);
        this.letters.set('angle', 0);

        // Update group coords
        this.letters._calcBounds();
        this.letters._updateObjectsCoords();
        //this.letters.saveCoords();
        // this.letters.render(ctx);

        this.letters.set('scaleX', scaleX);
        this.letters.set('scaleY', scaleY);
        this.letters.set('angle', angle);

        this.width=this.letters.width;
        this.height=this.letters.height;
        this.letters.left= -(this.letters.width/2);
        this.letters.top= -(this.letters.height/2);
      }
    },
    render: function (ctx){
      // do not render if object is not visible
      if(!this.visible)
        return;
      if(!this.letters)
        return;


      ctx.save();

      // if(noTransform){
      this.transform(ctx);
      // }

      var groupScaleFactor=Math.max(this.scaleX, this.scaleY);

      this.clipTo&&fabric.util.clipContext(this, ctx);

      //The array is now sorted in order of highest first, so start from end.
      for(var i=0, len=this.letters.size(); i<len; i++){
        var object=this.letters.item(i),
          originalScaleFactor=object.borderScaleFactor,
          originalHasRotatingPoint=object.hasRotatingPoint;

        // do not render if object is not visible
        if(!object.visible)
          continue;

//				object.borderScaleFactor=groupScaleFactor;
//				object.hasRotatingPoint=false;

        object.render(ctx);
//				object.borderScaleFactor=originalScaleFactor;
//				object.hasRotatingPoint=originalHasRotatingPoint;
      }
      this.clipTo&&ctx.restore();

      //Those lines causes double borders.. not sure why
//			if(!noTransform&&this.active){
//				this.drawBorders(ctx);
//				this.drawControls(ctx);
//			}
      ctx.restore();
      this.setCoords();
    },
    /**
     * @private
     */
    _set: function (key, value){
      if(key === "text"){
        this.setText(value);

        return;
      }
      this.callSuper('_set', key, value);
      if(this.text && this.letters){
        if(["angle","left","top","scaleX","scaleY","width","height"].indexOf(key) === -1){
          var i = this.letters.size();
          while(i--){
            this.letters.item(i).set(key, value);
          }
        }
        //Properties are delegated with the object is rendered
//				if (key in this.delegatedProperties) {
//					var i = this.letters.size();
//					while (i--) {
//						this.letters.item(i).set(key, value);
//					}
//				}
        if(this._dimensionAffectingProps.indexOf(key) !== -1){
          this._updateLetters();
          //this._initDimensions();
          this.setCoords();
        }
      }
    },
    initDimensions: function() {

    },
    toObject: function (propertiesToInclude){
      var object = extend(this.callSuper('toObject', propertiesToInclude), {
        radius: this.radius,
        spacing: this.spacing,
        reverse: this.reverse,
        effect: this.effect,
        range: this.range,
        smallFont: this.smallFont,
        largeFont: this.largeFont
        //letters: this.letters	//No need to pass this, the letters are recreated on the fly every time when initiated
      });

      if(!this.includeDefaultValues){
        this._removeDefaultValues(object);
      }
      return object;
    },
    /**
     * Returns string represenation of a group
     * @return {String}
     */
    toString: function (){
      return '#<fabric.CurvedText ('+this.complexity()+'): { "text": "'+this.text+'", "fontFamily": "'+this.fontFamily+'", "radius": "'+this.radius+'", "spacing": "'+this.spacing+'", "reverse": "'+this.reverse+'" }>';
    },
    /* _TO_SVG_START_ */
    /**
     * Returns svg representation of an instance
     * @param {Function} [reviver] Method for further parsing of svg representation.
     * @return {String} svg representation of an instance
     */
    toSVG: function (reviver){

	    var markup;
	    //fabricjs 3.+
	    if(fabric.version.search('3.') == 0) {
		     markup=[
		        '<g ',
		        this.getSvgTransform(),
		        '>'
		      ];
	    }
	    else {
		     markup=[
		        '<g ',
		        'transform="', this.getSvgTransform(),
		        '">'
		      ];
	    }

      if(this.letters){
        for(var i=0, len=this.letters.size(); i<len; i++){
          markup.push(this.letters.item(i).toSVG(reviver));
        }
      }
      markup.push('</g>');
      return reviver?reviver(markup.join('')):markup.join('');
    }
    /* _TO_SVG_END_ */
  });

  /**
   * Returns {@link fabric.CurvedText} instance from an object representation
   * @static
   * @memberOf fabric.CurvedText
   * @param {Object} object Object to create a group from
   * @param {Object} [options] Options object
   * @return {fabric.CurvedText} An instance of fabric.CurvedText
   */
  // fabric.CurvedText.fromObject=function (object){
  //   var obj =  new fabric.CurvedText(object.text, clone(object));
  //   return obj;
  // };

  fabric.CurvedText.fromObject = function(object, callback) {
    return fabric.Object._fromObject("CurvedText", object, callback,"text");
  };

  // fabric.util.createAccessors(fabric.CurvedText);

  /**
   * Indicates that instances of this type are async
   * @static
   * @memberOf fabric.CurvedText
   * @type Boolean
   * @default
   */
  fabric.CurvedText.async=false;

})(typeof exports!=='undefined'?exports:this);










/*! Hammer.JS - v2.0.8 - 2016-04-23
 * http://hammerjs.github.io/
 *
 * Copyright (c) 2016 Jorik Tangelder;
 * Licensed under the MIT license */
(function(window, document, exportName, undefined) {
  'use strict';

var VENDOR_PREFIXES = ['', 'webkit', 'Moz', 'MS', 'ms', 'o'];
var TEST_ELEMENT = document.createElement('div');

var TYPE_FUNCTION = 'function';

var round = Math.round;
var abs = Math.abs;
var now = Date.now;

/**
 * set a timeout with a given scope
 * @param {Function} fn
 * @param {Number} timeout
 * @param {Object} context
 * @returns {number}
 */
function setTimeoutContext(fn, timeout, context) {
    return setTimeout(bindFn(fn, context), timeout);
}

/**
 * if the argument is an array, we want to execute the fn on each entry
 * if it aint an array we don't want to do a thing.
 * this is used by all the methods that accept a single and array argument.
 * @param {*|Array} arg
 * @param {String} fn
 * @param {Object} [context]
 * @returns {Boolean}
 */
function invokeArrayArg(arg, fn, context) {
    if (Array.isArray(arg)) {
        each(arg, context[fn], context);
        return true;
    }
    return false;
}

/**
 * walk objects and arrays
 * @param {Object} obj
 * @param {Function} iterator
 * @param {Object} context
 */
function each(obj, iterator, context) {
    var i;

    if (!obj) {
        return;
    }

    if (obj.forEach) {
        obj.forEach(iterator, context);
    } else if (obj.length !== undefined) {
        i = 0;
        while (i < obj.length) {
            iterator.call(context, obj[i], i, obj);
            i++;
        }
    } else {
        for (i in obj) {
            obj.hasOwnProperty(i) && iterator.call(context, obj[i], i, obj);
        }
    }
}

/**
 * wrap a method with a deprecation warning and stack trace
 * @param {Function} method
 * @param {String} name
 * @param {String} message
 * @returns {Function} A new function wrapping the supplied method.
 */
function deprecate(method, name, message) {
    var deprecationMessage = 'DEPRECATED METHOD: ' + name + '\n' + message + ' AT \n';
    return function() {
        var e = new Error('get-stack-trace');
        var stack = e && e.stack ? e.stack.replace(/^[^\(]+?[\n$]/gm, '')
            .replace(/^\s+at\s+/gm, '')
            .replace(/^Object.<anonymous>\s*\(/gm, '{anonymous}()@') : 'Unknown Stack Trace';

        var log = window.console && (window.console.warn || window.console.log);
        if (log) {
            log.call(window.console, deprecationMessage, stack);
        }
        return method.apply(this, arguments);
    };
}

/**
 * extend object.
 * means that properties in dest will be overwritten by the ones in src.
 * @param {Object} target
 * @param {...Object} objects_to_assign
 * @returns {Object} target
 */
var assign;
if (typeof Object.assign !== 'function') {
    assign = function assign(target) {
        if (target === undefined || target === null) {
            throw new TypeError('Cannot convert undefined or null to object');
        }

        var output = Object(target);
        for (var index = 1; index < arguments.length; index++) {
            var source = arguments[index];
            if (source !== undefined && source !== null) {
                for (var nextKey in source) {
                    if (source.hasOwnProperty(nextKey)) {
                        output[nextKey] = source[nextKey];
                    }
                }
            }
        }
        return output;
    };
} else {
    assign = Object.assign;
}

/**
 * extend object.
 * means that properties in dest will be overwritten by the ones in src.
 * @param {Object} dest
 * @param {Object} src
 * @param {Boolean} [merge=false]
 * @returns {Object} dest
 */
var extend = deprecate(function extend(dest, src, merge) {
    var keys = Object.keys(src);
    var i = 0;
    while (i < keys.length) {
        if (!merge || (merge && dest[keys[i]] === undefined)) {
            dest[keys[i]] = src[keys[i]];
        }
        i++;
    }
    return dest;
}, 'extend', 'Use `assign`.');

/**
 * merge the values from src in the dest.
 * means that properties that exist in dest will not be overwritten by src
 * @param {Object} dest
 * @param {Object} src
 * @returns {Object} dest
 */
var merge = deprecate(function merge(dest, src) {
    return extend(dest, src, true);
}, 'merge', 'Use `assign`.');

/**
 * simple class inheritance
 * @param {Function} child
 * @param {Function} base
 * @param {Object} [properties]
 */
function inherit(child, base, properties) {
    var baseP = base.prototype,
        childP;

    childP = child.prototype = Object.create(baseP);
    childP.constructor = child;
    childP._super = baseP;

    if (properties) {
        assign(childP, properties);
    }
}

/**
 * simple function bind
 * @param {Function} fn
 * @param {Object} context
 * @returns {Function}
 */
function bindFn(fn, context) {
    return function boundFn() {
        return fn.apply(context, arguments);
    };
}

/**
 * let a boolean value also be a function that must return a boolean
 * this first item in args will be used as the context
 * @param {Boolean|Function} val
 * @param {Array} [args]
 * @returns {Boolean}
 */
function boolOrFn(val, args) {
    if (typeof val == TYPE_FUNCTION) {
        return val.apply(args ? args[0] || undefined : undefined, args);
    }
    return val;
}

/**
 * use the val2 when val1 is undefined
 * @param {*} val1
 * @param {*} val2
 * @returns {*}
 */
function ifUndefined(val1, val2) {
    return (val1 === undefined) ? val2 : val1;
}

/**
 * addEventListener with multiple events at once
 * @param {EventTarget} target
 * @param {String} types
 * @param {Function} handler
 */
function addEventListeners(target, types, handler) {
    each(splitStr(types), function(type) {
        target.addEventListener(type, handler, false);
    });
}

/**
 * removeEventListener with multiple events at once
 * @param {EventTarget} target
 * @param {String} types
 * @param {Function} handler
 */
function removeEventListeners(target, types, handler) {
    each(splitStr(types), function(type) {
        target.removeEventListener(type, handler, false);
    });
}

/**
 * find if a node is in the given parent
 * @method hasParent
 * @param {HTMLElement} node
 * @param {HTMLElement} parent
 * @return {Boolean} found
 */
function hasParent(node, parent) {
    while (node) {
        if (node == parent) {
            return true;
        }
        node = node.parentNode;
    }
    return false;
}

/**
 * small indexOf wrapper
 * @param {String} str
 * @param {String} find
 * @returns {Boolean} found
 */
function inStr(str, find) {
    return str.indexOf(find) > -1;
}

/**
 * split string on whitespace
 * @param {String} str
 * @returns {Array} words
 */
function splitStr(str) {
    return str.trim().split(/\s+/g);
}

/**
 * find if a array contains the object using indexOf or a simple polyFill
 * @param {Array} src
 * @param {String} find
 * @param {String} [findByKey]
 * @return {Boolean|Number} false when not found, or the index
 */
function inArray(src, find, findByKey) {
    if (src.indexOf && !findByKey) {
        return src.indexOf(find);
    } else {
        var i = 0;
        while (i < src.length) {
            if ((findByKey && src[i][findByKey] == find) || (!findByKey && src[i] === find)) {
                return i;
            }
            i++;
        }
        return -1;
    }
}

/**
 * convert array-like objects to real arrays
 * @param {Object} obj
 * @returns {Array}
 */
function toArray(obj) {
    return Array.prototype.slice.call(obj, 0);
}

/**
 * unique array with objects based on a key (like 'id') or just by the array's value
 * @param {Array} src [{id:1},{id:2},{id:1}]
 * @param {String} [key]
 * @param {Boolean} [sort=False]
 * @returns {Array} [{id:1},{id:2}]
 */
function uniqueArray(src, key, sort) {
    var results = [];
    var values = [];
    var i = 0;

    while (i < src.length) {
        var val = key ? src[i][key] : src[i];
        if (inArray(values, val) < 0) {
            results.push(src[i]);
        }
        values[i] = val;
        i++;
    }

    if (sort) {
        if (!key) {
            results = results.sort();
        } else {
            results = results.sort(function sortUniqueArray(a, b) {
                return a[key] > b[key];
            });
        }
    }

    return results;
}

/**
 * get the prefixed property
 * @param {Object} obj
 * @param {String} property
 * @returns {String|Undefined} prefixed
 */
function prefixed(obj, property) {
    var prefix, prop;
    var camelProp = property[0].toUpperCase() + property.slice(1);

    var i = 0;
    while (i < VENDOR_PREFIXES.length) {
        prefix = VENDOR_PREFIXES[i];
        prop = (prefix) ? prefix + camelProp : property;

        if (prop in obj) {
            return prop;
        }
        i++;
    }
    return undefined;
}

/**
 * get a unique id
 * @returns {number} uniqueId
 */
var _uniqueId = 1;
function uniqueId() {
    return _uniqueId++;
}

/**
 * get the window object of an element
 * @param {HTMLElement} element
 * @returns {DocumentView|Window}
 */
function getWindowForElement(element) {
    var doc = element.ownerDocument || element;
    return (doc.defaultView || doc.parentWindow || window);
}

var MOBILE_REGEX = /mobile|tablet|ip(ad|hone|od)|android/i;

var SUPPORT_TOUCH = ('ontouchstart' in window);
var SUPPORT_POINTER_EVENTS = prefixed(window, 'PointerEvent') !== undefined;
var SUPPORT_ONLY_TOUCH = SUPPORT_TOUCH && MOBILE_REGEX.test(navigator.userAgent);

var INPUT_TYPE_TOUCH = 'touch';
var INPUT_TYPE_PEN = 'pen';
var INPUT_TYPE_MOUSE = 'mouse';
var INPUT_TYPE_KINECT = 'kinect';

var COMPUTE_INTERVAL = 25;

var INPUT_START = 1;
var INPUT_MOVE = 2;
var INPUT_END = 4;
var INPUT_CANCEL = 8;

var DIRECTION_NONE = 1;
var DIRECTION_LEFT = 2;
var DIRECTION_RIGHT = 4;
var DIRECTION_UP = 8;
var DIRECTION_DOWN = 16;

var DIRECTION_HORIZONTAL = DIRECTION_LEFT | DIRECTION_RIGHT;
var DIRECTION_VERTICAL = DIRECTION_UP | DIRECTION_DOWN;
var DIRECTION_ALL = DIRECTION_HORIZONTAL | DIRECTION_VERTICAL;

var PROPS_XY = ['x', 'y'];
var PROPS_CLIENT_XY = ['clientX', 'clientY'];

/**
 * create new input type manager
 * @param {Manager} manager
 * @param {Function} callback
 * @returns {Input}
 * @constructor
 */
function Input(manager, callback) {
    var self = this;
    this.manager = manager;
    this.callback = callback;
    this.element = manager.element;
    this.target = manager.options.inputTarget;

    // smaller wrapper around the handler, for the scope and the enabled state of the manager,
    // so when disabled the input events are completely bypassed.
    this.domHandler = function(ev) {
        if (boolOrFn(manager.options.enable, [manager])) {
            self.handler(ev);
        }
    };

    this.init();

}

Input.prototype = {
    /**
     * should handle the inputEvent data and trigger the callback
     * @virtual
     */
    handler: function() { },

    /**
     * bind the events
     */
    init: function() {
        this.evEl && addEventListeners(this.element, this.evEl, this.domHandler);
        this.evTarget && addEventListeners(this.target, this.evTarget, this.domHandler);
        this.evWin && addEventListeners(getWindowForElement(this.element), this.evWin, this.domHandler);
    },

    /**
     * unbind the events
     */
    destroy: function() {
        this.evEl && removeEventListeners(this.element, this.evEl, this.domHandler);
        this.evTarget && removeEventListeners(this.target, this.evTarget, this.domHandler);
        this.evWin && removeEventListeners(getWindowForElement(this.element), this.evWin, this.domHandler);
    }
};

/**
 * create new input type manager
 * called by the Manager constructor
 * @param {Hammer} manager
 * @returns {Input}
 */
function createInputInstance(manager) {
    var Type;
    var inputClass = manager.options.inputClass;

    if (inputClass) {
        Type = inputClass;
    } else if (SUPPORT_POINTER_EVENTS) {
        Type = PointerEventInput;
    } else if (SUPPORT_ONLY_TOUCH) {
        Type = TouchInput;
    } else if (!SUPPORT_TOUCH) {
        Type = MouseInput;
    } else {
        Type = TouchMouseInput;
    }
    return new (Type)(manager, inputHandler);
}

/**
 * handle input events
 * @param {Manager} manager
 * @param {String} eventType
 * @param {Object} input
 */
function inputHandler(manager, eventType, input) {
    var pointersLen = input.pointers.length;
    var changedPointersLen = input.changedPointers.length;
    var isFirst = (eventType & INPUT_START && (pointersLen - changedPointersLen === 0));
    var isFinal = (eventType & (INPUT_END | INPUT_CANCEL) && (pointersLen - changedPointersLen === 0));

    input.isFirst = !!isFirst;
    input.isFinal = !!isFinal;

    if (isFirst) {
        manager.session = {};
    }

    // source event is the normalized value of the domEvents
    // like 'touchstart, mouseup, pointerdown'
    input.eventType = eventType;

    // compute scale, rotation etc
    computeInputData(manager, input);

    // emit secret event
    manager.emit('hammer.input', input);

    manager.recognize(input);
    manager.session.prevInput = input;
}

/**
 * extend the data with some usable properties like scale, rotate, velocity etc
 * @param {Object} manager
 * @param {Object} input
 */
function computeInputData(manager, input) {
    var session = manager.session;
    var pointers = input.pointers;
    var pointersLength = pointers.length;

    // store the first input to calculate the distance and direction
    if (!session.firstInput) {
        session.firstInput = simpleCloneInputData(input);
    }

    // to compute scale and rotation we need to store the multiple touches
    if (pointersLength > 1 && !session.firstMultiple) {
        session.firstMultiple = simpleCloneInputData(input);
    } else if (pointersLength === 1) {
        session.firstMultiple = false;
    }

    var firstInput = session.firstInput;
    var firstMultiple = session.firstMultiple;
    var offsetCenter = firstMultiple ? firstMultiple.center : firstInput.center;

    var center = input.center = getCenter(pointers);
    input.timeStamp = now();
    input.deltaTime = input.timeStamp - firstInput.timeStamp;

    input.angle = getAngle(offsetCenter, center);
    input.distance = getDistance(offsetCenter, center);

    computeDeltaXY(session, input);
    input.offsetDirection = getDirection(input.deltaX, input.deltaY);

    var overallVelocity = getVelocity(input.deltaTime, input.deltaX, input.deltaY);
    input.overallVelocityX = overallVelocity.x;
    input.overallVelocityY = overallVelocity.y;
    input.overallVelocity = (abs(overallVelocity.x) > abs(overallVelocity.y)) ? overallVelocity.x : overallVelocity.y;

    input.scale = firstMultiple ? getScale(firstMultiple.pointers, pointers) : 1;
    input.rotation = firstMultiple ? getRotation(firstMultiple.pointers, pointers) : 0;

    input.maxPointers = !session.prevInput ? input.pointers.length : ((input.pointers.length >
        session.prevInput.maxPointers) ? input.pointers.length : session.prevInput.maxPointers);

    computeIntervalInputData(session, input);

    // find the correct target
    var target = manager.element;
    if (hasParent(input.srcEvent.target, target)) {
        target = input.srcEvent.target;
    }
    input.target = target;
}

function computeDeltaXY(session, input) {
    var center = input.center;
    var offset = session.offsetDelta || {};
    var prevDelta = session.prevDelta || {};
    var prevInput = session.prevInput || {};

    if (input.eventType === INPUT_START || prevInput.eventType === INPUT_END) {
        prevDelta = session.prevDelta = {
            x: prevInput.deltaX || 0,
            y: prevInput.deltaY || 0
        };

        offset = session.offsetDelta = {
            x: center.x,
            y: center.y
        };
    }

    input.deltaX = prevDelta.x + (center.x - offset.x);
    input.deltaY = prevDelta.y + (center.y - offset.y);
}

/**
 * velocity is calculated every x ms
 * @param {Object} session
 * @param {Object} input
 */
function computeIntervalInputData(session, input) {
    var last = session.lastInterval || input,
        deltaTime = input.timeStamp - last.timeStamp,
        velocity, velocityX, velocityY, direction;

    if (input.eventType != INPUT_CANCEL && (deltaTime > COMPUTE_INTERVAL || last.velocity === undefined)) {
        var deltaX = input.deltaX - last.deltaX;
        var deltaY = input.deltaY - last.deltaY;

        var v = getVelocity(deltaTime, deltaX, deltaY);
        velocityX = v.x;
        velocityY = v.y;
        velocity = (abs(v.x) > abs(v.y)) ? v.x : v.y;
        direction = getDirection(deltaX, deltaY);

        session.lastInterval = input;
    } else {
        // use latest velocity info if it doesn't overtake a minimum period
        velocity = last.velocity;
        velocityX = last.velocityX;
        velocityY = last.velocityY;
        direction = last.direction;
    }

    input.velocity = velocity;
    input.velocityX = velocityX;
    input.velocityY = velocityY;
    input.direction = direction;
}

/**
 * create a simple clone from the input used for storage of firstInput and firstMultiple
 * @param {Object} input
 * @returns {Object} clonedInputData
 */
function simpleCloneInputData(input) {
    // make a simple copy of the pointers because we will get a reference if we don't
    // we only need clientXY for the calculations
    var pointers = [];
    var i = 0;
    while (i < input.pointers.length) {
        pointers[i] = {
            clientX: round(input.pointers[i].clientX),
            clientY: round(input.pointers[i].clientY)
        };
        i++;
    }

    return {
        timeStamp: now(),
        pointers: pointers,
        center: getCenter(pointers),
        deltaX: input.deltaX,
        deltaY: input.deltaY
    };
}

/**
 * get the center of all the pointers
 * @param {Array} pointers
 * @return {Object} center contains `x` and `y` properties
 */
function getCenter(pointers) {
    var pointersLength = pointers.length;

    // no need to loop when only one touch
    if (pointersLength === 1) {
        return {
            x: round(pointers[0].clientX),
            y: round(pointers[0].clientY)
        };
    }

    var x = 0, y = 0, i = 0;
    while (i < pointersLength) {
        x += pointers[i].clientX;
        y += pointers[i].clientY;
        i++;
    }

    return {
        x: round(x / pointersLength),
        y: round(y / pointersLength)
    };
}

/**
 * calculate the velocity between two points. unit is in px per ms.
 * @param {Number} deltaTime
 * @param {Number} x
 * @param {Number} y
 * @return {Object} velocity `x` and `y`
 */
function getVelocity(deltaTime, x, y) {
    return {
        x: x / deltaTime || 0,
        y: y / deltaTime || 0
    };
}

/**
 * get the direction between two points
 * @param {Number} x
 * @param {Number} y
 * @return {Number} direction
 */
function getDirection(x, y) {
    if (x === y) {
        return DIRECTION_NONE;
    }

    if (abs(x) >= abs(y)) {
        return x < 0 ? DIRECTION_LEFT : DIRECTION_RIGHT;
    }
    return y < 0 ? DIRECTION_UP : DIRECTION_DOWN;
}

/**
 * calculate the absolute distance between two points
 * @param {Object} p1 {x, y}
 * @param {Object} p2 {x, y}
 * @param {Array} [props] containing x and y keys
 * @return {Number} distance
 */
function getDistance(p1, p2, props) {
    if (!props) {
        props = PROPS_XY;
    }
    var x = p2[props[0]] - p1[props[0]],
        y = p2[props[1]] - p1[props[1]];

    return Math.sqrt((x * x) + (y * y));
}

/**
 * calculate the angle between two coordinates
 * @param {Object} p1
 * @param {Object} p2
 * @param {Array} [props] containing x and y keys
 * @return {Number} angle
 */
function getAngle(p1, p2, props) {
    if (!props) {
        props = PROPS_XY;
    }
    var x = p2[props[0]] - p1[props[0]],
        y = p2[props[1]] - p1[props[1]];
    return Math.atan2(y, x) * 180 / Math.PI;
}

/**
 * calculate the rotation degrees between two pointersets
 * @param {Array} start array of pointers
 * @param {Array} end array of pointers
 * @return {Number} rotation
 */
function getRotation(start, end) {
    return getAngle(end[1], end[0], PROPS_CLIENT_XY) + getAngle(start[1], start[0], PROPS_CLIENT_XY);
}

/**
 * calculate the scale factor between two pointersets
 * no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out
 * @param {Array} start array of pointers
 * @param {Array} end array of pointers
 * @return {Number} scale
 */
function getScale(start, end) {
    return getDistance(end[0], end[1], PROPS_CLIENT_XY) / getDistance(start[0], start[1], PROPS_CLIENT_XY);
}

var MOUSE_INPUT_MAP = {
    mousedown: INPUT_START,
    mousemove: INPUT_MOVE,
    mouseup: INPUT_END
};

var MOUSE_ELEMENT_EVENTS = 'mousedown';
var MOUSE_WINDOW_EVENTS = 'mousemove mouseup';

/**
 * Mouse events input
 * @constructor
 * @extends Input
 */
function MouseInput() {
    this.evEl = MOUSE_ELEMENT_EVENTS;
    this.evWin = MOUSE_WINDOW_EVENTS;

    this.pressed = false; // mousedown state

    Input.apply(this, arguments);
}

inherit(MouseInput, Input, {
    /**
     * handle mouse events
     * @param {Object} ev
     */
    handler: function MEhandler(ev) {
        var eventType = MOUSE_INPUT_MAP[ev.type];

        // on start we want to have the left mouse button down
        if (eventType & INPUT_START && ev.button === 0) {
            this.pressed = true;
        }

        if (eventType & INPUT_MOVE && ev.which !== 1) {
            eventType = INPUT_END;
        }

        // mouse must be down
        if (!this.pressed) {
            return;
        }

        if (eventType & INPUT_END) {
            this.pressed = false;
        }

        this.callback(this.manager, eventType, {
            pointers: [ev],
            changedPointers: [ev],
            pointerType: INPUT_TYPE_MOUSE,
            srcEvent: ev
        });
    }
});

var POINTER_INPUT_MAP = {
    pointerdown: INPUT_START,
    pointermove: INPUT_MOVE,
    pointerup: INPUT_END,
    pointercancel: INPUT_CANCEL,
    pointerout: INPUT_CANCEL
};

// in IE10 the pointer types is defined as an enum
var IE10_POINTER_TYPE_ENUM = {
    2: INPUT_TYPE_TOUCH,
    3: INPUT_TYPE_PEN,
    4: INPUT_TYPE_MOUSE,
    5: INPUT_TYPE_KINECT // see https://twitter.com/jacobrossi/status/480596438489890816
};

var POINTER_ELEMENT_EVENTS = 'pointerdown';
var POINTER_WINDOW_EVENTS = 'pointermove pointerup pointercancel';

// IE10 has prefixed support, and case-sensitive
if (window.MSPointerEvent && !window.PointerEvent) {
    POINTER_ELEMENT_EVENTS = 'MSPointerDown';
    POINTER_WINDOW_EVENTS = 'MSPointerMove MSPointerUp MSPointerCancel';
}

/**
 * Pointer events input
 * @constructor
 * @extends Input
 */
function PointerEventInput() {
    this.evEl = POINTER_ELEMENT_EVENTS;
    this.evWin = POINTER_WINDOW_EVENTS;

    Input.apply(this, arguments);

    this.store = (this.manager.session.pointerEvents = []);
}

inherit(PointerEventInput, Input, {
    /**
     * handle mouse events
     * @param {Object} ev
     */
    handler: function PEhandler(ev) {
        var store = this.store;
        var removePointer = false;

        var eventTypeNormalized = ev.type.toLowerCase().replace('ms', '');
        var eventType = POINTER_INPUT_MAP[eventTypeNormalized];
        var pointerType = IE10_POINTER_TYPE_ENUM[ev.pointerType] || ev.pointerType;

        var isTouch = (pointerType == INPUT_TYPE_TOUCH);

        // get index of the event in the store
        var storeIndex = inArray(store, ev.pointerId, 'pointerId');

        // start and mouse must be down
        if (eventType & INPUT_START && (ev.button === 0 || isTouch)) {
            if (storeIndex < 0) {
                store.push(ev);
                storeIndex = store.length - 1;
            }
        } else if (eventType & (INPUT_END | INPUT_CANCEL)) {
            removePointer = true;
        }

        // it not found, so the pointer hasn't been down (so it's probably a hover)
        if (storeIndex < 0) {
            return;
        }

        // update the event in the store
        store[storeIndex] = ev;

        this.callback(this.manager, eventType, {
            pointers: store,
            changedPointers: [ev],
            pointerType: pointerType,
            srcEvent: ev
        });

        if (removePointer) {
            // remove from the store
            store.splice(storeIndex, 1);
        }
    }
});

var SINGLE_TOUCH_INPUT_MAP = {
    touchstart: INPUT_START,
    touchmove: INPUT_MOVE,
    touchend: INPUT_END,
    touchcancel: INPUT_CANCEL
};

var SINGLE_TOUCH_TARGET_EVENTS = 'touchstart';
var SINGLE_TOUCH_WINDOW_EVENTS = 'touchstart touchmove touchend touchcancel';

/**
 * Touch events input
 * @constructor
 * @extends Input
 */
function SingleTouchInput() {
    this.evTarget = SINGLE_TOUCH_TARGET_EVENTS;
    this.evWin = SINGLE_TOUCH_WINDOW_EVENTS;
    this.started = false;

    Input.apply(this, arguments);
}

inherit(SingleTouchInput, Input, {
    handler: function TEhandler(ev) {
        var type = SINGLE_TOUCH_INPUT_MAP[ev.type];

        // should we handle the touch events?
        if (type === INPUT_START) {
            this.started = true;
        }

        if (!this.started) {
            return;
        }

        var touches = normalizeSingleTouches.call(this, ev, type);

        // when done, reset the started state
        if (type & (INPUT_END | INPUT_CANCEL) && touches[0].length - touches[1].length === 0) {
            this.started = false;
        }

        this.callback(this.manager, type, {
            pointers: touches[0],
            changedPointers: touches[1],
            pointerType: INPUT_TYPE_TOUCH,
            srcEvent: ev
        });
    }
});

/**
 * @this {TouchInput}
 * @param {Object} ev
 * @param {Number} type flag
 * @returns {undefined|Array} [all, changed]
 */
function normalizeSingleTouches(ev, type) {
    var all = toArray(ev.touches);
    var changed = toArray(ev.changedTouches);

    if (type & (INPUT_END | INPUT_CANCEL)) {
        all = uniqueArray(all.concat(changed), 'identifier', true);
    }

    return [all, changed];
}

var TOUCH_INPUT_MAP = {
    touchstart: INPUT_START,
    touchmove: INPUT_MOVE,
    touchend: INPUT_END,
    touchcancel: INPUT_CANCEL
};

var TOUCH_TARGET_EVENTS = 'touchstart touchmove touchend touchcancel';

/**
 * Multi-user touch events input
 * @constructor
 * @extends Input
 */
function TouchInput() {
    this.evTarget = TOUCH_TARGET_EVENTS;
    this.targetIds = {};

    Input.apply(this, arguments);
}

inherit(TouchInput, Input, {
    handler: function MTEhandler(ev) {
        var type = TOUCH_INPUT_MAP[ev.type];
        var touches = getTouches.call(this, ev, type);
        if (!touches) {
            return;
        }

        this.callback(this.manager, type, {
            pointers: touches[0],
            changedPointers: touches[1],
            pointerType: INPUT_TYPE_TOUCH,
            srcEvent: ev
        });
    }
});

/**
 * @this {TouchInput}
 * @param {Object} ev
 * @param {Number} type flag
 * @returns {undefined|Array} [all, changed]
 */
function getTouches(ev, type) {
    var allTouches = toArray(ev.touches);
    var targetIds = this.targetIds;

    // when there is only one touch, the process can be simplified
    if (type & (INPUT_START | INPUT_MOVE) && allTouches.length === 1) {
        targetIds[allTouches[0].identifier] = true;
        return [allTouches, allTouches];
    }

    var i,
        targetTouches,
        changedTouches = toArray(ev.changedTouches),
        changedTargetTouches = [],
        target = this.target;

    // get target touches from touches
    targetTouches = allTouches.filter(function(touch) {
        return hasParent(touch.target, target);
    });

    // collect touches
    if (type === INPUT_START) {
        i = 0;
        while (i < targetTouches.length) {
            targetIds[targetTouches[i].identifier] = true;
            i++;
        }
    }

    // filter changed touches to only contain touches that exist in the collected target ids
    i = 0;
    while (i < changedTouches.length) {
        if (targetIds[changedTouches[i].identifier]) {
            changedTargetTouches.push(changedTouches[i]);
        }

        // cleanup removed touches
        if (type & (INPUT_END | INPUT_CANCEL)) {
            delete targetIds[changedTouches[i].identifier];
        }
        i++;
    }

    if (!changedTargetTouches.length) {
        return;
    }

    return [
        // merge targetTouches with changedTargetTouches so it contains ALL touches, including 'end' and 'cancel'
        uniqueArray(targetTouches.concat(changedTargetTouches), 'identifier', true),
        changedTargetTouches
    ];
}

/**
 * Combined touch and mouse input
 *
 * Touch has a higher priority then mouse, and while touching no mouse events are allowed.
 * This because touch devices also emit mouse events while doing a touch.
 *
 * @constructor
 * @extends Input
 */

var DEDUP_TIMEOUT = 2500;
var DEDUP_DISTANCE = 25;

function TouchMouseInput() {
    Input.apply(this, arguments);

    var handler = bindFn(this.handler, this);
    this.touch = new TouchInput(this.manager, handler);
    this.mouse = new MouseInput(this.manager, handler);

    this.primaryTouch = null;
    this.lastTouches = [];
}

inherit(TouchMouseInput, Input, {
    /**
     * handle mouse and touch events
     * @param {Hammer} manager
     * @param {String} inputEvent
     * @param {Object} inputData
     */
    handler: function TMEhandler(manager, inputEvent, inputData) {
        var isTouch = (inputData.pointerType == INPUT_TYPE_TOUCH),
            isMouse = (inputData.pointerType == INPUT_TYPE_MOUSE);

        if (isMouse && inputData.sourceCapabilities && inputData.sourceCapabilities.firesTouchEvents) {
            return;
        }

        // when we're in a touch event, record touches to  de-dupe synthetic mouse event
        if (isTouch) {
            recordTouches.call(this, inputEvent, inputData);
        } else if (isMouse && isSyntheticEvent.call(this, inputData)) {
            return;
        }

        this.callback(manager, inputEvent, inputData);
    },

    /**
     * remove the event listeners
     */
    destroy: function destroy() {
        this.touch.destroy();
        this.mouse.destroy();
    }
});

function recordTouches(eventType, eventData) {
    if (eventType & INPUT_START) {
        this.primaryTouch = eventData.changedPointers[0].identifier;
        setLastTouch.call(this, eventData);
    } else if (eventType & (INPUT_END | INPUT_CANCEL)) {
        setLastTouch.call(this, eventData);
    }
}

function setLastTouch(eventData) {
    var touch = eventData.changedPointers[0];

    if (touch.identifier === this.primaryTouch) {
        var lastTouch = {x: touch.clientX, y: touch.clientY};
        this.lastTouches.push(lastTouch);
        var lts = this.lastTouches;
        var removeLastTouch = function() {
            var i = lts.indexOf(lastTouch);
            if (i > -1) {
                lts.splice(i, 1);
            }
        };
        setTimeout(removeLastTouch, DEDUP_TIMEOUT);
    }
}

function isSyntheticEvent(eventData) {
    var x = eventData.srcEvent.clientX, y = eventData.srcEvent.clientY;
    for (var i = 0; i < this.lastTouches.length; i++) {
        var t = this.lastTouches[i];
        var dx = Math.abs(x - t.x), dy = Math.abs(y - t.y);
        if (dx <= DEDUP_DISTANCE && dy <= DEDUP_DISTANCE) {
            return true;
        }
    }
    return false;
}

var PREFIXED_TOUCH_ACTION = prefixed(TEST_ELEMENT.style, 'touchAction');
var NATIVE_TOUCH_ACTION = PREFIXED_TOUCH_ACTION !== undefined;

// magical touchAction value
var TOUCH_ACTION_COMPUTE = 'compute';
var TOUCH_ACTION_AUTO = 'auto';
var TOUCH_ACTION_MANIPULATION = 'manipulation'; // not implemented
var TOUCH_ACTION_NONE = 'none';
var TOUCH_ACTION_PAN_X = 'pan-x';
var TOUCH_ACTION_PAN_Y = 'pan-y';
var TOUCH_ACTION_MAP = getTouchActionProps();

/**
 * Touch Action
 * sets the touchAction property or uses the js alternative
 * @param {Manager} manager
 * @param {String} value
 * @constructor
 */
function TouchAction(manager, value) {
    this.manager = manager;
    this.set(value);
}

TouchAction.prototype = {
    /**
     * set the touchAction value on the element or enable the polyfill
     * @param {String} value
     */
    set: function(value) {
        // find out the touch-action by the event handlers
        if (value == TOUCH_ACTION_COMPUTE) {
            value = this.compute();
        }

        if (NATIVE_TOUCH_ACTION && this.manager.element.style && TOUCH_ACTION_MAP[value]) {
            this.manager.element.style[PREFIXED_TOUCH_ACTION] = value;
        }
        this.actions = value.toLowerCase().trim();
    },

    /**
     * just re-set the touchAction value
     */
    update: function() {
        this.set(this.manager.options.touchAction);
    },

    /**
     * compute the value for the touchAction property based on the recognizer's settings
     * @returns {String} value
     */
    compute: function() {
        var actions = [];
        each(this.manager.recognizers, function(recognizer) {
            if (boolOrFn(recognizer.options.enable, [recognizer])) {
                actions = actions.concat(recognizer.getTouchAction());
            }
        });
        return cleanTouchActions(actions.join(' '));
    },

    /**
     * this method is called on each input cycle and provides the preventing of the browser behavior
     * @param {Object} input
     */
    preventDefaults: function(input) {
        var srcEvent = input.srcEvent;
        var direction = input.offsetDirection;

        // if the touch action did prevented once this session
        if (this.manager.session.prevented) {
            srcEvent.preventDefault();
            return;
        }

        var actions = this.actions;
        var hasNone = inStr(actions, TOUCH_ACTION_NONE) && !TOUCH_ACTION_MAP[TOUCH_ACTION_NONE];
        var hasPanY = inStr(actions, TOUCH_ACTION_PAN_Y) && !TOUCH_ACTION_MAP[TOUCH_ACTION_PAN_Y];
        var hasPanX = inStr(actions, TOUCH_ACTION_PAN_X) && !TOUCH_ACTION_MAP[TOUCH_ACTION_PAN_X];

        if (hasNone) {
            //do not prevent defaults if this is a tap gesture

            var isTapPointer = input.pointers.length === 1;
            var isTapMovement = input.distance < 2;
            var isTapTouchTime = input.deltaTime < 250;

            if (isTapPointer && isTapMovement && isTapTouchTime) {
                return;
            }
        }

        if (hasPanX && hasPanY) {
            // `pan-x pan-y` means browser handles all scrolling/panning, do not prevent
            return;
        }

        if (hasNone ||
            (hasPanY && direction & DIRECTION_HORIZONTAL) ||
            (hasPanX && direction & DIRECTION_VERTICAL)) {
            return this.preventSrc(srcEvent);
        }
    },

    /**
     * call preventDefault to prevent the browser's default behavior (scrolling in most cases)
     * @param {Object} srcEvent
     */
    preventSrc: function(srcEvent) {
        this.manager.session.prevented = true;
        srcEvent.preventDefault();
    }
};

/**
 * when the touchActions are collected they are not a valid value, so we need to clean things up. *
 * @param {String} actions
 * @returns {*}
 */
function cleanTouchActions(actions) {
    // none
    if (inStr(actions, TOUCH_ACTION_NONE)) {
        return TOUCH_ACTION_NONE;
    }

    var hasPanX = inStr(actions, TOUCH_ACTION_PAN_X);
    var hasPanY = inStr(actions, TOUCH_ACTION_PAN_Y);

    // if both pan-x and pan-y are set (different recognizers
    // for different directions, e.g. horizontal pan but vertical swipe?)
    // we need none (as otherwise with pan-x pan-y combined none of these
    // recognizers will work, since the browser would handle all panning
    if (hasPanX && hasPanY) {
        return TOUCH_ACTION_NONE;
    }

    // pan-x OR pan-y
    if (hasPanX || hasPanY) {
        return hasPanX ? TOUCH_ACTION_PAN_X : TOUCH_ACTION_PAN_Y;
    }

    // manipulation
    if (inStr(actions, TOUCH_ACTION_MANIPULATION)) {
        return TOUCH_ACTION_MANIPULATION;
    }

    return TOUCH_ACTION_AUTO;
}

function getTouchActionProps() {
    if (!NATIVE_TOUCH_ACTION) {
        return false;
    }
    var touchMap = {};
    var cssSupports = window.CSS && window.CSS.supports;
    ['auto', 'manipulation', 'pan-y', 'pan-x', 'pan-x pan-y', 'none'].forEach(function(val) {

        // If css.supports is not supported but there is native touch-action assume it supports
        // all values. This is the case for IE 10 and 11.
        touchMap[val] = cssSupports ? window.CSS.supports('touch-action', val) : true;
    });
    return touchMap;
}

/**
 * Recognizer flow explained; *
 * All recognizers have the initial state of POSSIBLE when a input session starts.
 * The definition of a input session is from the first input until the last input, with all it's movement in it. *
 * Example session for mouse-input: mousedown -> mousemove -> mouseup
 *
 * On each recognizing cycle (see Manager.recognize) the .recognize() method is executed
 * which determines with state it should be.
 *
 * If the recognizer has the state FAILED, CANCELLED or RECOGNIZED (equals ENDED), it is reset to
 * POSSIBLE to give it another change on the next cycle.
 *
 *               Possible
 *                  |
 *            +-----+---------------+
 *            |                     |
 *      +-----+-----+               |
 *      |           |               |
 *   Failed      Cancelled          |
 *                          +-------+------+
 *                          |              |
 *                      Recognized       Began
 *                                         |
 *                                      Changed
 *                                         |
 *                                  Ended/Recognized
 */
var STATE_POSSIBLE = 1;
var STATE_BEGAN = 2;
var STATE_CHANGED = 4;
var STATE_ENDED = 8;
var STATE_RECOGNIZED = STATE_ENDED;
var STATE_CANCELLED = 16;
var STATE_FAILED = 32;

/**
 * Recognizer
 * Every recognizer needs to extend from this class.
 * @constructor
 * @param {Object} options
 */
function Recognizer(options) {
    this.options = assign({}, this.defaults, options || {});

    this.id = uniqueId();

    this.manager = null;

    // default is enable true
    this.options.enable = ifUndefined(this.options.enable, true);

    this.state = STATE_POSSIBLE;

    this.simultaneous = {};
    this.requireFail = [];
}

Recognizer.prototype = {
    /**
     * @virtual
     * @type {Object}
     */
    defaults: {},

    /**
     * set options
     * @param {Object} options
     * @return {Recognizer}
     */
    set: function(options) {
        assign(this.options, options);

        // also update the touchAction, in case something changed about the directions/enabled state
        this.manager && this.manager.touchAction.update();
        return this;
    },

    /**
     * recognize simultaneous with an other recognizer.
     * @param {Recognizer} otherRecognizer
     * @returns {Recognizer} this
     */
    recognizeWith: function(otherRecognizer) {
        if (invokeArrayArg(otherRecognizer, 'recognizeWith', this)) {
            return this;
        }

        var simultaneous = this.simultaneous;
        otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this);
        if (!simultaneous[otherRecognizer.id]) {
            simultaneous[otherRecognizer.id] = otherRecognizer;
            otherRecognizer.recognizeWith(this);
        }
        return this;
    },

    /**
     * drop the simultaneous link. it doesnt remove the link on the other recognizer.
     * @param {Recognizer} otherRecognizer
     * @returns {Recognizer} this
     */
    dropRecognizeWith: function(otherRecognizer) {
        if (invokeArrayArg(otherRecognizer, 'dropRecognizeWith', this)) {
            return this;
        }

        otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this);
        delete this.simultaneous[otherRecognizer.id];
        return this;
    },

    /**
     * recognizer can only run when an other is failing
     * @param {Recognizer} otherRecognizer
     * @returns {Recognizer} this
     */
    requireFailure: function(otherRecognizer) {
        if (invokeArrayArg(otherRecognizer, 'requireFailure', this)) {
            return this;
        }

        var requireFail = this.requireFail;
        otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this);
        if (inArray(requireFail, otherRecognizer) === -1) {
            requireFail.push(otherRecognizer);
            otherRecognizer.requireFailure(this);
        }
        return this;
    },

    /**
     * drop the requireFailure link. it does not remove the link on the other recognizer.
     * @param {Recognizer} otherRecognizer
     * @returns {Recognizer} this
     */
    dropRequireFailure: function(otherRecognizer) {
        if (invokeArrayArg(otherRecognizer, 'dropRequireFailure', this)) {
            return this;
        }

        otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this);
        var index = inArray(this.requireFail, otherRecognizer);
        if (index > -1) {
            this.requireFail.splice(index, 1);
        }
        return this;
    },

    /**
     * has require failures boolean
     * @returns {boolean}
     */
    hasRequireFailures: function() {
        return this.requireFail.length > 0;
    },

    /**
     * if the recognizer can recognize simultaneous with an other recognizer
     * @param {Recognizer} otherRecognizer
     * @returns {Boolean}
     */
    canRecognizeWith: function(otherRecognizer) {
        return !!this.simultaneous[otherRecognizer.id];
    },

    /**
     * You should use `tryEmit` instead of `emit` directly to check
     * that all the needed recognizers has failed before emitting.
     * @param {Object} input
     */
    emit: function(input) {
        var self = this;
        var state = this.state;

        function emit(event) {
            self.manager.emit(event, input);
        }

        // 'panstart' and 'panmove'
        if (state < STATE_ENDED) {
            emit(self.options.event + stateStr(state));
        }

        emit(self.options.event); // simple 'eventName' events

        if (input.additionalEvent) { // additional event(panleft, panright, pinchin, pinchout...)
            emit(input.additionalEvent);
        }

        // panend and pancancel
        if (state >= STATE_ENDED) {
            emit(self.options.event + stateStr(state));
        }
    },

    /**
     * Check that all the require failure recognizers has failed,
     * if true, it emits a gesture event,
     * otherwise, setup the state to FAILED.
     * @param {Object} input
     */
    tryEmit: function(input) {
        if (this.canEmit()) {
            return this.emit(input);
        }
        // it's failing anyway
        this.state = STATE_FAILED;
    },

    /**
     * can we emit?
     * @returns {boolean}
     */
    canEmit: function() {
        var i = 0;
        while (i < this.requireFail.length) {
            if (!(this.requireFail[i].state & (STATE_FAILED | STATE_POSSIBLE))) {
                return false;
            }
            i++;
        }
        return true;
    },

    /**
     * update the recognizer
     * @param {Object} inputData
     */
    recognize: function(inputData) {
        // make a new copy of the inputData
        // so we can change the inputData without messing up the other recognizers
        var inputDataClone = assign({}, inputData);

        // is is enabled and allow recognizing?
        if (!boolOrFn(this.options.enable, [this, inputDataClone])) {
            this.reset();
            this.state = STATE_FAILED;
            return;
        }

        // reset when we've reached the end
        if (this.state & (STATE_RECOGNIZED | STATE_CANCELLED | STATE_FAILED)) {
            this.state = STATE_POSSIBLE;
        }

        this.state = this.process(inputDataClone);

        // the recognizer has recognized a gesture
        // so trigger an event
        if (this.state & (STATE_BEGAN | STATE_CHANGED | STATE_ENDED | STATE_CANCELLED)) {
            this.tryEmit(inputDataClone);
        }
    },

    /**
     * return the state of the recognizer
     * the actual recognizing happens in this method
     * @virtual
     * @param {Object} inputData
     * @returns {Const} STATE
     */
    process: function(inputData) { }, // jshint ignore:line

    /**
     * return the preferred touch-action
     * @virtual
     * @returns {Array}
     */
    getTouchAction: function() { },

    /**
     * called when the gesture isn't allowed to recognize
     * like when another is being recognized or it is disabled
     * @virtual
     */
    reset: function() { }
};

/**
 * get a usable string, used as event postfix
 * @param {Const} state
 * @returns {String} state
 */
function stateStr(state) {
    if (state & STATE_CANCELLED) {
        return 'cancel';
    } else if (state & STATE_ENDED) {
        return 'end';
    } else if (state & STATE_CHANGED) {
        return 'move';
    } else if (state & STATE_BEGAN) {
        return 'start';
    }
    return '';
}

/**
 * direction cons to string
 * @param {Const} direction
 * @returns {String}
 */
function directionStr(direction) {
    if (direction == DIRECTION_DOWN) {
        return 'down';
    } else if (direction == DIRECTION_UP) {
        return 'up';
    } else if (direction == DIRECTION_LEFT) {
        return 'left';
    } else if (direction == DIRECTION_RIGHT) {
        return 'right';
    }
    return '';
}

/**
 * get a recognizer by name if it is bound to a manager
 * @param {Recognizer|String} otherRecognizer
 * @param {Recognizer} recognizer
 * @returns {Recognizer}
 */
function getRecognizerByNameIfManager(otherRecognizer, recognizer) {
    var manager = recognizer.manager;
    if (manager) {
        return manager.get(otherRecognizer);
    }
    return otherRecognizer;
}

/**
 * This recognizer is just used as a base for the simple attribute recognizers.
 * @constructor
 * @extends Recognizer
 */
function AttrRecognizer() {
    Recognizer.apply(this, arguments);
}

inherit(AttrRecognizer, Recognizer, {
    /**
     * @namespace
     * @memberof AttrRecognizer
     */
    defaults: {
        /**
         * @type {Number}
         * @default 1
         */
        pointers: 1
    },

    /**
     * Used to check if it the recognizer receives valid input, like input.distance > 10.
     * @memberof AttrRecognizer
     * @param {Object} input
     * @returns {Boolean} recognized
     */
    attrTest: function(input) {
        var optionPointers = this.options.pointers;
        return optionPointers === 0 || input.pointers.length === optionPointers;
    },

    /**
     * Process the input and return the state for the recognizer
     * @memberof AttrRecognizer
     * @param {Object} input
     * @returns {*} State
     */
    process: function(input) {
        var state = this.state;
        var eventType = input.eventType;

        var isRecognized = state & (STATE_BEGAN | STATE_CHANGED);
        var isValid = this.attrTest(input);

        // on cancel input and we've recognized before, return STATE_CANCELLED
        if (isRecognized && (eventType & INPUT_CANCEL || !isValid)) {
            return state | STATE_CANCELLED;
        } else if (isRecognized || isValid) {
            if (eventType & INPUT_END) {
                return state | STATE_ENDED;
            } else if (!(state & STATE_BEGAN)) {
                return STATE_BEGAN;
            }
            return state | STATE_CHANGED;
        }
        return STATE_FAILED;
    }
});

/**
 * Pan
 * Recognized when the pointer is down and moved in the allowed direction.
 * @constructor
 * @extends AttrRecognizer
 */
function PanRecognizer() {
    AttrRecognizer.apply(this, arguments);

    this.pX = null;
    this.pY = null;
}

inherit(PanRecognizer, AttrRecognizer, {
    /**
     * @namespace
     * @memberof PanRecognizer
     */
    defaults: {
        event: 'pan',
        threshold: 10,
        pointers: 1,
        direction: DIRECTION_ALL
    },

    getTouchAction: function() {
        var direction = this.options.direction;
        var actions = [];
        if (direction & DIRECTION_HORIZONTAL) {
            actions.push(TOUCH_ACTION_PAN_Y);
        }
        if (direction & DIRECTION_VERTICAL) {
            actions.push(TOUCH_ACTION_PAN_X);
        }
        return actions;
    },

    directionTest: function(input) {
        var options = this.options;
        var hasMoved = true;
        var distance = input.distance;
        var direction = input.direction;
        var x = input.deltaX;
        var y = input.deltaY;

        // lock to axis?
        if (!(direction & options.direction)) {
            if (options.direction & DIRECTION_HORIZONTAL) {
                direction = (x === 0) ? DIRECTION_NONE : (x < 0) ? DIRECTION_LEFT : DIRECTION_RIGHT;
                hasMoved = x != this.pX;
                distance = Math.abs(input.deltaX);
            } else {
                direction = (y === 0) ? DIRECTION_NONE : (y < 0) ? DIRECTION_UP : DIRECTION_DOWN;
                hasMoved = y != this.pY;
                distance = Math.abs(input.deltaY);
            }
        }
        input.direction = direction;
        return hasMoved && distance > options.threshold && direction & options.direction;
    },

    attrTest: function(input) {
        return AttrRecognizer.prototype.attrTest.call(this, input) &&
            (this.state & STATE_BEGAN || (!(this.state & STATE_BEGAN) && this.directionTest(input)));
    },

    emit: function(input) {

        this.pX = input.deltaX;
        this.pY = input.deltaY;

        var direction = directionStr(input.direction);

        if (direction) {
            input.additionalEvent = this.options.event + direction;
        }
        this._super.emit.call(this, input);
    }
});

/**
 * Pinch
 * Recognized when two or more pointers are moving toward (zoom-in) or away from each other (zoom-out).
 * @constructor
 * @extends AttrRecognizer
 */
function PinchRecognizer() {
    AttrRecognizer.apply(this, arguments);
}

inherit(PinchRecognizer, AttrRecognizer, {
    /**
     * @namespace
     * @memberof PinchRecognizer
     */
    defaults: {
        event: 'pinch',
        threshold: 0,
        pointers: 2
    },

    getTouchAction: function() {
        return [TOUCH_ACTION_NONE];
    },

    attrTest: function(input) {
        return this._super.attrTest.call(this, input) &&
            (Math.abs(input.scale - 1) > this.options.threshold || this.state & STATE_BEGAN);
    },

    emit: function(input) {
        if (input.scale !== 1) {
            var inOut = input.scale < 1 ? 'in' : 'out';
            input.additionalEvent = this.options.event + inOut;
        }
        this._super.emit.call(this, input);
    }
});

/**
 * Press
 * Recognized when the pointer is down for x ms without any movement.
 * @constructor
 * @extends Recognizer
 */
function PressRecognizer() {
    Recognizer.apply(this, arguments);

    this._timer = null;
    this._input = null;
}

inherit(PressRecognizer, Recognizer, {
    /**
     * @namespace
     * @memberof PressRecognizer
     */
    defaults: {
        event: 'press',
        pointers: 1,
        time: 251, // minimal time of the pointer to be pressed
        threshold: 9 // a minimal movement is ok, but keep it low
    },

    getTouchAction: function() {
        return [TOUCH_ACTION_AUTO];
    },

    process: function(input) {
        var options = this.options;
        var validPointers = input.pointers.length === options.pointers;
        var validMovement = input.distance < options.threshold;
        var validTime = input.deltaTime > options.time;

        this._input = input;

        // we only allow little movement
        // and we've reached an end event, so a tap is possible
        if (!validMovement || !validPointers || (input.eventType & (INPUT_END | INPUT_CANCEL) && !validTime)) {
            this.reset();
        } else if (input.eventType & INPUT_START) {
            this.reset();
            this._timer = setTimeoutContext(function() {
                this.state = STATE_RECOGNIZED;
                this.tryEmit();
            }, options.time, this);
        } else if (input.eventType & INPUT_END) {
            return STATE_RECOGNIZED;
        }
        return STATE_FAILED;
    },

    reset: function() {
        clearTimeout(this._timer);
    },

    emit: function(input) {
        if (this.state !== STATE_RECOGNIZED) {
            return;
        }

        if (input && (input.eventType & INPUT_END)) {
            this.manager.emit(this.options.event + 'up', input);
        } else {
            this._input.timeStamp = now();
            this.manager.emit(this.options.event, this._input);
        }
    }
});

/**
 * Rotate
 * Recognized when two or more pointer are moving in a circular motion.
 * @constructor
 * @extends AttrRecognizer
 */
function RotateRecognizer() {
    AttrRecognizer.apply(this, arguments);
}

inherit(RotateRecognizer, AttrRecognizer, {
    /**
     * @namespace
     * @memberof RotateRecognizer
     */
    defaults: {
        event: 'rotate',
        threshold: 0,
        pointers: 2
    },

    getTouchAction: function() {
        return [TOUCH_ACTION_NONE];
    },

    attrTest: function(input) {
        return this._super.attrTest.call(this, input) &&
            (Math.abs(input.rotation) > this.options.threshold || this.state & STATE_BEGAN);
    }
});

/**
 * Swipe
 * Recognized when the pointer is moving fast (velocity), with enough distance in the allowed direction.
 * @constructor
 * @extends AttrRecognizer
 */
function SwipeRecognizer() {
    AttrRecognizer.apply(this, arguments);
}

inherit(SwipeRecognizer, AttrRecognizer, {
    /**
     * @namespace
     * @memberof SwipeRecognizer
     */
    defaults: {
        event: 'swipe',
        threshold: 10,
        velocity: 0.3,
        direction: DIRECTION_HORIZONTAL | DIRECTION_VERTICAL,
        pointers: 1
    },

    getTouchAction: function() {
        return PanRecognizer.prototype.getTouchAction.call(this);
    },

    attrTest: function(input) {
        var direction = this.options.direction;
        var velocity;

        if (direction & (DIRECTION_HORIZONTAL | DIRECTION_VERTICAL)) {
            velocity = input.overallVelocity;
        } else if (direction & DIRECTION_HORIZONTAL) {
            velocity = input.overallVelocityX;
        } else if (direction & DIRECTION_VERTICAL) {
            velocity = input.overallVelocityY;
        }

        return this._super.attrTest.call(this, input) &&
            direction & input.offsetDirection &&
            input.distance > this.options.threshold &&
            input.maxPointers == this.options.pointers &&
            abs(velocity) > this.options.velocity && input.eventType & INPUT_END;
    },

    emit: function(input) {
        var direction = directionStr(input.offsetDirection);
        if (direction) {
            this.manager.emit(this.options.event + direction, input);
        }

        this.manager.emit(this.options.event, input);
    }
});

/**
 * A tap is ecognized when the pointer is doing a small tap/click. Multiple taps are recognized if they occur
 * between the given interval and position. The delay option can be used to recognize multi-taps without firing
 * a single tap.
 *
 * The eventData from the emitted event contains the property `tapCount`, which contains the amount of
 * multi-taps being recognized.
 * @constructor
 * @extends Recognizer
 */
function TapRecognizer() {
    Recognizer.apply(this, arguments);

    // previous time and center,
    // used for tap counting
    this.pTime = false;
    this.pCenter = false;

    this._timer = null;
    this._input = null;
    this.count = 0;
}

inherit(TapRecognizer, Recognizer, {
    /**
     * @namespace
     * @memberof PinchRecognizer
     */
    defaults: {
        event: 'tap',
        pointers: 1,
        taps: 1,
        interval: 300, // max time between the multi-tap taps
        time: 250, // max time of the pointer to be down (like finger on the screen)
        threshold: 9, // a minimal movement is ok, but keep it low
        posThreshold: 10 // a multi-tap can be a bit off the initial position
    },

    getTouchAction: function() {
        return [TOUCH_ACTION_MANIPULATION];
    },

    process: function(input) {
        var options = this.options;

        var validPointers = input.pointers.length === options.pointers;
        var validMovement = input.distance < options.threshold;
        var validTouchTime = input.deltaTime < options.time;

        this.reset();

        if ((input.eventType & INPUT_START) && (this.count === 0)) {
            return this.failTimeout();
        }

        // we only allow little movement
        // and we've reached an end event, so a tap is possible
        if (validMovement && validTouchTime && validPointers) {
            if (input.eventType != INPUT_END) {
                return this.failTimeout();
            }

            var validInterval = this.pTime ? (input.timeStamp - this.pTime < options.interval) : true;
            var validMultiTap = !this.pCenter || getDistance(this.pCenter, input.center) < options.posThreshold;

            this.pTime = input.timeStamp;
            this.pCenter = input.center;

            if (!validMultiTap || !validInterval) {
                this.count = 1;
            } else {
                this.count += 1;
            }

            this._input = input;

            // if tap count matches we have recognized it,
            // else it has began recognizing...
            var tapCount = this.count % options.taps;
            if (tapCount === 0) {
                // no failing requirements, immediately trigger the tap event
                // or wait as long as the multitap interval to trigger
                if (!this.hasRequireFailures()) {
                    return STATE_RECOGNIZED;
                } else {
                    this._timer = setTimeoutContext(function() {
                        this.state = STATE_RECOGNIZED;
                        this.tryEmit();
                    }, options.interval, this);
                    return STATE_BEGAN;
                }
            }
        }
        return STATE_FAILED;
    },

    failTimeout: function() {
        this._timer = setTimeoutContext(function() {
            this.state = STATE_FAILED;
        }, this.options.interval, this);
        return STATE_FAILED;
    },

    reset: function() {
        clearTimeout(this._timer);
    },

    emit: function() {
        if (this.state == STATE_RECOGNIZED) {
            this._input.tapCount = this.count;
            this.manager.emit(this.options.event, this._input);
        }
    }
});

/**
 * Simple way to create a manager with a default set of recognizers.
 * @param {HTMLElement} element
 * @param {Object} [options]
 * @constructor
 */
function Hammer(element, options) {
    options = options || {};
    options.recognizers = ifUndefined(options.recognizers, Hammer.defaults.preset);
    return new Manager(element, options);
}

/**
 * @const {string}
 */
Hammer.VERSION = '2.0.8';

/**
 * default settings
 * @namespace
 */
Hammer.defaults = {
    /**
     * set if DOM events are being triggered.
     * But this is slower and unused by simple implementations, so disabled by default.
     * @type {Boolean}
     * @default false
     */
    domEvents: false,

    /**
     * The value for the touchAction property/fallback.
     * When set to `compute` it will magically set the correct value based on the added recognizers.
     * @type {String}
     * @default compute
     */
    touchAction: TOUCH_ACTION_COMPUTE,

    /**
     * @type {Boolean}
     * @default true
     */
    enable: true,

    /**
     * EXPERIMENTAL FEATURE -- can be removed/changed
     * Change the parent input target element.
     * If Null, then it is being set the to main element.
     * @type {Null|EventTarget}
     * @default null
     */
    inputTarget: null,

    /**
     * force an input class
     * @type {Null|Function}
     * @default null
     */
    inputClass: null,

    /**
     * Default recognizer setup when calling `Hammer()`
     * When creating a new Manager these will be skipped.
     * @type {Array}
     */
    preset: [
        // RecognizerClass, options, [recognizeWith, ...], [requireFailure, ...]
        [RotateRecognizer, {enable: false}],
        [PinchRecognizer, {enable: false}, ['rotate']],
        [SwipeRecognizer, {direction: DIRECTION_HORIZONTAL}],
        [PanRecognizer, {direction: DIRECTION_HORIZONTAL}, ['swipe']],
        [TapRecognizer],
        [TapRecognizer, {event: 'doubletap', taps: 2}, ['tap']],
        [PressRecognizer]
    ],

    /**
     * Some CSS properties can be used to improve the working of Hammer.
     * Add them to this method and they will be set when creating a new Manager.
     * @namespace
     */
    cssProps: {
        /**
         * Disables text selection to improve the dragging gesture. Mainly for desktop browsers.
         * @type {String}
         * @default 'none'
         */
        userSelect: 'none',

        /**
         * Disable the Windows Phone grippers when pressing an element.
         * @type {String}
         * @default 'none'
         */
        touchSelect: 'none',

        /**
         * Disables the default callout shown when you touch and hold a touch target.
         * On iOS, when you touch and hold a touch target such as a link, Safari displays
         * a callout containing information about the link. This property allows you to disable that callout.
         * @type {String}
         * @default 'none'
         */
        touchCallout: 'none',

        /**
         * Specifies whether zooming is enabled. Used by IE10>
         * @type {String}
         * @default 'none'
         */
        contentZooming: 'none',

        /**
         * Specifies that an entire element should be draggable instead of its contents. Mainly for desktop browsers.
         * @type {String}
         * @default 'none'
         */
        userDrag: 'none',

        /**
         * Overrides the highlight color shown when the user taps a link or a JavaScript
         * clickable element in iOS. This property obeys the alpha value, if specified.
         * @type {String}
         * @default 'rgba(0,0,0,0)'
         */
        tapHighlightColor: 'rgba(0,0,0,0)'
    }
};

var STOP = 1;
var FORCED_STOP = 2;

/**
 * Manager
 * @param {HTMLElement} element
 * @param {Object} [options]
 * @constructor
 */
function Manager(element, options) {
    this.options = assign({}, Hammer.defaults, options || {});

    this.options.inputTarget = this.options.inputTarget || element;

    this.handlers = {};
    this.session = {};
    this.recognizers = [];
    this.oldCssProps = {};

    this.element = element;
    this.input = createInputInstance(this);
    this.touchAction = new TouchAction(this, this.options.touchAction);

    toggleCssProps(this, true);

    each(this.options.recognizers, function(item) {
        var recognizer = this.add(new (item[0])(item[1]));
        item[2] && recognizer.recognizeWith(item[2]);
        item[3] && recognizer.requireFailure(item[3]);
    }, this);
}

Manager.prototype = {
    /**
     * set options
     * @param {Object} options
     * @returns {Manager}
     */
    set: function(options) {
        assign(this.options, options);

        // Options that need a little more setup
        if (options.touchAction) {
            this.touchAction.update();
        }
        if (options.inputTarget) {
            // Clean up existing event listeners and reinitialize
            this.input.destroy();
            this.input.target = options.inputTarget;
            this.input.init();
        }
        return this;
    },

    /**
     * stop recognizing for this session.
     * This session will be discarded, when a new [input]start event is fired.
     * When forced, the recognizer cycle is stopped immediately.
     * @param {Boolean} [force]
     */
    stop: function(force) {
        this.session.stopped = force ? FORCED_STOP : STOP;
    },

    /**
     * run the recognizers!
     * called by the inputHandler function on every movement of the pointers (touches)
     * it walks through all the recognizers and tries to detect the gesture that is being made
     * @param {Object} inputData
     */
    recognize: function(inputData) {
        var session = this.session;
        if (session.stopped) {
            return;
        }

        // run the touch-action polyfill
        this.touchAction.preventDefaults(inputData);

        var recognizer;
        var recognizers = this.recognizers;

        // this holds the recognizer that is being recognized.
        // so the recognizer's state needs to be BEGAN, CHANGED, ENDED or RECOGNIZED
        // if no recognizer is detecting a thing, it is set to `null`
        var curRecognizer = session.curRecognizer;

        // reset when the last recognizer is recognized
        // or when we're in a new session
        if (!curRecognizer || (curRecognizer && curRecognizer.state & STATE_RECOGNIZED)) {
            curRecognizer = session.curRecognizer = null;
        }

        var i = 0;
        while (i < recognizers.length) {
            recognizer = recognizers[i];

            // find out if we are allowed try to recognize the input for this one.
            // 1.   allow if the session is NOT forced stopped (see the .stop() method)
            // 2.   allow if we still haven't recognized a gesture in this session, or the this recognizer is the one
            //      that is being recognized.
            // 3.   allow if the recognizer is allowed to run simultaneous with the current recognized recognizer.
            //      this can be setup with the `recognizeWith()` method on the recognizer.
            if (session.stopped !== FORCED_STOP && ( // 1
                    !curRecognizer || recognizer == curRecognizer || // 2
                    recognizer.canRecognizeWith(curRecognizer))) { // 3
                recognizer.recognize(inputData);
            } else {
                recognizer.reset();
            }

            // if the recognizer has been recognizing the input as a valid gesture, we want to store this one as the
            // current active recognizer. but only if we don't already have an active recognizer
            if (!curRecognizer && recognizer.state & (STATE_BEGAN | STATE_CHANGED | STATE_ENDED)) {
                curRecognizer = session.curRecognizer = recognizer;
            }
            i++;
        }
    },

    /**
     * get a recognizer by its event name.
     * @param {Recognizer|String} recognizer
     * @returns {Recognizer|Null}
     */
    get: function(recognizer) {
        if (recognizer instanceof Recognizer) {
            return recognizer;
        }

        var recognizers = this.recognizers;
        for (var i = 0; i < recognizers.length; i++) {
            if (recognizers[i].options.event == recognizer) {
                return recognizers[i];
            }
        }
        return null;
    },

    /**
     * add a recognizer to the manager
     * existing recognizers with the same event name will be removed
     * @param {Recognizer} recognizer
     * @returns {Recognizer|Manager}
     */
    add: function(recognizer) {
        if (invokeArrayArg(recognizer, 'add', this)) {
            return this;
        }

        // remove existing
        var existing = this.get(recognizer.options.event);
        if (existing) {
            this.remove(existing);
        }

        this.recognizers.push(recognizer);
        recognizer.manager = this;

        this.touchAction.update();
        return recognizer;
    },

    /**
     * remove a recognizer by name or instance
     * @param {Recognizer|String} recognizer
     * @returns {Manager}
     */
    remove: function(recognizer) {
        if (invokeArrayArg(recognizer, 'remove', this)) {
            return this;
        }

        recognizer = this.get(recognizer);

        // let's make sure this recognizer exists
        if (recognizer) {
            var recognizers = this.recognizers;
            var index = inArray(recognizers, recognizer);

            if (index !== -1) {
                recognizers.splice(index, 1);
                this.touchAction.update();
            }
        }

        return this;
    },

    /**
     * bind event
     * @param {String} events
     * @param {Function} handler
     * @returns {EventEmitter} this
     */
    on: function(events, handler) {
        if (events === undefined) {
            return;
        }
        if (handler === undefined) {
            return;
        }

        var handlers = this.handlers;
        each(splitStr(events), function(event) {
            handlers[event] = handlers[event] || [];
            handlers[event].push(handler);
        });
        return this;
    },

    /**
     * unbind event, leave emit blank to remove all handlers
     * @param {String} events
     * @param {Function} [handler]
     * @returns {EventEmitter} this
     */
    off: function(events, handler) {
        if (events === undefined) {
            return;
        }

        var handlers = this.handlers;
        each(splitStr(events), function(event) {
            if (!handler) {
                delete handlers[event];
            } else {
                handlers[event] && handlers[event].splice(inArray(handlers[event], handler), 1);
            }
        });
        return this;
    },

    /**
     * emit event to the listeners
     * @param {String} event
     * @param {Object} data
     */
    emit: function(event, data) {
        // we also want to trigger dom events
        if (this.options.domEvents) {
            triggerDomEvent(event, data);
        }

        // no handlers, so skip it all
        var handlers = this.handlers[event] && this.handlers[event].slice();
        if (!handlers || !handlers.length) {
            return;
        }

        data.type = event;
        data.preventDefault = function() {
            data.srcEvent.preventDefault();
        };

        var i = 0;
        while (i < handlers.length) {
            handlers[i](data);
            i++;
        }
    },

    /**
     * destroy the manager and unbinds all events
     * it doesn't unbind dom events, that is the user own responsibility
     */
    destroy: function() {
        this.element && toggleCssProps(this, false);

        this.handlers = {};
        this.session = {};
        this.input.destroy();
        this.element = null;
    }
};

/**
 * add/remove the css properties as defined in manager.options.cssProps
 * @param {Manager} manager
 * @param {Boolean} add
 */
function toggleCssProps(manager, add) {
    var element = manager.element;
    if (!element.style) {
        return;
    }
    var prop;
    each(manager.options.cssProps, function(value, name) {
        prop = prefixed(element.style, name);
        if (add) {
            manager.oldCssProps[prop] = element.style[prop];
            element.style[prop] = value;
        } else {
            element.style[prop] = manager.oldCssProps[prop] || '';
        }
    });
    if (!add) {
        manager.oldCssProps = {};
    }
}

/**
 * trigger dom event
 * @param {String} event
 * @param {Object} data
 */
function triggerDomEvent(event, data) {
    var gestureEvent = document.createEvent('Event');
    gestureEvent.initEvent(event, true, true);
    gestureEvent.gesture = data;
    data.target.dispatchEvent(gestureEvent);
}

assign(Hammer, {
    INPUT_START: INPUT_START,
    INPUT_MOVE: INPUT_MOVE,
    INPUT_END: INPUT_END,
    INPUT_CANCEL: INPUT_CANCEL,

    STATE_POSSIBLE: STATE_POSSIBLE,
    STATE_BEGAN: STATE_BEGAN,
    STATE_CHANGED: STATE_CHANGED,
    STATE_ENDED: STATE_ENDED,
    STATE_RECOGNIZED: STATE_RECOGNIZED,
    STATE_CANCELLED: STATE_CANCELLED,
    STATE_FAILED: STATE_FAILED,

    DIRECTION_NONE: DIRECTION_NONE,
    DIRECTION_LEFT: DIRECTION_LEFT,
    DIRECTION_RIGHT: DIRECTION_RIGHT,
    DIRECTION_UP: DIRECTION_UP,
    DIRECTION_DOWN: DIRECTION_DOWN,
    DIRECTION_HORIZONTAL: DIRECTION_HORIZONTAL,
    DIRECTION_VERTICAL: DIRECTION_VERTICAL,
    DIRECTION_ALL: DIRECTION_ALL,

    Manager: Manager,
    Input: Input,
    TouchAction: TouchAction,

    TouchInput: TouchInput,
    MouseInput: MouseInput,
    PointerEventInput: PointerEventInput,
    TouchMouseInput: TouchMouseInput,
    SingleTouchInput: SingleTouchInput,

    Recognizer: Recognizer,
    AttrRecognizer: AttrRecognizer,
    Tap: TapRecognizer,
    Pan: PanRecognizer,
    Swipe: SwipeRecognizer,
    Pinch: PinchRecognizer,
    Rotate: RotateRecognizer,
    Press: PressRecognizer,

    on: addEventListeners,
    off: removeEventListeners,
    each: each,
    merge: merge,
    extend: extend,
    assign: assign,
    inherit: inherit,
    bindFn: bindFn,
    prefixed: prefixed
});

// this prevents errors when Hammer is loaded in the presence of an AMD
//  style loader but by script tag, not by the loader.
var freeGlobal = (typeof window !== 'undefined' ? window : (typeof self !== 'undefined' ? self : {})); // jshint ignore:line
freeGlobal.Hammer = Hammer;

if (typeof define === 'function' && define.amd) {
    define(function() {
        return Hammer;
    });
} else if (typeof module != 'undefined' && module.exports) {
    module.exports = Hammer;
} else {
    window[exportName] = Hammer;
}

})(window, document, 'Hammer');

/*
Copyright (c) 2009 Ben Leslie

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.
*/

/*
 This JavaScript library is used to parse meta-data from files
 with mime-type image/jpeg.

 Include it with something like:

   <script type="text/javascript" src="jpegmeta.js"></script>

 This adds a single 'module' object called 'JpegMeta' to the global
 namespace.

 Public Functions
 ----------------
 JpegMeta.parseNum - parse unsigned integers from binary data
 JpegMeta.parseSnum - parse signed integers from binary data

 Public Classes
 --------------
 JpegMeta.Rational - A rational number class
 JpegMeta.JfifSegment
 JpegMeta.ExifSegment
 JpegMeta.JpegFile - Primary class for Javascript parsing
*/

if (this.JpegMeta) {
    throw Error("Library included multiple times");
}

var JpegMeta = {};

JpegMeta.stringIsClean = function stringIsClean(str) {
    for (var i = 0; i < str.length; i++) {
	if (str.charCodeAt(i) < 0x20) {
	    return false;
	}
    }
    return true;
}

/*
   parse an unsigned number of size bytes at offset in some binary string data.
   If endian
   is "<" parse the data as little endian, if endian
   is ">" parse as big-endian.
*/
JpegMeta.parseNum = function parseNum(endian, data, offset, size) {
    var i;
    var ret;
    var big_endian = (endian === ">");
    if (offset === undefined) offset = 0;
    if (size === undefined) size = data.length - offset;
    for (big_endian ? i = offset : i = offset + size - 1;
	 big_endian ? i < offset + size : i >= offset;
	 big_endian ? i++ : i--) {
	ret <<= 8;
	ret += data.charCodeAt(i);
    }
    return ret;
};

/*
   parse an signed number of size bytes at offset in some binary string data.
   If endian
   is "<" parse the data as little endian, if endian
   is ">" parse as big-endian.
*/
JpegMeta.parseSnum = function parseSnum(endian, data, offset, size) {
    var i;
    var ret;
    var neg;
    var big_endian = (endian === ">");
    if (offset === undefined) offset = 0;
    if (size === undefined) size = data.length - offset;
    for (big_endian ? i = offset : i = offset + size - 1;
	 big_endian ? i < offset + size : i >= offset;
	 big_endian ? i++ : i--) {
	if (neg === undefined) {
	    /* Negative if top bit is set */
	    neg = (data.charCodeAt(i) & 0x80) === 0x80;
	}
	ret <<= 8;
	/* If it is negative we invert the bits */
	ret += neg ? ~data.charCodeAt(i) & 0xff: data.charCodeAt(i);
    }
    if (neg) {
	/* If it is negative we do two's complement */
	ret += 1;
	ret *= -1;
    }
    return ret;
};

/* Rational number class */
JpegMeta.Rational = function Rational(num, den)
{
    this.num = num;
    this.den = den || 1;
    return this;
};

/* Rational number methods */
JpegMeta.Rational.prototype.toString = function toString() {
    if (this.num === 0) {
	return "" + this.num;
    }
    if (this.den === 1) {
	return "" + this.num;
    }
    if (this.num === 1) {
	return this.num + " / " + this.den;
    }
    return this.num / this.den; // + "/" + this.den;
};

JpegMeta.Rational.prototype.asFloat = function asFloat() {
    return this.num / this.den;
};


/* MetaGroup class */
JpegMeta.MetaGroup = function MetaGroup(fieldName, description) {
    this.fieldName = fieldName;
    this.description = description;
    this.metaProps = {};
    return this;
};

JpegMeta.MetaGroup.prototype._addProperty = function _addProperty(fieldName, description, value) {
    var property = new JpegMeta.MetaProp(fieldName, description, value);
    this[property.fieldName] = property;
    this.metaProps[property.fieldName] = property;
};

JpegMeta.MetaGroup.prototype.toString = function toString() {
    return "[MetaGroup " + this.description + "]";
};


/* MetaProp class */
JpegMeta.MetaProp = function MetaProp(fieldName, description, value) {
    this.fieldName = fieldName;
    this.description = description;
    this.value = value;
    return this;
};

JpegMeta.MetaProp.prototype.toString = function toString() {
    return "" + this.value;
};



/* JpegFile class */
this.JpegMeta.JpegFile = function JpegFile(binary_data, filename) {
    /* Change this to EOI if we want to parse. */
    var break_segment = this._SOS;

    this.metaGroups = {};
    this._binary_data = binary_data;
    this.filename = filename;

    /* Go through and parse. */
    var pos = 0;
    var pos_start_of_segment = 0;
    var delim;
    var mark;
    var _mark;
    var segsize;
    var headersize;
    var mark_code;
    var mark_fn;

    /* Check to see if this looks like a JPEG file */
    if (this._binary_data.slice(0, 2) !== this._SOI_MARKER) {
	throw new Error("Doesn't look like a JPEG file. First two bytes are " +
			this._binary_data.charCodeAt(0) + "," +
			this._binary_data.charCodeAt(1) + ".");
    }

    pos += 2;

    while (pos < this._binary_data.length) {
	delim = this._binary_data.charCodeAt(pos++);
	mark = this._binary_data.charCodeAt(pos++);

	pos_start_of_segment = pos;

	if (delim != this._DELIM) {
	    break;
	}

	if (mark === break_segment) {
	    break;
	}

	headersize = JpegMeta.parseNum(">", this._binary_data, pos, 2);

	/* Find the end */
	pos += headersize;
	while (pos < this._binary_data.length) {
	    delim = this._binary_data.charCodeAt(pos++);
	    if (delim == this._DELIM) {
		_mark = this._binary_data.charCodeAt(pos++);
		if (_mark != 0x0) {
		    pos -= 2;
		    break;
		}
	    }
	}

	segsize = pos - pos_start_of_segment;

	if (this._markers[mark]) {
	    mark_code = this._markers[mark][0];
	    mark_fn = this._markers[mark][1];
	} else {
	    mark_code = "UNKN";
	    mark_fn = undefined;
	}

	if (mark_fn) {
	    this[mark_fn](mark, pos_start_of_segment + 2, segsize - 2);
	}

    }

    if (this.general === undefined) {
	throw Error("Invalid JPEG file.");
    }

    return this;
};

this.JpegMeta.JpegFile.prototype.toString = function () {
    return "[JpegFile " + this.filename + " " +
	this.general.type + " " +
	this.general.pixelWidth + "x" +
	this.general.pixelHeight +
	" Depth: " + this.general.depth + "]";
};

/* Some useful constants */
this.JpegMeta.JpegFile.prototype._SOI_MARKER = '\xff\xd8';
this.JpegMeta.JpegFile.prototype._DELIM = 0xff;
this.JpegMeta.JpegFile.prototype._EOI = 0xd9;
this.JpegMeta.JpegFile.prototype._SOS = 0xda;

this.JpegMeta.JpegFile.prototype._sofHandler = function _sofHandler (mark, pos) {
    if (this.general !== undefined) {
	throw Error("Unexpected multiple-frame image");
    }

    this._addMetaGroup("general", "General");
    this.general._addProperty("depth", "Depth", JpegMeta.parseNum(">", this._binary_data, pos, 1));
    this.general._addProperty("pixelHeight", "Pixel Height", JpegMeta.parseNum(">", this._binary_data, pos + 1, 2));
    this.general._addProperty("pixelWidth", "Pixel Width",JpegMeta.parseNum(">", this._binary_data, pos + 3, 2));
    this.general._addProperty("type", "Type", this._markers[mark][2]);
};

this.JpegMeta.JpegFile.prototype._commentHandler = function _commentHandler (mark, pos, size) {

    var _pos, result;
    pos++;
    size--;
    _pos = pos;
    result = "";

    while(_pos < pos+size) {
        result += String.fromCharCode(this._binary_data.charCodeAt(_pos));
        _pos++;
    }

    this._addMetaGroup("comment", "Comment");
    this.comment._addProperty("comment", "Comment", result);
};


/* JFIF idents */
this.JpegMeta.JpegFile.prototype._JFIF_IDENT = "JFIF\x00";
this.JpegMeta.JpegFile.prototype._JFXX_IDENT = "JFXX\x00";

/* EXIF idents */
this.JpegMeta.JpegFile.prototype._EXIF_IDENT = "Exif\x00";

/* TIFF types */
this.JpegMeta.JpegFile.prototype._types = {
    /* The format is identifier : ["type name", type_size_in_bytes ] */
    1 : ["BYTE", 1],
    2 : ["ASCII", 1],
    3 : ["SHORT", 2],
    4 : ["LONG", 4],
    5 : ["RATIONAL", 8],
    6 : ["SBYTE", 1],
    7 : ["UNDEFINED", 1],
    8 : ["SSHORT", 2],
    9 : ["SLONG", 4],
    10 : ["SRATIONAL", 8],
    11 : ["FLOAT", 4],
    12 : ["DOUBLE", 8]
};

this.JpegMeta.JpegFile.prototype._tifftags = {
    /* A. Tags relating to image data structure */
    256 : ["Image width", "ImageWidth"],
    257 : ["Image height", "ImageLength"],
    258 : ["Number of bits per component", "BitsPerSample"],
    259 : ["Compression scheme", "Compression",
	   {1 : "uncompressed", 6 : "JPEG compression" }],
    262 : ["Pixel composition", "PhotmetricInerpretation",
	   {2 : "RGB", 6 : "YCbCr"}],
    274 : ["Orientation of image", "Orientation",
	   /* FIXME: Check the mirror-image / reverse encoding and rotation */
	   {1 : "Normal", 2 : "Reverse?",
	    3 : "Upside-down", 4 : "Upside-down Reverse",
	    5 : "90 degree CW", 6 : "90 degree CW reverse",
	    7 : "90 degree CCW", 8 : "90 degree CCW reverse"}],
    277 : ["Number of components", "SamplesPerPixel"],
    284 : ["Image data arrangement", "PlanarConfiguration",
	   {1 : "chunky format", 2 : "planar format"}],
    530 : ["Subsampling ratio of Y to C", "YCbCrSubSampling"],
    531 : ["Y and C positioning", "YCbCrPositioning",
	   {1 : "centered", 2 : "co-sited"}],
    282 : ["X Resolution", "XResolution"],
    283 : ["Y Resolution", "YResolution"],
    296 : ["Resolution Unit", "ResolutionUnit",
	   {2 : "inches", 3 : "centimeters"}],
    /* B. Tags realting to recording offset */
    273 : ["Image data location", "StripOffsets"],
    278 : ["Number of rows per strip", "RowsPerStrip"],
    279 : ["Bytes per compressed strip", "StripByteCounts"],
    513 : ["Offset to JPEG SOI", "JPEGInterchangeFormat"],
    514 : ["Bytes of JPEG Data", "JPEGInterchangeFormatLength"],
    /* C. Tags relating to image data characteristics */
    301 : ["Transfer function", "TransferFunction"],
    318 : ["White point chromaticity", "WhitePoint"],
    319 : ["Chromaticities of primaries", "PrimaryChromaticities"],
    529 : ["Color space transformation matrix coefficients", "YCbCrCoefficients"],
    532 : ["Pair of black and white reference values", "ReferenceBlackWhite"],
    /* D. Other tags */
    306 : ["Date and time", "DateTime"],
    270 : ["Image title", "ImageDescription"],
    271 : ["Make", "Make"],
    272 : ["Model", "Model"],
    305 : ["Software", "Software"],
    315 : ["Person who created the image", "Artist"],
    316 : ["Host Computer", "HostComputer"],
    33432 : ["Copyright holder", "Copyright"],

    34665 : ["Exif tag", "ExifIfdPointer"],
    34853 : ["GPS tag", "GPSInfoIfdPointer"]
};

this.JpegMeta.JpegFile.prototype._exiftags = {
    /* Tag Support Levels (2) - 0th IFX Exif Private Tags */
    /* A. Tags Relating to Version */
    36864 : ["Exif Version", "ExifVersion"],
    40960 : ["FlashPix Version", "FlashpixVersion"],

    /* B. Tag Relating to Image Data Characteristics */
    40961 : ["Color Space", "ColorSpace"],

    /* C. Tags Relating to Image Configuration */
    37121 : ["Meaning of each component", "ComponentsConfiguration"],
    37122 : ["Compressed Bits Per Pixel", "CompressedBitsPerPixel"],
    40962 : ["Pixel X Dimension", "PixelXDimension"],
    40963 : ["Pixel Y Dimension", "PixelYDimension"],

    /* D. Tags Relating to User Information */
    37500 : ["Manufacturer notes", "MakerNote"],
    37510 : ["User comments", "UserComment"],

    /* E. Tag Relating to Related File Information */
    40964 : ["Related audio file", "RelatedSoundFile"],

    /* F. Tags Relating to Date and Time */
    36867 : ["Date Time Original", "DateTimeOriginal"],
    36868 : ["Date Time Digitized", "DateTimeDigitized"],
    37520 : ["DateTime subseconds", "SubSecTime"],
    37521 : ["DateTimeOriginal subseconds", "SubSecTimeOriginal"],
    37522 : ["DateTimeDigitized subseconds", "SubSecTimeDigitized"],

    /* G. Tags Relating to Picture-Taking Conditions */
    33434 : ["Exposure time", "ExposureTime"],
    33437 : ["FNumber", "FNumber"],
    34850 : ["Exposure program", "ExposureProgram"],
    34852 : ["Spectral sensitivity", "SpectralSensitivity"],
    34855 : ["ISO Speed Ratings", "ISOSpeedRatings"],
    34856 : ["Optoelectric coefficient", "OECF"],
    37377 : ["Shutter Speed",  "ShutterSpeedValue"],
    37378 : ["Aperture Value", "ApertureValue"],
    37379 : ["Brightness", "BrightnessValue"],
    37380 : ["Exposure Bias Value", "ExposureBiasValue"],
    37381 : ["Max Aperture Value", "MaxApertureValue"],
    37382 : ["Subject Distance", "SubjectDistance"],
    37383 : ["Metering Mode", "MeteringMode"],
    37384 : ["Light Source", "LightSource"],
    37385 : ["Flash", "Flash"],
    37386 : ["Focal Length", "FocalLength"],
    37396 : ["Subject Area", "SubjectArea"],
    41483 : ["Flash Energy", "FlashEnergy"],
    41484 : ["Spatial Frequency Response", "SpatialFrequencyResponse"],
    41486 : ["Focal Plane X Resolution", "FocalPlaneXResolution"],
    41487 : ["Focal Plane Y Resolution", "FocalPlaneYResolution"],
    41488 : ["Focal Plane Resolution Unit", "FocalPlaneResolutionUnit"],
    41492 : ["Subject Location", "SubjectLocation"],
    41493 : ["Exposure Index", "ExposureIndex"],
    41495 : ["Sensing Method", "SensingMethod"],
    41728 : ["File Source", "FileSource"],
    41729 : ["Scene Type", "SceneType"],
    41730 : ["CFA Pattern", "CFAPattern"],
    41985 : ["Custom Rendered", "CustomRendered"],
    41986 : ["Exposure Mode", "Exposure Mode"],
    41987 : ["White Balance", "WhiteBalance"],
    41988 : ["Digital Zoom Ratio", "DigitalZoomRatio"],
    41989 : ["Focal length in 35 mm film", "FocalLengthIn35mmFilm"],
    41990 : ["Scene Capture Type", "SceneCaptureType"],
    41991 : ["Gain Control", "GainControl"],
    41992 : ["Contrast", "Contrast"],
    41993 : ["Saturation", "Saturation"],
    41994 : ["Sharpness", "Sharpness"],
    41995 : ["Device settings description", "DeviceSettingDescription"],
    41996 : ["Subject distance range", "SubjectDistanceRange"],

    /* H. Other Tags */
    42016 : ["Unique image ID", "ImageUniqueID"],

    40965 : ["Interoperability tag", "InteroperabilityIFDPointer"]
};

this.JpegMeta.JpegFile.prototype._gpstags = {
    /* A. Tags Relating to GPS */
    0 : ["GPS tag version", "GPSVersionID"],
    1 : ["North or South Latitude", "GPSLatitudeRef"],
    2 : ["Latitude", "GPSLatitude"],
    3 : ["East or West Longitude", "GPSLongitudeRef"],
    4 : ["Longitude", "GPSLongitude"],
    5 : ["Altitude reference", "GPSAltitudeRef"],
    6 : ["Altitude", "GPSAltitude"],
    7 : ["GPS time (atomic clock)", "GPSTimeStamp"],
    8 : ["GPS satellites usedd for measurement", "GPSSatellites"],
    9 : ["GPS receiver status", "GPSStatus"],
    10 : ["GPS mesaurement mode", "GPSMeasureMode"],
    11 : ["Measurement precision", "GPSDOP"],
    12 : ["Speed unit", "GPSSpeedRef"],
    13 : ["Speed of GPS receiver", "GPSSpeed"],
    14 : ["Reference for direction of movement", "GPSTrackRef"],
    15 : ["Direction of movement", "GPSTrack"],
    16 : ["Reference for direction of image", "GPSImgDirectionRef"],
    17 : ["Direction of image", "GPSImgDirection"],
    18 : ["Geodetic survey data used", "GPSMapDatum"],
    19 : ["Reference for latitude of destination", "GPSDestLatitudeRef"],
    20 : ["Latitude of destination", "GPSDestLatitude"],
    21 : ["Reference for longitude of destination", "GPSDestLongitudeRef"],
    22 : ["Longitude of destination", "GPSDestLongitude"],
    23 : ["Reference for bearing of destination", "GPSDestBearingRef"],
    24 : ["Bearing of destination", "GPSDestBearing"],
    25 : ["Reference for distance to destination", "GPSDestDistanceRef"],
    26 : ["Distance to destination", "GPSDestDistance"],
    27 : ["Name of GPS processing method", "GPSProcessingMethod"],
    28 : ["Name of GPS area", "GPSAreaInformation"],
    29 : ["GPS Date", "GPSDateStamp"],
    30 : ["GPS differential correction", "GPSDifferential"]
};

this.JpegMeta.JpegFile.prototype._iptctags = {
    0 : ['Record Version', 'recordVersion'],
    3 : ['Object Type Reference', 'objectType'],
    4 : ['Object Attribute Reference', 'objectAttribute'],
    5 : ['Object Name', 'objectName'],
    7 : ['Edit Status', 'editStatus'],
    8 : ['Editorial Update', 'editorialUpdate'],
    10 : ['Urgency', 'urgency'],
    12 : ['Subject Reference', 'subjectRef'],
    15 : ['Category', 'category'],
    20 : ['Supplemental Category', 'supplCategory'],
    22 : ['Fixture Identifier', 'fixtureID'],
    25 : ['Keywords', 'keywords'],
    26 : ['Content Location Code', 'contentLocCode'],
    27 : ['Content Location Name', 'contentLocName'],
    30 : ['Release Date', 'releaseDate'],
    35 : ['Release Time', 'releaseTime'],
    37 : ['Expiration Date', 'expirationDate'],
    38 : ['Expiration Time', 'expirationTime'],
    40 : ['Special Instructions', 'specialInstructions'],
    42 : ['Action Advised', 'actionAdvised'],
    45 : ['Reference Service', 'refService'],
    47 : ['Reference Date', 'refDate'],
    50 : ['Reference Number', 'refNumber'],
    55 : ['Date Created', 'dateCreated'],
    60 : ['Time Created', 'timeCreated'],
    62 : ['Digital Creation Date', 'digitalCreationDate'],
    63 : ['Digital Creation Time', 'digitalCreationTime'],
    65 : ['Originating Program', 'originatingProgram'],
    70 : ['Program Version', 'programVersion'],
    75 : ['Object Cycle', 'objectCycle'],
    80 : ['By-line', 'byline'],
    85 : ['By-line Title', 'bylineTitle'],
    90 : ['City', 'city'],
    92 : ['Sub-location', 'sublocation'],
    95 : ['Province/State', 'state'],
    100 : ['Country Code', 'countryCode'],
    101 : ['Country Name', 'countryName'],
    103 : ['Original Transmission Reference', 'origTransRef'],
    105 : ['Headline', 'headline'],
    110 : ['Credit', 'credit'],
    115 : ['Source', 'source'],
    116 : ['Copyright Notice', 'copyrightNotice'],
    118 : ['Contact', 'contact'],
    120 : ['Caption/Abstract', 'caption'],
    122 : ['Writer/Editor', 'writerEditor'],
    125 : ['Rasterized Caption', 'rasterizedCaption'],
    130 : ['Image Type', 'imageType'],
    131 : ['Image Orientation', 'imageOrientation'],
    135 : ['Language Identifier', 'languageID'],
    150 : ['Audio Type', 'audioType'],
    151 : ['Audio Sampling Rate', 'audioSamplingRate'],
    152 : ['Audio Sampling Resolution', 'audioSamplingRes'],
    153 : ['Audio Duration', 'audioDuration'],
    154 : ['Audio Outcue', 'audioOutcue'],
    200 : ['Preview File Format', 'previewFileFormat'],
    201 : ['Preview File Format Version', 'previewFileFormatVer'],
    202 : ['Preview Data', 'previewData']
};

this.JpegMeta.JpegFile.prototype._markers = {
    /* Start Of Frame markers, non-differential, Huffman coding */
    0xc0: ["SOF0", "_sofHandler", "Baseline DCT"],
    0xc1: ["SOF1", "_sofHandler", "Extended sequential DCT"],
    0xc2: ["SOF2", "_sofHandler", "Progressive DCT"],
    0xc3: ["SOF3", "_sofHandler", "Lossless (sequential)"],

    /* Start Of Frame markers, differential, Huffman coding */
    0xc5: ["SOF5", "_sofHandler", "Differential sequential DCT"],
    0xc6: ["SOF6", "_sofHandler", "Differential progressive DCT"],
    0xc7: ["SOF7", "_sofHandler", "Differential lossless (sequential)"],

    /* Start Of Frame markers, non-differential, arithmetic coding */
    0xc8: ["JPG", null, "Reserved for JPEG extensions"],
    0xc9: ["SOF9", "_sofHandler", "Extended sequential DCT"],
    0xca: ["SOF10", "_sofHandler", "Progressive DCT"],
    0xcb: ["SOF11", "_sofHandler", "Lossless (sequential)"],

    /* Start Of Frame markers, differential, arithmetic coding */
    0xcd: ["SOF13", "_sofHandler", "Differential sequential DCT"],
    0xce: ["SOF14", "_sofHandler", "Differential progressive DCT"],
    0xcf: ["SOF15", "_sofHandler", "Differential lossless (sequential)"],

    /* Huffman table specification */
    0xc4: ["DHT", null, "Define Huffman table(s)"],
    0xcc: ["DAC", null, "Define arithmetic coding conditioning(s)"],

    /* Restart interval termination" */
    0xd0: ["RST0", null, "Restart with modulo 8 count �0�"],
    0xd1: ["RST1", null, "Restart with modulo 8 count �1�"],
    0xd2: ["RST2", null, "Restart with modulo 8 count �2�"],
    0xd3: ["RST3", null, "Restart with modulo 8 count �3�"],
    0xd4: ["RST4", null, "Restart with modulo 8 count �4�"],
    0xd5: ["RST5", null, "Restart with modulo 8 count �5�"],
    0xd6: ["RST6", null, "Restart with modulo 8 count �6�"],
    0xd7: ["RST7", null, "Restart with modulo 8 count �7�"],

    /* Other markers */
    0xd8: ["SOI", null, "Start of image"],
    0xd9: ["EOI", null, "End of image"],
    0xda: ["SOS", null, "Start of scan"],
    0xdb: ["DQT", null, "Define quantization table(s)"],
    0xdc: ["DNL", null, "Define number of lines"],
    0xdd: ["DRI", null, "Define restart interval"],
    0xde: ["DHP", null, "Define hierarchical progression"],
    0xdf: ["EXP", null, "Expand reference component(s)"],
    0xe0: ["APP0", "_app0Handler", "Reserved for application segments"],
    0xe1: ["APP1", "_app1Handler"],
    0xe2: ["APP2", null],
    0xe3: ["APP3", null],
    0xe4: ["APP4", null],
    0xe5: ["APP5", null],
    0xe6: ["APP6", null],
    0xe7: ["APP7", null],
    0xe8: ["APP8", null],
    0xe9: ["APP9", null],
    0xea: ["APP10", null],
    0xeb: ["APP11", null],
    0xec: ["APP12", null],
    0xed: ["IPTC", "_iptcHandler", "IPTC Photo Metadata"],
    0xee: ["APP14", null],
    0xef: ["APP15", null],
    0xf0: ["JPG0", null], /* Reserved for JPEG extensions */
    0xf1: ["JPG1", null],
    0xf2: ["JPG2", null],
    0xf3: ["JPG3", null],
    0xf4: ["JPG4", null],
    0xf5: ["JPG5", null],
    0xf6: ["JPG6", null],
    0xf7: ["JPG7", null],
    0xf8: ["JPG8", null],
    0xf9: ["JPG9", null],
    0xfa: ["JPG10", null],
    0xfb: ["JPG11", null],
    0xfc: ["JPG12", null],
    0xfd: ["JPG13", null],
    0xfe: ["COM", "_commentHandler", "Comment"], /* Comment */

    /* Reserved markers */
    0x01: ["JPG13", null] /* For temporary private use in arithmetic coding */
    /* 02 -> bf are reserverd */
};

/* Private methods */
this.JpegMeta.JpegFile.prototype._addMetaGroup = function _addMetaGroup(name, description) {
    var group = new JpegMeta.MetaGroup(name, description);
    this[group.fieldName] = group;
    this.metaGroups[group.fieldName] = group;
    return group;
};

this.JpegMeta.JpegFile.prototype._parseIfd = function _parseIfd(endian, _binary_data, base, ifd_offset, tags, name, description) {
    var num_fields = JpegMeta.parseNum(endian, _binary_data, base + ifd_offset, 2);
    /* Per tag variables */
    var tag_base;
    var tag_field;
    var type, type_field, type_size;
    var num_values;
    var value_offset;
    var value;
    var _val;
    var num;
    var den;

    var group;

    group = this._addMetaGroup(name, description);

    for (var i = 0; i < num_fields; i++) {
	/* parse the field */
	tag_base = base + ifd_offset + 2 + (i * 12);
	tag_field = JpegMeta.parseNum(endian, _binary_data, tag_base, 2);
	type_field = JpegMeta.parseNum(endian, _binary_data, tag_base + 2, 2);
	num_values = JpegMeta.parseNum(endian, _binary_data, tag_base + 4, 4);
	value_offset = JpegMeta.parseNum(endian, _binary_data, tag_base + 8, 4);
	if (this._types[type_field] === undefined) {
	    continue;
	}
	type = this._types[type_field][0];
	type_size = this._types[type_field][1];

	if (type_size * num_values <= 4) {
	    /* Data is in-line */
	    value_offset = tag_base + 8;
	} else {
	    value_offset = base + value_offset;
	}

	/* Read the value */
	if (type == "UNDEFINED") {
	    /* FIXME: This should be done better */
	    /*value = _binary_data.slice(value_offset, value_offset + num_values); */
	    value = undefined;
	} else if (type == "ASCII") {
	    value = _binary_data.slice(value_offset, value_offset + num_values);
	    value = value.split('\x00')[0];
	    if (!JpegMeta.stringIsClean(value)) {
		value = "";
	    }
	    /* strip trail nul */
	} else {
	    value = new Array();
	    for (var j = 0; j < num_values; j++, value_offset += type_size) {
		if (type == "BYTE" || type == "SHORT" || type == "LONG") {
		    value.push(JpegMeta.parseNum(endian, _binary_data, value_offset, type_size));
		}
		if (type == "SBYTE" || type == "SSHORT" || type == "SLONG") {
		    value.push(JpegMeta.parseSnum(endian, _binary_data, value_offset, type_size));
		}
		if (type == "RATIONAL") {
		    num = JpegMeta.parseNum(endian, _binary_data, value_offset, 4);
		    den = JpegMeta.parseNum(endian, _binary_data, value_offset + 4, 4);
		    value.push(new JpegMeta.Rational(num, den));
		}
		if (type == "SRATIONAL") {
		    num = JpegMeta.parseSnum(endian, _binary_data, value_offset, 4);
		    den = JpegMeta.parseSnum(endian, _binary_data, value_offset + 4, 4);
		    value.push(new JpegMeta.Rational(num, den));
		}
		value.push();
	    }
	    if (num_values === 1) {
		value = value[0];
	    }
	}
        if (tags.hasOwnProperty(tag_field)) {
	    group._addProperty(tags[tag_field][1], tags[tag_field][0], value);
        } else {
            console.log("WARNING(jpegmeta.js): Unknown tag: ", tag_field);
        }
    }
};

this.JpegMeta.JpegFile.prototype._jfifHandler = function _jfifHandler(mark, pos) {
    if (this.jfif !== undefined) {
	throw Error("Multiple JFIF segments found");
    }
    this._addMetaGroup("jfif", "JFIF");
    this.jfif._addProperty("version_major", "Version Major", this._binary_data.charCodeAt(pos + 5));
    this.jfif._addProperty("version_minor", "Version Minor", this._binary_data.charCodeAt(pos + 6));
    this.jfif._addProperty("version", "JFIF Version", this.jfif.version_major.value + "." + this.jfif.version_minor.value);
    this.jfif._addProperty("units", "Density Unit", this._binary_data.charCodeAt(pos + 7));
    this.jfif._addProperty("Xdensity", "X density", JpegMeta.parseNum(">", this._binary_data, pos + 8, 2));
    this.jfif._addProperty("Ydensity", "Y Density", JpegMeta.parseNum(">", this._binary_data, pos + 10, 2));
    this.jfif._addProperty("Xthumbnail", "X Thumbnail", JpegMeta.parseNum(">", this._binary_data, pos + 12, 1));
    this.jfif._addProperty("Ythumbnail", "Y Thumbnail", JpegMeta.parseNum(">", this._binary_data, pos + 13, 1));
};


/* Handle app0 segments */
this.JpegMeta.JpegFile.prototype._app0Handler = function app0Handler(mark, pos) {
    var ident = this._binary_data.slice(pos, pos + 5);
    if (ident == this._JFIF_IDENT) {
	this._jfifHandler(mark, pos);
    } else if (ident == this._JFXX_IDENT) {
	/* Don't handle JFXX Ident yet */
    } else {
	/* Don't know about other idents */
    }
};


/* Handle app1 segments */
this.JpegMeta.JpegFile.prototype._app1Handler = function _app1Handler(mark, pos) {
    var ident = this._binary_data.slice(pos, pos + 5);
    if (ident == this._EXIF_IDENT) {
	this._exifHandler(mark, pos + 6);
    } else {
	/* Don't know about other idents */
    }
};

/* Handle exif segments */
JpegMeta.JpegFile.prototype._exifHandler = function _exifHandler(mark, pos) {
    if (this.exif !== undefined) {
	throw new Error("Multiple JFIF segments found");
    }

    /* Parse this TIFF header */
    var endian;
    var magic_field;
    var ifd_offset;
    var primary_ifd, exif_ifd, gps_ifd;
    var endian_field = this._binary_data.slice(pos, pos + 2);

    /* Trivia: This 'I' is for Intel, the 'M' is for Motorola */
    if (endian_field === "II") {
	endian = "<";
    } else if (endian_field === "MM") {
	endian = ">";
    } else {
	throw new Error("Malformed TIFF meta-data. Unknown endianess: " + endian_field);
    }

    magic_field = JpegMeta.parseNum(endian, this._binary_data, pos + 2, 2);

    if (magic_field !== 42) {
	throw new Error("Malformed TIFF meta-data. Bad magic: " + magic_field);
    }

    ifd_offset = JpegMeta.parseNum(endian, this._binary_data, pos + 4, 4);

    /* Parse 0th IFD */
    this._parseIfd(endian, this._binary_data, pos, ifd_offset, this._tifftags, "tiff", "TIFF");

    if (this.tiff.ExifIfdPointer) {
	this._parseIfd(endian, this._binary_data, pos, this.tiff.ExifIfdPointer.value, this._exiftags, "exif", "Exif");
    }

    if (this.tiff.GPSInfoIfdPointer) {
	this._parseIfd(endian, this._binary_data, pos, this.tiff.GPSInfoIfdPointer.value, this._gpstags, "gps", "GPS");
	if (this.gps.GPSLatitude) {
	    var latitude;
	    latitude = this.gps.GPSLatitude.value[0].asFloat() +
		(1 / 60) * this.gps.GPSLatitude.value[1].asFloat() +
		(1 / 3600) * this.gps.GPSLatitude.value[2].asFloat();
	    if (this.gps.GPSLatitudeRef.value === "S") {
		latitude = -latitude;
	    }
	    this.gps._addProperty("latitude", "Dec. Latitude", latitude);
	}
	if (this.gps.GPSLongitude) {
	    var longitude;
	    longitude = this.gps.GPSLongitude.value[0].asFloat() +
		(1 / 60) * this.gps.GPSLongitude.value[1].asFloat() +
		(1 / 3600) * this.gps.GPSLongitude.value[2].asFloat();
	    if (this.gps.GPSLongitudeRef.value === "W") {
		longitude = -longitude;
	    }
	    this.gps._addProperty("longitude", "Dec. Longitude", longitude);
	}
    }
};

this.JpegMeta.JpegFile.prototype._iptcHandler = function _iptcHandler(mark, pos, segsize) {
    this._addMetaGroup("iptc", "IPTC");

    var endian = '<';
    var offset, fieldStart, title, value, tag;
    var length = JpegMeta.parseNum(endian, this._binary_data, pos + 4, 1);
    var FILE_SEPARATOR_CHAR = 28,
        START_OF_TEXT_CHAR = 2;

    for (var i = 0; i < segsize; i++) {
        fieldStart = pos + i;
        if (JpegMeta.parseNum(endian, this._binary_data, fieldStart, 1) == START_OF_TEXT_CHAR) {
            tag = JpegMeta.parseNum(endian, this._binary_data, fieldStart + 1, 1);
            tag_desc = this._iptctags[tag];

            if (!tag_desc) continue;
            length = 0;
            offset = 2;

            while (
                offset < segsize &&
                JpegMeta.parseNum(endian, this._binary_data, fieldStart + offset, 1) != FILE_SEPARATOR_CHAR &&
                JpegMeta.parseNum(endian, this._binary_data, fieldStart + offset + 1, 1) != START_OF_TEXT_CHAR) {
                offset++;
                length++;
            }

            if (!length) continue;

            value = this._binary_data.slice(pos + i + 2, pos + i + 2 + length);
            value = value.replace('\000', '').trim();

            this.iptc._addProperty(tag_desc[1], tag_desc[0], value);
            i += length - 1;
        }
    }
};

"function"!=typeof Object.create&&(Object.create=function(o){function e(){}return e.prototype=o,new e}),function($,o,e,i){var t={init:function(o,e){var i=this;i.elem=e,i.$elem=$(e),i.imageSrc=i.$elem.data("zoom-image")?i.$elem.data("zoom-image"):i.$elem.attr("src"),i.options=$.extend({},$.fn.elevateZoom.options,o),i.options.tint&&(i.options.lensColour="none",i.options.lensOpacity="1"),"inner"==i.options.zoomType&&(i.options.showLens=!1),i.$elem.parent().removeAttr("title").removeAttr("alt"),i.zoomImage=i.imageSrc,i.refresh(1),$("#"+i.options.gallery+" a").click(function(o){return i.options.galleryActiveClass&&($("#"+i.options.gallery+" a").removeClass(i.options.galleryActiveClass),$(this).addClass(i.options.galleryActiveClass)),o.preventDefault(),$(this).data("zoom-image")?i.zoomImagePre=$(this).data("zoom-image"):i.zoomImagePre=$(this).data("image"),i.swaptheimage($(this).data("image"),i.zoomImagePre),!1})},refresh:function(o){var e=this;setTimeout(function(){e.fetch(e.imageSrc)},o||e.options.refresh)},fetch:function(o){var e=this,i=new Image;i.onload=function(){e.largeWidth=i.width,e.largeHeight=i.height,e.startZoom(),e.currentImage=e.imageSrc,e.options.onZoomedImageLoaded(e.$elem)},i.src=o},startZoom:function(){var o=this;if(o.nzWidth=o.$elem.width(),o.nzHeight=o.$elem.height(),o.isWindowActive=!1,o.isLensActive=!1,o.isTintActive=!1,o.overWindow=!1,o.options.imageCrossfade&&(o.zoomWrap=o.$elem.wrap('<div style="height:'+o.nzHeight+"px;width:"+o.nzWidth+'px;" class="zoomWrapper" />'),o.$elem.css("position","absolute")),o.zoomLock=1,o.scrollingLock=!1,o.changeBgSize=!1,o.currentZoomLevel=o.options.zoomLevel,o.nzOffset=o.$elem.offset(),o.widthRatio=o.largeWidth/o.currentZoomLevel/o.nzWidth,o.heightRatio=o.largeHeight/o.currentZoomLevel/o.nzHeight,"window"==o.options.zoomType&&(o.zoomWindowStyle="overflow: hidden;background-position: 0px 0px;text-align:center;background-color: "+String(o.options.zoomWindowBgColour)+";width: "+String(o.options.zoomWindowWidth)+"px;height: "+String(o.options.zoomWindowHeight)+"px;float: left;background-size: "+o.largeWidth/o.currentZoomLevel+"px "+o.largeHeight/o.currentZoomLevel+"px;display: none;z-index:100;border: "+String(o.options.borderSize)+"px solid "+o.options.borderColour+";background-repeat: no-repeat;position: absolute;"),"inner"==o.options.zoomType){var e=o.$elem.css("border-left-width");o.zoomWindowStyle="overflow: hidden;margin-left: "+String(e)+";margin-top: "+String(e)+";background-position: 0px 0px;width: "+String(o.nzWidth)+"px;height: "+String(o.nzHeight)+"px;px;float: left;display: none;cursor:"+o.options.cursor+";px solid "+o.options.borderColour+";background-repeat: no-repeat;position: absolute;"}"window"==o.options.zoomType&&(o.nzHeight<o.options.zoomWindowWidth/o.widthRatio?lensHeight=o.nzHeight:lensHeight=String(o.options.zoomWindowHeight/o.heightRatio),o.largeWidth<o.options.zoomWindowWidth?lensWidth=o.nzWidth:lensWidth=o.options.zoomWindowWidth/o.widthRatio,o.lensStyle="background-position: 0px 0px;width: "+String(o.options.zoomWindowWidth/o.widthRatio)+"px;height: "+String(o.options.zoomWindowHeight/o.heightRatio)+"px;float: right;display: none;overflow: hidden;z-index: 999;-webkit-transform: translateZ(0);opacity:"+o.options.lensOpacity+";filter: alpha(opacity = "+100*o.options.lensOpacity+"); zoom:1;width:"+lensWidth+"px;height:"+lensHeight+"px;background-color:"+o.options.lensColour+";cursor:"+o.options.cursor+";border: "+o.options.lensBorderSize+"px solid "+o.options.lensBorderColour+";background-repeat: no-repeat;position: absolute;"),o.tintStyle="display: block;position: absolute;background-color: "+o.options.tintColour+";filter:alpha(opacity=0);opacity: 0;width: "+o.nzWidth+"px;height: "+o.nzHeight+"px;",o.lensRound="","lens"==o.options.zoomType&&(o.lensStyle="background-position: 0px 0px;float: left;display: none;border: "+String(o.options.borderSize)+"px solid "+o.options.borderColour+";width:"+String(o.options.lensSize)+"px;height:"+String(o.options.lensSize)+"px;background-repeat: no-repeat;position: absolute;"),"round"==o.options.lensShape&&(o.lensRound="border-top-left-radius: "+String(o.options.lensSize/2+o.options.borderSize)+"px;border-top-right-radius: "+String(o.options.lensSize/2+o.options.borderSize)+"px;border-bottom-left-radius: "+String(o.options.lensSize/2+o.options.borderSize)+"px;border-bottom-right-radius: "+String(o.options.lensSize/2+o.options.borderSize)+"px;"),o.zoomContainer=$('<div class="zoomContainer" style="-webkit-transform: translateZ(0);position:absolute;left:'+o.nzOffset.left+"px;top:"+o.nzOffset.top+"px;height:"+o.nzHeight+"px;width:"+o.nzWidth+'px;"></div>'),$("body").append(o.zoomContainer),o.options.containLensZoom&&"lens"==o.options.zoomType&&o.zoomContainer.css("overflow","hidden"),"inner"!=o.options.zoomType&&(o.zoomLens=$("<div class='zoomLens' style='"+o.lensStyle+o.lensRound+"'>&nbsp;</div>").appendTo(o.zoomContainer).click(function(){o.$elem.trigger("click")}),o.options.tint&&(o.tintContainer=$("<div/>").addClass("tintContainer"),o.zoomTint=$("<div class='zoomTint' style='"+o.tintStyle+"'></div>"),o.zoomLens.wrap(o.tintContainer),o.zoomTintcss=o.zoomLens.after(o.zoomTint),o.zoomTintImage=$('<img style="position: absolute; left: 0px; top: 0px; max-width: none; width: '+o.nzWidth+"px; height: "+o.nzHeight+'px;" src="'+o.imageSrc+'">').appendTo(o.zoomLens).click(function(){o.$elem.trigger("click")}))),isNaN(o.options.zoomWindowPosition)?o.zoomWindow=$("<div style='z-index:999;left:"+o.windowOffsetLeft+"px;top:"+o.windowOffsetTop+"px;"+o.zoomWindowStyle+"' class='zoomWindow'>&nbsp;</div>").appendTo("body").click(function(){o.$elem.trigger("click")}):o.zoomWindow=$("<div style='z-index:999;left:"+o.windowOffsetLeft+"px;top:"+o.windowOffsetTop+"px;"+o.zoomWindowStyle+"' class='zoomWindow'>&nbsp;</div>").appendTo(o.zoomContainer).click(function(){o.$elem.trigger("click")}),o.zoomWindowContainer=$("<div/>").addClass("zoomWindowContainer").css("width",o.options.zoomWindowWidth),o.zoomWindow.wrap(o.zoomWindowContainer),"lens"==o.options.zoomType&&o.zoomLens.css({backgroundImage:"url('"+o.imageSrc+"')"}),"window"==o.options.zoomType&&o.zoomWindow.css({backgroundImage:"url('"+o.imageSrc+"')"}),"inner"==o.options.zoomType&&o.zoomWindow.css({backgroundImage:"url('"+o.imageSrc+"')"}),o.$elem.bind("touchmove",function(e){e.preventDefault();var i=e.originalEvent.touches[0]||e.originalEvent.changedTouches[0];o.setPosition(i)}),o.zoomContainer.bind("touchmove",function(e){"inner"==o.options.zoomType&&o.showHideWindow("show"),e.preventDefault();var i=e.originalEvent.touches[0]||e.originalEvent.changedTouches[0];o.setPosition(i)}),o.zoomContainer.bind("touchend",function(e){o.showHideWindow("hide"),o.options.showLens&&o.showHideLens("hide"),o.options.tint&&"inner"!=o.options.zoomType&&o.showHideTint("hide")}),o.$elem.bind("touchend",function(e){o.showHideWindow("hide"),o.options.showLens&&o.showHideLens("hide"),o.options.tint&&"inner"!=o.options.zoomType&&o.showHideTint("hide")}),o.options.showLens&&(o.zoomLens.bind("touchmove",function(e){e.preventDefault();var i=e.originalEvent.touches[0]||e.originalEvent.changedTouches[0];o.setPosition(i)}),o.zoomLens.bind("touchend",function(e){o.showHideWindow("hide"),o.options.showLens&&o.showHideLens("hide"),o.options.tint&&"inner"!=o.options.zoomType&&o.showHideTint("hide")})),o.$elem.bind("mousemove",function(e){0==o.overWindow&&o.setElements("show"),(o.lastX!==e.clientX||o.lastY!==e.clientY)&&(o.setPosition(e),o.currentLoc=e),o.lastX=e.clientX,o.lastY=e.clientY}),o.zoomContainer.bind("mousemove",function(e){0==o.overWindow&&o.setElements("show"),(o.lastX!==e.clientX||o.lastY!==e.clientY)&&(o.setPosition(e),o.currentLoc=e),o.lastX=e.clientX,o.lastY=e.clientY}),"inner"!=o.options.zoomType&&o.zoomLens.bind("mousemove",function(e){(o.lastX!==e.clientX||o.lastY!==e.clientY)&&(o.setPosition(e),o.currentLoc=e),o.lastX=e.clientX,o.lastY=e.clientY}),o.options.tint&&"inner"!=o.options.zoomType&&o.zoomTint.bind("mousemove",function(e){(o.lastX!==e.clientX||o.lastY!==e.clientY)&&(o.setPosition(e),o.currentLoc=e),o.lastX=e.clientX,o.lastY=e.clientY}),"inner"==o.options.zoomType&&o.zoomWindow.bind("mousemove",function(e){(o.lastX!==e.clientX||o.lastY!==e.clientY)&&(o.setPosition(e),o.currentLoc=e),o.lastX=e.clientX,o.lastY=e.clientY}),o.zoomContainer.add(o.$elem).mouseenter(function(){0==o.overWindow&&o.setElements("show")}).mouseleave(function(){o.scrollLock||(o.setElements("hide"),o.options.onDestroy(o.$elem))}),"inner"!=o.options.zoomType&&o.zoomWindow.mouseenter(function(){o.overWindow=!0,o.setElements("hide")}).mouseleave(function(){o.overWindow=!1}),1!=o.options.zoomLevel,o.options.minZoomLevel?o.minZoomLevel=o.options.minZoomLevel:o.minZoomLevel=2*o.options.scrollZoomIncrement,o.options.scrollZoom&&o.zoomContainer.add(o.$elem).bind("mousewheel DOMMouseScroll MozMousePixelScroll",function(e){o.scrollLock=!0,clearTimeout($.data(this,"timer")),$.data(this,"timer",setTimeout(function(){o.scrollLock=!1},250));var i=e.originalEvent.wheelDelta||-1*e.originalEvent.detail;return e.stopImmediatePropagation(),e.stopPropagation(),e.preventDefault(),i/120>0?o.currentZoomLevel>=o.minZoomLevel&&o.changeZoomLevel(o.currentZoomLevel-o.options.scrollZoomIncrement):o.options.maxZoomLevel?o.currentZoomLevel<=o.options.maxZoomLevel&&o.changeZoomLevel(parseFloat(o.currentZoomLevel)+o.options.scrollZoomIncrement):o.changeZoomLevel(parseFloat(o.currentZoomLevel)+o.options.scrollZoomIncrement),!1})},setElements:function(o){var e=this;return e.options.zoomEnabled?("show"==o&&e.isWindowSet&&("inner"==e.options.zoomType&&e.showHideWindow("show"),"window"==e.options.zoomType&&e.showHideWindow("show"),e.options.showLens&&e.showHideLens("show"),e.options.tint&&"inner"!=e.options.zoomType&&e.showHideTint("show")),void("hide"==o&&("window"==e.options.zoomType&&e.showHideWindow("hide"),e.options.tint||e.showHideWindow("hide"),e.options.showLens&&e.showHideLens("hide"),e.options.tint&&e.showHideTint("hide")))):!1},setPosition:function(o){var e=this;return e.options.zoomEnabled?(e.nzHeight=e.$elem.height(),e.nzWidth=e.$elem.width(),e.nzOffset=e.$elem.offset(),e.options.tint&&"inner"!=e.options.zoomType&&(e.zoomTint.css({top:0}),e.zoomTint.css({left:0})),e.options.responsive&&!e.options.scrollZoom&&e.options.showLens&&(e.nzHeight<e.options.zoomWindowWidth/e.widthRatio?lensHeight=e.nzHeight:lensHeight=String(e.options.zoomWindowHeight/e.heightRatio),e.largeWidth<e.options.zoomWindowWidth?lensWidth=e.nzWidth:lensWidth=e.options.zoomWindowWidth/e.widthRatio,e.widthRatio=e.largeWidth/e.nzWidth,e.heightRatio=e.largeHeight/e.nzHeight,"lens"!=e.options.zoomType&&(e.nzHeight<e.options.zoomWindowWidth/e.widthRatio?lensHeight=e.nzHeight:lensHeight=String(e.options.zoomWindowHeight/e.heightRatio),e.nzWidth<e.options.zoomWindowHeight/e.heightRatio?lensWidth=e.nzWidth:lensWidth=String(e.options.zoomWindowWidth/e.widthRatio),e.zoomLens.css("width",lensWidth),e.zoomLens.css("height",lensHeight),e.options.tint&&(e.zoomTintImage.css("width",e.nzWidth),e.zoomTintImage.css("height",e.nzHeight))),"lens"==e.options.zoomType&&e.zoomLens.css({width:String(e.options.lensSize)+"px",height:String(e.options.lensSize)+"px"})),e.zoomContainer.css({top:e.nzOffset.top}),e.zoomContainer.css({left:e.nzOffset.left}),e.mouseLeft=parseInt(o.pageX-e.nzOffset.left),e.mouseTop=parseInt(o.pageY-e.nzOffset.top),"window"==e.options.zoomType&&(e.Etoppos=e.mouseTop<e.zoomLens.height()/2,e.Eboppos=e.mouseTop>e.nzHeight-e.zoomLens.height()/2-2*e.options.lensBorderSize,e.Eloppos=e.mouseLeft<0+e.zoomLens.width()/2,e.Eroppos=e.mouseLeft>e.nzWidth-e.zoomLens.width()/2-2*e.options.lensBorderSize),"inner"==e.options.zoomType&&(e.Etoppos=e.mouseTop<e.nzHeight/2/e.heightRatio,e.Eboppos=e.mouseTop>e.nzHeight-e.nzHeight/2/e.heightRatio,e.Eloppos=e.mouseLeft<0+e.nzWidth/2/e.widthRatio,e.Eroppos=e.mouseLeft>e.nzWidth-e.nzWidth/2/e.widthRatio-2*e.options.lensBorderSize),e.mouseLeft<0||e.mouseTop<0||e.mouseLeft>e.nzWidth||e.mouseTop>e.nzHeight?void e.setElements("hide"):(e.options.showLens&&(e.lensLeftPos=String(Math.floor(e.mouseLeft-e.zoomLens.width()/2)),e.lensTopPos=String(Math.floor(e.mouseTop-e.zoomLens.height()/2))),e.Etoppos&&(e.lensTopPos=0),e.Eloppos&&(e.windowLeftPos=0,e.lensLeftPos=0,e.tintpos=0),"window"==e.options.zoomType&&(e.Eboppos&&(e.lensTopPos=Math.max(e.nzHeight-e.zoomLens.height()-2*e.options.lensBorderSize,0)),e.Eroppos&&(e.lensLeftPos=e.nzWidth-e.zoomLens.width()-2*e.options.lensBorderSize)),"inner"==e.options.zoomType&&(e.Eboppos&&(e.lensTopPos=Math.max(e.nzHeight-2*e.options.lensBorderSize,0)),e.Eroppos&&(e.lensLeftPos=e.nzWidth-e.nzWidth-2*e.options.lensBorderSize)),"lens"==e.options.zoomType&&(e.windowLeftPos=String(-1*((o.pageX-e.nzOffset.left)*e.widthRatio-e.zoomLens.width()/2)),e.windowTopPos=String(-1*((o.pageY-e.nzOffset.top)*e.heightRatio-e.zoomLens.height()/2)),e.zoomLens.css({backgroundPosition:e.windowLeftPos+"px "+e.windowTopPos+"px"}),e.changeBgSize&&(e.nzHeight>e.nzWidth?("lens"==e.options.zoomType&&e.zoomLens.css({"background-size":e.largeWidth/e.newvalueheight+"px "+e.largeHeight/e.newvalueheight+"px"}),e.zoomWindow.css({"background-size":e.largeWidth/e.newvalueheight+"px "+e.largeHeight/e.newvalueheight+"px"})):("lens"==e.options.zoomType&&e.zoomLens.css({"background-size":e.largeWidth/e.newvaluewidth+"px "+e.largeHeight/e.newvaluewidth+"px"}),e.zoomWindow.css({"background-size":e.largeWidth/e.newvaluewidth+"px "+e.largeHeight/e.newvaluewidth+"px"})),e.changeBgSize=!1),e.setWindowPostition(o)),e.options.tint&&"inner"!=e.options.zoomType&&e.setTintPosition(o),"window"==e.options.zoomType&&e.setWindowPostition(o),"inner"==e.options.zoomType&&e.setWindowPostition(o),e.options.showLens&&(e.fullwidth&&"lens"!=e.options.zoomType&&(e.lensLeftPos=0),e.zoomLens.css({left:e.lensLeftPos+"px",top:e.lensTopPos+"px"})),void 0)):!1},showHideWindow:function(o){var e=this;"show"==o&&(e.isWindowActive||(e.options.zoomWindowFadeIn?e.zoomWindow.stop(!0,!0,!1).fadeIn(e.options.zoomWindowFadeIn):e.zoomWindow.show(),e.isWindowActive=!0)),"hide"==o&&e.isWindowActive&&(e.options.zoomWindowFadeOut?e.zoomWindow.stop(!0,!0).fadeOut(e.options.zoomWindowFadeOut,function(){e.loop&&(clearInterval(e.loop),e.loop=!1)}):e.zoomWindow.hide(),e.isWindowActive=!1)},showHideLens:function(o){var e=this;"show"==o&&(e.isLensActive||(e.options.lensFadeIn?e.zoomLens.stop(!0,!0,!1).fadeIn(e.options.lensFadeIn):e.zoomLens.show(),e.isLensActive=!0)),"hide"==o&&e.isLensActive&&(e.options.lensFadeOut?e.zoomLens.stop(!0,!0).fadeOut(e.options.lensFadeOut):e.zoomLens.hide(),e.isLensActive=!1)},showHideTint:function(o){var e=this;"show"==o&&(e.isTintActive||(e.options.zoomTintFadeIn?e.zoomTint.css({opacity:e.options.tintOpacity}).animate().stop(!0,!0).fadeIn("slow"):(e.zoomTint.css({opacity:e.options.tintOpacity}).animate(),e.zoomTint.show()),e.isTintActive=!0)),"hide"==o&&e.isTintActive&&(e.options.zoomTintFadeOut?e.zoomTint.stop(!0,!0).fadeOut(e.options.zoomTintFadeOut):e.zoomTint.hide(),e.isTintActive=!1)},setLensPostition:function(o){},setWindowPostition:function(o){var e=this;if(isNaN(e.options.zoomWindowPosition))e.externalContainer=$("#"+e.options.zoomWindowPosition),e.externalContainerWidth=e.externalContainer.width(),e.externalContainerHeight=e.externalContainer.height(),e.externalContainerOffset=e.externalContainer.offset(),e.windowOffsetTop=e.externalContainerOffset.top,e.windowOffsetLeft=e.externalContainerOffset.left;else switch(e.options.zoomWindowPosition){case 1:e.windowOffsetTop=e.options.zoomWindowOffety,e.windowOffsetLeft=+e.nzWidth;break;case 2:e.options.zoomWindowHeight>e.nzHeight&&(e.windowOffsetTop=-1*(e.options.zoomWindowHeight/2-e.nzHeight/2),e.windowOffsetLeft=e.nzWidth);break;case 3:e.windowOffsetTop=e.nzHeight-e.zoomWindow.height()-2*e.options.borderSize,e.windowOffsetLeft=e.nzWidth;break;case 4:e.windowOffsetTop=e.nzHeight,e.windowOffsetLeft=e.nzWidth;break;case 5:e.windowOffsetTop=e.nzHeight,e.windowOffsetLeft=e.nzWidth-e.zoomWindow.width()-2*e.options.borderSize;break;case 6:e.options.zoomWindowHeight>e.nzHeight&&(e.windowOffsetTop=e.nzHeight,e.windowOffsetLeft=-1*(e.options.zoomWindowWidth/2-e.nzWidth/2+2*e.options.borderSize));break;case 7:e.windowOffsetTop=e.nzHeight,e.windowOffsetLeft=0;break;case 8:e.windowOffsetTop=e.nzHeight,e.windowOffsetLeft=-1*(e.zoomWindow.width()+2*e.options.borderSize);break;case 9:e.windowOffsetTop=e.nzHeight-e.zoomWindow.height()-2*e.options.borderSize,e.windowOffsetLeft=-1*(e.zoomWindow.width()+2*e.options.borderSize);break;case 10:e.options.zoomWindowHeight>e.nzHeight&&(e.windowOffsetTop=-1*(e.options.zoomWindowHeight/2-e.nzHeight/2),e.windowOffsetLeft=-1*(e.zoomWindow.width()+2*e.options.borderSize));break;case 11:e.windowOffsetTop=e.options.zoomWindowOffety,e.windowOffsetLeft=-1*(e.zoomWindow.width()+2*e.options.borderSize);break;case 12:e.windowOffsetTop=-1*(e.zoomWindow.height()+2*e.options.borderSize),e.windowOffsetLeft=-1*(e.zoomWindow.width()+2*e.options.borderSize);break;case 13:e.windowOffsetTop=-1*(e.zoomWindow.height()+2*e.options.borderSize),e.windowOffsetLeft=0;break;case 14:e.options.zoomWindowHeight>e.nzHeight&&(e.windowOffsetTop=-1*(e.zoomWindow.height()+2*e.options.borderSize),e.windowOffsetLeft=-1*(e.options.zoomWindowWidth/2-e.nzWidth/2+2*e.options.borderSize));break;case 15:e.windowOffsetTop=-1*(e.zoomWindow.height()+2*e.options.borderSize),e.windowOffsetLeft=e.nzWidth-e.zoomWindow.width()-2*e.options.borderSize;break;case 16:e.windowOffsetTop=-1*(e.zoomWindow.height()+2*e.options.borderSize),e.windowOffsetLeft=e.nzWidth;break;default:e.windowOffsetTop=e.options.zoomWindowOffety,e.windowOffsetLeft=e.nzWidth}e.isWindowSet=!0,e.windowOffsetTop=e.windowOffsetTop+e.options.zoomWindowOffety,e.windowOffsetLeft=e.windowOffsetLeft+e.options.zoomWindowOffetx,e.zoomWindow.css({top:e.windowOffsetTop}),e.zoomWindow.css({left:e.windowOffsetLeft}),"inner"==e.options.zoomType&&(e.zoomWindow.css({top:0}),e.zoomWindow.css({left:0})),e.windowLeftPos=String(-1*((o.pageX-e.nzOffset.left)*e.widthRatio-e.zoomWindow.width()/2)),e.windowTopPos=String(-1*((o.pageY-e.nzOffset.top)*e.heightRatio-e.zoomWindow.height()/2)),e.Etoppos&&(e.windowTopPos=0),e.Eloppos&&(e.windowLeftPos=0),e.Eboppos&&(e.windowTopPos=-1*(e.largeHeight/e.currentZoomLevel-e.zoomWindow.height())),e.Eroppos&&(e.windowLeftPos=-1*(e.largeWidth/e.currentZoomLevel-e.zoomWindow.width())),e.fullheight&&(e.windowTopPos=0),e.fullwidth&&(e.windowLeftPos=0),("window"==e.options.zoomType||"inner"==e.options.zoomType)&&(1==e.zoomLock&&(e.widthRatio<=1&&(e.windowLeftPos=0),e.heightRatio<=1&&(e.windowTopPos=0)),"window"==e.options.zoomType&&(e.largeHeight<e.options.zoomWindowHeight&&(e.windowTopPos=0),e.largeWidth<e.options.zoomWindowWidth&&(e.windowLeftPos=0)),e.options.easing?(e.xp||(e.xp=0),e.yp||(e.yp=0),e.loop||(e.loop=setInterval(function(){e.xp+=(e.windowLeftPos-e.xp)/e.options.easingAmount,e.yp+=(e.windowTopPos-e.yp)/e.options.easingAmount,e.scrollingLock?(clearInterval(e.loop),e.xp=e.windowLeftPos,e.yp=e.windowTopPos,e.xp=-1*((o.pageX-e.nzOffset.left)*e.widthRatio-e.zoomWindow.width()/2),e.yp=-1*((o.pageY-e.nzOffset.top)*e.heightRatio-e.zoomWindow.height()/2),e.changeBgSize&&(e.nzHeight>e.nzWidth?("lens"==e.options.zoomType&&e.zoomLens.css({"background-size":e.largeWidth/e.newvalueheight+"px "+e.largeHeight/e.newvalueheight+"px"}),e.zoomWindow.css({"background-size":e.largeWidth/e.newvalueheight+"px "+e.largeHeight/e.newvalueheight+"px"})):("lens"!=e.options.zoomType&&e.zoomLens.css({"background-size":e.largeWidth/e.newvaluewidth+"px "+e.largeHeight/e.newvalueheight+"px"}),e.zoomWindow.css({"background-size":e.largeWidth/e.newvaluewidth+"px "+e.largeHeight/e.newvaluewidth+"px"})),e.changeBgSize=!1),e.zoomWindow.css({backgroundPosition:e.windowLeftPos+"px "+e.windowTopPos+"px"}),e.scrollingLock=!1,e.loop=!1):Math.round(Math.abs(e.xp-e.windowLeftPos)+Math.abs(e.yp-e.windowTopPos))<1?(clearInterval(e.loop),e.zoomWindow.css({backgroundPosition:e.windowLeftPos+"px "+e.windowTopPos+"px"}),e.loop=!1):(e.changeBgSize&&(e.nzHeight>e.nzWidth?("lens"==e.options.zoomType&&e.zoomLens.css({"background-size":e.largeWidth/e.newvalueheight+"px "+e.largeHeight/e.newvalueheight+"px"}),e.zoomWindow.css({"background-size":e.largeWidth/e.newvalueheight+"px "+e.largeHeight/e.newvalueheight+"px"})):("lens"!=e.options.zoomType&&e.zoomLens.css({"background-size":e.largeWidth/e.newvaluewidth+"px "+e.largeHeight/e.newvaluewidth+"px"}),e.zoomWindow.css({"background-size":e.largeWidth/e.newvaluewidth+"px "+e.largeHeight/e.newvaluewidth+"px"})),e.changeBgSize=!1),e.zoomWindow.css({backgroundPosition:e.xp+"px "+e.yp+"px"}))},16))):(e.changeBgSize&&(e.nzHeight>e.nzWidth?("lens"==e.options.zoomType&&e.zoomLens.css({"background-size":e.largeWidth/e.newvalueheight+"px "+e.largeHeight/e.newvalueheight+"px"}),e.zoomWindow.css({"background-size":e.largeWidth/e.newvalueheight+"px "+e.largeHeight/e.newvalueheight+"px"})):("lens"==e.options.zoomType&&e.zoomLens.css({"background-size":e.largeWidth/e.newvaluewidth+"px "+e.largeHeight/e.newvaluewidth+"px"}),e.largeHeight/e.newvaluewidth<e.options.zoomWindowHeight?e.zoomWindow.css({"background-size":e.largeWidth/e.newvaluewidth+"px "+e.largeHeight/e.newvaluewidth+"px"}):e.zoomWindow.css({"background-size":e.largeWidth/e.newvalueheight+"px "+e.largeHeight/e.newvalueheight+"px"})),e.changeBgSize=!1),e.zoomWindow.css({backgroundPosition:e.windowLeftPos+"px "+e.windowTopPos+"px"})))},setTintPosition:function(o){var e=this;e.nzOffset=e.$elem.offset(),e.tintpos=String(-1*(o.pageX-e.nzOffset.left-e.zoomLens.width()/2)),e.tintposy=String(-1*(o.pageY-e.nzOffset.top-e.zoomLens.height()/2)),e.Etoppos&&(e.tintposy=0),e.Eloppos&&(e.tintpos=0),e.Eboppos&&(e.tintposy=-1*(e.nzHeight-e.zoomLens.height()-2*e.options.lensBorderSize)),e.Eroppos&&(e.tintpos=-1*(e.nzWidth-e.zoomLens.width()-2*e.options.lensBorderSize)),e.options.tint&&(e.fullheight&&(e.tintposy=0),e.fullwidth&&(e.tintpos=0),e.zoomTintImage.css({left:e.tintpos+"px"}),e.zoomTintImage.css({top:e.tintposy+"px"}))},swaptheimage:function(o,e){var i=this,t=new Image;i.options.loadingIcon&&(i.spinner=$("<div style=\"background: url('"+i.options.loadingIcon+"') no-repeat center;height:"+i.nzHeight+"px;width:"+i.nzWidth+'px;z-index: 2000;position: absolute; background-position: center center;"></div>'),i.$elem.after(i.spinner)),i.options.onImageSwap(i.$elem),t.onload=function(){i.largeWidth=t.width,i.largeHeight=t.height,i.zoomImage=e,i.zoomWindow.css({"background-size":i.largeWidth+"px "+i.largeHeight+"px"}),i.swapAction(o,e)},t.src=e},swapAction:function(o,e){var i=this,t=new Image;if(t.onload=function(){i.nzHeight=t.height,i.nzWidth=t.width,i.options.onImageSwapComplete(i.$elem),i.doneCallback()},t.src=o,i.currentZoomLevel=i.options.zoomLevel,i.options.maxZoomLevel=!1,"lens"==i.options.zoomType&&i.zoomLens.css({backgroundImage:"url('"+e+"')"}),"window"==i.options.zoomType&&i.zoomWindow.css({backgroundImage:"url('"+e+"')"}),"inner"==i.options.zoomType&&i.zoomWindow.css({backgroundImage:"url('"+e+"')"}),i.currentImage=e,i.options.imageCrossfade){var n=i.$elem,s=n.clone();if(i.$elem.attr("src",o),i.$elem.after(s),s.stop(!0).fadeOut(i.options.imageCrossfade,function(){$(this).remove()}),i.$elem.width("auto").removeAttr("width"),i.$elem.height("auto").removeAttr("height"),n.fadeIn(i.options.imageCrossfade),i.options.tint&&"inner"!=i.options.zoomType){var h=i.zoomTintImage,a=h.clone();i.zoomTintImage.attr("src",e),i.zoomTintImage.after(a),a.stop(!0).fadeOut(i.options.imageCrossfade,function(){$(this).remove()}),h.fadeIn(i.options.imageCrossfade),i.zoomTint.css({height:i.$elem.height()}),i.zoomTint.css({width:i.$elem.width()})}i.zoomContainer.css("height",i.$elem.height()),i.zoomContainer.css("width",i.$elem.width()),"inner"==i.options.zoomType&&(i.options.constrainType||(i.zoomWrap.parent().css("height",i.$elem.height()),i.zoomWrap.parent().css("width",i.$elem.width()),i.zoomWindow.css("height",i.$elem.height()),i.zoomWindow.css("width",i.$elem.width()))),i.options.imageCrossfade&&(i.zoomWrap.css("height",i.$elem.height()),i.zoomWrap.css("width",i.$elem.width()))}else i.$elem.attr("src",o),i.options.tint&&(i.zoomTintImage.attr("src",e),i.zoomTintImage.attr("height",i.$elem.height()),i.zoomTintImage.css({height:i.$elem.height()}),i.zoomTint.css({height:i.$elem.height()})),i.zoomContainer.css("height",i.$elem.height()),i.zoomContainer.css("width",i.$elem.width()),i.options.imageCrossfade&&(i.zoomWrap.css("height",i.$elem.height()),i.zoomWrap.css("width",i.$elem.width()));i.options.constrainType&&("height"==i.options.constrainType&&(i.zoomContainer.css("height",i.options.constrainSize),i.zoomContainer.css("width","auto"),i.options.imageCrossfade?(i.zoomWrap.css("height",i.options.constrainSize),i.zoomWrap.css("width","auto"),i.constwidth=i.zoomWrap.width()):(i.$elem.css("height",i.options.constrainSize),i.$elem.css("width","auto"),i.constwidth=i.$elem.width()),"inner"==i.options.zoomType&&(i.zoomWrap.parent().css("height",i.options.constrainSize),i.zoomWrap.parent().css("width",i.constwidth),i.zoomWindow.css("height",i.options.constrainSize),i.zoomWindow.css("width",i.constwidth)),i.options.tint&&(i.tintContainer.css("height",i.options.constrainSize),i.tintContainer.css("width",i.constwidth),i.zoomTint.css("height",i.options.constrainSize),i.zoomTint.css("width",i.constwidth),i.zoomTintImage.css("height",i.options.constrainSize),i.zoomTintImage.css("width",i.constwidth))),"width"==i.options.constrainType&&(i.zoomContainer.css("height","auto"),i.zoomContainer.css("width",i.options.constrainSize),i.options.imageCrossfade?(i.zoomWrap.css("height","auto"),i.zoomWrap.css("width",i.options.constrainSize),i.constheight=i.zoomWrap.height()):(i.$elem.css("height","auto"),i.$elem.css("width",i.options.constrainSize),i.constheight=i.$elem.height()),"inner"==i.options.zoomType&&(i.zoomWrap.parent().css("height",i.constheight),i.zoomWrap.parent().css("width",i.options.constrainSize),i.zoomWindow.css("height",i.constheight),i.zoomWindow.css("width",i.options.constrainSize)),i.options.tint&&(i.tintContainer.css("height",i.constheight),i.tintContainer.css("width",i.options.constrainSize),i.zoomTint.css("height",i.constheight),i.zoomTint.css("width",i.options.constrainSize),i.zoomTintImage.css("height",i.constheight),i.zoomTintImage.css("width",i.options.constrainSize))))},doneCallback:function(){var o=this;o.options.loadingIcon&&o.spinner.hide(),o.nzOffset=o.$elem.offset(),o.nzWidth=o.$elem.width(),o.nzHeight=o.$elem.height(),o.currentZoomLevel=o.options.zoomLevel,o.widthRatio=o.largeWidth/o.nzWidth,o.heightRatio=o.largeHeight/o.nzHeight,"window"==o.options.zoomType&&(o.nzHeight<o.options.zoomWindowWidth/o.widthRatio?lensHeight=o.nzHeight:lensHeight=String(o.options.zoomWindowHeight/o.heightRatio),o.options.zoomWindowWidth<o.options.zoomWindowWidth?lensWidth=o.nzWidth:lensWidth=o.options.zoomWindowWidth/o.widthRatio,o.zoomLens&&(o.zoomLens.css("width",lensWidth),o.zoomLens.css("height",lensHeight)))},getCurrentImage:function(){var o=this;return o.zoomImage},getGalleryList:function(){var o=this;return o.gallerylist=[],o.options.gallery?$("#"+o.options.gallery+" a").each(function(){var e="";$(this).data("zoom-image")?e=$(this).data("zoom-image"):$(this).data("image")&&(e=$(this).data("image")),e==o.zoomImage?o.gallerylist.unshift({href:""+e,title:$(this).find("img").attr("title")}):o.gallerylist.push({href:""+e,title:$(this).find("img").attr("title")})}):o.gallerylist.push({href:""+o.zoomImage,title:$(this).find("img").attr("title")}),o.gallerylist},changeZoomLevel:function(o){var e=this;e.scrollingLock=!0,e.newvalue=parseFloat(o).toFixed(2),newvalue=parseFloat(o).toFixed(2),maxheightnewvalue=e.largeHeight/(e.options.zoomWindowHeight/e.nzHeight*e.nzHeight),maxwidthtnewvalue=e.largeWidth/(e.options.zoomWindowWidth/e.nzWidth*e.nzWidth),"inner"!=e.options.zoomType&&(maxheightnewvalue<=newvalue?(e.heightRatio=e.largeHeight/maxheightnewvalue/e.nzHeight,e.newvalueheight=maxheightnewvalue,e.fullheight=!0):(e.heightRatio=e.largeHeight/newvalue/e.nzHeight,e.newvalueheight=newvalue,e.fullheight=!1),maxwidthtnewvalue<=newvalue?(e.widthRatio=e.largeWidth/maxwidthtnewvalue/e.nzWidth,e.newvaluewidth=maxwidthtnewvalue,e.fullwidth=!0):(e.widthRatio=e.largeWidth/newvalue/e.nzWidth,e.newvaluewidth=newvalue,e.fullwidth=!1),"lens"==e.options.zoomType&&(maxheightnewvalue<=newvalue?(e.fullwidth=!0,e.newvaluewidth=maxheightnewvalue):(e.widthRatio=e.largeWidth/newvalue/e.nzWidth,e.newvaluewidth=newvalue,e.fullwidth=!1))),"inner"==e.options.zoomType&&(maxheightnewvalue=parseFloat(e.largeHeight/e.nzHeight).toFixed(2),maxwidthtnewvalue=parseFloat(e.largeWidth/e.nzWidth).toFixed(2),newvalue>maxheightnewvalue&&(newvalue=maxheightnewvalue),newvalue>maxwidthtnewvalue&&(newvalue=maxwidthtnewvalue),maxheightnewvalue<=newvalue?(e.heightRatio=e.largeHeight/newvalue/e.nzHeight,newvalue>maxheightnewvalue?e.newvalueheight=maxheightnewvalue:e.newvalueheight=newvalue,e.fullheight=!0):(e.heightRatio=e.largeHeight/newvalue/e.nzHeight,newvalue>maxheightnewvalue?e.newvalueheight=maxheightnewvalue:e.newvalueheight=newvalue,e.fullheight=!1),maxwidthtnewvalue<=newvalue?(e.widthRatio=e.largeWidth/newvalue/e.nzWidth,newvalue>maxwidthtnewvalue?e.newvaluewidth=maxwidthtnewvalue:e.newvaluewidth=newvalue,e.fullwidth=!0):(e.widthRatio=e.largeWidth/newvalue/e.nzWidth,e.newvaluewidth=newvalue,e.fullwidth=!1)),scrcontinue=!1,"inner"==e.options.zoomType&&(e.nzWidth>=e.nzHeight&&(e.newvaluewidth<=maxwidthtnewvalue?scrcontinue=!0:(scrcontinue=!1,e.fullheight=!0,e.fullwidth=!0)),e.nzHeight>e.nzWidth&&(e.newvaluewidth<=maxwidthtnewvalue?scrcontinue=!0:(scrcontinue=!1,e.fullheight=!0,e.fullwidth=!0))),"inner"!=e.options.zoomType&&(scrcontinue=!0),scrcontinue&&(e.zoomLock=0,e.changeZoom=!0,e.options.zoomWindowHeight/e.heightRatio<=e.nzHeight&&(e.currentZoomLevel=e.newvalueheight,"lens"!=e.options.zoomType&&"inner"!=e.options.zoomType&&(e.changeBgSize=!0,e.zoomLens.css({height:String(e.options.zoomWindowHeight/e.heightRatio)+"px"})),("lens"==e.options.zoomType||"inner"==e.options.zoomType)&&(e.changeBgSize=!0)),e.options.zoomWindowWidth/e.widthRatio<=e.nzWidth&&("inner"!=e.options.zoomType&&e.newvaluewidth>e.newvalueheight&&(e.currentZoomLevel=e.newvaluewidth),"lens"!=e.options.zoomType&&"inner"!=e.options.zoomType&&(e.changeBgSize=!0,e.zoomLens.css({width:String(e.options.zoomWindowWidth/e.widthRatio)+"px"})),("lens"==e.options.zoomType||"inner"==e.options.zoomType)&&(e.changeBgSize=!0)),"inner"==e.options.zoomType&&(e.changeBgSize=!0,e.nzWidth>e.nzHeight&&(e.currentZoomLevel=e.newvaluewidth),e.nzHeight>e.nzWidth&&(e.currentZoomLevel=e.newvaluewidth))),e.setPosition(e.currentLoc)},closeAll:function(){self.zoomWindow&&self.zoomWindow.hide(),self.zoomLens&&self.zoomLens.hide(),self.zoomTint&&self.zoomTint.hide()},changeState:function(o){var e=this;"enable"==o&&(e.options.zoomEnabled=!0),"disable"==o&&(e.options.zoomEnabled=!1)}};$.fn.elevateZoom=function(o){return this.each(function(){var e=Object.create(t);e.init(o,this),$.data(this,"elevateZoom",e)})},$.fn.elevateZoom.options={zoomActivation:"hover",zoomEnabled:!0,preloading:1,zoomLevel:1,scrollZoom:!1,scrollZoomIncrement:.1,minZoomLevel:!1,maxZoomLevel:!1,easing:!1,easingAmount:12,lensSize:200,zoomWindowWidth:400,zoomWindowHeight:400,zoomWindowOffetx:0,zoomWindowOffety:0,zoomWindowPosition:1,zoomWindowBgColour:"#fff",lensFadeIn:!1,lensFadeOut:!1,debug:!1,zoomWindowFadeIn:!1,zoomWindowFadeOut:!1,zoomWindowAlwaysShow:!1,zoomTintFadeIn:!1,zoomTintFadeOut:!1,borderSize:4,showLens:!0,borderColour:"#888",lensBorderSize:1,lensBorderColour:"#000",lensShape:"square",zoomType:"window",containLensZoom:!1,lensColour:"white",lensOpacity:.4,lenszoom:!1,tint:!1,tintColour:"#333",tintOpacity:.4,gallery:!1,galleryActiveClass:"zoomGalleryActive",imageCrossfade:!1,constrainType:!1,constrainSize:!1,loadingIcon:!1,cursor:"default",responsive:!0,onComplete:$.noop,onDestroy:function(){},onZoomedImageLoaded:function(){},onImageSwap:$.noop,onImageSwapComplete:$.noop
}}(jQuery,window,document);

/*
== malihu jquery custom scrollbar plugin ==
Version: 3.1.5
Plugin URI: http://manos.malihu.gr/jquery-custom-content-scroller
Author: malihu
Author URI: http://manos.malihu.gr
License: MIT License (MIT)
*/

/*
Copyright Manos Malihutsakis (email: manos@malihu.gr)

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.
*/

/*
The code below is fairly long, fully commented and should be normally used in development.
For production, use either the minified jquery.mCustomScrollbar.min.js script or
the production-ready jquery.mCustomScrollbar.concat.min.js which contains the plugin
and dependencies (minified).
*/

(function(factory){
	if(typeof define==="function" && define.amd){
		define(["jquery"],factory);
	}else if(typeof module!=="undefined" && module.exports){
		module.exports=factory;
	}else{
		factory(jQuery,window,document);
	}
}(function($){
(function(init){
	var _rjs=typeof define==="function" && define.amd, /* RequireJS */
		_njs=typeof module !== "undefined" && module.exports, /* NodeJS */
		_dlp=("https:"==document.location.protocol) ? "https:" : "http:", /* location protocol */
		_url="cdnjs.cloudflare.com/ajax/libs/jquery-mousewheel/3.1.13/jquery.mousewheel.min.js";
	if(!_rjs){
		if(_njs){
			require("jquery-mousewheel")($);
		}else{
			/* load jquery-mousewheel plugin (via CDN) if it's not present or not loaded via RequireJS
			(works when mCustomScrollbar fn is called on window load) */
			$.event.special.mousewheel || $("head").append(decodeURI("%3Cscript src="+_dlp+"//"+_url+"%3E%3C/script%3E"));
		}
	}
	init();
}(function(){

	/*
	----------------------------------------
	PLUGIN NAMESPACE, PREFIX, DEFAULT SELECTOR(S)
	----------------------------------------
	*/

	var pluginNS="mCustomScrollbar",
		pluginPfx="mCS",
		defaultSelector=".mCustomScrollbar",





	/*
	----------------------------------------
	DEFAULT OPTIONS
	----------------------------------------
	*/

		defaults={
			/*
			set element/content width/height programmatically
			values: boolean, pixels, percentage
				option						default
				-------------------------------------
				setWidth					false
				setHeight					false
			*/
			/*
			set the initial css top property of content
			values: string (e.g. "-100px", "10%" etc.)
			*/
			setTop:0,
			/*
			set the initial css left property of content
			values: string (e.g. "-100px", "10%" etc.)
			*/
			setLeft:0,
			/*
			scrollbar axis (vertical and/or horizontal scrollbars)
			values (string): "y", "x", "yx"
			*/
			axis:"y",
			/*
			position of scrollbar relative to content
			values (string): "inside", "outside" ("outside" requires elements with position:relative)
			*/
			scrollbarPosition:"inside",
			/*
			scrolling inertia
			values: integer (milliseconds)
			*/
			scrollInertia:950,
			/*
			auto-adjust scrollbar dragger length
			values: boolean
			*/
			autoDraggerLength:true,
			/*
			auto-hide scrollbar when idle
			values: boolean
				option						default
				-------------------------------------
				autoHideScrollbar			false
			*/
			/*
			auto-expands scrollbar on mouse-over and dragging
			values: boolean
				option						default
				-------------------------------------
				autoExpandScrollbar			false
			*/
			/*
			always show scrollbar, even when there's nothing to scroll
			values: integer (0=disable, 1=always show dragger rail and buttons, 2=always show dragger rail, dragger and buttons), boolean
			*/
			alwaysShowScrollbar:0,
			/*
			scrolling always snaps to a multiple of this number in pixels
			values: integer, array ([y,x])
				option						default
				-------------------------------------
				snapAmount					null
			*/
			/*
			when snapping, snap with this number in pixels as an offset
			values: integer
			*/
			snapOffset:0,
			/*
			mouse-wheel scrolling
			*/
			mouseWheel:{
				/*
				enable mouse-wheel scrolling
				values: boolean
				*/
				enable:true,
				/*
				scrolling amount in pixels
				values: "auto", integer
				*/
				scrollAmount:"auto",
				/*
				mouse-wheel scrolling axis
				the default scrolling direction when both vertical and horizontal scrollbars are present
				values (string): "y", "x"
				*/
				axis:"y",
				/*
				prevent the default behaviour which automatically scrolls the parent element(s) when end of scrolling is reached
				values: boolean
					option						default
					-------------------------------------
					preventDefault				null
				*/
				/*
				the reported mouse-wheel delta value. The number of lines (translated to pixels) one wheel notch scrolls.
				values: "auto", integer
				"auto" uses the default OS/browser value
				*/
				deltaFactor:"auto",
				/*
				normalize mouse-wheel delta to -1 or 1 (disables mouse-wheel acceleration)
				values: boolean
					option						default
					-------------------------------------
					normalizeDelta				null
				*/
				/*
				invert mouse-wheel scrolling direction
				values: boolean
					option						default
					-------------------------------------
					invert						null
				*/
				/*
				the tags that disable mouse-wheel when cursor is over them
				*/
				disableOver:["select","option","keygen","datalist","textarea"]
			},
			/*
			scrollbar buttons
			*/
			scrollButtons:{
				/*
				enable scrollbar buttons
				values: boolean
					option						default
					-------------------------------------
					enable						null
				*/
				/*
				scrollbar buttons scrolling type
				values (string): "stepless", "stepped"
				*/
				scrollType:"stepless",
				/*
				scrolling amount in pixels
				values: "auto", integer
				*/
				scrollAmount:"auto"
				/*
				tabindex of the scrollbar buttons
				values: false, integer
					option						default
					-------------------------------------
					tabindex					null
				*/
			},
			/*
			keyboard scrolling
			*/
			keyboard:{
				/*
				enable scrolling via keyboard
				values: boolean
				*/
				enable:true,
				/*
				keyboard scrolling type
				values (string): "stepless", "stepped"
				*/
				scrollType:"stepless",
				/*
				scrolling amount in pixels
				values: "auto", integer
				*/
				scrollAmount:"auto"
			},
			/*
			enable content touch-swipe scrolling
			values: boolean, integer, string (number)
			integer values define the axis-specific minimum amount required for scrolling momentum
			*/
			contentTouchScroll:25,
			/*
			enable/disable document (default) touch-swipe scrolling
			*/
			documentTouchScroll:true,
			/*
			advanced option parameters
			*/
			advanced:{
				/*
				auto-expand content horizontally (for "x" or "yx" axis)
				values: boolean, integer (the value 2 forces the non scrollHeight/scrollWidth method, the value 3 forces the scrollHeight/scrollWidth method)
					option						default
					-------------------------------------
					autoExpandHorizontalScroll	null
				*/
				/*
				auto-scroll to elements with focus
				*/
				autoScrollOnFocus:"input,textarea,select,button,datalist,keygen,a[tabindex],area,object,[contenteditable='true']",
				/*
				auto-update scrollbars on content, element or viewport resize
				should be true for fluid layouts/elements, adding/removing content dynamically, hiding/showing elements, content with images etc.
				values: boolean
				*/
				updateOnContentResize:true,
				/*
				auto-update scrollbars each time each image inside the element is fully loaded
				values: "auto", boolean
				*/
				updateOnImageLoad:"auto",
				/*
				auto-update scrollbars based on the amount and size changes of specific selectors
				useful when you need to update the scrollbar(s) automatically, each time a type of element is added, removed or changes its size
				values: boolean, string (e.g. "ul li" will auto-update scrollbars each time list-items inside the element are changed)
				a value of true (boolean) will auto-update scrollbars each time any element is changed
					option						default
					-------------------------------------
					updateOnSelectorChange		null
				*/
				/*
				extra selectors that'll allow scrollbar dragging upon mousemove/up, pointermove/up, touchend etc. (e.g. "selector-1, selector-2")
					option						default
					-------------------------------------
					extraDraggableSelectors		null
				*/
				/*
				extra selectors that'll release scrollbar dragging upon mouseup, pointerup, touchend etc. (e.g. "selector-1, selector-2")
					option						default
					-------------------------------------
					releaseDraggableSelectors	null
				*/
				/*
				auto-update timeout
				values: integer (milliseconds)
				*/
				autoUpdateTimeout:60
			},
			/*
			scrollbar theme
			values: string (see CSS/plugin URI for a list of ready-to-use themes)
			*/
			theme:"light",
			/*
			user defined callback functions
			*/
			callbacks:{
				/*
				Available callbacks:
					callback					default
					-------------------------------------
					onCreate					null
					onInit						null
					onScrollStart				null
					onScroll					null
					onTotalScroll				null
					onTotalScrollBack			null
					whileScrolling				null
					onOverflowY					null
					onOverflowX					null
					onOverflowYNone				null
					onOverflowXNone				null
					onImageLoad					null
					onSelectorChange			null
					onBeforeUpdate				null
					onUpdate					null
				*/
				onTotalScrollOffset:0,
				onTotalScrollBackOffset:0,
				alwaysTriggerOffsets:true
			}
			/*
			add scrollbar(s) on all elements matching the current selector, now and in the future
			values: boolean, string
			string values: "on" (enable), "once" (disable after first invocation), "off" (disable)
			liveSelector values: string (selector)
				option						default
				-------------------------------------
				live						false
				liveSelector				null
			*/
		},





	/*
	----------------------------------------
	VARS, CONSTANTS
	----------------------------------------
	*/

		totalInstances=0, /* plugin instances amount */
		liveTimers={}, /* live option timers */
		oldIE=(window.attachEvent && !window.addEventListener) ? 1 : 0, /* detect IE < 9 */
		touchActive=false,touchable, /* global touch vars (for touch and pointer events) */
		/* general plugin classes */
		classes=[
			"mCSB_dragger_onDrag","mCSB_scrollTools_onDrag","mCS_img_loaded","mCS_disabled","mCS_destroyed","mCS_no_scrollbar",
			"mCS-autoHide","mCS-dir-rtl","mCS_no_scrollbar_y","mCS_no_scrollbar_x","mCS_y_hidden","mCS_x_hidden","mCSB_draggerContainer",
			"mCSB_buttonUp","mCSB_buttonDown","mCSB_buttonLeft","mCSB_buttonRight"
		],





	/*
	----------------------------------------
	METHODS
	----------------------------------------
	*/

		methods={

			/*
			plugin initialization method
			creates the scrollbar(s), plugin data object and options
			----------------------------------------
			*/

			init:function(options){

				var options=$.extend(true,{},defaults,options),
					selector=_selector.call(this); /* validate selector */

				/*
				if live option is enabled, monitor for elements matching the current selector and
				apply scrollbar(s) when found (now and in the future)
				*/
				if(options.live){
					var liveSelector=options.liveSelector || this.selector || defaultSelector, /* live selector(s) */
						$liveSelector=$(liveSelector); /* live selector(s) as jquery object */
					if(options.live==="off"){
						/*
						disable live if requested
						usage: $(selector).mCustomScrollbar({live:"off"});
						*/
						removeLiveTimers(liveSelector);
						return;
					}
					liveTimers[liveSelector]=setTimeout(function(){
						/* call mCustomScrollbar fn on live selector(s) every half-second */
						$liveSelector.mCustomScrollbar(options);
						if(options.live==="once" && $liveSelector.length){
							/* disable live after first invocation */
							removeLiveTimers(liveSelector);
						}
					},500);
				}else{
					removeLiveTimers(liveSelector);
				}

				/* options backward compatibility (for versions < 3.0.0) and normalization */
				options.setWidth=(options.set_width) ? options.set_width : options.setWidth;
				options.setHeight=(options.set_height) ? options.set_height : options.setHeight;
				options.axis=(options.horizontalScroll) ? "x" : _findAxis(options.axis);
				options.scrollInertia=options.scrollInertia>0 && options.scrollInertia<17 ? 17 : options.scrollInertia;
				if(typeof options.mouseWheel!=="object" &&  options.mouseWheel==true){ /* old school mouseWheel option (non-object) */
					options.mouseWheel={enable:true,scrollAmount:"auto",axis:"y",preventDefault:false,deltaFactor:"auto",normalizeDelta:false,invert:false}
				}
				options.mouseWheel.scrollAmount=!options.mouseWheelPixels ? options.mouseWheel.scrollAmount : options.mouseWheelPixels;
				options.mouseWheel.normalizeDelta=!options.advanced.normalizeMouseWheelDelta ? options.mouseWheel.normalizeDelta : options.advanced.normalizeMouseWheelDelta;
				options.scrollButtons.scrollType=_findScrollButtonsType(options.scrollButtons.scrollType);

				_theme(options); /* theme-specific options */

				/* plugin constructor */
				return $(selector).each(function(){

					var $this=$(this);

					if(!$this.data(pluginPfx)){ /* prevent multiple instantiations */

						/* store options and create objects in jquery data */
						$this.data(pluginPfx,{
							idx:++totalInstances, /* instance index */
							opt:options, /* options */
							scrollRatio:{y:null,x:null}, /* scrollbar to content ratio */
							overflowed:null, /* overflowed axis */
							contentReset:{y:null,x:null}, /* object to check when content resets */
							bindEvents:false, /* object to check if events are bound */
							tweenRunning:false, /* object to check if tween is running */
							sequential:{}, /* sequential scrolling object */
							langDir:$this.css("direction"), /* detect/store direction (ltr or rtl) */
							cbOffsets:null, /* object to check whether callback offsets always trigger */
							/*
							object to check how scrolling events where last triggered
							"internal" (default - triggered by this script), "external" (triggered by other scripts, e.g. via scrollTo method)
							usage: object.data("mCS").trigger
							*/
							trigger:null,
							/*
							object to check for changes in elements in order to call the update method automatically
							*/
							poll:{size:{o:0,n:0},img:{o:0,n:0},change:{o:0,n:0}}
						});

						var d=$this.data(pluginPfx),o=d.opt,
							/* HTML data attributes */
							htmlDataAxis=$this.data("mcs-axis"),htmlDataSbPos=$this.data("mcs-scrollbar-position"),htmlDataTheme=$this.data("mcs-theme");

						if(htmlDataAxis){o.axis=htmlDataAxis;} /* usage example: data-mcs-axis="y" */
						if(htmlDataSbPos){o.scrollbarPosition=htmlDataSbPos;} /* usage example: data-mcs-scrollbar-position="outside" */
						if(htmlDataTheme){ /* usage example: data-mcs-theme="minimal" */
							o.theme=htmlDataTheme;
							_theme(o); /* theme-specific options */
						}

						_pluginMarkup.call(this); /* add plugin markup */

						if(d && o.callbacks.onCreate && typeof o.callbacks.onCreate==="function"){o.callbacks.onCreate.call(this);} /* callbacks: onCreate */

						$("#mCSB_"+d.idx+"_container img:not(."+classes[2]+")").addClass(classes[2]); /* flag loaded images */

						methods.update.call(null,$this); /* call the update method */

					}

				});

			},
			/* ---------------------------------------- */



			/*
			plugin update method
			updates content and scrollbar(s) values, events and status
			----------------------------------------
			usage: $(selector).mCustomScrollbar("update");
			*/

			update:function(el,cb){

				var selector=el || _selector.call(this); /* validate selector */

				return $(selector).each(function(){

					var $this=$(this);

					if($this.data(pluginPfx)){ /* check if plugin has initialized */

						var d=$this.data(pluginPfx),o=d.opt,
							mCSB_container=$("#mCSB_"+d.idx+"_container"),
							mCustomScrollBox=$("#mCSB_"+d.idx),
							mCSB_dragger=[$("#mCSB_"+d.idx+"_dragger_vertical"),$("#mCSB_"+d.idx+"_dragger_horizontal")];

						if(!mCSB_container.length){return;}

						if(d.tweenRunning){_stop($this);} /* stop any running tweens while updating */

						if(cb && d && o.callbacks.onBeforeUpdate && typeof o.callbacks.onBeforeUpdate==="function"){o.callbacks.onBeforeUpdate.call(this);} /* callbacks: onBeforeUpdate */

						/* if element was disabled or destroyed, remove class(es) */
						if($this.hasClass(classes[3])){$this.removeClass(classes[3]);}
						if($this.hasClass(classes[4])){$this.removeClass(classes[4]);}

						/* css flexbox fix, detect/set max-height */
						mCustomScrollBox.css("max-height","none");
						if(mCustomScrollBox.height()!==$this.height()){mCustomScrollBox.css("max-height",$this.height());}

						_expandContentHorizontally.call(this); /* expand content horizontally */

						if(o.axis!=="y" && !o.advanced.autoExpandHorizontalScroll){
							mCSB_container.css("width",_contentWidth(mCSB_container));
						}

						d.overflowed=_overflowed.call(this); /* determine if scrolling is required */

						_scrollbarVisibility.call(this); /* show/hide scrollbar(s) */

						/* auto-adjust scrollbar dragger length analogous to content */
						if(o.autoDraggerLength){_setDraggerLength.call(this);}

						_scrollRatio.call(this); /* calculate and store scrollbar to content ratio */

						_bindEvents.call(this); /* bind scrollbar events */

						/* reset scrolling position and/or events */
						var to=[Math.abs(mCSB_container[0].offsetTop),Math.abs(mCSB_container[0].offsetLeft)];
						if(o.axis!=="x"){ /* y/yx axis */
							if(!d.overflowed[0]){ /* y scrolling is not required */
								_resetContentPosition.call(this); /* reset content position */
								if(o.axis==="y"){
									_unbindEvents.call(this);
								}else if(o.axis==="yx" && d.overflowed[1]){
									_scrollTo($this,to[1].toString(),{dir:"x",dur:0,overwrite:"none"});
								}
							}else if(mCSB_dragger[0].height()>mCSB_dragger[0].parent().height()){
								_resetContentPosition.call(this); /* reset content position */
							}else{ /* y scrolling is required */
								_scrollTo($this,to[0].toString(),{dir:"y",dur:0,overwrite:"none"});
								d.contentReset.y=null;
							}
						}
						if(o.axis!=="y"){ /* x/yx axis */
							if(!d.overflowed[1]){ /* x scrolling is not required */
								_resetContentPosition.call(this); /* reset content position */
								if(o.axis==="x"){
									_unbindEvents.call(this);
								}else if(o.axis==="yx" && d.overflowed[0]){
									_scrollTo($this,to[0].toString(),{dir:"y",dur:0,overwrite:"none"});
								}
							}else if(mCSB_dragger[1].width()>mCSB_dragger[1].parent().width()){
								_resetContentPosition.call(this); /* reset content position */
							}else{ /* x scrolling is required */
								_scrollTo($this,to[1].toString(),{dir:"x",dur:0,overwrite:"none"});
								d.contentReset.x=null;
							}
						}

						/* callbacks: onImageLoad, onSelectorChange, onUpdate */
						if(cb && d){
							if(cb===2 && o.callbacks.onImageLoad && typeof o.callbacks.onImageLoad==="function"){
								o.callbacks.onImageLoad.call(this);
							}else if(cb===3 && o.callbacks.onSelectorChange && typeof o.callbacks.onSelectorChange==="function"){
								o.callbacks.onSelectorChange.call(this);
							}else if(o.callbacks.onUpdate && typeof o.callbacks.onUpdate==="function"){
								o.callbacks.onUpdate.call(this);
							}
						}

						_autoUpdate.call(this); /* initialize automatic updating (for dynamic content, fluid layouts etc.) */

					}

				});

			},
			/* ---------------------------------------- */



			/*
			plugin scrollTo method
			triggers a scrolling event to a specific value
			----------------------------------------
			usage: $(selector).mCustomScrollbar("scrollTo",value,options);
			*/

			scrollTo:function(val,options){

				/* prevent silly things like $(selector).mCustomScrollbar("scrollTo",undefined); */
				if(typeof val=="undefined" || val==null){return;}

				var selector=_selector.call(this); /* validate selector */

				return $(selector).each(function(){

					var $this=$(this);

					if($this.data(pluginPfx)){ /* check if plugin has initialized */

						var d=$this.data(pluginPfx),o=d.opt,
							/* method default options */
							methodDefaults={
								trigger:"external", /* method is by default triggered externally (e.g. from other scripts) */
								scrollInertia:o.scrollInertia, /* scrolling inertia (animation duration) */
								scrollEasing:"mcsEaseInOut", /* animation easing */
								moveDragger:false, /* move dragger instead of content */
								timeout:60, /* scroll-to delay */
								callbacks:true, /* enable/disable callbacks */
								onStart:true,
								onUpdate:true,
								onComplete:true
							},
							methodOptions=$.extend(true,{},methodDefaults,options),
							to=_arr.call(this,val),dur=methodOptions.scrollInertia>0 && methodOptions.scrollInertia<17 ? 17 : methodOptions.scrollInertia;

						/* translate yx values to actual scroll-to positions */
						to[0]=_to.call(this,to[0],"y");
						to[1]=_to.call(this,to[1],"x");

						/*
						check if scroll-to value moves the dragger instead of content.
						Only pixel values apply on dragger (e.g. 100, "100px", "-=100" etc.)
						*/
						if(methodOptions.moveDragger){
							to[0]*=d.scrollRatio.y;
							to[1]*=d.scrollRatio.x;
						}

						methodOptions.dur=_isTabHidden() ? 0 : dur; //skip animations if browser tab is hidden

						setTimeout(function(){
							/* do the scrolling */
							if(to[0]!==null && typeof to[0]!=="undefined" && o.axis!=="x" && d.overflowed[0]){ /* scroll y */
								methodOptions.dir="y";
								methodOptions.overwrite="all";
								_scrollTo($this,to[0].toString(),methodOptions);
							}
							if(to[1]!==null && typeof to[1]!=="undefined" && o.axis!=="y" && d.overflowed[1]){ /* scroll x */
								methodOptions.dir="x";
								methodOptions.overwrite="none";
								_scrollTo($this,to[1].toString(),methodOptions);
							}
						},methodOptions.timeout);

					}

				});

			},
			/* ---------------------------------------- */



			/*
			plugin stop method
			stops scrolling animation
			----------------------------------------
			usage: $(selector).mCustomScrollbar("stop");
			*/
			stop:function(){

				var selector=_selector.call(this); /* validate selector */

				return $(selector).each(function(){

					var $this=$(this);

					if($this.data(pluginPfx)){ /* check if plugin has initialized */

						_stop($this);

					}

				});

			},
			/* ---------------------------------------- */



			/*
			plugin disable method
			temporarily disables the scrollbar(s)
			----------------------------------------
			usage: $(selector).mCustomScrollbar("disable",reset);
			reset (boolean): resets content position to 0
			*/
			disable:function(r){

				var selector=_selector.call(this); /* validate selector */

				return $(selector).each(function(){

					var $this=$(this);

					if($this.data(pluginPfx)){ /* check if plugin has initialized */

						var d=$this.data(pluginPfx);

						_autoUpdate.call(this,"remove"); /* remove automatic updating */

						_unbindEvents.call(this); /* unbind events */

						if(r){_resetContentPosition.call(this);} /* reset content position */

						_scrollbarVisibility.call(this,true); /* show/hide scrollbar(s) */

						$this.addClass(classes[3]); /* add disable class */

					}

				});

			},
			/* ---------------------------------------- */



			/*
			plugin destroy method
			completely removes the scrollbar(s) and returns the element to its original state
			----------------------------------------
			usage: $(selector).mCustomScrollbar("destroy");
			*/
			destroy:function(){

				var selector=_selector.call(this); /* validate selector */

				return $(selector).each(function(){

					var $this=$(this);

					if($this.data(pluginPfx)){ /* check if plugin has initialized */

						var d=$this.data(pluginPfx),o=d.opt,
							mCustomScrollBox=$("#mCSB_"+d.idx),
							mCSB_container=$("#mCSB_"+d.idx+"_container"),
							scrollbar=$(".mCSB_"+d.idx+"_scrollbar");

						if(o.live){removeLiveTimers(o.liveSelector || $(selector).selector);} /* remove live timers */

						_autoUpdate.call(this,"remove"); /* remove automatic updating */

						_unbindEvents.call(this); /* unbind events */

						_resetContentPosition.call(this); /* reset content position */

						$this.removeData(pluginPfx); /* remove plugin data object */

						_delete(this,"mcs"); /* delete callbacks object */

						/* remove plugin markup */
						scrollbar.remove(); /* remove scrollbar(s) first (those can be either inside or outside plugin's inner wrapper) */
						mCSB_container.find("img."+classes[2]).removeClass(classes[2]); /* remove loaded images flag */
						mCustomScrollBox.replaceWith(mCSB_container.contents()); /* replace plugin's inner wrapper with the original content */
						/* remove plugin classes from the element and add destroy class */
						$this.removeClass(pluginNS+" _"+pluginPfx+"_"+d.idx+" "+classes[6]+" "+classes[7]+" "+classes[5]+" "+classes[3]).addClass(classes[4]);

					}

				});

			}
			/* ---------------------------------------- */

		},





	/*
	----------------------------------------
	FUNCTIONS
	----------------------------------------
	*/

		/* validates selector (if selector is invalid or undefined uses the default one) */
		_selector=function(){
			return (typeof $(this)!=="object" || $(this).length<1) ? defaultSelector : this;
		},
		/* -------------------- */


		/* changes options according to theme */
		_theme=function(obj){
			var fixedSizeScrollbarThemes=["rounded","rounded-dark","rounded-dots","rounded-dots-dark"],
				nonExpandedScrollbarThemes=["rounded-dots","rounded-dots-dark","3d","3d-dark","3d-thick","3d-thick-dark","inset","inset-dark","inset-2","inset-2-dark","inset-3","inset-3-dark"],
				disabledScrollButtonsThemes=["minimal","minimal-dark"],
				enabledAutoHideScrollbarThemes=["minimal","minimal-dark"],
				scrollbarPositionOutsideThemes=["minimal","minimal-dark"];
			obj.autoDraggerLength=$.inArray(obj.theme,fixedSizeScrollbarThemes) > -1 ? false : obj.autoDraggerLength;
			obj.autoExpandScrollbar=$.inArray(obj.theme,nonExpandedScrollbarThemes) > -1 ? false : obj.autoExpandScrollbar;
			obj.scrollButtons.enable=$.inArray(obj.theme,disabledScrollButtonsThemes) > -1 ? false : obj.scrollButtons.enable;
			obj.autoHideScrollbar=$.inArray(obj.theme,enabledAutoHideScrollbarThemes) > -1 ? true : obj.autoHideScrollbar;
			obj.scrollbarPosition=$.inArray(obj.theme,scrollbarPositionOutsideThemes) > -1 ? "outside" : obj.scrollbarPosition;
		},
		/* -------------------- */


		/* live option timers removal */
		removeLiveTimers=function(selector){
			if(liveTimers[selector]){
				clearTimeout(liveTimers[selector]);
				_delete(liveTimers,selector);
			}
		},
		/* -------------------- */


		/* normalizes axis option to valid values: "y", "x", "yx" */
		_findAxis=function(val){
			return (val==="yx" || val==="xy" || val==="auto") ? "yx" : (val==="x" || val==="horizontal") ? "x" : "y";
		},
		/* -------------------- */


		/* normalizes scrollButtons.scrollType option to valid values: "stepless", "stepped" */
		_findScrollButtonsType=function(val){
			return (val==="stepped" || val==="pixels" || val==="step" || val==="click") ? "stepped" : "stepless";
		},
		/* -------------------- */


		/* generates plugin markup */
		_pluginMarkup=function(){
			var $this=$(this),d=$this.data(pluginPfx),o=d.opt,
				expandClass=o.autoExpandScrollbar ? " "+classes[1]+"_expand" : "",
				scrollbar=["<div id='mCSB_"+d.idx+"_scrollbar_vertical' class='mCSB_scrollTools mCSB_"+d.idx+"_scrollbar mCS-"+o.theme+" mCSB_scrollTools_vertical"+expandClass+"'><div class='"+classes[12]+"'><div id='mCSB_"+d.idx+"_dragger_vertical' class='mCSB_dragger' style='position:absolute;'><div class='mCSB_dragger_bar' /></div></div><div class='mCSB_draggerRail' /></div>","<div id='mCSB_"+d.idx+"_scrollbar_horizontal' class='mCSB_scrollTools mCSB_"+d.idx+"_scrollbar mCS-"+o.theme+" mCSB_scrollTools_horizontal"+expandClass+"'><div class='"+classes[12]+"'><div id='mCSB_"+d.idx+"_dragger_horizontal' class='mCSB_dragger' style='position:absolute;'><div class='mCSB_dragger_bar' /></div><div class='mCSB_draggerRail' /></div></div>"],
				wrapperClass=o.axis==="yx" ? "mCSB_vertical_horizontal" : o.axis==="x" ? "mCSB_horizontal" : "mCSB_vertical",
				scrollbars=o.axis==="yx" ? scrollbar[0]+scrollbar[1] : o.axis==="x" ? scrollbar[1] : scrollbar[0],
				contentWrapper=o.axis==="yx" ? "<div id='mCSB_"+d.idx+"_container_wrapper' class='mCSB_container_wrapper' />" : "",
				autoHideClass=o.autoHideScrollbar ? " "+classes[6] : "",
				scrollbarDirClass=(o.axis!=="x" && d.langDir==="rtl") ? " "+classes[7] : "";
			if(o.setWidth){$this.css("width",o.setWidth);} /* set element width */
			if(o.setHeight){$this.css("height",o.setHeight);} /* set element height */
			o.setLeft=(o.axis!=="y" && d.langDir==="rtl") ? "989999px" : o.setLeft; /* adjust left position for rtl direction */
			$this.addClass(pluginNS+" _"+pluginPfx+"_"+d.idx+autoHideClass+scrollbarDirClass).wrapInner("<div id='mCSB_"+d.idx+"' class='mCustomScrollBox mCS-"+o.theme+" "+wrapperClass+"'><div id='mCSB_"+d.idx+"_container' class='mCSB_container' style='position:relative; top:"+o.setTop+"; left:"+o.setLeft+";' dir='"+d.langDir+"' /></div>");
			var mCustomScrollBox=$("#mCSB_"+d.idx),
				mCSB_container=$("#mCSB_"+d.idx+"_container");
			if(o.axis!=="y" && !o.advanced.autoExpandHorizontalScroll){
				mCSB_container.css("width",_contentWidth(mCSB_container));
			}
			if(o.scrollbarPosition==="outside"){
				if($this.css("position")==="static"){ /* requires elements with non-static position */
					$this.css("position","relative");
				}
				$this.css("overflow","visible");
				mCustomScrollBox.addClass("mCSB_outside").after(scrollbars);
			}else{
				mCustomScrollBox.addClass("mCSB_inside").append(scrollbars);
				mCSB_container.wrap(contentWrapper);
			}
			_scrollButtons.call(this); /* add scrollbar buttons */
			/* minimum dragger length */
			var mCSB_dragger=[$("#mCSB_"+d.idx+"_dragger_vertical"),$("#mCSB_"+d.idx+"_dragger_horizontal")];
			mCSB_dragger[0].css("min-height",mCSB_dragger[0].height());
			mCSB_dragger[1].css("min-width",mCSB_dragger[1].width());
		},
		/* -------------------- */


		/* calculates content width */
		_contentWidth=function(el){
			var val=[el[0].scrollWidth,Math.max.apply(Math,el.children().map(function(){return $(this).outerWidth(true);}).get())],w=el.parent().width();
			return val[0]>w ? val[0] : val[1]>w ? val[1] : "100%";
		},
		/* -------------------- */


		/* expands content horizontally */
		_expandContentHorizontally=function(){
			var $this=$(this),d=$this.data(pluginPfx),o=d.opt,
				mCSB_container=$("#mCSB_"+d.idx+"_container");
			if(o.advanced.autoExpandHorizontalScroll && o.axis!=="y"){
				/* calculate scrollWidth */
				mCSB_container.css({"width":"auto","min-width":0,"overflow-x":"scroll"});
				var w=Math.ceil(mCSB_container[0].scrollWidth);
				if(o.advanced.autoExpandHorizontalScroll===3 || (o.advanced.autoExpandHorizontalScroll!==2 && w>mCSB_container.parent().width())){
					mCSB_container.css({"width":w,"min-width":"100%","overflow-x":"inherit"});
				}else{
					/*
					wrap content with an infinite width div and set its position to absolute and width to auto.
					Setting width to auto before calculating the actual width is important!
					We must let the browser set the width as browser zoom values are impossible to calculate.
					*/
					mCSB_container.css({"overflow-x":"inherit","position":"absolute"})
						.wrap("<div class='mCSB_h_wrapper' style='position:relative; left:0; width:999999px;' />")
						.css({ /* set actual width, original position and un-wrap */
							/*
							get the exact width (with decimals) and then round-up.
							Using jquery outerWidth() will round the width value which will mess up with inner elements that have non-integer width
							*/
							"width":(Math.ceil(mCSB_container[0].getBoundingClientRect().right+0.4)-Math.floor(mCSB_container[0].getBoundingClientRect().left)),
							"min-width":"100%",
							"position":"relative"
						}).unwrap();
				}
			}
		},
		/* -------------------- */


		/* adds scrollbar buttons */
		_scrollButtons=function(){
			var $this=$(this),d=$this.data(pluginPfx),o=d.opt,
				mCSB_scrollTools=$(".mCSB_"+d.idx+"_scrollbar:first"),
				tabindex=!_isNumeric(o.scrollButtons.tabindex) ? "" : "tabindex='"+o.scrollButtons.tabindex+"'",
				btnHTML=[
					"<a href='#' class='"+classes[13]+"' "+tabindex+" />",
					"<a href='#' class='"+classes[14]+"' "+tabindex+" />",
					"<a href='#' class='"+classes[15]+"' "+tabindex+" />",
					"<a href='#' class='"+classes[16]+"' "+tabindex+" />"
				],
				btn=[(o.axis==="x" ? btnHTML[2] : btnHTML[0]),(o.axis==="x" ? btnHTML[3] : btnHTML[1]),btnHTML[2],btnHTML[3]];
			if(o.scrollButtons.enable){
				mCSB_scrollTools.prepend(btn[0]).append(btn[1]).next(".mCSB_scrollTools").prepend(btn[2]).append(btn[3]);
			}
		},
		/* -------------------- */


		/* auto-adjusts scrollbar dragger length */
		_setDraggerLength=function(){
			var $this=$(this),d=$this.data(pluginPfx),
				mCustomScrollBox=$("#mCSB_"+d.idx),
				mCSB_container=$("#mCSB_"+d.idx+"_container"),
				mCSB_dragger=[$("#mCSB_"+d.idx+"_dragger_vertical"),$("#mCSB_"+d.idx+"_dragger_horizontal")],
				ratio=[mCustomScrollBox.height()/mCSB_container.outerHeight(false),mCustomScrollBox.width()/mCSB_container.outerWidth(false)],
				l=[
					parseInt(mCSB_dragger[0].css("min-height")),Math.round(ratio[0]*mCSB_dragger[0].parent().height()),
					parseInt(mCSB_dragger[1].css("min-width")),Math.round(ratio[1]*mCSB_dragger[1].parent().width())
				],
				h=oldIE && (l[1]<l[0]) ? l[0] : l[1],w=oldIE && (l[3]<l[2]) ? l[2] : l[3];
			mCSB_dragger[0].css({
				"height":h,"max-height":(mCSB_dragger[0].parent().height()-10)
			}).find(".mCSB_dragger_bar").css({"line-height":l[0]+"px"});
			mCSB_dragger[1].css({
				"width":w,"max-width":(mCSB_dragger[1].parent().width()-10)
			});
		},
		/* -------------------- */


		/* calculates scrollbar to content ratio */
		_scrollRatio=function(){
			var $this=$(this),d=$this.data(pluginPfx),
				mCustomScrollBox=$("#mCSB_"+d.idx),
				mCSB_container=$("#mCSB_"+d.idx+"_container"),
				mCSB_dragger=[$("#mCSB_"+d.idx+"_dragger_vertical"),$("#mCSB_"+d.idx+"_dragger_horizontal")],
				scrollAmount=[mCSB_container.outerHeight(false)-mCustomScrollBox.height(),mCSB_container.outerWidth(false)-mCustomScrollBox.width()],
				ratio=[
					scrollAmount[0]/(mCSB_dragger[0].parent().height()-mCSB_dragger[0].height()),
					scrollAmount[1]/(mCSB_dragger[1].parent().width()-mCSB_dragger[1].width())
				];
			d.scrollRatio={y:ratio[0],x:ratio[1]};
		},
		/* -------------------- */


		/* toggles scrolling classes */
		_onDragClasses=function(el,action,xpnd){
			var expandClass=xpnd ? classes[0]+"_expanded" : "",
				scrollbar=el.closest(".mCSB_scrollTools");
			if(action==="active"){
				el.toggleClass(classes[0]+" "+expandClass); scrollbar.toggleClass(classes[1]);
				el[0]._draggable=el[0]._draggable ? 0 : 1;
			}else{
				if(!el[0]._draggable){
					if(action==="hide"){
						el.removeClass(classes[0]); scrollbar.removeClass(classes[1]);
					}else{
						el.addClass(classes[0]); scrollbar.addClass(classes[1]);
					}
				}
			}
		},
		/* -------------------- */


		/* checks if content overflows its container to determine if scrolling is required */
		_overflowed=function(){
			var $this=$(this),d=$this.data(pluginPfx),
				mCustomScrollBox=$("#mCSB_"+d.idx),
				mCSB_container=$("#mCSB_"+d.idx+"_container"),
				contentHeight=d.overflowed==null ? mCSB_container.height() : mCSB_container.outerHeight(false),
				contentWidth=d.overflowed==null ? mCSB_container.width() : mCSB_container.outerWidth(false),
				h=mCSB_container[0].scrollHeight,w=mCSB_container[0].scrollWidth;
			if(h>contentHeight){contentHeight=h;}
			if(w>contentWidth){contentWidth=w;}
			return [contentHeight>mCustomScrollBox.height(),contentWidth>mCustomScrollBox.width()];
		},
		/* -------------------- */


		/* resets content position to 0 */
		_resetContentPosition=function(){
			var $this=$(this),d=$this.data(pluginPfx),o=d.opt,
				mCustomScrollBox=$("#mCSB_"+d.idx),
				mCSB_container=$("#mCSB_"+d.idx+"_container"),
				mCSB_dragger=[$("#mCSB_"+d.idx+"_dragger_vertical"),$("#mCSB_"+d.idx+"_dragger_horizontal")];
			_stop($this); /* stop any current scrolling before resetting */
			if((o.axis!=="x" && !d.overflowed[0]) || (o.axis==="y" && d.overflowed[0])){ /* reset y */
				mCSB_dragger[0].add(mCSB_container).css("top",0);
				_scrollTo($this,"_resetY");
			}
			if((o.axis!=="y" && !d.overflowed[1]) || (o.axis==="x" && d.overflowed[1])){ /* reset x */
				var cx=dx=0;
				if(d.langDir==="rtl"){ /* adjust left position for rtl direction */
					cx=mCustomScrollBox.width()-mCSB_container.outerWidth(false);
					dx=Math.abs(cx/d.scrollRatio.x);
				}
				mCSB_container.css("left",cx);
				mCSB_dragger[1].css("left",dx);
				_scrollTo($this,"_resetX");
			}
		},
		/* -------------------- */


		/* binds scrollbar events */
		_bindEvents=function(){
			var $this=$(this),d=$this.data(pluginPfx),o=d.opt;
			if(!d.bindEvents){ /* check if events are already bound */
				_draggable.call(this);
				if(o.contentTouchScroll){_contentDraggable.call(this);}
				_selectable.call(this);
				if(o.mouseWheel.enable){ /* bind mousewheel fn when plugin is available */
					function _mwt(){
						mousewheelTimeout=setTimeout(function(){
							if(!$.event.special.mousewheel){
								_mwt();
							}else{
								clearTimeout(mousewheelTimeout);
								_mousewheel.call($this[0]);
							}
						},100);
					}
					var mousewheelTimeout;
					_mwt();
				}
				_draggerRail.call(this);
				_wrapperScroll.call(this);
				if(o.advanced.autoScrollOnFocus){_focus.call(this);}
				if(o.scrollButtons.enable){_buttons.call(this);}
				if(o.keyboard.enable){_keyboard.call(this);}
				d.bindEvents=true;
			}
		},
		/* -------------------- */


		/* unbinds scrollbar events */
		_unbindEvents=function(){
			var $this=$(this),d=$this.data(pluginPfx),o=d.opt,
				namespace=pluginPfx+"_"+d.idx,
				sb=".mCSB_"+d.idx+"_scrollbar",
				sel=$("#mCSB_"+d.idx+",#mCSB_"+d.idx+"_container,#mCSB_"+d.idx+"_container_wrapper,"+sb+" ."+classes[12]+",#mCSB_"+d.idx+"_dragger_vertical,#mCSB_"+d.idx+"_dragger_horizontal,"+sb+">a"),
				mCSB_container=$("#mCSB_"+d.idx+"_container");
			if(o.advanced.releaseDraggableSelectors){sel.add($(o.advanced.releaseDraggableSelectors));}
			if(o.advanced.extraDraggableSelectors){sel.add($(o.advanced.extraDraggableSelectors));}
			if(d.bindEvents){ /* check if events are bound */
				/* unbind namespaced events from document/selectors */
				$(document).add($(!_canAccessIFrame() || top.document)).unbind("."+namespace);
				sel.each(function(){
					$(this).unbind("."+namespace);
				});
				/* clear and delete timeouts/objects */
				clearTimeout($this[0]._focusTimeout); _delete($this[0],"_focusTimeout");
				clearTimeout(d.sequential.step); _delete(d.sequential,"step");
				clearTimeout(mCSB_container[0].onCompleteTimeout); _delete(mCSB_container[0],"onCompleteTimeout");
				d.bindEvents=false;
			}
		},
		/* -------------------- */


		/* toggles scrollbar visibility */
		_scrollbarVisibility=function(disabled){
			var $this=$(this),d=$this.data(pluginPfx),o=d.opt,
				contentWrapper=$("#mCSB_"+d.idx+"_container_wrapper"),
				content=contentWrapper.length ? contentWrapper : $("#mCSB_"+d.idx+"_container"),
				scrollbar=[$("#mCSB_"+d.idx+"_scrollbar_vertical"),$("#mCSB_"+d.idx+"_scrollbar_horizontal")],
				mCSB_dragger=[scrollbar[0].find(".mCSB_dragger"),scrollbar[1].find(".mCSB_dragger")];
			if(o.axis!=="x"){
				if(d.overflowed[0] && !disabled){
					scrollbar[0].add(mCSB_dragger[0]).add(scrollbar[0].children("a")).css("display","block");
					content.removeClass(classes[8]+" "+classes[10]);
				}else{
					if(o.alwaysShowScrollbar){
						if(o.alwaysShowScrollbar!==2){mCSB_dragger[0].css("display","none");}
						content.removeClass(classes[10]);
					}else{
						scrollbar[0].css("display","none");
						content.addClass(classes[10]);
					}
					content.addClass(classes[8]);
				}
			}
			if(o.axis!=="y"){
				if(d.overflowed[1] && !disabled){
					scrollbar[1].add(mCSB_dragger[1]).add(scrollbar[1].children("a")).css("display","block");
					content.removeClass(classes[9]+" "+classes[11]);
				}else{
					if(o.alwaysShowScrollbar){
						if(o.alwaysShowScrollbar!==2){mCSB_dragger[1].css("display","none");}
						content.removeClass(classes[11]);
					}else{
						scrollbar[1].css("display","none");
						content.addClass(classes[11]);
					}
					content.addClass(classes[9]);
				}
			}
			if(!d.overflowed[0] && !d.overflowed[1]){
				$this.addClass(classes[5]);
			}else{
				$this.removeClass(classes[5]);
			}
		},
		/* -------------------- */


		/* returns input coordinates of pointer, touch and mouse events (relative to document) */
		_coordinates=function(e){
			var t=e.type,o=e.target.ownerDocument!==document && frameElement!==null ? [$(frameElement).offset().top,$(frameElement).offset().left] : null,
				io=_canAccessIFrame() && e.target.ownerDocument!==top.document && frameElement!==null ? [$(e.view.frameElement).offset().top,$(e.view.frameElement).offset().left] : [0,0];
			switch(t){
				case "pointerdown": case "MSPointerDown": case "pointermove": case "MSPointerMove": case "pointerup": case "MSPointerUp":
					return o ? [e.originalEvent.pageY-o[0]+io[0],e.originalEvent.pageX-o[1]+io[1],false] : [e.originalEvent.pageY,e.originalEvent.pageX,false];
					break;
				case "touchstart": case "touchmove": case "touchend":
					var touch=e.originalEvent.touches[0] || e.originalEvent.changedTouches[0],
						touches=e.originalEvent.touches.length || e.originalEvent.changedTouches.length;
					return e.target.ownerDocument!==document ? [touch.screenY,touch.screenX,touches>1] : [touch.pageY,touch.pageX,touches>1];
					break;
				default:
					return o ? [e.pageY-o[0]+io[0],e.pageX-o[1]+io[1],false] : [e.pageY,e.pageX,false];
			}
		},
		/* -------------------- */


		/*
		SCROLLBAR DRAG EVENTS
		scrolls content via scrollbar dragging
		*/
		_draggable=function(){
			var $this=$(this),d=$this.data(pluginPfx),o=d.opt,
				namespace=pluginPfx+"_"+d.idx,
				draggerId=["mCSB_"+d.idx+"_dragger_vertical","mCSB_"+d.idx+"_dragger_horizontal"],
				mCSB_container=$("#mCSB_"+d.idx+"_container"),
				mCSB_dragger=$("#"+draggerId[0]+",#"+draggerId[1]),
				draggable,dragY,dragX,
				rds=o.advanced.releaseDraggableSelectors ? mCSB_dragger.add($(o.advanced.releaseDraggableSelectors)) : mCSB_dragger,
				eds=o.advanced.extraDraggableSelectors ? $(!_canAccessIFrame() || top.document).add($(o.advanced.extraDraggableSelectors)) : $(!_canAccessIFrame() || top.document);
			mCSB_dragger.bind("contextmenu."+namespace,function(e){
				e.preventDefault(); //prevent right click
			}).bind("mousedown."+namespace+" touchstart."+namespace+" pointerdown."+namespace+" MSPointerDown."+namespace,function(e){
				e.stopImmediatePropagation();
				e.preventDefault();
				if(!_mouseBtnLeft(e)){return;} /* left mouse button only */
				touchActive=true;
				if(oldIE){document.onselectstart=function(){return false;}} /* disable text selection for IE < 9 */
				_iframe.call(mCSB_container,false); /* enable scrollbar dragging over iframes by disabling their events */
				_stop($this);
				draggable=$(this);
				var offset=draggable.offset(),y=_coordinates(e)[0]-offset.top,x=_coordinates(e)[1]-offset.left,
					h=draggable.height()+offset.top,w=draggable.width()+offset.left;
				if(y<h && y>0 && x<w && x>0){
					dragY=y;
					dragX=x;
				}
				_onDragClasses(draggable,"active",o.autoExpandScrollbar);
			}).bind("touchmove."+namespace,function(e){
				e.stopImmediatePropagation();
				e.preventDefault();
				var offset=draggable.offset(),y=_coordinates(e)[0]-offset.top,x=_coordinates(e)[1]-offset.left;
				_drag(dragY,dragX,y,x);
			});
			$(document).add(eds).bind("mousemove."+namespace+" pointermove."+namespace+" MSPointerMove."+namespace,function(e){
				if(draggable){
					var offset=draggable.offset(),y=_coordinates(e)[0]-offset.top,x=_coordinates(e)[1]-offset.left;
					if(dragY===y && dragX===x){return;} /* has it really moved? */
					_drag(dragY,dragX,y,x);
				}
			}).add(rds).bind("mouseup."+namespace+" touchend."+namespace+" pointerup."+namespace+" MSPointerUp."+namespace,function(e){
				if(draggable){
					_onDragClasses(draggable,"active",o.autoExpandScrollbar);
					draggable=null;
				}
				touchActive=false;
				if(oldIE){document.onselectstart=null;} /* enable text selection for IE < 9 */
				_iframe.call(mCSB_container,true); /* enable iframes events */
			});
			function _drag(dragY,dragX,y,x){
				mCSB_container[0].idleTimer=o.scrollInertia<233 ? 250 : 0;
				if(draggable.attr("id")===draggerId[1]){
					var dir="x",to=((draggable[0].offsetLeft-dragX)+x)*d.scrollRatio.x;
				}else{
					var dir="y",to=((draggable[0].offsetTop-dragY)+y)*d.scrollRatio.y;
				}
				_scrollTo($this,to.toString(),{dir:dir,drag:true});
			}
		},
		/* -------------------- */


		/*
		TOUCH SWIPE EVENTS
		scrolls content via touch swipe
		Emulates the native touch-swipe scrolling with momentum found in iOS, Android and WP devices
		*/
		_contentDraggable=function(){
			var $this=$(this),d=$this.data(pluginPfx),o=d.opt,
				namespace=pluginPfx+"_"+d.idx,
				mCustomScrollBox=$("#mCSB_"+d.idx),
				mCSB_container=$("#mCSB_"+d.idx+"_container"),
				mCSB_dragger=[$("#mCSB_"+d.idx+"_dragger_vertical"),$("#mCSB_"+d.idx+"_dragger_horizontal")],
				draggable,dragY,dragX,touchStartY,touchStartX,touchMoveY=[],touchMoveX=[],startTime,runningTime,endTime,distance,speed,amount,
				durA=0,durB,overwrite=o.axis==="yx" ? "none" : "all",touchIntent=[],touchDrag,docDrag,
				iframe=mCSB_container.find("iframe"),
				events=[
					"touchstart."+namespace+" pointerdown."+namespace+" MSPointerDown."+namespace, //start
					"touchmove."+namespace+" pointermove."+namespace+" MSPointerMove."+namespace, //move
					"touchend."+namespace+" pointerup."+namespace+" MSPointerUp."+namespace //end
				],
				touchAction=document.body.style.touchAction!==undefined && document.body.style.touchAction!=="";
			mCSB_container.bind(events[0],function(e){
				_onTouchstart(e);
			}).bind(events[1],function(e){
				_onTouchmove(e);
				//e.preventDefault();
			});
			mCustomScrollBox.bind(events[0],function(e){
				_onTouchstart2(e);
			}).bind(events[2],function(e){
				_onTouchend(e);
			});
			if(iframe.length){
				iframe.each(function(){
					$(this).bind("load",function(){
						/* bind events on accessible iframes */
						if(_canAccessIFrame(this)){
							$(this.contentDocument || this.contentWindow.document).bind(events[0],function(e){
								_onTouchstart(e);
								_onTouchstart2(e);
							}).bind(events[1],function(e){
								_onTouchmove(e);
							}).bind(events[2],function(e){
								_onTouchend(e);
							});
						}
					});
				});
			}
			function _onTouchstart(e){
				if(!_pointerTouch(e) || touchActive || _coordinates(e)[2]){touchable=0; return;}
				touchable=1; touchDrag=0; docDrag=0; draggable=1;
				$this.removeClass("mCS_touch_action");
				var offset=mCSB_container.offset();
				dragY=_coordinates(e)[0]-offset.top;
				dragX=_coordinates(e)[1]-offset.left;
				touchIntent=[_coordinates(e)[0],_coordinates(e)[1]];
			}
			function _onTouchmove(e){
				if(!_pointerTouch(e) || touchActive || _coordinates(e)[2]){return;}
				if(!o.documentTouchScroll){e.preventDefault();}
				e.stopImmediatePropagation();
				if(docDrag && !touchDrag){return;}
				if(draggable){
					runningTime=_getTime();
					var offset=mCustomScrollBox.offset(),y=_coordinates(e)[0]-offset.top,x=_coordinates(e)[1]-offset.left,
						easing="mcsLinearOut";
					touchMoveY.push(y);
					touchMoveX.push(x);
					touchIntent[2]=Math.abs(_coordinates(e)[0]-touchIntent[0]); touchIntent[3]=Math.abs(_coordinates(e)[1]-touchIntent[1]);
					if(d.overflowed[0]){
						var limit=mCSB_dragger[0].parent().height()-mCSB_dragger[0].height(),
							prevent=((dragY-y)>0 && (y-dragY)>-(limit*d.scrollRatio.y) && (touchIntent[3]*2<touchIntent[2] || o.axis==="yx"));
					}
					if(d.overflowed[1]){
						var limitX=mCSB_dragger[1].parent().width()-mCSB_dragger[1].width(),
							preventX=((dragX-x)>0 && (x-dragX)>-(limitX*d.scrollRatio.x) && (touchIntent[2]*2<touchIntent[3] || o.axis==="yx"));
					}
					if(prevent || preventX){ /* prevent native document scrolling */
						if(!touchAction){e.preventDefault();}
						touchDrag=1;
					}else{
						docDrag=1;
						$this.addClass("mCS_touch_action");
					}
					if(touchAction){e.preventDefault();}
					amount=o.axis==="yx" ? [(dragY-y),(dragX-x)] : o.axis==="x" ? [null,(dragX-x)] : [(dragY-y),null];
					mCSB_container[0].idleTimer=250;
					if(d.overflowed[0]){_drag(amount[0],durA,easing,"y","all",true);}
					if(d.overflowed[1]){_drag(amount[1],durA,easing,"x",overwrite,true);}
				}
			}
			function _onTouchstart2(e){
				if(!_pointerTouch(e) || touchActive || _coordinates(e)[2]){touchable=0; return;}
				touchable=1;
				e.stopImmediatePropagation();
				_stop($this);
				startTime=_getTime();
				var offset=mCustomScrollBox.offset();
				touchStartY=_coordinates(e)[0]-offset.top;
				touchStartX=_coordinates(e)[1]-offset.left;
				touchMoveY=[]; touchMoveX=[];
			}
			function _onTouchend(e){
				if(!_pointerTouch(e) || touchActive || _coordinates(e)[2]){return;}
				draggable=0;
				e.stopImmediatePropagation();
				touchDrag=0; docDrag=0;
				endTime=_getTime();
				var offset=mCustomScrollBox.offset(),y=_coordinates(e)[0]-offset.top,x=_coordinates(e)[1]-offset.left;
				if((endTime-runningTime)>30){return;}
				speed=1000/(endTime-startTime);
				var easing="mcsEaseOut",slow=speed<2.5,
					diff=slow ? [touchMoveY[touchMoveY.length-2],touchMoveX[touchMoveX.length-2]] : [0,0];
				distance=slow ? [(y-diff[0]),(x-diff[1])] : [y-touchStartY,x-touchStartX];
				var absDistance=[Math.abs(distance[0]),Math.abs(distance[1])];
				speed=slow ? [Math.abs(distance[0]/4),Math.abs(distance[1]/4)] : [speed,speed];
				var a=[
					Math.abs(mCSB_container[0].offsetTop)-(distance[0]*_m((absDistance[0]/speed[0]),speed[0])),
					Math.abs(mCSB_container[0].offsetLeft)-(distance[1]*_m((absDistance[1]/speed[1]),speed[1]))
				];
				amount=o.axis==="yx" ? [a[0],a[1]] : o.axis==="x" ? [null,a[1]] : [a[0],null];
				durB=[(absDistance[0]*4)+o.scrollInertia,(absDistance[1]*4)+o.scrollInertia];
				var md=parseInt(o.contentTouchScroll) || 0; /* absolute minimum distance required */
				amount[0]=absDistance[0]>md ? amount[0] : 0;
				amount[1]=absDistance[1]>md ? amount[1] : 0;
				if(d.overflowed[0]){_drag(amount[0],durB[0],easing,"y",overwrite,false);}
				if(d.overflowed[1]){_drag(amount[1],durB[1],easing,"x",overwrite,false);}
			}
			function _m(ds,s){
				var r=[s*1.5,s*2,s/1.5,s/2];
				if(ds>90){
					return s>4 ? r[0] : r[3];
				}else if(ds>60){
					return s>3 ? r[3] : r[2];
				}else if(ds>30){
					return s>8 ? r[1] : s>6 ? r[0] : s>4 ? s : r[2];
				}else{
					return s>8 ? s : r[3];
				}
			}
			function _drag(amount,dur,easing,dir,overwrite,drag){
				if(!amount){return;}
				_scrollTo($this,amount.toString(),{dur:dur,scrollEasing:easing,dir:dir,overwrite:overwrite,drag:drag});
			}
		},
		/* -------------------- */


		/*
		SELECT TEXT EVENTS
		scrolls content when text is selected
		*/
		_selectable=function(){
			var $this=$(this),d=$this.data(pluginPfx),o=d.opt,seq=d.sequential,
				namespace=pluginPfx+"_"+d.idx,
				mCSB_container=$("#mCSB_"+d.idx+"_container"),
				wrapper=mCSB_container.parent(),
				action;
			mCSB_container.bind("mousedown."+namespace,function(e){
				if(touchable){return;}
				if(!action){action=1; touchActive=true;}
			}).add(document).bind("mousemove."+namespace,function(e){
				if(!touchable && action && _sel()){
					var offset=mCSB_container.offset(),
						y=_coordinates(e)[0]-offset.top+mCSB_container[0].offsetTop,x=_coordinates(e)[1]-offset.left+mCSB_container[0].offsetLeft;
					if(y>0 && y<wrapper.height() && x>0 && x<wrapper.width()){
						if(seq.step){_seq("off",null,"stepped");}
					}else{
						if(o.axis!=="x" && d.overflowed[0]){
							if(y<0){
								_seq("on",38);
							}else if(y>wrapper.height()){
								_seq("on",40);
							}
						}
						if(o.axis!=="y" && d.overflowed[1]){
							if(x<0){
								_seq("on",37);
							}else if(x>wrapper.width()){
								_seq("on",39);
							}
						}
					}
				}
			}).bind("mouseup."+namespace+" dragend."+namespace,function(e){
				if(touchable){return;}
				if(action){action=0; _seq("off",null);}
				touchActive=false;
			});
			function _sel(){
				return 	window.getSelection ? window.getSelection().toString() :
						document.selection && document.selection.type!="Control" ? document.selection.createRange().text : 0;
			}
			function _seq(a,c,s){
				seq.type=s && action ? "stepped" : "stepless";
				seq.scrollAmount=10;
				_sequentialScroll($this,a,c,"mcsLinearOut",s ? 60 : null);
			}
		},
		/* -------------------- */


		/*
		MOUSE WHEEL EVENT
		scrolls content via mouse-wheel
		via mouse-wheel plugin (https://github.com/brandonaaron/jquery-mousewheel)
		*/
		_mousewheel=function(){
			if(!$(this).data(pluginPfx)){return;} /* Check if the scrollbar is ready to use mousewheel events (issue: #185) */
			var $this=$(this),d=$this.data(pluginPfx),o=d.opt,
				namespace=pluginPfx+"_"+d.idx,
				mCustomScrollBox=$("#mCSB_"+d.idx),
				mCSB_dragger=[$("#mCSB_"+d.idx+"_dragger_vertical"),$("#mCSB_"+d.idx+"_dragger_horizontal")],
				iframe=$("#mCSB_"+d.idx+"_container").find("iframe");
			if(iframe.length){
				iframe.each(function(){
					$(this).bind("load",function(){
						/* bind events on accessible iframes */
						if(_canAccessIFrame(this)){
							$(this.contentDocument || this.contentWindow.document).bind("mousewheel."+namespace,function(e,delta){
								_onMousewheel(e,delta);
							});
						}
					});
				});
			}
			mCustomScrollBox.bind("mousewheel."+namespace,function(e,delta){
				_onMousewheel(e,delta);
			});
			function _onMousewheel(e,delta){
				_stop($this);
				if(_disableMousewheel($this,e.target)){return;} /* disables mouse-wheel when hovering specific elements */
				var deltaFactor=o.mouseWheel.deltaFactor!=="auto" ? parseInt(o.mouseWheel.deltaFactor) : (oldIE && e.deltaFactor<100) ? 100 : e.deltaFactor || 100,
					dur=o.scrollInertia;
				if(o.axis==="x" || o.mouseWheel.axis==="x"){
					var dir="x",
						px=[Math.round(deltaFactor*d.scrollRatio.x),parseInt(o.mouseWheel.scrollAmount)],
						amount=o.mouseWheel.scrollAmount!=="auto" ? px[1] : px[0]>=mCustomScrollBox.width() ? mCustomScrollBox.width()*0.9 : px[0],
						contentPos=Math.abs($("#mCSB_"+d.idx+"_container")[0].offsetLeft),
						draggerPos=mCSB_dragger[1][0].offsetLeft,
						limit=mCSB_dragger[1].parent().width()-mCSB_dragger[1].width(),
						dlt=o.mouseWheel.axis==="y" ? (e.deltaY || delta) : e.deltaX;
				}else{
					var dir="y",
						px=[Math.round(deltaFactor*d.scrollRatio.y),parseInt(o.mouseWheel.scrollAmount)],
						amount=o.mouseWheel.scrollAmount!=="auto" ? px[1] : px[0]>=mCustomScrollBox.height() ? mCustomScrollBox.height()*0.9 : px[0],
						contentPos=Math.abs($("#mCSB_"+d.idx+"_container")[0].offsetTop),
						draggerPos=mCSB_dragger[0][0].offsetTop,
						limit=mCSB_dragger[0].parent().height()-mCSB_dragger[0].height(),
						dlt=e.deltaY || delta;
				}
				if((dir==="y" && !d.overflowed[0]) || (dir==="x" && !d.overflowed[1])){return;}
				if(o.mouseWheel.invert || e.webkitDirectionInvertedFromDevice){dlt=-dlt;}
				if(o.mouseWheel.normalizeDelta){dlt=dlt<0 ? -1 : 1;}
				if((dlt>0 && draggerPos!==0) || (dlt<0 && draggerPos!==limit) || o.mouseWheel.preventDefault){
					e.stopImmediatePropagation();
					e.preventDefault();
				}
				if(e.deltaFactor<5 && !o.mouseWheel.normalizeDelta){
					//very low deltaFactor values mean some kind of delta acceleration (e.g. osx trackpad), so adjusting scrolling accordingly
					amount=e.deltaFactor; dur=17;
				}
				_scrollTo($this,(contentPos-(dlt*amount)).toString(),{dir:dir,dur:dur});
			}
		},
		/* -------------------- */


		/* checks if iframe can be accessed */
		_canAccessIFrameCache=new Object(),
		_canAccessIFrame=function(iframe){
		    var result=false,cacheKey=false,html=null;
		    if(iframe===undefined){
				cacheKey="#empty";
		    }else if($(iframe).attr("id")!==undefined){
				cacheKey=$(iframe).attr("id");
		    }
			if(cacheKey!==false && _canAccessIFrameCache[cacheKey]!==undefined){
				return _canAccessIFrameCache[cacheKey];
			}
			if(!iframe){
				try{
					var doc=top.document;
					html=doc.body.innerHTML;
				}catch(err){/* do nothing */}
				result=(html!==null);
			}else{
				try{
					var doc=iframe.contentDocument || iframe.contentWindow.document;
					html=doc.body.innerHTML;
				}catch(err){/* do nothing */}
				result=(html!==null);
			}
			if(cacheKey!==false){_canAccessIFrameCache[cacheKey]=result;}
			return result;
		},
		/* -------------------- */


		/* switches iframe's pointer-events property (drag, mousewheel etc. over cross-domain iframes) */
		_iframe=function(evt){
			var el=this.find("iframe");
			if(!el.length){return;} /* check if content contains iframes */
			var val=!evt ? "none" : "auto";
			el.css("pointer-events",val); /* for IE11, iframe's display property should not be "block" */
		},
		/* -------------------- */


		/* disables mouse-wheel when hovering specific elements like select, datalist etc. */
		_disableMousewheel=function(el,target){
			var tag=target.nodeName.toLowerCase(),
				tags=el.data(pluginPfx).opt.mouseWheel.disableOver,
				/* elements that require focus */
				focusTags=["select","textarea"];
			return $.inArray(tag,tags) > -1 && !($.inArray(tag,focusTags) > -1 && !$(target).is(":focus"));
		},
		/* -------------------- */


		/*
		DRAGGER RAIL CLICK EVENT
		scrolls content via dragger rail
		*/
		_draggerRail=function(){
			var $this=$(this),d=$this.data(pluginPfx),
				namespace=pluginPfx+"_"+d.idx,
				mCSB_container=$("#mCSB_"+d.idx+"_container"),
				wrapper=mCSB_container.parent(),
				mCSB_draggerContainer=$(".mCSB_"+d.idx+"_scrollbar ."+classes[12]),
				clickable;
			mCSB_draggerContainer.bind("mousedown."+namespace+" touchstart."+namespace+" pointerdown."+namespace+" MSPointerDown."+namespace,function(e){
				touchActive=true;
				if(!$(e.target).hasClass("mCSB_dragger")){clickable=1;}
			}).bind("touchend."+namespace+" pointerup."+namespace+" MSPointerUp."+namespace,function(e){
				touchActive=false;
			}).bind("click."+namespace,function(e){
				if(!clickable){return;}
				clickable=0;
				if($(e.target).hasClass(classes[12]) || $(e.target).hasClass("mCSB_draggerRail")){
					_stop($this);
					var el=$(this),mCSB_dragger=el.find(".mCSB_dragger");
					if(el.parent(".mCSB_scrollTools_horizontal").length>0){
						if(!d.overflowed[1]){return;}
						var dir="x",
							clickDir=e.pageX>mCSB_dragger.offset().left ? -1 : 1,
							to=Math.abs(mCSB_container[0].offsetLeft)-(clickDir*(wrapper.width()*0.9));
					}else{
						if(!d.overflowed[0]){return;}
						var dir="y",
							clickDir=e.pageY>mCSB_dragger.offset().top ? -1 : 1,
							to=Math.abs(mCSB_container[0].offsetTop)-(clickDir*(wrapper.height()*0.9));
					}
					_scrollTo($this,to.toString(),{dir:dir,scrollEasing:"mcsEaseInOut"});
				}
			});
		},
		/* -------------------- */


		/*
		FOCUS EVENT
		scrolls content via element focus (e.g. clicking an input, pressing TAB key etc.)
		*/
		_focus=function(){
			var $this=$(this),d=$this.data(pluginPfx),o=d.opt,
				namespace=pluginPfx+"_"+d.idx,
				mCSB_container=$("#mCSB_"+d.idx+"_container"),
				wrapper=mCSB_container.parent();
			mCSB_container.bind("focusin."+namespace,function(e){
				var el=$(document.activeElement),
					nested=mCSB_container.find(".mCustomScrollBox").length,
					dur=0;
				if(!el.is(o.advanced.autoScrollOnFocus)){return;}
				_stop($this);
				clearTimeout($this[0]._focusTimeout);
				$this[0]._focusTimer=nested ? (dur+17)*nested : 0;
				$this[0]._focusTimeout=setTimeout(function(){
					var	to=[_childPos(el)[0],_childPos(el)[1]],
						contentPos=[mCSB_container[0].offsetTop,mCSB_container[0].offsetLeft],
						isVisible=[
							(contentPos[0]+to[0]>=0 && contentPos[0]+to[0]<wrapper.height()-el.outerHeight(false)),
							(contentPos[1]+to[1]>=0 && contentPos[0]+to[1]<wrapper.width()-el.outerWidth(false))
						],
						overwrite=(o.axis==="yx" && !isVisible[0] && !isVisible[1]) ? "none" : "all";
					if(o.axis!=="x" && !isVisible[0]){
						_scrollTo($this,to[0].toString(),{dir:"y",scrollEasing:"mcsEaseInOut",overwrite:overwrite,dur:dur});
					}
					if(o.axis!=="y" && !isVisible[1]){
						_scrollTo($this,to[1].toString(),{dir:"x",scrollEasing:"mcsEaseInOut",overwrite:overwrite,dur:dur});
					}
				},$this[0]._focusTimer);
			});
		},
		/* -------------------- */


		/* sets content wrapper scrollTop/scrollLeft always to 0 */
		_wrapperScroll=function(){
			var $this=$(this),d=$this.data(pluginPfx),
				namespace=pluginPfx+"_"+d.idx,
				wrapper=$("#mCSB_"+d.idx+"_container").parent();
			wrapper.bind("scroll."+namespace,function(e){
				if(wrapper.scrollTop()!==0 || wrapper.scrollLeft()!==0){
					$(".mCSB_"+d.idx+"_scrollbar").css("visibility","hidden"); /* hide scrollbar(s) */
				}
			});
		},
		/* -------------------- */


		/*
		BUTTONS EVENTS
		scrolls content via up, down, left and right buttons
		*/
		_buttons=function(){
			var $this=$(this),d=$this.data(pluginPfx),o=d.opt,seq=d.sequential,
				namespace=pluginPfx+"_"+d.idx,
				sel=".mCSB_"+d.idx+"_scrollbar",
				btn=$(sel+">a");
			btn.bind("contextmenu."+namespace,function(e){
				e.preventDefault(); //prevent right click
			}).bind("mousedown."+namespace+" touchstart."+namespace+" pointerdown."+namespace+" MSPointerDown."+namespace+" mouseup."+namespace+" touchend."+namespace+" pointerup."+namespace+" MSPointerUp."+namespace+" mouseout."+namespace+" pointerout."+namespace+" MSPointerOut."+namespace+" click."+namespace,function(e){
				e.preventDefault();
				if(!_mouseBtnLeft(e)){return;} /* left mouse button only */
				var btnClass=$(this).attr("class");
				seq.type=o.scrollButtons.scrollType;
				switch(e.type){
					case "mousedown": case "touchstart": case "pointerdown": case "MSPointerDown":
						if(seq.type==="stepped"){return;}
						touchActive=true;
						d.tweenRunning=false;
						_seq("on",btnClass);
						break;
					case "mouseup": case "touchend": case "pointerup": case "MSPointerUp":
					case "mouseout": case "pointerout": case "MSPointerOut":
						if(seq.type==="stepped"){return;}
						touchActive=false;
						if(seq.dir){_seq("off",btnClass);}
						break;
					case "click":
						if(seq.type!=="stepped" || d.tweenRunning){return;}
						_seq("on",btnClass);
						break;
				}
				function _seq(a,c){
					seq.scrollAmount=o.scrollButtons.scrollAmount;
					_sequentialScroll($this,a,c);
				}
			});
		},
		/* -------------------- */


		/*
		KEYBOARD EVENTS
		scrolls content via keyboard
		Keys: up arrow, down arrow, left arrow, right arrow, PgUp, PgDn, Home, End
		*/
		_keyboard=function(){
			var $this=$(this),d=$this.data(pluginPfx),o=d.opt,seq=d.sequential,
				namespace=pluginPfx+"_"+d.idx,
				mCustomScrollBox=$("#mCSB_"+d.idx),
				mCSB_container=$("#mCSB_"+d.idx+"_container"),
				wrapper=mCSB_container.parent(),
				editables="input,textarea,select,datalist,keygen,[contenteditable='true']",
				iframe=mCSB_container.find("iframe"),
				events=["blur."+namespace+" keydown."+namespace+" keyup."+namespace];
			if(iframe.length){
				iframe.each(function(){
					$(this).bind("load",function(){
						/* bind events on accessible iframes */
						if(_canAccessIFrame(this)){
							$(this.contentDocument || this.contentWindow.document).bind(events[0],function(e){
								_onKeyboard(e);
							});
						}
					});
				});
			}
			mCustomScrollBox.attr("tabindex","0").bind(events[0],function(e){
				_onKeyboard(e);
			});
			function _onKeyboard(e){
				switch(e.type){
					case "blur":
						if(d.tweenRunning && seq.dir){_seq("off",null);}
						break;
					case "keydown": case "keyup":
						var code=e.keyCode ? e.keyCode : e.which,action="on";
						if((o.axis!=="x" && (code===38 || code===40)) || (o.axis!=="y" && (code===37 || code===39))){
							/* up (38), down (40), left (37), right (39) arrows */
							if(((code===38 || code===40) && !d.overflowed[0]) || ((code===37 || code===39) && !d.overflowed[1])){return;}
							if(e.type==="keyup"){action="off";}
							if(!$(document.activeElement).is(editables)){
								e.preventDefault();
								e.stopImmediatePropagation();
								_seq(action,code);
							}
						}else if(code===33 || code===34){
							/* PgUp (33), PgDn (34) */
							if(d.overflowed[0] || d.overflowed[1]){
								e.preventDefault();
								e.stopImmediatePropagation();
							}
							if(e.type==="keyup"){
								_stop($this);
								var keyboardDir=code===34 ? -1 : 1;
								if(o.axis==="x" || (o.axis==="yx" && d.overflowed[1] && !d.overflowed[0])){
									var dir="x",to=Math.abs(mCSB_container[0].offsetLeft)-(keyboardDir*(wrapper.width()*0.9));
								}else{
									var dir="y",to=Math.abs(mCSB_container[0].offsetTop)-(keyboardDir*(wrapper.height()*0.9));
								}
								_scrollTo($this,to.toString(),{dir:dir,scrollEasing:"mcsEaseInOut"});
							}
						}else if(code===35 || code===36){
							/* End (35), Home (36) */
							if(!$(document.activeElement).is(editables)){
								if(d.overflowed[0] || d.overflowed[1]){
									e.preventDefault();
									e.stopImmediatePropagation();
								}
								if(e.type==="keyup"){
									if(o.axis==="x" || (o.axis==="yx" && d.overflowed[1] && !d.overflowed[0])){
										var dir="x",to=code===35 ? Math.abs(wrapper.width()-mCSB_container.outerWidth(false)) : 0;
									}else{
										var dir="y",to=code===35 ? Math.abs(wrapper.height()-mCSB_container.outerHeight(false)) : 0;
									}
									_scrollTo($this,to.toString(),{dir:dir,scrollEasing:"mcsEaseInOut"});
								}
							}
						}
						break;
				}
				function _seq(a,c){
					seq.type=o.keyboard.scrollType;
					seq.scrollAmount=o.keyboard.scrollAmount;
					if(seq.type==="stepped" && d.tweenRunning){return;}
					_sequentialScroll($this,a,c);
				}
			}
		},
		/* -------------------- */


		/* scrolls content sequentially (used when scrolling via buttons, keyboard arrows etc.) */
		_sequentialScroll=function(el,action,trigger,e,s){
			var d=el.data(pluginPfx),o=d.opt,seq=d.sequential,
				mCSB_container=$("#mCSB_"+d.idx+"_container"),
				once=seq.type==="stepped" ? true : false,
				steplessSpeed=o.scrollInertia < 26 ? 26 : o.scrollInertia, /* 26/1.5=17 */
				steppedSpeed=o.scrollInertia < 1 ? 17 : o.scrollInertia;
			switch(action){
				case "on":
					seq.dir=[
						(trigger===classes[16] || trigger===classes[15] || trigger===39 || trigger===37 ? "x" : "y"),
						(trigger===classes[13] || trigger===classes[15] || trigger===38 || trigger===37 ? -1 : 1)
					];
					_stop(el);
					if(_isNumeric(trigger) && seq.type==="stepped"){return;}
					_on(once);
					break;
				case "off":
					_off();
					if(once || (d.tweenRunning && seq.dir)){
						_on(true);
					}
					break;
			}

			/* starts sequence */
			function _on(once){
				if(o.snapAmount){seq.scrollAmount=!(o.snapAmount instanceof Array) ? o.snapAmount : seq.dir[0]==="x" ? o.snapAmount[1] : o.snapAmount[0];} /* scrolling snapping */
				var c=seq.type!=="stepped", /* continuous scrolling */
					t=s ? s : !once ? 1000/60 : c ? steplessSpeed/1.5 : steppedSpeed, /* timer */
					m=!once ? 2.5 : c ? 7.5 : 40, /* multiplier */
					contentPos=[Math.abs(mCSB_container[0].offsetTop),Math.abs(mCSB_container[0].offsetLeft)],
					ratio=[d.scrollRatio.y>10 ? 10 : d.scrollRatio.y,d.scrollRatio.x>10 ? 10 : d.scrollRatio.x],
					amount=seq.dir[0]==="x" ? contentPos[1]+(seq.dir[1]*(ratio[1]*m)) : contentPos[0]+(seq.dir[1]*(ratio[0]*m)),
					px=seq.dir[0]==="x" ? contentPos[1]+(seq.dir[1]*parseInt(seq.scrollAmount)) : contentPos[0]+(seq.dir[1]*parseInt(seq.scrollAmount)),
					to=seq.scrollAmount!=="auto" ? px : amount,
					easing=e ? e : !once ? "mcsLinear" : c ? "mcsLinearOut" : "mcsEaseInOut",
					onComplete=!once ? false : true;
				if(once && t<17){
					to=seq.dir[0]==="x" ? contentPos[1] : contentPos[0];
				}
				_scrollTo(el,to.toString(),{dir:seq.dir[0],scrollEasing:easing,dur:t,onComplete:onComplete});
				if(once){
					seq.dir=false;
					return;
				}
				clearTimeout(seq.step);
				seq.step=setTimeout(function(){
					_on();
				},t);
			}
			/* stops sequence */
			function _off(){
				clearTimeout(seq.step);
				_delete(seq,"step");
				_stop(el);
			}
		},
		/* -------------------- */


		/* returns a yx array from value */
		_arr=function(val){
			var o=$(this).data(pluginPfx).opt,vals=[];
			if(typeof val==="function"){val=val();} /* check if the value is a single anonymous function */
			/* check if value is object or array, its length and create an array with yx values */
			if(!(val instanceof Array)){ /* object value (e.g. {y:"100",x:"100"}, 100 etc.) */
				vals[0]=val.y ? val.y : val.x || o.axis==="x" ? null : val;
				vals[1]=val.x ? val.x : val.y || o.axis==="y" ? null : val;
			}else{ /* array value (e.g. [100,100]) */
				vals=val.length>1 ? [val[0],val[1]] : o.axis==="x" ? [null,val[0]] : [val[0],null];
			}
			/* check if array values are anonymous functions */
			if(typeof vals[0]==="function"){vals[0]=vals[0]();}
			if(typeof vals[1]==="function"){vals[1]=vals[1]();}
			return vals;
		},
		/* -------------------- */


		/* translates values (e.g. "top", 100, "100px", "#id") to actual scroll-to positions */
		_to=function(val,dir){
			if(val==null || typeof val=="undefined"){return;}
			var $this=$(this),d=$this.data(pluginPfx),o=d.opt,
				mCSB_container=$("#mCSB_"+d.idx+"_container"),
				wrapper=mCSB_container.parent(),
				t=typeof val;
			if(!dir){dir=o.axis==="x" ? "x" : "y";}
			var contentLength=dir==="x" ? mCSB_container.outerWidth(false)-wrapper.width() : mCSB_container.outerHeight(false)-wrapper.height(),
				contentPos=dir==="x" ? mCSB_container[0].offsetLeft : mCSB_container[0].offsetTop,
				cssProp=dir==="x" ? "left" : "top";
			switch(t){
				case "function": /* this currently is not used. Consider removing it */
					return val();
					break;
				case "object": /* js/jquery object */
					var obj=val.jquery ? val : $(val);
					if(!obj.length){return;}
					return dir==="x" ? _childPos(obj)[1] : _childPos(obj)[0];
					break;
				case "string": case "number":
					if(_isNumeric(val)){ /* numeric value */
						return Math.abs(val);
					}else if(val.indexOf("%")!==-1){ /* percentage value */
						return Math.abs(contentLength*parseInt(val)/100);
					}else if(val.indexOf("-=")!==-1){ /* decrease value */
						return Math.abs(contentPos-parseInt(val.split("-=")[1]));
					}else if(val.indexOf("+=")!==-1){ /* inrease value */
						var p=(contentPos+parseInt(val.split("+=")[1]));
						return p>=0 ? 0 : Math.abs(p);
					}else if(val.indexOf("px")!==-1 && _isNumeric(val.split("px")[0])){ /* pixels string value (e.g. "100px") */
						return Math.abs(val.split("px")[0]);
					}else{
						if(val==="top" || val==="left"){ /* special strings */
							return 0;
						}else if(val==="bottom"){
							return Math.abs(wrapper.height()-mCSB_container.outerHeight(false));
						}else if(val==="right"){
							return Math.abs(wrapper.width()-mCSB_container.outerWidth(false));
						}else if(val==="first" || val==="last"){
							var obj=mCSB_container.find(":"+val);
							return dir==="x" ? _childPos(obj)[1] : _childPos(obj)[0];
						}else{
							if($(val).length){ /* jquery selector */
								return dir==="x" ? _childPos($(val))[1] : _childPos($(val))[0];
							}else{ /* other values (e.g. "100em") */
								mCSB_container.css(cssProp,val);
								methods.update.call(null,$this[0]);
								return;
							}
						}
					}
					break;
			}
		},
		/* -------------------- */


		/* calls the update method automatically */
		_autoUpdate=function(rem){
			var $this=$(this),d=$this.data(pluginPfx),o=d.opt,
				mCSB_container=$("#mCSB_"+d.idx+"_container");
			if(rem){
				/*
				removes autoUpdate timer
				usage: _autoUpdate.call(this,"remove");
				*/
				clearTimeout(mCSB_container[0].autoUpdate);
				_delete(mCSB_container[0],"autoUpdate");
				return;
			}
			upd();
			function upd(){
				clearTimeout(mCSB_container[0].autoUpdate);
				if($this.parents("html").length===0){
					/* check element in dom tree */
					$this=null;
					return;
				}
				mCSB_container[0].autoUpdate=setTimeout(function(){
					/* update on specific selector(s) length and size change */
					if(o.advanced.updateOnSelectorChange){
						d.poll.change.n=sizesSum();
						if(d.poll.change.n!==d.poll.change.o){
							d.poll.change.o=d.poll.change.n;
							doUpd(3);
							return;
						}
					}
					/* update on main element and scrollbar size changes */
					if(o.advanced.updateOnContentResize){
						d.poll.size.n=$this[0].scrollHeight+$this[0].scrollWidth+mCSB_container[0].offsetHeight+$this[0].offsetHeight+$this[0].offsetWidth;
						if(d.poll.size.n!==d.poll.size.o){
							d.poll.size.o=d.poll.size.n;
							doUpd(1);
							return;
						}
					}
					/* update on image load */
					if(o.advanced.updateOnImageLoad){
						if(!(o.advanced.updateOnImageLoad==="auto" && o.axis==="y")){ //by default, it doesn't run on vertical content
							d.poll.img.n=mCSB_container.find("img").length;
							if(d.poll.img.n!==d.poll.img.o){
								d.poll.img.o=d.poll.img.n;
								mCSB_container.find("img").each(function(){
									imgLoader(this);
								});
								return;
							}
						}
					}
					if(o.advanced.updateOnSelectorChange || o.advanced.updateOnContentResize || o.advanced.updateOnImageLoad){upd();}
				},o.advanced.autoUpdateTimeout);
			}
			/* a tiny image loader */
			function imgLoader(el){
				if($(el).hasClass(classes[2])){doUpd(); return;}
				var img=new Image();
				function createDelegate(contextObject,delegateMethod){
					return function(){return delegateMethod.apply(contextObject,arguments);}
				}
				function imgOnLoad(){
					this.onload=null;
					$(el).addClass(classes[2]);
					doUpd(2);
				}
				img.onload=createDelegate(img,imgOnLoad);
				img.src=el.src;
			}
			/* returns the total height and width sum of all elements matching the selector */
			function sizesSum(){
				if(o.advanced.updateOnSelectorChange===true){o.advanced.updateOnSelectorChange="*";}
				var total=0,sel=mCSB_container.find(o.advanced.updateOnSelectorChange);
				if(o.advanced.updateOnSelectorChange && sel.length>0){sel.each(function(){total+=this.offsetHeight+this.offsetWidth;});}
				return total;
			}
			/* calls the update method */
			function doUpd(cb){
				clearTimeout(mCSB_container[0].autoUpdate);
				methods.update.call(null,$this[0],cb);
			}
		},
		/* -------------------- */


		/* snaps scrolling to a multiple of a pixels number */
		_snapAmount=function(to,amount,offset){
			return (Math.round(to/amount)*amount-offset);
		},
		/* -------------------- */


		/* stops content and scrollbar animations */
		_stop=function(el){
			var d=el.data(pluginPfx),
				sel=$("#mCSB_"+d.idx+"_container,#mCSB_"+d.idx+"_container_wrapper,#mCSB_"+d.idx+"_dragger_vertical,#mCSB_"+d.idx+"_dragger_horizontal");
			sel.each(function(){
				_stopTween.call(this);
			});
		},
		/* -------------------- */


		/*
		ANIMATES CONTENT
		This is where the actual scrolling happens
		*/
		_scrollTo=function(el,to,options){
			var d=el.data(pluginPfx),o=d.opt,
				defaults={
					trigger:"internal",
					dir:"y",
					scrollEasing:"mcsEaseOut",
					drag:false,
					dur:o.scrollInertia,
					overwrite:"all",
					callbacks:true,
					onStart:true,
					onUpdate:true,
					onComplete:true
				},
				options=$.extend(defaults,options),
				dur=[options.dur,(options.drag ? 0 : options.dur)],
				mCustomScrollBox=$("#mCSB_"+d.idx),
				mCSB_container=$("#mCSB_"+d.idx+"_container"),
				wrapper=mCSB_container.parent(),
				totalScrollOffsets=o.callbacks.onTotalScrollOffset ? _arr.call(el,o.callbacks.onTotalScrollOffset) : [0,0],
				totalScrollBackOffsets=o.callbacks.onTotalScrollBackOffset ? _arr.call(el,o.callbacks.onTotalScrollBackOffset) : [0,0];
			d.trigger=options.trigger;
			if(wrapper.scrollTop()!==0 || wrapper.scrollLeft()!==0){ /* always reset scrollTop/Left */
				$(".mCSB_"+d.idx+"_scrollbar").css("visibility","visible");
				wrapper.scrollTop(0).scrollLeft(0);
			}
			if(to==="_resetY" && !d.contentReset.y){
				/* callbacks: onOverflowYNone */
				if(_cb("onOverflowYNone")){o.callbacks.onOverflowYNone.call(el[0]);}
				d.contentReset.y=1;
			}
			if(to==="_resetX" && !d.contentReset.x){
				/* callbacks: onOverflowXNone */
				if(_cb("onOverflowXNone")){o.callbacks.onOverflowXNone.call(el[0]);}
				d.contentReset.x=1;
			}
			if(to==="_resetY" || to==="_resetX"){return;}
			if((d.contentReset.y || !el[0].mcs) && d.overflowed[0]){
				/* callbacks: onOverflowY */
				if(_cb("onOverflowY")){o.callbacks.onOverflowY.call(el[0]);}
				d.contentReset.x=null;
			}
			if((d.contentReset.x || !el[0].mcs) && d.overflowed[1]){
				/* callbacks: onOverflowX */
				if(_cb("onOverflowX")){o.callbacks.onOverflowX.call(el[0]);}
				d.contentReset.x=null;
			}
			if(o.snapAmount){ /* scrolling snapping */
				var snapAmount=!(o.snapAmount instanceof Array) ? o.snapAmount : options.dir==="x" ? o.snapAmount[1] : o.snapAmount[0];
				to=_snapAmount(to,snapAmount,o.snapOffset);
			}
			switch(options.dir){
				case "x":
					var mCSB_dragger=$("#mCSB_"+d.idx+"_dragger_horizontal"),
						property="left",
						contentPos=mCSB_container[0].offsetLeft,
						limit=[
							mCustomScrollBox.width()-mCSB_container.outerWidth(false),
							mCSB_dragger.parent().width()-mCSB_dragger.width()
						],
						scrollTo=[to,to===0 ? 0 : (to/d.scrollRatio.x)],
						tso=totalScrollOffsets[1],
						tsbo=totalScrollBackOffsets[1],
						totalScrollOffset=tso>0 ? tso/d.scrollRatio.x : 0,
						totalScrollBackOffset=tsbo>0 ? tsbo/d.scrollRatio.x : 0;
					break;
				case "y":
					var mCSB_dragger=$("#mCSB_"+d.idx+"_dragger_vertical"),
						property="top",
						contentPos=mCSB_container[0].offsetTop,
						limit=[
							mCustomScrollBox.height()-mCSB_container.outerHeight(false),
							mCSB_dragger.parent().height()-mCSB_dragger.height()
						],
						scrollTo=[to,to===0 ? 0 : (to/d.scrollRatio.y)],
						tso=totalScrollOffsets[0],
						tsbo=totalScrollBackOffsets[0],
						totalScrollOffset=tso>0 ? tso/d.scrollRatio.y : 0,
						totalScrollBackOffset=tsbo>0 ? tsbo/d.scrollRatio.y : 0;
					break;
			}
			if(scrollTo[1]<0 || (scrollTo[0]===0 && scrollTo[1]===0)){
				scrollTo=[0,0];
			}else if(scrollTo[1]>=limit[1]){
				scrollTo=[limit[0],limit[1]];
			}else{
				scrollTo[0]=-scrollTo[0];
			}
			if(!el[0].mcs){
				_mcs();  /* init mcs object (once) to make it available before callbacks */
				if(_cb("onInit")){o.callbacks.onInit.call(el[0]);} /* callbacks: onInit */
			}
			clearTimeout(mCSB_container[0].onCompleteTimeout);
			_tweenTo(mCSB_dragger[0],property,Math.round(scrollTo[1]),dur[1],options.scrollEasing);
			if(!d.tweenRunning && ((contentPos===0 && scrollTo[0]>=0) || (contentPos===limit[0] && scrollTo[0]<=limit[0]))){return;}
			_tweenTo(mCSB_container[0],property,Math.round(scrollTo[0]),dur[0],options.scrollEasing,options.overwrite,{
				onStart:function(){
					if(options.callbacks && options.onStart && !d.tweenRunning){
						/* callbacks: onScrollStart */
						if(_cb("onScrollStart")){_mcs(); o.callbacks.onScrollStart.call(el[0]);}
						d.tweenRunning=true;
						_onDragClasses(mCSB_dragger);
						d.cbOffsets=_cbOffsets();
					}
				},onUpdate:function(){
					if(options.callbacks && options.onUpdate){
						/* callbacks: whileScrolling */
						if(_cb("whileScrolling")){_mcs(); o.callbacks.whileScrolling.call(el[0]);}
					}
				},onComplete:function(){
					if(options.callbacks && options.onComplete){
						if(o.axis==="yx"){clearTimeout(mCSB_container[0].onCompleteTimeout);}
						var t=mCSB_container[0].idleTimer || 0;
						mCSB_container[0].onCompleteTimeout=setTimeout(function(){
							/* callbacks: onScroll, onTotalScroll, onTotalScrollBack */
							if(_cb("onScroll")){_mcs(); o.callbacks.onScroll.call(el[0]);}
							if(_cb("onTotalScroll") && scrollTo[1]>=limit[1]-totalScrollOffset && d.cbOffsets[0]){_mcs(); o.callbacks.onTotalScroll.call(el[0]);}
							if(_cb("onTotalScrollBack") && scrollTo[1]<=totalScrollBackOffset && d.cbOffsets[1]){_mcs(); o.callbacks.onTotalScrollBack.call(el[0]);}
							d.tweenRunning=false;
							mCSB_container[0].idleTimer=0;
							_onDragClasses(mCSB_dragger,"hide");
						},t);
					}
				}
			});
			/* checks if callback function exists */
			function _cb(cb){
				return d && o.callbacks[cb] && typeof o.callbacks[cb]==="function";
			}
			/* checks whether callback offsets always trigger */
			function _cbOffsets(){
				return [o.callbacks.alwaysTriggerOffsets || contentPos>=limit[0]+tso,o.callbacks.alwaysTriggerOffsets || contentPos<=-tsbo];
			}
			/*
			populates object with useful values for the user
			values:
				content: this.mcs.content
				content top position: this.mcs.top
				content left position: this.mcs.left
				dragger top position: this.mcs.draggerTop
				dragger left position: this.mcs.draggerLeft
				scrolling y percentage: this.mcs.topPct
				scrolling x percentage: this.mcs.leftPct
				scrolling direction: this.mcs.direction
			*/
			function _mcs(){
				var cp=[mCSB_container[0].offsetTop,mCSB_container[0].offsetLeft], /* content position */
					dp=[mCSB_dragger[0].offsetTop,mCSB_dragger[0].offsetLeft], /* dragger position */
					cl=[mCSB_container.outerHeight(false),mCSB_container.outerWidth(false)], /* content length */
					pl=[mCustomScrollBox.height(),mCustomScrollBox.width()]; /* content parent length */
				el[0].mcs={
					content:mCSB_container, /* original content wrapper as jquery object */
					top:cp[0],left:cp[1],draggerTop:dp[0],draggerLeft:dp[1],
					topPct:Math.round((100*Math.abs(cp[0]))/(Math.abs(cl[0])-pl[0])),leftPct:Math.round((100*Math.abs(cp[1]))/(Math.abs(cl[1])-pl[1])),
					direction:options.dir
				};
				/*
				this refers to the original element containing the scrollbar(s)
				usage: this.mcs.top, this.mcs.leftPct etc.
				*/
			}
		},
		/* -------------------- */


		/*
		CUSTOM JAVASCRIPT ANIMATION TWEEN
		Lighter and faster than jquery animate() and css transitions
		Animates top/left properties and includes easings
		*/
		_tweenTo=function(el,prop,to,duration,easing,overwrite,callbacks){
			if(!el._mTween){el._mTween={top:{},left:{}};}
			var callbacks=callbacks || {},
				onStart=callbacks.onStart || function(){},onUpdate=callbacks.onUpdate || function(){},onComplete=callbacks.onComplete || function(){},
				startTime=_getTime(),_delay,progress=0,from=el.offsetTop,elStyle=el.style,_request,tobj=el._mTween[prop];
			if(prop==="left"){from=el.offsetLeft;}
			var diff=to-from;
			tobj.stop=0;
			if(overwrite!=="none"){_cancelTween();}
			_startTween();
			function _step(){
				if(tobj.stop){return;}
				if(!progress){onStart.call();}
				progress=_getTime()-startTime;
				_tween();
				if(progress>=tobj.time){
					tobj.time=(progress>tobj.time) ? progress+_delay-(progress-tobj.time) : progress+_delay-1;
					if(tobj.time<progress+1){tobj.time=progress+1;}
				}
				if(tobj.time<duration){tobj.id=_request(_step);}else{onComplete.call();}
			}
			function _tween(){
				if(duration>0){
					tobj.currVal=_ease(tobj.time,from,diff,duration,easing);
					elStyle[prop]=Math.round(tobj.currVal)+"px";
				}else{
					elStyle[prop]=to+"px";
				}
				onUpdate.call();
			}
			function _startTween(){
				_delay=1000/60;
				tobj.time=progress+_delay;
				_request=(!window.requestAnimationFrame) ? function(f){_tween(); return setTimeout(f,0.01);} : window.requestAnimationFrame;
				tobj.id=_request(_step);
			}
			function _cancelTween(){
				if(tobj.id==null){return;}
				if(!window.requestAnimationFrame){clearTimeout(tobj.id);
				}else{window.cancelAnimationFrame(tobj.id);}
				tobj.id=null;
			}
			function _ease(t,b,c,d,type){
				switch(type){
					case "linear": case "mcsLinear":
						return c*t/d + b;
						break;
					case "mcsLinearOut":
						t/=d; t--; return c * Math.sqrt(1 - t*t) + b;
						break;
					case "easeInOutSmooth":
						t/=d/2;
						if(t<1) return c/2*t*t + b;
						t--;
						return -c/2 * (t*(t-2) - 1) + b;
						break;
					case "easeInOutStrong":
						t/=d/2;
						if(t<1) return c/2 * Math.pow( 2, 10 * (t - 1) ) + b;
						t--;
						return c/2 * ( -Math.pow( 2, -10 * t) + 2 ) + b;
						break;
					case "easeInOut": case "mcsEaseInOut":
						t/=d/2;
						if(t<1) return c/2*t*t*t + b;
						t-=2;
						return c/2*(t*t*t + 2) + b;
						break;
					case "easeOutSmooth":
						t/=d; t--;
						return -c * (t*t*t*t - 1) + b;
						break;
					case "easeOutStrong":
						return c * ( -Math.pow( 2, -10 * t/d ) + 1 ) + b;
						break;
					case "easeOut": case "mcsEaseOut": default:
						var ts=(t/=d)*t,tc=ts*t;
						return b+c*(0.499999999999997*tc*ts + -2.5*ts*ts + 5.5*tc + -6.5*ts + 4*t);
				}
			}
		},
		/* -------------------- */


		/* returns current time */
		_getTime=function(){
			if(window.performance && window.performance.now){
				return window.performance.now();
			}else{
				if(window.performance && window.performance.webkitNow){
					return window.performance.webkitNow();
				}else{
					if(Date.now){return Date.now();}else{return new Date().getTime();}
				}
			}
		},
		/* -------------------- */


		/* stops a tween */
		_stopTween=function(){
			var el=this;
			if(!el._mTween){el._mTween={top:{},left:{}};}
			var props=["top","left"];
			for(var i=0; i<props.length; i++){
				var prop=props[i];
				if(el._mTween[prop].id){
					if(!window.requestAnimationFrame){clearTimeout(el._mTween[prop].id);
					}else{window.cancelAnimationFrame(el._mTween[prop].id);}
					el._mTween[prop].id=null;
					el._mTween[prop].stop=1;
				}
			}
		},
		/* -------------------- */


		/* deletes a property (avoiding the exception thrown by IE) */
		_delete=function(c,m){
			try{delete c[m];}catch(e){c[m]=null;}
		},
		/* -------------------- */


		/* detects left mouse button */
		_mouseBtnLeft=function(e){
			return !(e.which && e.which!==1);
		},
		/* -------------------- */


		/* detects if pointer type event is touch */
		_pointerTouch=function(e){
			var t=e.originalEvent.pointerType;
			return !(t && t!=="touch" && t!==2);
		},
		/* -------------------- */


		/* checks if value is numeric */
		_isNumeric=function(val){
			return !isNaN(parseFloat(val)) && isFinite(val);
		},
		/* -------------------- */


		/* returns element position according to content */
		_childPos=function(el){
			var p=el.parents(".mCSB_container");
			return [el.offset().top-p.offset().top,el.offset().left-p.offset().left];
		},
		/* -------------------- */


		/* checks if browser tab is hidden/inactive via Page Visibility API */
		_isTabHidden=function(){
			var prop=_getHiddenProp();
			if(!prop) return false;
			return document[prop];
			function _getHiddenProp(){
				var pfx=["webkit","moz","ms","o"];
				if("hidden" in document) return "hidden"; //natively supported
				for(var i=0; i<pfx.length; i++){ //prefixed
				    if((pfx[i]+"Hidden") in document)
				        return pfx[i]+"Hidden";
				}
				return null; //not supported
			}
		};
		/* -------------------- */





	/*
	----------------------------------------
	PLUGIN SETUP
	----------------------------------------
	*/

	/* plugin constructor functions */
	$.fn[pluginNS]=function(method){ /* usage: $(selector).mCustomScrollbar(); */
		if(methods[method]){
			return methods[method].apply(this,Array.prototype.slice.call(arguments,1));
		}else if(typeof method==="object" || !method){
			return methods.init.apply(this,arguments);
		}else{
			$.error("Method "+method+" does not exist");
		}
	};
	$[pluginNS]=function(method){ /* usage: $.mCustomScrollbar(); */
		if(methods[method]){
			return methods[method].apply(this,Array.prototype.slice.call(arguments,1));
		}else if(typeof method==="object" || !method){
			return methods.init.apply(this,arguments);
		}else{
			$.error("Method "+method+" does not exist");
		}
	};

	/*
	allow setting plugin default options.
	usage: $.mCustomScrollbar.defaults.scrollInertia=500;
	to apply any changed default options on default selectors (below), use inside document ready fn
	e.g.: $(document).ready(function(){ $.mCustomScrollbar.defaults.scrollInertia=500; });
	*/
	$[pluginNS].defaults=defaults;

	/*
	add window object (window.mCustomScrollbar)
	usage: if(window.mCustomScrollbar){console.log("custom scrollbar plugin loaded");}
	*/
	window[pluginNS]=true;

	$(window).bind("load",function(){

		$(defaultSelector)[pluginNS](); /* add scrollbars automatically on default selector */

		/* extend jQuery expressions */
		$.extend($.expr[":"],{
			/* checks if element is within scrollable viewport */
			mcsInView:$.expr[":"].mcsInView || function(el){
				var $el=$(el),content=$el.parents(".mCSB_container"),wrapper,cPos;
				if(!content.length){return;}
				wrapper=content.parent();
				cPos=[content[0].offsetTop,content[0].offsetLeft];
				return 	cPos[0]+_childPos($el)[0]>=0 && cPos[0]+_childPos($el)[0]<wrapper.height()-$el.outerHeight(false) &&
						cPos[1]+_childPos($el)[1]>=0 && cPos[1]+_childPos($el)[1]<wrapper.width()-$el.outerWidth(false);
			},
			/* checks if element or part of element is in view of scrollable viewport */
			mcsInSight:$.expr[":"].mcsInSight || function(el,i,m){
				var $el=$(el),elD,content=$el.parents(".mCSB_container"),wrapperView,pos,wrapperViewPct,
					pctVals=m[3]==="exact" ? [[1,0],[1,0]] : [[0.9,0.1],[0.6,0.4]];
				if(!content.length){return;}
				elD=[$el.outerHeight(false),$el.outerWidth(false)];
				pos=[content[0].offsetTop+_childPos($el)[0],content[0].offsetLeft+_childPos($el)[1]];
				wrapperView=[content.parent()[0].offsetHeight,content.parent()[0].offsetWidth];
				wrapperViewPct=[elD[0]<wrapperView[0] ? pctVals[0] : pctVals[1],elD[1]<wrapperView[1] ? pctVals[0] : pctVals[1]];
				return 	pos[0]-(wrapperView[0]*wrapperViewPct[0][0])<0 && pos[0]+elD[0]-(wrapperView[0]*wrapperViewPct[0][1])>=0 &&
						pos[1]-(wrapperView[1]*wrapperViewPct[1][0])<0 && pos[1]+elD[1]-(wrapperView[1]*wrapperViewPct[1][1])>=0;
			},
			/* checks if element is overflowed having visible scrollbar(s) */
			mcsOverflow:$.expr[":"].mcsOverflow || function(el){
				var d=$(el).data(pluginPfx);
				if(!d){return;}
				return d.overflowed[0] || d.overflowed[1];
			}
		});

	});

}))}));

!function(t,o,e){function i(o,e){this.bodyOverflowX,this.callbacks={hide:[],show:[]},this.checkInterval=null,this.Content,this.$el=t(o),this.$elProxy,this.elProxyPosition,this.enabled=!0,this.options=t.extend({},l,e),this.mouseIsOverProxy=!1,this.namespace="tooltipster-"+Math.round(1e5*Math.random()),this.Status="hidden",this.timerHide=null,this.timerShow=null,this.$tooltip,this.options.iconTheme=this.options.iconTheme.replace(".",""),this.options.theme=this.options.theme.replace(".",""),this._init()}function n(o,e){var i=!0;return t.each(o,function(t,n){return"undefined"==typeof e[t]||o[t]!==e[t]?(i=!1,!1):void 0}),i}function s(){return!f&&p}function r(){var t=e.body||e.documentElement,o=t.style,i="transition";if("string"==typeof o[i])return!0;v=["Moz","Webkit","Khtml","O","ms"],i=i.charAt(0).toUpperCase()+i.substr(1);for(var n=0;n<v.length;n++)if("string"==typeof o[v[n]+i])return!0;return!1}var a="tooltipster",l={animation:"fade",arrow:!0,arrowColor:"",autoClose:!0,content:null,contentAsHTML:!1,contentCloning:!0,debug:!0,delay:200,minWidth:0,maxWidth:null,functionInit:function(t,o){},functionBefore:function(t,o){o()},functionReady:function(t,o){},functionAfter:function(t){},hideOnClick:!1,icon:"(?)",iconCloning:!0,iconDesktop:!1,iconTouch:!1,iconTheme:"tooltipster-icon",interactive:!1,interactiveTolerance:350,multiple:!1,offsetX:0,offsetY:0,onlyOne:!1,position:"top",positionTracker:!1,positionTrackerCallback:function(t){"hover"==this.option("trigger")&&this.option("autoClose")&&this.hide()},restoration:"current",speed:350,timer:0,theme:"tooltipster-default",touchDevices:!0,trigger:"hover",updateAnimation:!0};i.prototype={_init:function(){var o=this;if(e.querySelector){var i=null;void 0===o.$el.data("tooltipster-initialTitle")&&(i=o.$el.attr("title"),void 0===i&&(i=null),o.$el.data("tooltipster-initialTitle",i)),null!==o.options.content?o._content_set(o.options.content):o._content_set(i);var n=o.options.functionInit.call(o.$el,o.$el,o.Content);"undefined"!=typeof n&&o._content_set(n),o.$el.removeAttr("title").addClass("tooltipstered"),!p&&o.options.iconDesktop||p&&o.options.iconTouch?("string"==typeof o.options.icon?(o.$elProxy=t('<span class="'+o.options.iconTheme+'"></span>'),o.$elProxy.text(o.options.icon)):o.options.iconCloning?o.$elProxy=o.options.icon.clone(!0):o.$elProxy=o.options.icon,o.$elProxy.insertAfter(o.$el)):o.$elProxy=o.$el,"hover"==o.options.trigger?(o.$elProxy.on("mouseenter."+o.namespace,function(){(!s()||o.options.touchDevices)&&(o.mouseIsOverProxy=!0,o._show())}).on("mouseleave."+o.namespace,function(){(!s()||o.options.touchDevices)&&(o.mouseIsOverProxy=!1)}),p&&o.options.touchDevices&&o.$elProxy.on("touchstart."+o.namespace,function(){o._showNow()})):"click"==o.options.trigger&&o.$elProxy.on("click."+o.namespace,function(){(!s()||o.options.touchDevices)&&o._show()})}},_show:function(){var t=this;"shown"!=t.Status&&"appearing"!=t.Status&&(t.options.delay?t.timerShow=setTimeout(function(){("click"==t.options.trigger||"hover"==t.options.trigger&&t.mouseIsOverProxy)&&t._showNow()},t.options.delay):t._showNow())},_showNow:function(e){var i=this;i.options.functionBefore.call(i.$el,i.$el,function(){if(i.enabled&&null!==i.Content){e&&i.callbacks.show.push(e),i.callbacks.hide=[],clearTimeout(i.timerShow),i.timerShow=null,clearTimeout(i.timerHide),i.timerHide=null,i.options.onlyOne&&t(".tooltipstered").not(i.$el).each(function(o,e){var i=t(e),n=i.data("tooltipster-ns");t.each(n,function(t,o){var e=i.data(o),n=e.status(),s=e.option("autoClose");"hidden"!==n&&"disappearing"!==n&&s&&e.hide()})});var n=function(){i.Status="shown",t.each(i.callbacks.show,function(t,o){o.call(i.$el)}),i.callbacks.show=[]};if("hidden"!==i.Status){var s=0;"disappearing"===i.Status?(i.Status="appearing",r()?(i.$tooltip.clearQueue().removeClass("tooltipster-dying").addClass("tooltipster-"+i.options.animation+"-show"),i.options.speed>0&&i.$tooltip.delay(i.options.speed),i.$tooltip.queue(n)):i.$tooltip.stop().fadeIn(n)):"shown"===i.Status&&n()}else{i.Status="appearing";var s=i.options.speed;i.bodyOverflowX=t("body").css("overflow-x"),t("body").css("overflow-x","hidden");var a="tooltipster-"+i.options.animation,l="-webkit-transition-duration: "+i.options.speed+"ms; -webkit-animation-duration: "+i.options.speed+"ms; -moz-transition-duration: "+i.options.speed+"ms; -moz-animation-duration: "+i.options.speed+"ms; -o-transition-duration: "+i.options.speed+"ms; -o-animation-duration: "+i.options.speed+"ms; -ms-transition-duration: "+i.options.speed+"ms; -ms-animation-duration: "+i.options.speed+"ms; transition-duration: "+i.options.speed+"ms; animation-duration: "+i.options.speed+"ms;",f=i.options.minWidth?"min-width:"+Math.round(i.options.minWidth)+"px;":"",d=i.options.maxWidth?"max-width:"+Math.round(i.options.maxWidth)+"px;":"",c=i.options.interactive?"pointer-events: auto;":"";if(i.$tooltip=t('<div class="tooltipster-base '+i.options.theme+'" style="'+f+" "+d+" "+c+" "+l+'"><div class="tooltipster-content"></div></div>'),r()&&i.$tooltip.addClass(a),i._content_insert(),i.$tooltip.appendTo("body"),i.reposition(),i.options.functionReady.call(i.$el,i.$el,i.$tooltip),r()?(i.$tooltip.addClass(a+"-show"),i.options.speed>0&&i.$tooltip.delay(i.options.speed),i.$tooltip.queue(n)):i.$tooltip.css("display","none").fadeIn(i.options.speed,n),i._interval_set(),t(o).on("scroll."+i.namespace+" resize."+i.namespace,function(){i.reposition()}),i.options.autoClose)if(t("body").off("."+i.namespace),"hover"==i.options.trigger){if(p&&setTimeout(function(){t("body").on("touchstart."+i.namespace,function(){i.hide()})},0),i.options.interactive){p&&i.$tooltip.on("touchstart."+i.namespace,function(t){t.stopPropagation()});var h=null;i.$elProxy.add(i.$tooltip).on("mouseleave."+i.namespace+"-autoClose",function(){clearTimeout(h),h=setTimeout(function(){i.hide()},i.options.interactiveTolerance)}).on("mouseenter."+i.namespace+"-autoClose",function(){clearTimeout(h)})}else i.$elProxy.on("mouseleave."+i.namespace+"-autoClose",function(){i.hide()});i.options.hideOnClick&&i.$elProxy.on("click."+i.namespace+"-autoClose",function(){i.hide()})}else"click"==i.options.trigger&&(setTimeout(function(){t("body").on("click."+i.namespace+" touchstart."+i.namespace,function(){i.hide()})},0),i.options.interactive&&i.$tooltip.on("click."+i.namespace+" touchstart."+i.namespace,function(t){t.stopPropagation()}))}i.options.timer>0&&(i.timerHide=setTimeout(function(){i.timerHide=null,i.hide()},i.options.timer+s))}})},_interval_set:function(){var o=this;o.checkInterval=setInterval(function(){if(0===t("body").find(o.$el).length||0===t("body").find(o.$elProxy).length||"hidden"==o.Status||0===t("body").find(o.$tooltip).length)("shown"==o.Status||"appearing"==o.Status)&&o.hide(),o._interval_cancel();else if(o.options.positionTracker){var e=o._repositionInfo(o.$elProxy),i=!1;n(e.dimension,o.elProxyPosition.dimension)&&("fixed"===o.$elProxy.css("position")?n(e.position,o.elProxyPosition.position)&&(i=!0):n(e.offset,o.elProxyPosition.offset)&&(i=!0)),i||(o.reposition(),o.options.positionTrackerCallback.call(o,o.$el))}},200)},_interval_cancel:function(){clearInterval(this.checkInterval),this.checkInterval=null},_content_set:function(t){"object"==typeof t&&null!==t&&this.options.contentCloning&&(t=t.clone(!0)),this.Content=t},_content_insert:function(){var t=this,o=this.$tooltip.find(".tooltipster-content");"string"!=typeof t.Content||t.options.contentAsHTML?o.empty().append(t.Content):o.text(t.Content)},_update:function(t){var o=this;o._content_set(t),null!==o.Content?"hidden"!==o.Status&&(o._content_insert(),o.reposition(),o.options.updateAnimation&&(r()?(o.$tooltip.css({width:"","-webkit-transition":"all "+o.options.speed+"ms, width 0ms, height 0ms, left 0ms, top 0ms","-moz-transition":"all "+o.options.speed+"ms, width 0ms, height 0ms, left 0ms, top 0ms","-o-transition":"all "+o.options.speed+"ms, width 0ms, height 0ms, left 0ms, top 0ms","-ms-transition":"all "+o.options.speed+"ms, width 0ms, height 0ms, left 0ms, top 0ms",transition:"all "+o.options.speed+"ms, width 0ms, height 0ms, left 0ms, top 0ms"}).addClass("tooltipster-content-changing"),setTimeout(function(){"hidden"!=o.Status&&(o.$tooltip.removeClass("tooltipster-content-changing"),setTimeout(function(){"hidden"!==o.Status&&o.$tooltip.css({"-webkit-transition":o.options.speed+"ms","-moz-transition":o.options.speed+"ms","-o-transition":o.options.speed+"ms","-ms-transition":o.options.speed+"ms",transition:o.options.speed+"ms"})},o.options.speed))},o.options.speed)):o.$tooltip.fadeTo(o.options.speed,.5,function(){"hidden"!=o.Status&&o.$tooltip.fadeTo(o.options.speed,1)}))):o.hide()},_repositionInfo:function(t){return{dimension:{height:t.outerHeight(!1),width:t.outerWidth(!1)},offset:t.offset(),position:{left:parseInt(t.css("left")),top:parseInt(t.css("top"))}}},hide:function(e){var i=this;e&&i.callbacks.hide.push(e),i.callbacks.show=[],clearTimeout(i.timerShow),i.timerShow=null,clearTimeout(i.timerHide),i.timerHide=null;var n=function(){t.each(i.callbacks.hide,function(t,o){o.call(i.$el)}),i.callbacks.hide=[]};if("shown"==i.Status||"appearing"==i.Status){i.Status="disappearing";var s=function(){i.Status="hidden","object"==typeof i.Content&&null!==i.Content&&i.Content.detach(),i.$tooltip.remove(),i.$tooltip=null,t(o).off("."+i.namespace),t("body").off("."+i.namespace).css("overflow-x",i.bodyOverflowX),t("body").off("."+i.namespace),i.$elProxy.off("."+i.namespace+"-autoClose"),i.options.functionAfter.call(i.$el,i.$el),n()};r()?(i.$tooltip.clearQueue().removeClass("tooltipster-"+i.options.animation+"-show").addClass("tooltipster-dying"),i.options.speed>0&&i.$tooltip.delay(i.options.speed),i.$tooltip.queue(s)):i.$tooltip.stop().fadeOut(i.options.speed,s)}else"hidden"==i.Status&&n();return i},show:function(t){return this._showNow(t),this},update:function(t){return this.content(t)},content:function(t){return"undefined"==typeof t?this.Content:(this._update(t),this)},reposition:function(){function e(){var e=t(o).scrollLeft();0>M-e&&(s=M-e,M=e),M+l-e>r&&(s=M-(r+e-l),M=r+e-l)}function i(e,i){a.offset.top-t(o).scrollTop()-f-A-12<0&&i.indexOf("top")>-1&&(F=e),a.offset.top+a.dimension.height+f+12+A>t(o).scrollTop()+t(o).height()&&i.indexOf("bottom")>-1&&(F=e,W=a.offset.top-f-A-12)}var n=this;if(0!==t("body").find(n.$tooltip).length){n.$tooltip.css("width",""),n.elProxyPosition=n._repositionInfo(n.$elProxy);var s=null,r=t(o).width(),a=n.elProxyPosition,l=n.$tooltip.outerWidth(!1),p=n.$tooltip.innerWidth()+1,f=n.$tooltip.outerHeight(!1);if(n.$elProxy.is("area")){var d=n.$elProxy.attr("shape"),c=n.$elProxy.parent().attr("name"),h=t('img[usemap="#'+c+'"]'),u=h.offset().left,m=h.offset().top,v=void 0!==n.$elProxy.attr("coords")?n.$elProxy.attr("coords").split(","):void 0;if("circle"==d){var g=parseInt(v[0]),y=parseInt(v[1]),w=parseInt(v[2]);a.dimension.height=2*w,a.dimension.width=2*w,a.offset.top=m+y-w,a.offset.left=u+g-w}else if("rect"==d){var g=parseInt(v[0]),y=parseInt(v[1]),b=parseInt(v[2]),x=parseInt(v[3]);a.dimension.height=x-y,a.dimension.width=b-g,a.offset.top=m+y,a.offset.left=u+g}else if("poly"==d){for(var C=[],P=[],T=0,_=0,k=0,I=0,S="even",O=0;O<v.length;O++){var H=parseInt(v[O]);"even"==S?(H>k&&(k=H,0===O&&(T=k)),T>H&&(T=H),S="odd"):(H>I&&(I=H,1==O&&(_=I)),_>H&&(_=H),S="even")}a.dimension.height=I-_,a.dimension.width=k-T,a.offset.top=m+_,a.offset.left=u+T}else a.dimension.height=h.outerHeight(!1),a.dimension.width=h.outerWidth(!1),a.offset.top=m,a.offset.left=u}var M=0,D=0,W=0,A=parseInt(n.options.offsetY),z=parseInt(n.options.offsetX),F=n.options.position;if("top"==F){var N=a.offset.left+l-(a.offset.left+a.dimension.width);M=a.offset.left+z-N/2,W=a.offset.top-f-A-12,e(),i("bottom","top")}if("top-left"==F&&(M=a.offset.left+z,W=a.offset.top-f-A-12,e(),i("bottom-left","top-left")),"top-right"==F&&(M=a.offset.left+a.dimension.width+z-l,W=a.offset.top-f-A-12,e(),i("bottom-right","top-right")),"bottom"==F){var N=a.offset.left+l-(a.offset.left+a.dimension.width);M=a.offset.left-N/2+z,W=a.offset.top+a.dimension.height+A+12,e(),i("top","bottom")}if("bottom-left"==F&&(M=a.offset.left+z,W=a.offset.top+a.dimension.height+A+12,e(),i("top-left","bottom-left")),"bottom-right"==F&&(M=a.offset.left+a.dimension.width+z-l,W=a.offset.top+a.dimension.height+A+12,e(),i("top-right","bottom-right")),"left"==F){M=a.offset.left-z-l-12,D=a.offset.left+z+a.dimension.width+12;var X=a.offset.top+f-(a.offset.top+a.dimension.height);if(W=a.offset.top-X/2-A,0>M&&D+l>r){var q=2*parseFloat(n.$tooltip.css("border-width")),j=l+M-q;n.$tooltip.css("width",j+"px"),f=n.$tooltip.outerHeight(!1),M=a.offset.left-z-j-12-q,X=a.offset.top+f-(a.offset.top+a.dimension.height),W=a.offset.top-X/2-A}else 0>M&&(M=a.offset.left+z+a.dimension.width+12,s="left")}if("right"==F){M=a.offset.left+z+a.dimension.width+12,D=a.offset.left-z-l-12;var X=a.offset.top+f-(a.offset.top+a.dimension.height);if(W=a.offset.top-X/2-A,M+l>r&&0>D){var q=2*parseFloat(n.$tooltip.css("border-width")),j=r-M-q;n.$tooltip.css("width",j+"px"),f=n.$tooltip.outerHeight(!1),X=a.offset.top+f-(a.offset.top+a.dimension.height),W=a.offset.top-X/2-A}else M+l>r&&(M=a.offset.left-z-l-12,s="right")}if(n.options.arrow){var E="tooltipster-arrow-"+F;if(n.options.arrowColor.length<1)var L=n.$tooltip.css("background-color");else var L=n.options.arrowColor;if(s?"left"==s?(E="tooltipster-arrow-right",s=""):"right"==s?(E="tooltipster-arrow-left",s=""):s="left:"+Math.round(s)+"px;":s="","top"==F||"top-left"==F||"top-right"==F)var Q=parseFloat(n.$tooltip.css("border-bottom-width")),U=n.$tooltip.css("border-bottom-color");else if("bottom"==F||"bottom-left"==F||"bottom-right"==F)var Q=parseFloat(n.$tooltip.css("border-top-width")),U=n.$tooltip.css("border-top-color");else if("left"==F)var Q=parseFloat(n.$tooltip.css("border-right-width")),U=n.$tooltip.css("border-right-color");else if("right"==F)var Q=parseFloat(n.$tooltip.css("border-left-width")),U=n.$tooltip.css("border-left-color");else var Q=parseFloat(n.$tooltip.css("border-bottom-width")),U=n.$tooltip.css("border-bottom-color");Q>1&&Q++;var Y="";if(0!==Q){var B="",R="border-color: "+U+";";-1!==E.indexOf("bottom")?B="margin-top: -"+Math.round(Q)+"px;":-1!==E.indexOf("top")?B="margin-bottom: -"+Math.round(Q)+"px;":-1!==E.indexOf("left")?B="margin-right: -"+Math.round(Q)+"px;":-1!==E.indexOf("right")&&(B="margin-left: -"+Math.round(Q)+"px;"),Y='<span class="tooltipster-arrow-border" style="'+B+" "+R+';"></span>'}n.$tooltip.find(".tooltipster-arrow").remove();var K='<div class="'+E+' tooltipster-arrow" style="'+s+'">'+Y+'<span style="border-color:'+L+';"></span></div>';n.$tooltip.append(K)}n.$tooltip.css({top:Math.round(W)+"px",left:Math.round(M)+"px"})}return n},enable:function(){return this.enabled=!0,this},disable:function(){return this.hide(),this.enabled=!1,this},destroy:function(){var o=this;o.hide(),o.$el[0]!==o.$elProxy[0]&&o.$elProxy.remove(),o.$el.removeData(o.namespace).off("."+o.namespace);var e=o.$el.data("tooltipster-ns");if(1===e.length){var i=null;"previous"===o.options.restoration?i=o.$el.data("tooltipster-initialTitle"):"current"===o.options.restoration&&(i="string"==typeof o.Content?o.Content:t("<div></div>").append(o.Content).html()),i&&o.$el.attr("title",i),o.$el.removeClass("tooltipstered").removeData("tooltipster-ns").removeData("tooltipster-initialTitle")}else e=t.grep(e,function(t,e){return t!==o.namespace}),o.$el.data("tooltipster-ns",e);return o},elementIcon:function(){return this.$el[0]!==this.$elProxy[0]?this.$elProxy[0]:void 0},elementTooltip:function(){return this.$tooltip?this.$tooltip[0]:void 0},option:function(t,o){return"undefined"==typeof o?this.options[t]:(this.options[t]=o,this)},status:function(){return this.Status}},t.fn[a]=function(){var o=arguments;if(0===this.length){if("string"==typeof o[0]){var e=!0;switch(o[0]){case"setDefaults":t.extend(l,o[1]);break;default:e=!1}return e?!0:this}return this}if("string"==typeof o[0]){var n="#*$~&";return this.each(function(){var e=t(this).data("tooltipster-ns"),i=e?t(this).data(e[0]):null;if(!i)throw new Error("You called Tooltipster's \""+o[0]+'" method on an uninitialized element');if("function"!=typeof i[o[0]])throw new Error('Unknown method .tooltipster("'+o[0]+'")');var s=i[o[0]](o[1],o[2]);return s!==i?(n=s,!1):void 0}),"#*$~&"!==n?n:this}var s=[],r=o[0]&&"undefined"!=typeof o[0].multiple,a=r&&o[0].multiple||!r&&l.multiple,p=o[0]&&"undefined"!=typeof o[0].debug,f=p&&o[0].debug||!p&&l.debug;return this.each(function(){var e=!1,n=t(this).data("tooltipster-ns"),r=null;n?a?e=!0:f&&console.log('Tooltipster: one or more tooltips are already attached to this element: ignoring. Use the "multiple" option to attach more tooltips.'):e=!0,e&&(r=new i(this,o[0]),n||(n=[]),n.push(r.namespace),t(this).data("tooltipster-ns",n),t(this).data(r.namespace,r)),s.push(r)}),a?s:this};var p=!!("ontouchstart"in o),f=!1;t("body").one("mousemove",function(){f=!0})}(jQuery,window,document);

/*!
 * jQuery UI Touch Punch 0.2.3
 *
 * Copyright 2011�2014, Dave Furfero
 * Dual licensed under the MIT or GPL Version 2 licenses.
 *
 * Depends:
 *  jquery.ui.widget.js
 *  jquery.ui.mouse.js
 */
(function ($) {

  // Detect touch support
  $.support.touch = 'ontouchend' in document;

  // Ignore browsers without touch support
  if (!$.support.touch) {
    return;
  }

  var mouseProto = $.ui.mouse.prototype,
      _mouseInit = mouseProto._mouseInit,
      _mouseDestroy = mouseProto._mouseDestroy,
      touchHandled;

  /**
   * Simulate a mouse event based on a corresponding touch event
   * @param {Object} event A touch event
   * @param {String} simulatedType The corresponding mouse event
   */
  function simulateMouseEvent (event, simulatedType) {

    // Ignore multi-touch events
    if (event.originalEvent.touches.length > 1) {
      return;
    }

    event.preventDefault();

    var touch = event.originalEvent.changedTouches[0],
        simulatedEvent = document.createEvent('MouseEvents');

    // Initialize the simulated mouse event using the touch event's coordinates
    simulatedEvent.initMouseEvent(
      simulatedType,    // type
      true,             // bubbles
      true,             // cancelable
      window,           // view
      1,                // detail
      touch.screenX,    // screenX
      touch.screenY,    // screenY
      touch.clientX,    // clientX
      touch.clientY,    // clientY
      false,            // ctrlKey
      false,            // altKey
      false,            // shiftKey
      false,            // metaKey
      0,                // button
      null              // relatedTarget
    );

    // Dispatch the simulated event to the target element
    event.target.dispatchEvent(simulatedEvent);
  }

  /**
   * Handle the jQuery UI widget's touchstart events
   * @param {Object} event The widget element's touchstart event
   */
  mouseProto._touchStart = function (event) {

    var self = this;

    // Ignore the event if another widget is already being handled
    if (touchHandled || !self._mouseCapture(event.originalEvent.changedTouches[0])) {
      return;
    }

    // Set the flag to prevent other widgets from inheriting the touch event
    touchHandled = true;

    // Track movement to determine if interaction was a click
    self._touchMoved = false;

    // Simulate the mouseover event
    simulateMouseEvent(event, 'mouseover');

    // Simulate the mousemove event
    simulateMouseEvent(event, 'mousemove');

    // Simulate the mousedown event
    simulateMouseEvent(event, 'mousedown');
  };

  /**
   * Handle the jQuery UI widget's touchmove events
   * @param {Object} event The document's touchmove event
   */
  mouseProto._touchMove = function (event) {

    // Ignore event if not handled
    if (!touchHandled) {
      return;
    }

    // Interaction was not a click
    this._touchMoved = true;

    // Simulate the mousemove event
    simulateMouseEvent(event, 'mousemove');
  };

  /**
   * Handle the jQuery UI widget's touchend events
   * @param {Object} event The document's touchend event
   */
  mouseProto._touchEnd = function (event) {

    // Ignore event if not handled
    if (!touchHandled) {
      return;
    }

    // Simulate the mouseup event
    simulateMouseEvent(event, 'mouseup');

    // Simulate the mouseout event
    simulateMouseEvent(event, 'mouseout');

    // If the touch interaction did not move, it should trigger a click
    if (!this._touchMoved) {

      // Simulate the click event
      simulateMouseEvent(event, 'click');
    }

    // Unset the flag to allow other widgets to inherit the touch event
    touchHandled = false;
  };

  /**
   * A duck punch of the $.ui.mouse _mouseInit method to support touch events.
   * This method extends the widget with bound touch event handlers that
   * translate touch events to mouse events and pass them to the widget's
   * original mouse event handling methods.
   */
  mouseProto._mouseInit = function () {

    var self = this;

    // Delegate the touch handlers to the widget's element
    self.element.bind({
      touchstart: $.proxy(self, '_touchStart'),
      touchmove: $.proxy(self, '_touchMove'),
      touchend: $.proxy(self, '_touchEnd')
    });

    // Call the original $.ui.mouse init method
    _mouseInit.call(self);
  };

  /**
   * Remove the touch event handlers
   */
  mouseProto._mouseDestroy = function () {

    var self = this;

    // Delegate the touch handlers to the widget's element
    self.element.unbind({
      touchstart: $.proxy(self, '_touchStart'),
      touchmove: $.proxy(self, '_touchMove'),
      touchend: $.proxy(self, '_touchEnd')
    });

    // Call the original $.ui.mouse destroy method
    _mouseDestroy.call(self);
  };

})(jQuery);

/** @license
 *
 * jsPDF - PDF Document creation from JavaScript
 * Version 2.2.0 Built on 2020-12-07T14:12:49.843Z
 *                      CommitID 00000000
 *
 * Copyright (c) 2010-2020 James Hall <james@parall.ax>, https://github.com/MrRio/jsPDF
 *               2015-2020 yWorks GmbH, http://www.yworks.com
 *               2015-2020 Lukas Holländer <lukas.hollaender@yworks.com>, https://github.com/HackbrettXXX
 *               2016-2018 Aras Abbasi <aras.abbasi@gmail.com>
 *               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
 *
 * 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.
 *
 * Contributor(s):
 *    siefkenj, ahwolf, rickygu, Midnith, saintclair, eaparango,
 *    kim3er, mfo, alnorth, Flamenco
 */

(function (global, factory) {
  typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  typeof define === 'function' && define.amd ? define(['exports'], factory) :
  (global = global || self, factory(global.jspdf = {}));
}(this, (function (exports) { 'use strict';

  var globalObject = (function() {
    return "undefined" !== typeof window
      ? window
      : "undefined" !== typeof global
      ? global
      : "undefined" !== typeof self
      ? self
      : this;
  })();

  function consoleLog() {
    if (globalObject.console && typeof globalObject.console.log === "function") {
      globalObject.console.log.apply(globalObject.console, arguments);
    }
  }

  function consoleWarn(str) {
    if (globalObject.console) {
      if (typeof globalObject.console.warn === "function") {
        globalObject.console.warn.apply(globalObject.console, arguments);
      } else {
        consoleLog.call(null, arguments);
      }
    }
  }

  function consoleError(str) {
    if (globalObject.console) {
      if (typeof globalObject.console.error === "function") {
        globalObject.console.error.apply(globalObject.console, arguments);
      } else {
        consoleLog(str);
      }
    }
  }
  var console = {
    log: consoleLog,
    warn: consoleWarn,
    error: consoleError
  };

  /**
   * @license
   * FileSaver.js
   * A saveAs() FileSaver implementation.
   *
   * By Eli Grey, http://eligrey.com
   *
   * License : https://github.com/eligrey/FileSaver.js/blob/master/LICENSE.md (MIT)
   * source  : http://purl.eligrey.com/github/FileSaver.js
   */

  function bom(blob, opts) {
    if (typeof opts === "undefined") opts = { autoBom: false };
    else if (typeof opts !== "object") {
      console.warn("Deprecated: Expected third argument to be a object");
      opts = { autoBom: !opts };
    }

    // prepend BOM for UTF-8 XML and text/* types (including HTML)
    // note: your browser will automatically convert UTF-16 U+FEFF to EF BB BF
    if (
      opts.autoBom &&
      /^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(
        blob.type
      )
    ) {
      return new Blob([String.fromCharCode(0xfeff), blob], { type: blob.type });
    }
    return blob;
  }

  function download(url, name, opts) {
    var xhr = new XMLHttpRequest();
    xhr.open("GET", url);
    xhr.responseType = "blob";
    xhr.onload = function() {
      saveAs(xhr.response, name, opts);
    };
    xhr.onerror = function() {
      console.error("could not download file");
    };
    xhr.send();
  }

  function corsEnabled(url) {
    var xhr = new XMLHttpRequest();
    // use sync to avoid popup blocker
    xhr.open("HEAD", url, false);
    try {
      xhr.send();
    } catch (e) {}
    return xhr.status >= 200 && xhr.status <= 299;
  }

  // `a.click()` doesn't work for all browsers (#465)
  function click(node) {
    try {
      node.dispatchEvent(new MouseEvent("click"));
    } catch (e) {
      var evt = document.createEvent("MouseEvents");
      evt.initMouseEvent(
        "click",
        true,
        true,
        window,
        0,
        0,
        0,
        80,
        20,
        false,
        false,
        false,
        false,
        0,
        null
      );
      node.dispatchEvent(evt);
    }
  }

  var saveAs =
    globalObject.saveAs ||
    // probably in some web worker
    (typeof window !== "object" || window !== globalObject
      ? function saveAs() {
          /* noop */
        }
      : // Use download attribute first if possible (#193 Lumia mobile)
      "download" in HTMLAnchorElement.prototype
      ? function saveAs(blob, name, opts) {
          var URL = globalObject.URL || globalObject.webkitURL;
          var a = document.createElement("a");
          name = name || blob.name || "download";

          a.download = name;
          a.rel = "noopener"; // tabnabbing

          // TODO: detect chrome extensions & packaged apps
          // a.target = '_blank'

          if (typeof blob === "string") {
            // Support regular links
            a.href = blob;
            if (a.origin !== location.origin) {
              corsEnabled(a.href)
                ? download(blob, name, opts)
                : click(a, (a.target = "_blank"));
            } else {
              click(a);
            }
          } else {
            // Support blobs
            a.href = URL.createObjectURL(blob);
            setTimeout(function() {
              URL.revokeObjectURL(a.href);
            }, 4e4); // 40s
            setTimeout(function() {
              click(a);
            }, 0);
          }
        }
      : // Use msSaveOrOpenBlob as a second approach
      "msSaveOrOpenBlob" in navigator
      ? function saveAs(blob, name, opts) {
          name = name || blob.name || "download";

          if (typeof blob === "string") {
            if (corsEnabled(blob)) {
              download(blob, name, opts);
            } else {
              var a = document.createElement("a");
              a.href = blob;
              a.target = "_blank";
              setTimeout(function() {
                click(a);
              });
            }
          } else {
            navigator.msSaveOrOpenBlob(bom(blob, opts), name);
          }
        }
      : // Fallback to using FileReader and a popup
        function saveAs(blob, name, opts, popup) {
          // Open a popup immediately do go around popup blocker
          // Mostly only available on user interaction and the fileReader is async so...
          popup = popup || open("", "_blank");
          if (popup) {
            popup.document.title = popup.document.body.innerText =
              "downloading...";
          }

          if (typeof blob === "string") return download(blob, name, opts);

          var force = blob.type === "application/octet-stream";
          var isSafari =
            /constructor/i.test(globalObject.HTMLElement) || globalObject.safari;
          var isChromeIOS = /CriOS\/[\d]+/.test(navigator.userAgent);

          if (
            (isChromeIOS || (force && isSafari)) &&
            typeof FileReader === "object"
          ) {
            // Safari doesn't allow downloading of blob URLs
            var reader = new FileReader();
            reader.onloadend = function() {
              var url = reader.result;
              url = isChromeIOS
                ? url
                : url.replace(/^data:[^;]*;/, "data:attachment/file;");
              if (popup) popup.location.href = url;
              else location = url;
              popup = null; // reverse-tabnabbing #460
            };
            reader.readAsDataURL(blob);
          } else {
            var URL = globalObject.URL || globalObject.webkitURL;
            var url = URL.createObjectURL(blob);
            if (popup) popup.location = url;
            else location.href = url;
            popup = null; // reverse-tabnabbing #460
            setTimeout(function() {
              URL.revokeObjectURL(url);
            }, 4e4); // 40s
          }
        });

  /**
   * A class to parse color values
   * @author Stoyan Stefanov <sstoo@gmail.com>
   * {@link   http://www.phpied.com/rgb-color-parser-in-javascript/}
   * @license Use it if you like it
   */

  function RGBColor(color_string) {
    color_string = color_string || "";
    this.ok = false;

    // strip any leading #
    if (color_string.charAt(0) == "#") {
      // remove # if any
      color_string = color_string.substr(1, 6);
    }

    color_string = color_string.replace(/ /g, "");
    color_string = color_string.toLowerCase();

    var channels;

    // before getting into regexps, try simple matches
    // and overwrite the input
    var simple_colors = {
      aliceblue: "f0f8ff",
      antiquewhite: "faebd7",
      aqua: "00ffff",
      aquamarine: "7fffd4",
      azure: "f0ffff",
      beige: "f5f5dc",
      bisque: "ffe4c4",
      black: "000000",
      blanchedalmond: "ffebcd",
      blue: "0000ff",
      blueviolet: "8a2be2",
      brown: "a52a2a",
      burlywood: "deb887",
      cadetblue: "5f9ea0",
      chartreuse: "7fff00",
      chocolate: "d2691e",
      coral: "ff7f50",
      cornflowerblue: "6495ed",
      cornsilk: "fff8dc",
      crimson: "dc143c",
      cyan: "00ffff",
      darkblue: "00008b",
      darkcyan: "008b8b",
      darkgoldenrod: "b8860b",
      darkgray: "a9a9a9",
      darkgreen: "006400",
      darkkhaki: "bdb76b",
      darkmagenta: "8b008b",
      darkolivegreen: "556b2f",
      darkorange: "ff8c00",
      darkorchid: "9932cc",
      darkred: "8b0000",
      darksalmon: "e9967a",
      darkseagreen: "8fbc8f",
      darkslateblue: "483d8b",
      darkslategray: "2f4f4f",
      darkturquoise: "00ced1",
      darkviolet: "9400d3",
      deeppink: "ff1493",
      deepskyblue: "00bfff",
      dimgray: "696969",
      dodgerblue: "1e90ff",
      feldspar: "d19275",
      firebrick: "b22222",
      floralwhite: "fffaf0",
      forestgreen: "228b22",
      fuchsia: "ff00ff",
      gainsboro: "dcdcdc",
      ghostwhite: "f8f8ff",
      gold: "ffd700",
      goldenrod: "daa520",
      gray: "808080",
      green: "008000",
      greenyellow: "adff2f",
      honeydew: "f0fff0",
      hotpink: "ff69b4",
      indianred: "cd5c5c",
      indigo: "4b0082",
      ivory: "fffff0",
      khaki: "f0e68c",
      lavender: "e6e6fa",
      lavenderblush: "fff0f5",
      lawngreen: "7cfc00",
      lemonchiffon: "fffacd",
      lightblue: "add8e6",
      lightcoral: "f08080",
      lightcyan: "e0ffff",
      lightgoldenrodyellow: "fafad2",
      lightgrey: "d3d3d3",
      lightgreen: "90ee90",
      lightpink: "ffb6c1",
      lightsalmon: "ffa07a",
      lightseagreen: "20b2aa",
      lightskyblue: "87cefa",
      lightslateblue: "8470ff",
      lightslategray: "778899",
      lightsteelblue: "b0c4de",
      lightyellow: "ffffe0",
      lime: "00ff00",
      limegreen: "32cd32",
      linen: "faf0e6",
      magenta: "ff00ff",
      maroon: "800000",
      mediumaquamarine: "66cdaa",
      mediumblue: "0000cd",
      mediumorchid: "ba55d3",
      mediumpurple: "9370d8",
      mediumseagreen: "3cb371",
      mediumslateblue: "7b68ee",
      mediumspringgreen: "00fa9a",
      mediumturquoise: "48d1cc",
      mediumvioletred: "c71585",
      midnightblue: "191970",
      mintcream: "f5fffa",
      mistyrose: "ffe4e1",
      moccasin: "ffe4b5",
      navajowhite: "ffdead",
      navy: "000080",
      oldlace: "fdf5e6",
      olive: "808000",
      olivedrab: "6b8e23",
      orange: "ffa500",
      orangered: "ff4500",
      orchid: "da70d6",
      palegoldenrod: "eee8aa",
      palegreen: "98fb98",
      paleturquoise: "afeeee",
      palevioletred: "d87093",
      papayawhip: "ffefd5",
      peachpuff: "ffdab9",
      peru: "cd853f",
      pink: "ffc0cb",
      plum: "dda0dd",
      powderblue: "b0e0e6",
      purple: "800080",
      red: "ff0000",
      rosybrown: "bc8f8f",
      royalblue: "4169e1",
      saddlebrown: "8b4513",
      salmon: "fa8072",
      sandybrown: "f4a460",
      seagreen: "2e8b57",
      seashell: "fff5ee",
      sienna: "a0522d",
      silver: "c0c0c0",
      skyblue: "87ceeb",
      slateblue: "6a5acd",
      slategray: "708090",
      snow: "fffafa",
      springgreen: "00ff7f",
      steelblue: "4682b4",
      tan: "d2b48c",
      teal: "008080",
      thistle: "d8bfd8",
      tomato: "ff6347",
      turquoise: "40e0d0",
      violet: "ee82ee",
      violetred: "d02090",
      wheat: "f5deb3",
      white: "ffffff",
      whitesmoke: "f5f5f5",
      yellow: "ffff00",
      yellowgreen: "9acd32"
    };
    color_string = simple_colors[color_string] || color_string;

    // array of color definition objects
    var color_defs = [
      {
        re: /^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/,
        example: ["rgb(123, 234, 45)", "rgb(255,234,245)"],
        process: function(bits) {
          return [parseInt(bits[1]), parseInt(bits[2]), parseInt(bits[3])];
        }
      },
      {
        re: /^(\w{2})(\w{2})(\w{2})$/,
        example: ["#00ff00", "336699"],
        process: function(bits) {
          return [
            parseInt(bits[1], 16),
            parseInt(bits[2], 16),
            parseInt(bits[3], 16)
          ];
        }
      },
      {
        re: /^(\w{1})(\w{1})(\w{1})$/,
        example: ["#fb0", "f0f"],
        process: function(bits) {
          return [
            parseInt(bits[1] + bits[1], 16),
            parseInt(bits[2] + bits[2], 16),
            parseInt(bits[3] + bits[3], 16)
          ];
        }
      }
    ];

    // search through the definitions to find a match
    for (var i = 0; i < color_defs.length; i++) {
      var re = color_defs[i].re;
      var processor = color_defs[i].process;
      var bits = re.exec(color_string);
      if (bits) {
        channels = processor(bits);
        this.r = channels[0];
        this.g = channels[1];
        this.b = channels[2];
        this.ok = true;
      }
    }

    // validate/cleanup values
    this.r = this.r < 0 || isNaN(this.r) ? 0 : this.r > 255 ? 255 : this.r;
    this.g = this.g < 0 || isNaN(this.g) ? 0 : this.g > 255 ? 255 : this.g;
    this.b = this.b < 0 || isNaN(this.b) ? 0 : this.b > 255 ? 255 : this.b;

    // some getters
    this.toRGB = function() {
      return "rgb(" + this.r + ", " + this.g + ", " + this.b + ")";
    };
    this.toHex = function() {
      var r = this.r.toString(16);
      var g = this.g.toString(16);
      var b = this.b.toString(16);
      if (r.length == 1) r = "0" + r;
      if (g.length == 1) g = "0" + g;
      if (b.length == 1) b = "0" + b;
      return "#" + r + g + b;
    };
  }

  var atob, btoa;

  (function() {
    atob = globalObject.atob.bind(globalObject);
    btoa = globalObject.btoa.bind(globalObject);
    return;

  })();

  /**
   * @license
   * Joseph Myers does not specify a particular license for his work.
   *
   * Author: Joseph Myers
   * Accessed from: http://www.myersdaily.org/joseph/javascript/md5.js
   *
   * Modified by: Owen Leong
   */

  function md5cycle(x, k) {
    var a = x[0],
      b = x[1],
      c = x[2],
      d = x[3];

    a = ff(a, b, c, d, k[0], 7, -680876936);
    d = ff(d, a, b, c, k[1], 12, -389564586);
    c = ff(c, d, a, b, k[2], 17, 606105819);
    b = ff(b, c, d, a, k[3], 22, -1044525330);
    a = ff(a, b, c, d, k[4], 7, -176418897);
    d = ff(d, a, b, c, k[5], 12, 1200080426);
    c = ff(c, d, a, b, k[6], 17, -1473231341);
    b = ff(b, c, d, a, k[7], 22, -45705983);
    a = ff(a, b, c, d, k[8], 7, 1770035416);
    d = ff(d, a, b, c, k[9], 12, -1958414417);
    c = ff(c, d, a, b, k[10], 17, -42063);
    b = ff(b, c, d, a, k[11], 22, -1990404162);
    a = ff(a, b, c, d, k[12], 7, 1804603682);
    d = ff(d, a, b, c, k[13], 12, -40341101);
    c = ff(c, d, a, b, k[14], 17, -1502002290);
    b = ff(b, c, d, a, k[15], 22, 1236535329);

    a = gg(a, b, c, d, k[1], 5, -165796510);
    d = gg(d, a, b, c, k[6], 9, -1069501632);
    c = gg(c, d, a, b, k[11], 14, 643717713);
    b = gg(b, c, d, a, k[0], 20, -373897302);
    a = gg(a, b, c, d, k[5], 5, -701558691);
    d = gg(d, a, b, c, k[10], 9, 38016083);
    c = gg(c, d, a, b, k[15], 14, -660478335);
    b = gg(b, c, d, a, k[4], 20, -405537848);
    a = gg(a, b, c, d, k[9], 5, 568446438);
    d = gg(d, a, b, c, k[14], 9, -1019803690);
    c = gg(c, d, a, b, k[3], 14, -187363961);
    b = gg(b, c, d, a, k[8], 20, 1163531501);
    a = gg(a, b, c, d, k[13], 5, -1444681467);
    d = gg(d, a, b, c, k[2], 9, -51403784);
    c = gg(c, d, a, b, k[7], 14, 1735328473);
    b = gg(b, c, d, a, k[12], 20, -1926607734);

    a = hh(a, b, c, d, k[5], 4, -378558);
    d = hh(d, a, b, c, k[8], 11, -2022574463);
    c = hh(c, d, a, b, k[11], 16, 1839030562);
    b = hh(b, c, d, a, k[14], 23, -35309556);
    a = hh(a, b, c, d, k[1], 4, -1530992060);
    d = hh(d, a, b, c, k[4], 11, 1272893353);
    c = hh(c, d, a, b, k[7], 16, -155497632);
    b = hh(b, c, d, a, k[10], 23, -1094730640);
    a = hh(a, b, c, d, k[13], 4, 681279174);
    d = hh(d, a, b, c, k[0], 11, -358537222);
    c = hh(c, d, a, b, k[3], 16, -722521979);
    b = hh(b, c, d, a, k[6], 23, 76029189);
    a = hh(a, b, c, d, k[9], 4, -640364487);
    d = hh(d, a, b, c, k[12], 11, -421815835);
    c = hh(c, d, a, b, k[15], 16, 530742520);
    b = hh(b, c, d, a, k[2], 23, -995338651);

    a = ii(a, b, c, d, k[0], 6, -198630844);
    d = ii(d, a, b, c, k[7], 10, 1126891415);
    c = ii(c, d, a, b, k[14], 15, -1416354905);
    b = ii(b, c, d, a, k[5], 21, -57434055);
    a = ii(a, b, c, d, k[12], 6, 1700485571);
    d = ii(d, a, b, c, k[3], 10, -1894986606);
    c = ii(c, d, a, b, k[10], 15, -1051523);
    b = ii(b, c, d, a, k[1], 21, -2054922799);
    a = ii(a, b, c, d, k[8], 6, 1873313359);
    d = ii(d, a, b, c, k[15], 10, -30611744);
    c = ii(c, d, a, b, k[6], 15, -1560198380);
    b = ii(b, c, d, a, k[13], 21, 1309151649);
    a = ii(a, b, c, d, k[4], 6, -145523070);
    d = ii(d, a, b, c, k[11], 10, -1120210379);
    c = ii(c, d, a, b, k[2], 15, 718787259);
    b = ii(b, c, d, a, k[9], 21, -343485551);

    x[0] = add32(a, x[0]);
    x[1] = add32(b, x[1]);
    x[2] = add32(c, x[2]);
    x[3] = add32(d, x[3]);
  }

  function cmn(q, a, b, x, s, t) {
    a = add32(add32(a, q), add32(x, t));
    return add32((a << s) | (a >>> (32 - s)), b);
  }

  function ff(a, b, c, d, x, s, t) {
    return cmn((b & c) | (~b & d), a, b, x, s, t);
  }

  function gg(a, b, c, d, x, s, t) {
    return cmn((b & d) | (c & ~d), a, b, x, s, t);
  }

  function hh(a, b, c, d, x, s, t) {
    return cmn(b ^ c ^ d, a, b, x, s, t);
  }

  function ii(a, b, c, d, x, s, t) {
    return cmn(c ^ (b | ~d), a, b, x, s, t);
  }

  function md51(s) {
    // txt = '';
    var n = s.length,
      state = [1732584193, -271733879, -1732584194, 271733878],
      i;
    for (i = 64; i <= s.length; i += 64) {
      md5cycle(state, md5blk(s.substring(i - 64, i)));
    }
    s = s.substring(i - 64);
    var tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
    for (i = 0; i < s.length; i++)
      tail[i >> 2] |= s.charCodeAt(i) << (i % 4 << 3);
    tail[i >> 2] |= 0x80 << (i % 4 << 3);
    if (i > 55) {
      md5cycle(state, tail);
      for (i = 0; i < 16; i++) tail[i] = 0;
    }
    tail[14] = n * 8;
    md5cycle(state, tail);
    return state;
  }

  /* there needs to be support for Unicode here,
   * unless we pretend that we can redefine the MD-5
   * algorithm for multi-byte characters (perhaps
   * by adding every four 16-bit characters and
   * shortening the sum to 32 bits). Otherwise
   * I suggest performing MD-5 as if every character
   * was two bytes--e.g., 0040 0025 = @%--but then
   * how will an ordinary MD-5 sum be matched?
   * There is no way to standardize text to something
   * like UTF-8 before transformation; speed cost is
   * utterly prohibitive. The JavaScript standard
   * itself needs to look at this: it should start
   * providing access to strings as preformed UTF-8
   * 8-bit unsigned value arrays.
   */
  function md5blk(s) {
    /* I figured global was faster.   */
    var md5blks = [],
      i; /* Andy King said do it this way. */
    for (i = 0; i < 64; i += 4) {
      md5blks[i >> 2] =
        s.charCodeAt(i) +
        (s.charCodeAt(i + 1) << 8) +
        (s.charCodeAt(i + 2) << 16) +
        (s.charCodeAt(i + 3) << 24);
    }
    return md5blks;
  }

  var hex_chr = "0123456789abcdef".split("");

  function rhex(n) {
    var s = "",
      j = 0;
    for (; j < 4; j++)
      s += hex_chr[(n >> (j * 8 + 4)) & 0x0f] + hex_chr[(n >> (j * 8)) & 0x0f];
    return s;
  }

  function hex(x) {
    for (var i = 0; i < x.length; i++) x[i] = rhex(x[i]);
    return x.join("");
  }

  // Converts a 4-byte number to byte string
  function singleToByteString(n) {
    return String.fromCharCode(
      (n & 0xff) >> 0,
      (n & 0xff00) >> 8,
      (n & 0xff0000) >> 16,
      (n & 0xff000000) >> 24
    );
  }

  // Converts an array of numbers to a byte string
  function toByteString(x) {
    return x.map(singleToByteString).join("");
  }

  // Returns the MD5 hash as a byte string
  function md5Bin(s) {
    return toByteString(md51(s));
  }

  // Returns MD5 hash as a hex string
  function md5(s) {
    return hex(md51(s));
  }

  /* this function is much faster,
  so if possible we use it. Some IEs
  are the only ones I know of that
  need the idiotic second function,
  generated by an if clause.  */

  function add32(a, b) {
    return (a + b) & 0xffffffff;
  }

  if (md5("hello") != "5d41402abc4b2a76b9719d911017c592") {
    function add32(x, y) {
      var lsw = (x & 0xffff) + (y & 0xffff),
        msw = (x >> 16) + (y >> 16) + (lsw >> 16);
      return (msw << 16) | (lsw & 0xffff);
    }
  }

  /**
   * @license
   * FPDF is released under a permissive license: there is no usage restriction.
   * You may embed it freely in your application (commercial or not), with or
   * without modifications.
   *
   * Reference: http://www.fpdf.org/en/script/script37.php
   */

  function repeat(str, num) {
    return new Array(num + 1).join(str);
  }

  /**
   * Converts a byte string to a hex string
   *
   * @name rc4
   * @function
   * @param {string} key Byte string of encryption key
   * @param {string} data Byte string of data to be encrypted
   * @returns {string} Encrypted string
   */
  function rc4(key, data) {
    var lastKey, lastState;
    if (key !== lastKey) {
      var k = repeat(key, ((256 / key.length) >> 0) + 1);
      var state = [];
      for (var i = 0; i < 256; i++) {
        state[i] = i;
      }
      var j = 0;
      for (var i = 0; i < 256; i++) {
        var t = state[i];
        j = (j + t + k.charCodeAt(i)) % 256;
        state[i] = state[j];
        state[j] = t;
      }
      lastKey = key;
      lastState = state;
    } else {
      state = lastState;
    }
    var length = data.length;
    var a = 0;
    var b = 0;
    var out = "";
    for (var i = 0; i < length; i++) {
      a = (a + 1) % 256;
      t = state[a];
      b = (b + t) % 256;
      state[a] = state[b];
      state[b] = t;
      k = state[(state[a] + state[b]) % 256];
      out += String.fromCharCode(data.charCodeAt(i) ^ k);
    }
    return out;
  }

  /**
   * @license
   * Licensed under the MIT License.
   * http://opensource.org/licenses/mit-license
   * Author: Owen Leong (@owenl131)
   * Date: 15 Oct 2020
   * References:
   * https://www.cs.cmu.edu/~dst/Adobe/Gallery/anon21jul01-pdf-encryption.txt
   * https://github.com/foliojs/pdfkit/blob/master/lib/security.js
   * http://www.fpdf.org/en/script/script37.php
   */

  var permissionOptions = {
    print: 4,
    modify: 8,
    copy: 16,
    "annot-forms": 32
  };

  /**
   * Initializes encryption settings
   *
   * @name constructor
   * @function
   * @param {Array} permissions Permissions allowed for user, "print", "modify", "copy" and "annot-forms".
   * @param {String} userPassword Permissions apply to this user. Leaving this empty means the document
   *                              is not password protected but viewer has the above permissions.
   * @param {String} ownerPassword Owner has full functionalities to the file.
   * @param {String} fileId As hex string, should be same as the file ID in the trailer.
   * @example
   * var security = new PDFSecurity(["print"])
   */
  function PDFSecurity(permissions, userPassword, ownerPassword, fileId) {
    this.v = 1; // algorithm 1, future work can add in more recent encryption schemes
    this.r = 2; // revision 2

    // set flags for what functionalities the user can access
    let protection = 192;
    permissions.forEach(function(perm) {
      if (typeof permissionOptions.perm !== "undefined") {
        throw new Error("Invalid permission: " + perm);
      }
      protection += permissionOptions[perm];
    });

    // padding is used to pad the passwords to 32 bytes, also is hashed and stored in the final PDF
    this.padding =
      "\x28\xBF\x4E\x5E\x4E\x75\x8A\x41\x64\x00\x4E\x56\xFF\xFA\x01\x08" +
      "\x2E\x2E\x00\xB6\xD0\x68\x3E\x80\x2F\x0C\xA9\xFE\x64\x53\x69\x7A";
    let paddedUserPassword = (userPassword + this.padding).substr(0, 32);
    let paddedOwnerPassword = (ownerPassword + this.padding).substr(0, 32);

    this.O = this.processOwnerPassword(paddedUserPassword, paddedOwnerPassword);
    this.P = -((protection ^ 255) + 1);
    this.encryptionKey = md5Bin(
      paddedUserPassword +
        this.O +
        this.lsbFirstWord(this.P) +
        this.hexToBytes(fileId)
    ).substr(0, 5);
    this.U = rc4(this.encryptionKey, this.padding);
  }

  /**
   * Breaks down a 4-byte number into its individual bytes, with the least significant bit first
   *
   * @name lsbFirstWord
   * @function
   * @param {number} data 32-bit number
   * @returns {Array}
   */
  PDFSecurity.prototype.lsbFirstWord = function(data) {
    return String.fromCharCode(
      (data >> 0) & 0xff,
      (data >> 8) & 0xff,
      (data >> 16) & 0xff,
      (data >> 24) & 0xff
    );
  };

  /**
   * Converts a byte string to a hex string
   *
   * @name toHexString
   * @function
   * @param {String} byteString Byte string
   * @returns {String}
   */
  PDFSecurity.prototype.toHexString = function(byteString) {
    return byteString
      .split("")
      .map(function(byte) {
        return ("0" + (byte.charCodeAt(0) & 0xff).toString(16)).slice(-2);
      })
      .join("");
  };

  /**
   * Converts a hex string to a byte string
   *
   * @name hexToBytes
   * @function
   * @param {String} hex Hex string
   * @returns {String}
   */
  PDFSecurity.prototype.hexToBytes = function(hex) {
    for (var bytes = [], c = 0; c < hex.length; c += 2)
      bytes.push(String.fromCharCode(parseInt(hex.substr(c, 2), 16)));
    return bytes.join("");
  };

  /**
   * Computes the 'O' field in the encryption dictionary
   *
   * @name processOwnerPassword
   * @function
   * @param {String} paddedUserPassword Byte string of padded user password
   * @param {String} paddedOwnerPassword Byte string of padded owner password
   * @returns {String}
   */
  PDFSecurity.prototype.processOwnerPassword = function(
    paddedUserPassword,
    paddedOwnerPassword
  ) {
    let key = md5Bin(paddedOwnerPassword).substr(0, 5);
    return rc4(key, paddedUserPassword);
  };

  /**
   * Returns an encryptor function which can take in a byte string and returns the encrypted version
   *
   * @name encryptor
   * @function
   * @param {number} objectId
   * @param {number} generation Not sure what this is for, you can set it to 0
   * @returns {Function}
   * @example
   * out("stream");
   * encryptor = security.encryptor(object.id, 0);
   * out(encryptor(data));
   * out("endstream");
   */
  PDFSecurity.prototype.encryptor = function(objectId, generation) {
    let key = md5Bin(
      this.encryptionKey +
        String.fromCharCode(
          objectId & 0xff,
          (objectId >> 8) & 0xff,
          (objectId >> 16) & 0xff,
          generation & 0xff,
          (generation >> 8) & 0xff
        )
    ).substr(0, 10);
    return function(data) {
      return rc4(key, data);
    };
  };

  /* eslint-disable no-console */

  /**
   * jsPDF's Internal PubSub Implementation.
   * Backward compatible rewritten on 2014 by
   * Diego Casorran, https://github.com/diegocr
   *
   * @class
   * @name PubSub
   * @ignore
   */
  function PubSub(context) {
    if (typeof context !== "object") {
      throw new Error(
        "Invalid Context passed to initialize PubSub (jsPDF-module)"
      );
    }
    var topics = {};

    this.subscribe = function(topic, callback, once) {
      once = once || false;
      if (
        typeof topic !== "string" ||
        typeof callback !== "function" ||
        typeof once !== "boolean"
      ) {
        throw new Error(
          "Invalid arguments passed to PubSub.subscribe (jsPDF-module)"
        );
      }

      if (!topics.hasOwnProperty(topic)) {
        topics[topic] = {};
      }

      var token = Math.random().toString(35);
      topics[topic][token] = [callback, !!once];

      return token;
    };

    this.unsubscribe = function(token) {
      for (var topic in topics) {
        if (topics[topic][token]) {
          delete topics[topic][token];
          if (Object.keys(topics[topic]).length === 0) {
            delete topics[topic];
          }
          return true;
        }
      }
      return false;
    };

    this.publish = function(topic) {
      if (topics.hasOwnProperty(topic)) {
        var args = Array.prototype.slice.call(arguments, 1),
          tokens = [];

        for (var token in topics[topic]) {
          var sub = topics[topic][token];
          try {
            sub[0].apply(context, args);
          } catch (ex) {
            if (globalObject.console) {
              console.error("jsPDF PubSub Error", ex.message, ex);
            }
          }
          if (sub[1]) tokens.push(token);
        }
        if (tokens.length) tokens.forEach(this.unsubscribe);
      }
    };

    this.getTopics = function() {
      return topics;
    };
  }

  function GState(parameters) {
    if (!(this instanceof GState)) {
      return new GState(parameters);
    }

    /**
     * @name GState#opacity
     * @type {any}
     */
    /**
     * @name GState#stroke-opacity
     * @type {any}
     */
    var supported = "opacity,stroke-opacity".split(",");
    for (var p in parameters) {
      if (parameters.hasOwnProperty(p) && supported.indexOf(p) >= 0) {
        this[p] = parameters[p];
      }
    }
    /**
     * @name GState#id
     * @type {string}
     */
    this.id = ""; // set by addGState()
    /**
     * @name GState#objectNumber
     * @type {number}
     */
    this.objectNumber = -1; // will be set by putGState()
  }

  GState.prototype.equals = function equals(other) {
    var ignore = "id,objectNumber,equals";
    var p;
    if (!other || typeof other !== typeof this) return false;
    var count = 0;
    for (p in this) {
      if (ignore.indexOf(p) >= 0) continue;
      if (this.hasOwnProperty(p) && !other.hasOwnProperty(p)) return false;
      if (this[p] !== other[p]) return false;
      count++;
    }
    for (p in other) {
      if (other.hasOwnProperty(p) && ignore.indexOf(p) < 0) count--;
    }
    return count === 0;
  };

  function Pattern(gState, matrix) {
    this.gState = gState;
    this.matrix = matrix;

    this.id = ""; // set by addPattern()
    this.objectNumber = -1; // will be set by putPattern()
  }

  function ShadingPattern(type, coords, colors, gState, matrix) {
    if (!(this instanceof ShadingPattern)) {
      return new ShadingPattern(type, coords, colors, gState, matrix);
    }

    // see putPattern() for information how they are realized
    this.type = type === "axial" ? 2 : 3;
    this.coords = coords;
    this.colors = colors;

    Pattern.call(this, gState, matrix);
  }

  function TilingPattern(boundingBox, xStep, yStep, gState, matrix) {
    if (!(this instanceof TilingPattern)) {
      return new TilingPattern(boundingBox, xStep, yStep, gState, matrix);
    }

    this.boundingBox = boundingBox;
    this.xStep = xStep;
    this.yStep = yStep;

    this.stream = ""; // set by endTilingPattern();

    this.cloneIndex = 0;

    Pattern.call(this, gState, matrix);
  }

  /**
   * Creates new jsPDF document object instance.
   * @name jsPDF
   * @class
   * @param {Object} [options] - Collection of settings initializing the jsPDF-instance
   * @param {string} [options.orientation=portrait] - Orientation of the first page. Possible values are "portrait" or "landscape" (or shortcuts "p" or "l").<br />
   * @param {string} [options.unit=mm] Measurement unit (base unit) to be used when coordinates are specified.<br />
   * Possible values are "pt" (points), "mm", "cm", "m", "in" or "px". Note that in order to get the correct scaling for "px"
   * units, you need to enable the hotfix "px_scaling" by setting options.hotfixes = ["px_scaling"].
   * @param {string/Array} [options.format=a4] The format of the first page. Can be:<ul><li>a0 - a10</li><li>b0 - b10</li><li>c0 - c10</li><li>dl</li><li>letter</li><li>government-letter</li><li>legal</li><li>junior-legal</li><li>ledger</li><li>tabloid</li><li>credit-card</li></ul><br />
   * Default is "a4". If you want to use your own format just pass instead of one of the above predefined formats the size as an number-array, e.g. [595.28, 841.89]
   * @param {boolean} [options.putOnlyUsedFonts=false] Only put fonts into the PDF, which were used.
   * @param {boolean} [options.compress=false] Compress the generated PDF.
   * @param {number} [options.precision=16] Precision of the element-positions.
   * @param {number} [options.userUnit=1.0] Not to be confused with the base unit. Please inform yourself before you use it.
   * @param {string[]} [options.hotfixes] An array of strings to enable hotfixes such as correct pixel scaling.
   * @param {Object} [options.encryption]
   * @param {string} [options.encryption.userPassword] Password for the user bound by the given permissions list.
   * @param {string} [options.encryption.ownerPassword] Both userPassword and ownerPassword should be set for proper authentication.
   * @param {string[]} [options.encryption.userPermissions] Array of permissions "print", "modify", "copy", "annot-forms", accessible by the user.
   * @param {number|"smart"} [options.floatPrecision=16]
   * @returns {jsPDF} jsPDF-instance
   * @description
   * ```
   * {
   *  orientation: 'p',
   *  unit: 'mm',
   *  format: 'a4',
   *  putOnlyUsedFonts:true,
   *  floatPrecision: 16 // or "smart", default is 16
   * }
   * ```
   *
   * @constructor
   */
  function jsPDF(options) {
    var orientation = typeof arguments[0] === "string" ? arguments[0] : "p";
    var unit = arguments[1];
    var format = arguments[2];
    var compressPdf = arguments[3];
    var filters = [];
    var userUnit = 1.0;
    var precision;
    var floatPrecision = 16;
    var defaultPathOperation = "S";
    var encryptionOptions = null;

    options = options || {};

    if (typeof options === "object") {
      orientation = options.orientation;
      unit = options.unit || unit;
      format = options.format || format;
      compressPdf = options.compress || options.compressPdf || compressPdf;
      encryptionOptions = options.encryption || null;
      if (encryptionOptions !== null) {
        encryptionOptions.userPassword = encryptionOptions.userPassword || "";
        encryptionOptions.ownerPassword = encryptionOptions.ownerPassword || "";
        encryptionOptions.userPermissions =
          encryptionOptions.userPermissions || [];
      }
      userUnit =
        typeof options.userUnit === "number" ? Math.abs(options.userUnit) : 1.0;
      if (typeof options.precision !== "undefined") {
        precision = options.precision;
      }
      if (typeof options.floatPrecision !== "undefined") {
        floatPrecision = options.floatPrecision;
      }
      defaultPathOperation = options.defaultPathOperation || "S";
    }

    filters =
      options.filters || (compressPdf === true ? ["FlateEncode"] : filters);

    unit = unit || "mm";
    orientation = ("" + (orientation || "P")).toLowerCase();
    var putOnlyUsedFonts = options.putOnlyUsedFonts || false;
    var usedFonts = {};

    var API = {
      internal: {},
      __private__: {}
    };

    API.__private__.PubSub = PubSub;

    var pdfVersion = "1.3";
    var getPdfVersion = (API.__private__.getPdfVersion = function() {
      return pdfVersion;
    });

    API.__private__.setPdfVersion = function(value) {
      pdfVersion = value;
    };

    // Size in pt of various paper formats
    var pageFormats = {
      a0: [2383.94, 3370.39],
      a1: [1683.78, 2383.94],
      a2: [1190.55, 1683.78],
      a3: [841.89, 1190.55],
      a4: [595.28, 841.89],
      a5: [419.53, 595.28],
      a6: [297.64, 419.53],
      a7: [209.76, 297.64],
      a8: [147.4, 209.76],
      a9: [104.88, 147.4],
      a10: [73.7, 104.88],
      b0: [2834.65, 4008.19],
      b1: [2004.09, 2834.65],
      b2: [1417.32, 2004.09],
      b3: [1000.63, 1417.32],
      b4: [708.66, 1000.63],
      b5: [498.9, 708.66],
      b6: [354.33, 498.9],
      b7: [249.45, 354.33],
      b8: [175.75, 249.45],
      b9: [124.72, 175.75],
      b10: [87.87, 124.72],
      c0: [2599.37, 3676.54],
      c1: [1836.85, 2599.37],
      c2: [1298.27, 1836.85],
      c3: [918.43, 1298.27],
      c4: [649.13, 918.43],
      c5: [459.21, 649.13],
      c6: [323.15, 459.21],
      c7: [229.61, 323.15],
      c8: [161.57, 229.61],
      c9: [113.39, 161.57],
      c10: [79.37, 113.39],
      dl: [311.81, 623.62],
      letter: [612, 792],
      "government-letter": [576, 756],
      legal: [612, 1008],
      "junior-legal": [576, 360],
      ledger: [1224, 792],
      tabloid: [792, 1224],
      "credit-card": [153, 243]
    };

    API.__private__.getPageFormats = function() {
      return pageFormats;
    };

    var getPageFormat = (API.__private__.getPageFormat = function(value) {
      return pageFormats[value];
    });

    format = format || "a4";

    var ApiMode = {
      COMPAT: "compat",
      ADVANCED: "advanced"
    };
    var apiMode = ApiMode.COMPAT;

    function advancedAPI() {
      // prepend global change of basis matrix
      // (Now, instead of converting every coordinate to the pdf coordinate system, we apply a matrix
      // that does this job for us (however, texts, images and similar objects must be drawn bottom up))
      this.saveGraphicsState();
      out(
        new Matrix(
          scaleFactor,
          0,
          0,
          -scaleFactor,
          0,
          getPageHeight() * scaleFactor
        ).toString() + " cm"
      );
      this.setFontSize(this.getFontSize() / scaleFactor);

      // The default in MrRio's implementation is "S" (stroke), whereas the default in the yWorks implementation
      // was "n" (none). Although this has nothing to do with transforms, we should use the API switch here.
      defaultPathOperation = "n";

      apiMode = ApiMode.ADVANCED;
    }

    function compatAPI() {
      this.restoreGraphicsState();
      defaultPathOperation = "S";
      apiMode = ApiMode.COMPAT;
    }

    /**
     * @callback ApiSwitchBody
     * @param {jsPDF} pdf
     */

    /**
     * For compatibility reasons jsPDF offers two API modes which differ in the way they convert between the the usual
     * screen coordinates and the PDF coordinate system.
     *   - "compat": Offers full compatibility across all plugins but does not allow arbitrary transforms
     *   - "advanced": Allows arbitrary transforms and more advanced features like pattern fills. Some plugins might
     *     not support this mode, though.
     * Initial mode is "compat".
     *
     * You can either provide a callback to the body argument, which means that jsPDF will automatically switch back to
     * the original API mode afterwards; or you can omit the callback and switch back manually using {@link compatAPI}.
     *
     * Note, that the calls to {@link saveGraphicsState} and {@link restoreGraphicsState} need to be balanced within the
     * callback or between calls of this method and its counterpart {@link compatAPI}. Calls to {@link beginFormObject}
     * or {@link beginTilingPattern} need to be closed by their counterparts before switching back to "compat" API mode.
     *
     * @param {ApiSwitchBody=} body When provided, this callback will be called after the API mode has been switched.
     * The API mode will be switched back automatically afterwards.
     * @returns {jsPDF}
     * @memberof jsPDF#
     * @name advancedAPI
     */
    API.advancedAPI = function(body) {
      var doSwitch = apiMode === ApiMode.COMPAT;

      if (doSwitch) {
        advancedAPI.call(this);
      }

      if (typeof body !== "function") {
        return this;
      }

      body(this);

      if (doSwitch) {
        compatAPI.call(this);
      }

      return this;
    };

    /**
     * Switches to "compat" API mode. See {@link advancedAPI} for more details.
     *
     * @param {ApiSwitchBody=} body When provided, this callback will be called after the API mode has been switched.
     * The API mode will be switched back automatically afterwards.
     * @return {jsPDF}
     * @memberof jsPDF#
     * @name compatApi
     */
    API.compatAPI = function(body) {
      var doSwitch = apiMode === ApiMode.ADVANCED;

      if (doSwitch) {
        compatAPI.call(this);
      }

      if (typeof body !== "function") {
        return this;
      }

      body(this);

      if (doSwitch) {
        advancedAPI.call(this);
      }

      return this;
    };

    /**
     * @return {boolean} True iff the current API mode is "advanced". See {@link advancedAPI}.
     * @memberof jsPDF#
     * @name isAdvancedAPI
     */
    API.isAdvancedAPI = function() {
      return apiMode === ApiMode.ADVANCED;
    };

    var advancedApiModeTrap = function(methodName) {
      if (apiMode !== ApiMode.ADVANCED) {
        throw new Error(
          methodName +
            " is only available in 'advanced' API mode. " +
            "You need to call advancedAPI() first."
        );
      }
    };

    var roundToPrecision = (API.roundToPrecision = API.__private__.roundToPrecision = function(
      number,
      parmPrecision
    ) {
      var tmpPrecision = precision || parmPrecision;
      if (isNaN(number) || isNaN(tmpPrecision)) {
        throw new Error("Invalid argument passed to jsPDF.roundToPrecision");
      }
      return number.toFixed(tmpPrecision).replace(/0+$/, "");
    });

    // high precision float
    var hpf;
    if (typeof floatPrecision === "number") {
      hpf = API.hpf = API.__private__.hpf = function(number) {
        if (isNaN(number)) {
          throw new Error("Invalid argument passed to jsPDF.hpf");
        }
        return roundToPrecision(number, floatPrecision);
      };
    } else if (floatPrecision === "smart") {
      hpf = API.hpf = API.__private__.hpf = function(number) {
        if (isNaN(number)) {
          throw new Error("Invalid argument passed to jsPDF.hpf");
        }
        if (number > -1 && number < 1) {
          return roundToPrecision(number, 16);
        } else {
          return roundToPrecision(number, 5);
        }
      };
    } else {
      hpf = API.hpf = API.__private__.hpf = function(number) {
        if (isNaN(number)) {
          throw new Error("Invalid argument passed to jsPDF.hpf");
        }
        return roundToPrecision(number, 16);
      };
    }
    var f2 = (API.f2 = API.__private__.f2 = function(number) {
      if (isNaN(number)) {
        throw new Error("Invalid argument passed to jsPDF.f2");
      }
      return roundToPrecision(number, 2);
    });

    var f3 = (API.__private__.f3 = function(number) {
      if (isNaN(number)) {
        throw new Error("Invalid argument passed to jsPDF.f3");
      }
      return roundToPrecision(number, 3);
    });

    var scale = (API.scale = API.__private__.scale = function(number) {
      if (isNaN(number)) {
        throw new Error("Invalid argument passed to jsPDF.scale");
      }
      if (apiMode === ApiMode.COMPAT) {
        return number * scaleFactor;
      } else if (apiMode === ApiMode.ADVANCED) {
        return number;
      }
    });

    var transformY = function(y) {
      if (apiMode === ApiMode.COMPAT) {
        return getPageHeight() - y;
      } else if (apiMode === ApiMode.ADVANCED) {
        return y;
      }
    };

    var transformScaleY = function(y) {
      return scale(transformY(y));
    };

    /**
     * @name setPrecision
     * @memberof jsPDF#
     * @function
     * @instance
     * @param {string} precision
     * @returns {jsPDF}
     */
    API.__private__.setPrecision = API.setPrecision = function(value) {
      if (typeof parseInt(value, 10) === "number") {
        precision = parseInt(value, 10);
      }
    };

    var fileId = "00000000000000000000000000000000";

    var getFileId = (API.__private__.getFileId = function() {
      return fileId;
    });

    var setFileId = (API.__private__.setFileId = function(value) {
      if (typeof value !== "undefined" && /^[a-fA-F0-9]{32}$/.test(value)) {
        fileId = value.toUpperCase();
      } else {
        fileId = fileId
          .split("")
          .map(function() {
            return "ABCDEF0123456789".charAt(Math.floor(Math.random() * 16));
          })
          .join("");
      }

      if (encryptionOptions !== null) {
        encryption = new PDFSecurity(
          encryptionOptions.userPermissions,
          encryptionOptions.userPassword,
          encryptionOptions.ownerPassword,
          fileId
        );
      }
      return fileId;
    });

    /**
     * @name setFileId
     * @memberof jsPDF#
     * @function
     * @instance
     * @param {string} value GUID.
     * @returns {jsPDF}
     */
    API.setFileId = function(value) {
      setFileId(value);
      return this;
    };

    /**
     * @name getFileId
     * @memberof jsPDF#
     * @function
     * @instance
     *
     * @returns {string} GUID.
     */
    API.getFileId = function() {
      return getFileId();
    };

    var creationDate;

    var convertDateToPDFDate = (API.__private__.convertDateToPDFDate = function(
      parmDate
    ) {
      var result = "";
      var tzoffset = parmDate.getTimezoneOffset(),
        tzsign = tzoffset < 0 ? "+" : "-",
        tzhour = Math.floor(Math.abs(tzoffset / 60)),
        tzmin = Math.abs(tzoffset % 60),
        timeZoneString = [tzsign, padd2(tzhour), "'", padd2(tzmin), "'"].join("");

      result = [
        "D:",
        parmDate.getFullYear(),
        padd2(parmDate.getMonth() + 1),
        padd2(parmDate.getDate()),
        padd2(parmDate.getHours()),
        padd2(parmDate.getMinutes()),
        padd2(parmDate.getSeconds()),
        timeZoneString
      ].join("");
      return result;
    });

    var convertPDFDateToDate = (API.__private__.convertPDFDateToDate = function(
      parmPDFDate
    ) {
      var year = parseInt(parmPDFDate.substr(2, 4), 10);
      var month = parseInt(parmPDFDate.substr(6, 2), 10) - 1;
      var date = parseInt(parmPDFDate.substr(8, 2), 10);
      var hour = parseInt(parmPDFDate.substr(10, 2), 10);
      var minutes = parseInt(parmPDFDate.substr(12, 2), 10);
      var seconds = parseInt(parmPDFDate.substr(14, 2), 10);
      // var timeZoneHour = parseInt(parmPDFDate.substr(16, 2), 10);
      // var timeZoneMinutes = parseInt(parmPDFDate.substr(20, 2), 10);

      var resultingDate = new Date(year, month, date, hour, minutes, seconds, 0);
      return resultingDate;
    });

    var setCreationDate = (API.__private__.setCreationDate = function(date) {
      var tmpCreationDateString;
      var regexPDFCreationDate = /^D:(20[0-2][0-9]|203[0-7]|19[7-9][0-9])(0[0-9]|1[0-2])([0-2][0-9]|3[0-1])(0[0-9]|1[0-9]|2[0-3])(0[0-9]|[1-5][0-9])(0[0-9]|[1-5][0-9])(\+0[0-9]|\+1[0-4]|-0[0-9]|-1[0-1])'(0[0-9]|[1-5][0-9])'?$/;
      if (typeof date === "undefined") {
        date = new Date();
      }

      if (date instanceof Date) {
        tmpCreationDateString = convertDateToPDFDate(date);
      } else if (regexPDFCreationDate.test(date)) {
        tmpCreationDateString = date;
      } else {
        throw new Error("Invalid argument passed to jsPDF.setCreationDate");
      }
      creationDate = tmpCreationDateString;
      return creationDate;
    });

    var getCreationDate = (API.__private__.getCreationDate = function(type) {
      var result = creationDate;
      if (type === "jsDate") {
        result = convertPDFDateToDate(creationDate);
      }
      return result;
    });

    /**
     * @name setCreationDate
     * @memberof jsPDF#
     * @function
     * @instance
     * @param {Object} date
     * @returns {jsPDF}
     */
    API.setCreationDate = function(date) {
      setCreationDate(date);
      return this;
    };

    /**
     * @name getCreationDate
     * @memberof jsPDF#
     * @function
     * @instance
     * @param {Object} type
     * @returns {Object}
     */
    API.getCreationDate = function(type) {
      return getCreationDate(type);
    };

    var padd2 = (API.__private__.padd2 = function(number) {
      return ("0" + parseInt(number)).slice(-2);
    });

    var padd2Hex = (API.__private__.padd2Hex = function(hexString) {
      hexString = hexString.toString();
      return ("00" + hexString).substr(hexString.length);
    });

    var objectNumber = 0; // 'n' Current object number
    var offsets = []; // List of offsets. Activated and reset by buildDocument(). Pupulated by various calls buildDocument makes.
    var content = [];
    var contentLength = 0;
    var additionalObjects = [];

    var pages = [];
    var currentPage;
    var hasCustomDestination = false;
    var outputDestination = content;

    var resetDocument = function() {
      //reset fields relevant for objectNumber generation and xref.
      objectNumber = 0;
      contentLength = 0;
      content = [];
      offsets = [];
      additionalObjects = [];

      rootDictionaryObjId = newObjectDeferred();
      resourceDictionaryObjId = newObjectDeferred();
    };

    API.__private__.setCustomOutputDestination = function(destination) {
      hasCustomDestination = true;
      outputDestination = destination;
    };
    var setOutputDestination = function(destination) {
      if (!hasCustomDestination) {
        outputDestination = destination;
      }
    };

    API.__private__.resetCustomOutputDestination = function() {
      hasCustomDestination = false;
      outputDestination = content;
    };

    var out = (API.__private__.out = function(string) {
      string = string.toString();
      contentLength += string.length + 1;
      outputDestination.push(string);

      return outputDestination;
    });

    var write = (API.__private__.write = function(value) {
      return out(
        arguments.length === 1
          ? value.toString()
          : Array.prototype.join.call(arguments, " ")
      );
    });

    var getArrayBuffer = (API.__private__.getArrayBuffer = function(data) {
      var len = data.length,
        ab = new ArrayBuffer(len),
        u8 = new Uint8Array(ab);

      while (len--) u8[len] = data.charCodeAt(len);
      return ab;
    });

    var standardFonts = [
      ["Helvetica", "helvetica", "normal", "WinAnsiEncoding"],
      ["Helvetica-Bold", "helvetica", "bold", "WinAnsiEncoding"],
      ["Helvetica-Oblique", "helvetica", "italic", "WinAnsiEncoding"],
      ["Helvetica-BoldOblique", "helvetica", "bolditalic", "WinAnsiEncoding"],
      ["Courier", "courier", "normal", "WinAnsiEncoding"],
      ["Courier-Bold", "courier", "bold", "WinAnsiEncoding"],
      ["Courier-Oblique", "courier", "italic", "WinAnsiEncoding"],
      ["Courier-BoldOblique", "courier", "bolditalic", "WinAnsiEncoding"],
      ["Times-Roman", "times", "normal", "WinAnsiEncoding"],
      ["Times-Bold", "times", "bold", "WinAnsiEncoding"],
      ["Times-Italic", "times", "italic", "WinAnsiEncoding"],
      ["Times-BoldItalic", "times", "bolditalic", "WinAnsiEncoding"],
      ["ZapfDingbats", "zapfdingbats", "normal", null],
      ["Symbol", "symbol", "normal", null]
    ];

    API.__private__.getStandardFonts = function() {
      return standardFonts;
    };

    var activeFontSize = options.fontSize || 16;

    /**
     * Sets font size for upcoming text elements.
     *
     * @param {number} size Font size in points.
     * @function
     * @instance
     * @returns {jsPDF}
     * @memberof jsPDF#
     * @name setFontSize
     */
    API.__private__.setFontSize = API.setFontSize = function(size) {
      if (apiMode === ApiMode.ADVANCED) {
        activeFontSize = size / scaleFactor;
      } else {
        activeFontSize = size;
      }
      return this;
    };

    /**
     * Gets the fontsize for upcoming text elements.
     *
     * @function
     * @instance
     * @returns {number}
     * @memberof jsPDF#
     * @name getFontSize
     */
    var getFontSize = (API.__private__.getFontSize = API.getFontSize = function() {
      if (apiMode === ApiMode.COMPAT) {
        return activeFontSize;
      } else {
        return activeFontSize * scaleFactor;
      }
    });

    var R2L = options.R2L || false;

    /**
     * Set value of R2L functionality.
     *
     * @param {boolean} value
     * @function
     * @instance
     * @returns {jsPDF} jsPDF-instance
     * @memberof jsPDF#
     * @name setR2L
     */
    API.__private__.setR2L = API.setR2L = function(value) {
      R2L = value;
      return this;
    };

    /**
     * Get value of R2L functionality.
     *
     * @function
     * @instance
     * @returns {boolean} jsPDF-instance
     * @memberof jsPDF#
     * @name getR2L
     */
    API.__private__.getR2L = API.getR2L = function() {
      return R2L;
    };

    var zoomMode; // default: 1;

    var setZoomMode = (API.__private__.setZoomMode = function(zoom) {
      var validZoomModes = [
        undefined,
        null,
        "fullwidth",
        "fullheight",
        "fullpage",
        "original"
      ];

      if (/^\d*\.?\d*%$/.test(zoom)) {
        zoomMode = zoom;
      } else if (!isNaN(zoom)) {
        zoomMode = parseInt(zoom, 10);
      } else if (validZoomModes.indexOf(zoom) !== -1) {
        zoomMode = zoom;
      } else {
        throw new Error(
          'zoom must be Integer (e.g. 2), a percentage Value (e.g. 300%) or fullwidth, fullheight, fullpage, original. "' +
            zoom +
            '" is not recognized.'
        );
      }
    });

    API.__private__.getZoomMode = function() {
      return zoomMode;
    };

    var pageMode; // default: 'UseOutlines';
    var setPageMode = (API.__private__.setPageMode = function(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.'
        );
      }
      pageMode = pmode;
    });

    API.__private__.getPageMode = function() {
      return pageMode;
    };

    var layoutMode; // default: 'continuous';
    var setLayoutMode = (API.__private__.setLayoutMode = function(layout) {
      var validLayoutModes = [
        undefined,
        null,
        "continuous",
        "single",
        "twoleft",
        "tworight",
        "two"
      ];

      if (validLayoutModes.indexOf(layout) == -1) {
        throw new Error(
          'Layout mode must be one of continuous, single, twoleft, tworight. "' +
            layout +
            '" is not recognized.'
        );
      }
      layoutMode = layout;
    });

    API.__private__.getLayoutMode = function() {
      return layoutMode;
    };

    /**
     * Set the display mode options of the page like zoom and layout.
     *
     * @name setDisplayMode
     * @memberof jsPDF#
     * @function
     * @instance
     * @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.
     *
     * @returns {jsPDF}
     */
    API.__private__.setDisplayMode = API.setDisplayMode = function(
      zoom,
      layout,
      pmode
    ) {
      setZoomMode(zoom);
      setLayoutMode(layout);
      setPageMode(pmode);
      return this;
    };

    var documentProperties = {
      title: "",
      subject: "",
      author: "",
      keywords: "",
      creator: ""
    };

    API.__private__.getDocumentProperty = function(key) {
      if (Object.keys(documentProperties).indexOf(key) === -1) {
        throw new Error("Invalid argument passed to jsPDF.getDocumentProperty");
      }
      return documentProperties[key];
    };

    API.__private__.getDocumentProperties = function() {
      return documentProperties;
    };

    /**
     * Adds a properties to the PDF document.
     *
     * @param {Object} A property_name-to-property_value object structure.
     * @function
     * @instance
     * @returns {jsPDF}
     * @memberof jsPDF#
     * @name setDocumentProperties
     */
    API.__private__.setDocumentProperties = API.setProperties = API.setDocumentProperties = 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;
    };

    API.__private__.setDocumentProperty = function(key, value) {
      if (Object.keys(documentProperties).indexOf(key) === -1) {
        throw new Error("Invalid arguments passed to jsPDF.setDocumentProperty");
      }
      return (documentProperties[key] = value);
    };

    var fonts = {}; // collection of font objects, where key is fontKey - a dynamically created label for a given font.
    var fontmap = {}; // mapping structure fontName > fontStyle > font key - performance layer. See addFont()
    var activeFontKey; // will be string representing the KEY of the font as combination of fontName + fontStyle
    var fontStateStack = []; //
    var patterns = {}; // collection of pattern objects
    var patternMap = {}; // see fonts
    var gStates = {}; // collection of graphic state objects
    var gStatesMap = {}; // see fonts
    var activeGState = null;
    var scaleFactor; // Scale factor
    var page = 0;
    var pagesContext = [];
    var events = new PubSub(API);
    var hotfixes = options.hotfixes || [];

    var renderTargets = {};
    var renderTargetMap = {};
    var renderTargetStack = [];
    var pageX;
    var pageY;
    var pageMatrix; // only used for FormObjects

    /**
     * A matrix object for 2D homogenous transformations: <br>
     * | a b 0 | <br>
     * | c d 0 | <br>
     * | e f 1 | <br>
     * pdf multiplies matrices righthand: v' = v x m1 x m2 x ...
     *
     * @class
     * @name Matrix
     * @param {number} sx
     * @param {number} shy
     * @param {number} shx
     * @param {number} sy
     * @param {number} tx
     * @param {number} ty
     * @constructor
     */
    var Matrix = function(sx, shy, shx, sy, tx, ty) {
      if (!(this instanceof Matrix)) {
        return new Matrix(sx, shy, shx, sy, tx, ty);
      }

      if (isNaN(sx)) sx = 1;
      if (isNaN(shy)) shy = 0;
      if (isNaN(shx)) shx = 0;
      if (isNaN(sy)) sy = 1;
      if (isNaN(tx)) tx = 0;
      if (isNaN(ty)) ty = 0;

      this._matrix = [sx, shy, shx, sy, tx, ty];
    };

    /**
     * @name sx
     * @memberof Matrix#
     */
    Object.defineProperty(Matrix.prototype, "sx", {
      get: function() {
        return this._matrix[0];
      },
      set: function(value) {
        this._matrix[0] = value;
      }
    });

    /**
     * @name shy
     * @memberof Matrix#
     */
    Object.defineProperty(Matrix.prototype, "shy", {
      get: function() {
        return this._matrix[1];
      },
      set: function(value) {
        this._matrix[1] = value;
      }
    });

    /**
     * @name shx
     * @memberof Matrix#
     */
    Object.defineProperty(Matrix.prototype, "shx", {
      get: function() {
        return this._matrix[2];
      },
      set: function(value) {
        this._matrix[2] = value;
      }
    });

    /**
     * @name sy
     * @memberof Matrix#
     */
    Object.defineProperty(Matrix.prototype, "sy", {
      get: function() {
        return this._matrix[3];
      },
      set: function(value) {
        this._matrix[3] = value;
      }
    });

    /**
     * @name tx
     * @memberof Matrix#
     */
    Object.defineProperty(Matrix.prototype, "tx", {
      get: function() {
        return this._matrix[4];
      },
      set: function(value) {
        this._matrix[4] = value;
      }
    });

    /**
     * @name ty
     * @memberof Matrix#
     */
    Object.defineProperty(Matrix.prototype, "ty", {
      get: function() {
        return this._matrix[5];
      },
      set: function(value) {
        this._matrix[5] = value;
      }
    });

    Object.defineProperty(Matrix.prototype, "a", {
      get: function() {
        return this._matrix[0];
      },
      set: function(value) {
        this._matrix[0] = value;
      }
    });

    Object.defineProperty(Matrix.prototype, "b", {
      get: function() {
        return this._matrix[1];
      },
      set: function(value) {
        this._matrix[1] = value;
      }
    });

    Object.defineProperty(Matrix.prototype, "c", {
      get: function() {
        return this._matrix[2];
      },
      set: function(value) {
        this._matrix[2] = value;
      }
    });

    Object.defineProperty(Matrix.prototype, "d", {
      get: function() {
        return this._matrix[3];
      },
      set: function(value) {
        this._matrix[3] = value;
      }
    });

    Object.defineProperty(Matrix.prototype, "e", {
      get: function() {
        return this._matrix[4];
      },
      set: function(value) {
        this._matrix[4] = value;
      }
    });

    Object.defineProperty(Matrix.prototype, "f", {
      get: function() {
        return this._matrix[5];
      },
      set: function(value) {
        this._matrix[5] = value;
      }
    });

    /**
     * @name rotation
     * @memberof Matrix#
     */
    Object.defineProperty(Matrix.prototype, "rotation", {
      get: function() {
        return Math.atan2(this.shx, this.sx);
      }
    });

    /**
     * @name scaleX
     * @memberof Matrix#
     */
    Object.defineProperty(Matrix.prototype, "scaleX", {
      get: function() {
        return this.decompose().scale.sx;
      }
    });

    /**
     * @name scaleY
     * @memberof Matrix#
     */
    Object.defineProperty(Matrix.prototype, "scaleY", {
      get: function() {
        return this.decompose().scale.sy;
      }
    });

    /**
     * @name isIdentity
     * @memberof Matrix#
     */
    Object.defineProperty(Matrix.prototype, "isIdentity", {
      get: function() {
        if (this.sx !== 1) {
          return false;
        }
        if (this.shy !== 0) {
          return false;
        }
        if (this.shx !== 0) {
          return false;
        }
        if (this.sy !== 1) {
          return false;
        }
        if (this.tx !== 0) {
          return false;
        }
        if (this.ty !== 0) {
          return false;
        }
        return true;
      }
    });

    /**
     * Join the Matrix Values to a String
     *
     * @function join
     * @param {string} separator Specifies a string to separate each pair of adjacent elements of the array. The separator is converted to a string if necessary. If omitted, the array elements are separated with a comma (","). If separator is an empty string, all elements are joined without any characters in between them.
     * @returns {string} A string with all array elements joined.
     * @memberof Matrix#
     */
    Matrix.prototype.join = function(separator) {
      return [this.sx, this.shy, this.shx, this.sy, this.tx, this.ty]
        .map(hpf)
        .join(separator);
    };

    /**
     * Multiply the matrix with given Matrix
     *
     * @function multiply
     * @param matrix
     * @returns {Matrix}
     * @memberof Matrix#
     */
    Matrix.prototype.multiply = function(matrix) {
      var sx = matrix.sx * this.sx + matrix.shy * this.shx;
      var shy = matrix.sx * this.shy + matrix.shy * this.sy;
      var shx = matrix.shx * this.sx + matrix.sy * this.shx;
      var sy = matrix.shx * this.shy + matrix.sy * this.sy;
      var tx = matrix.tx * this.sx + matrix.ty * this.shx + this.tx;
      var ty = matrix.tx * this.shy + matrix.ty * this.sy + this.ty;

      return new Matrix(sx, shy, shx, sy, tx, ty);
    };

    /**
     * @function decompose
     * @memberof Matrix#
     */
    Matrix.prototype.decompose = function() {
      var a = this.sx;
      var b = this.shy;
      var c = this.shx;
      var d = this.sy;
      var e = this.tx;
      var f = this.ty;

      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: new Matrix(scaleX, 0, 0, scaleY, 0, 0),
        translate: new Matrix(1, 0, 0, 1, e, f),
        rotate: new Matrix(a, b, -b, a, 0, 0),
        skew: new Matrix(1, 0, shear, 1, 0, 0)
      };
    };

    /**
     * @function toString
     * @memberof Matrix#
     */
    Matrix.prototype.toString = function(parmPrecision) {
      return this.join(" ");
    };

    /**
     * @function inversed
     * @memberof Matrix#
     */
    Matrix.prototype.inversed = function() {
      var a = this.sx,
        b = this.shy,
        c = this.shx,
        d = this.sy,
        e = this.tx,
        f = this.ty;

      var quot = 1 / (a * d - b * c);

      var aInv = d * quot;
      var bInv = -b * quot;
      var cInv = -c * quot;
      var dInv = a * quot;
      var eInv = -aInv * e - cInv * f;
      var fInv = -bInv * e - dInv * f;

      return new Matrix(aInv, bInv, cInv, dInv, eInv, fInv);
    };

    /**
     * @function applyToPoint
     * @memberof Matrix#
     */
    Matrix.prototype.applyToPoint = function(pt) {
      var x = pt.x * this.sx + pt.y * this.shx + this.tx;
      var y = pt.x * this.shy + pt.y * this.sy + this.ty;
      return new Point(x, y);
    };

    /**
     * @function applyToRectangle
     * @memberof Matrix#
     */
    Matrix.prototype.applyToRectangle = function(rect) {
      var pt1 = this.applyToPoint(rect);
      var pt2 = this.applyToPoint(new Point(rect.x + rect.w, rect.y + rect.h));
      return new Rectangle(pt1.x, pt1.y, pt2.x - pt1.x, pt2.y - pt1.y);
    };

    /**
     * Clone the Matrix
     *
     * @function clone
     * @memberof Matrix#
     * @name clone
     * @instance
     */
    Matrix.prototype.clone = function() {
      var sx = this.sx;
      var shy = this.shy;
      var shx = this.shx;
      var sy = this.sy;
      var tx = this.tx;
      var ty = this.ty;

      return new Matrix(sx, shy, shx, sy, tx, ty);
    };

    API.Matrix = Matrix;

    /**
     * Multiplies two matrices. (see {@link Matrix})
     * @param {Matrix} m1
     * @param {Matrix} m2
     * @memberof jsPDF#
     * @name matrixMult
     */
    var matrixMult = (API.matrixMult = function(m1, m2) {
      return m2.multiply(m1);
    });

    /**
     * The identity matrix (equivalent to new Matrix(1, 0, 0, 1, 0, 0)).
     * @type {Matrix}
     * @memberof! jsPDF#
     * @name identityMatrix
     */
    var identityMatrix = new Matrix(1, 0, 0, 1, 0, 0);
    API.unitMatrix = API.identityMatrix = identityMatrix;

    /**
     * Adds a new pattern for later use.
     * @param {String} key The key by it can be referenced later. The keys must be unique!
     * @param {API.Pattern} pattern The pattern
     */
    var addPattern = function(key, pattern) {
      // only add it if it is not already present (the keys provided by the user must be unique!)
      if (patternMap[key]) return;

      var prefix = pattern instanceof ShadingPattern ? "Sh" : "P";
      var patternKey = prefix + (Object.keys(patterns).length + 1).toString(10);
      pattern.id = patternKey;

      patternMap[key] = patternKey;
      patterns[patternKey] = pattern;

      events.publish("addPattern", pattern);
    };

    /**
     * A pattern describing a shading pattern.
     *
     * Only available in "advanced" API mode.
     *
     * @param {String} type One of "axial" or "radial"
     * @param {Array<Number>} coords Either [x1, y1, x2, y2] for "axial" type describing the two interpolation points
     * or [x1, y1, r, x2, y2, r2] for "radial" describing inner and the outer circle.
     * @param {Array<Object>} colors An array of objects with the fields "offset" and "color". "offset" describes
     * the offset in parameter space [0, 1]. "color" is an array of length 3 describing RGB values in [0, 255].
     * @param {GState=} gState An additional graphics state that gets applied to the pattern (optional).
     * @param {Matrix=} matrix A matrix that describes the transformation between the pattern coordinate system
     * and the use coordinate system (optional).
     * @constructor
     * @extends API.Pattern
     */
    API.ShadingPattern = ShadingPattern;

    /**
     * A PDF Tiling pattern.
     *
     * Only available in "advanced" API mode.
     *
     * @param {Array.<Number>} boundingBox The bounding box at which one pattern cell gets clipped.
     * @param {Number} xStep Horizontal spacing between pattern cells.
     * @param {Number} yStep Vertical spacing between pattern cells.
     * @param {API.GState=} gState An additional graphics state that gets applied to the pattern (optional).
     * @param {Matrix=} matrix A matrix that describes the transformation between the pattern coordinate system
     * and the use coordinate system (optional).
     * @constructor
     * @extends API.Pattern
     */
    API.TilingPattern = TilingPattern;

    /**
     * Adds a new {@link API.ShadingPattern} for later use. Only available in "advanced" API mode.
     * @param {String} key
     * @param {Pattern} pattern
     * @function
     * @returns {jsPDF}
     * @memberof jsPDF#
     * @name addPattern
     */
    API.addShadingPattern = function(key, pattern) {
      advancedApiModeTrap("addShadingPattern()");

      addPattern(key, pattern);
      return this;
    };

    /**
     * Begins a new tiling pattern. All subsequent render calls are drawn to this pattern until {@link API.endTilingPattern}
     * gets called. Only available in "advanced" API mode.
     * @param {API.Pattern} pattern
     * @memberof jsPDF#
     * @name beginTilingPattern
     */
    API.beginTilingPattern = function(pattern) {
      advancedApiModeTrap("beginTilingPattern()");

      beginNewRenderTarget(
        pattern.boundingBox[0],
        pattern.boundingBox[1],
        pattern.boundingBox[2] - pattern.boundingBox[0],
        pattern.boundingBox[3] - pattern.boundingBox[1],
        pattern.matrix
      );
    };

    /**
     * Ends a tiling pattern and sets the render target to the one active before {@link API.beginTilingPattern} has been called.
     *
     * Only available in "advanced" API mode.
     *
     * @param {string} key A unique key that is used to reference this pattern at later use.
     * @param {API.Pattern} pattern The pattern to end.
     * @memberof jsPDF#
     * @name endTilingPattern
     */
    API.endTilingPattern = function(key, pattern) {
      advancedApiModeTrap("endTilingPattern()");

      // retrieve the stream
      pattern.stream = pages[currentPage].join("\n");

      addPattern(key, pattern);

      events.publish("endTilingPattern", pattern);

      // restore state from stack
      renderTargetStack.pop().restore();
    };

    var newObject = (API.__private__.newObject = function() {
      var oid = newObjectDeferred();
      newObjectDeferredBegin(oid, true);
      return oid;
    });

    // Does not output the object.  The caller must call newObjectDeferredBegin(oid) before outputing any data
    var newObjectDeferred = (API.__private__.newObjectDeferred = function() {
      objectNumber++;
      offsets[objectNumber] = function() {
        return contentLength;
      };
      return objectNumber;
    });

    var newObjectDeferredBegin = function(oid, doOutput) {
      doOutput = typeof doOutput === "boolean" ? doOutput : false;
      offsets[oid] = contentLength;
      if (doOutput) {
        out(oid + " 0 obj");
      }
      return oid;
    };
    // 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.
    var newAdditionalObject = (API.__private__.newAdditionalObject = function() {
      var objId = newObjectDeferred();
      var obj = {
        objId: objId,
        content: ""
      };
      additionalObjects.push(obj);
      return obj;
    });

    var rootDictionaryObjId = newObjectDeferred();
    var resourceDictionaryObjId = newObjectDeferred();

    /////////////////////
    // Private functions
    /////////////////////

    var decodeColorString = (API.__private__.decodeColorString = function(color) {
      var colorEncoded = color.split(" ");
      if (
        colorEncoded.length === 2 &&
        (colorEncoded[1] === "g" || colorEncoded[1] === "G")
      ) {
        // convert grayscale value to rgb so that it can be converted to hex for consistency
        var floatVal = parseFloat(colorEncoded[0]);
        colorEncoded = [floatVal, floatVal, floatVal, "r"];
      } else if (
        colorEncoded.length === 5 &&
        (colorEncoded[4] === "k" || colorEncoded[4] === "K")
      ) {
        // convert CMYK values to rbg so that it can be converted to hex for consistency
        var red = (1.0 - colorEncoded[0]) * (1.0 - colorEncoded[3]);
        var green = (1.0 - colorEncoded[1]) * (1.0 - colorEncoded[3]);
        var blue = (1.0 - colorEncoded[2]) * (1.0 - colorEncoded[3]);

        colorEncoded = [red, green, blue, "r"];
      }
      var colorAsRGB = "#";
      for (var i = 0; i < 3; i++) {
        colorAsRGB += (
          "0" + Math.floor(parseFloat(colorEncoded[i]) * 255).toString(16)
        ).slice(-2);
      }
      return colorAsRGB;
    });

    var encodeColorString = (API.__private__.encodeColorString = function(
      options
    ) {
      var color;

      if (typeof options === "string") {
        options = {
          ch1: options
        };
      }
      var ch1 = options.ch1;
      var ch2 = options.ch2;
      var ch3 = options.ch3;
      var ch4 = options.ch4;
      var letterArray =
        options.pdfColorType === "draw" ? ["G", "RG", "K"] : ["g", "rg", "k"];

      if (typeof ch1 === "string" && ch1.charAt(0) !== "#") {
        var rgbColor = new RGBColor(ch1);
        if (rgbColor.ok) {
          ch1 = rgbColor.toHex();
        } else if (!/^\d*\.?\d*$/.test(ch1)) {
          throw new Error(
            'Invalid color "' + ch1 + '" passed to jsPDF.encodeColorString.'
          );
        }
      }
      //convert short rgb to long form
      if (typeof ch1 === "string" && /^#[0-9A-Fa-f]{3}$/.test(ch1)) {
        ch1 = "#" + ch1[1] + ch1[1] + ch1[2] + ch1[2] + ch1[3] + ch1[3];
      }

      if (typeof ch1 === "string" && /^#[0-9A-Fa-f]{6}$/.test(ch1)) {
        var hex = parseInt(ch1.substr(1), 16);
        ch1 = (hex >> 16) & 255;
        ch2 = (hex >> 8) & 255;
        ch3 = hex & 255;
      }

      if (
        typeof ch2 === "undefined" ||
        (typeof ch4 === "undefined" && ch1 === ch2 && ch2 === ch3)
      ) {
        // Gray color space.
        if (typeof ch1 === "string") {
          color = ch1 + " " + letterArray[0];
        } else {
          switch (options.precision) {
            case 2:
              color = f2(ch1 / 255) + " " + letterArray[0];
              break;
            case 3:
            default:
              color = f3(ch1 / 255) + " " + letterArray[0];
          }
        }
      } else if (typeof ch4 === "undefined" || typeof ch4 === "object") {
        // assume RGBA
        if (ch4 && !isNaN(ch4.a)) {
          //TODO Implement transparency.
          //WORKAROUND use white for now, if transparent, otherwise handle as rgb
          if (ch4.a === 0) {
            color = ["1.", "1.", "1.", letterArray[1]].join(" ");
            return color;
          }
        }
        // assume RGB
        if (typeof ch1 === "string") {
          color = [ch1, ch2, ch3, letterArray[1]].join(" ");
        } else {
          switch (options.precision) {
            case 2:
              color = [
                f2(ch1 / 255),
                f2(ch2 / 255),
                f2(ch3 / 255),
                letterArray[1]
              ].join(" ");
              break;
            default:
            case 3:
              color = [
                f3(ch1 / 255),
                f3(ch2 / 255),
                f3(ch3 / 255),
                letterArray[1]
              ].join(" ");
          }
        }
      } else {
        // assume CMYK
        if (typeof ch1 === "string") {
          color = [ch1, ch2, ch3, ch4, letterArray[2]].join(" ");
        } else {
          switch (options.precision) {
            case 2:
              color = [f2(ch1), f2(ch2), f2(ch3), f2(ch4), letterArray[2]].join(
                " "
              );
              break;
            case 3:
            default:
              color = [f3(ch1), f3(ch2), f3(ch3), f3(ch4), letterArray[2]].join(
                " "
              );
          }
        }
      }
      return color;
    });

    var getFilters = (API.__private__.getFilters = function() {
      return filters;
    });

    var putStream = (API.__private__.putStream = function(options) {
      options = options || {};
      var data = options.data || "";
      var filters = options.filters || getFilters();
      var alreadyAppliedFilters = options.alreadyAppliedFilters || [];
      var addLength1 = options.addLength1 || false;
      var valueOfLength1 = data.length;
      var objectId = options.objectId;
      var encryptor = function(data) {
        return data;
      };
      if (encryptionOptions !== null && typeof objectId == "undefined") {
        throw new Error(
          "ObjectId must be passed to putStream for file encryption"
        );
      }
      if (encryptionOptions !== null) {
        encryptor = encryption.encryptor(objectId, 0);
      }

      var processedData = {};
      if (filters === true) {
        filters = ["FlateEncode"];
      }
      var keyValues = options.additionalKeyValues || [];
      if (typeof jsPDF.API.processDataByFilters !== "undefined") {
        processedData = jsPDF.API.processDataByFilters(data, filters);
      } else {
        processedData = { data: data, reverseChain: [] };
      }
      var filterAsString =
        processedData.reverseChain +
        (Array.isArray(alreadyAppliedFilters)
          ? alreadyAppliedFilters.join(" ")
          : alreadyAppliedFilters.toString());

      if (processedData.data.length !== 0) {
        keyValues.push({
          key: "Length",
          value: processedData.data.length
        });
        if (addLength1 === true) {
          keyValues.push({
            key: "Length1",
            value: valueOfLength1
          });
        }
      }

      if (filterAsString.length != 0) {
        if (filterAsString.split("/").length - 1 === 1) {
          keyValues.push({
            key: "Filter",
            value: filterAsString
          });
        } else {
          keyValues.push({
            key: "Filter",
            value: "[" + filterAsString + "]"
          });

          for (var j = 0; j < keyValues.length; j += 1) {
            if (keyValues[j].key === "DecodeParms") {
              var decodeParmsArray = [];

              for (
                var i = 0;
                i < processedData.reverseChain.split("/").length - 1;
                i += 1
              ) {
                decodeParmsArray.push("null");
              }

              decodeParmsArray.push(keyValues[j].value);
              keyValues[j].value = "[" + decodeParmsArray.join(" ") + "]";
            }
          }
        }
      }

      out("<<");
      for (var k = 0; k < keyValues.length; k++) {
        out("/" + keyValues[k].key + " " + keyValues[k].value);
      }
      out(">>");
      if (processedData.data.length !== 0) {
        out("stream");
        out(encryptor(processedData.data));
        out("endstream");
      }
    });

    var putPage = (API.__private__.putPage = function(page) {
      var pageNumber = page.number;
      var data = page.data;
      var pageObjectNumber = page.objId;
      var pageContentsObjId = page.contentsObjId;

      newObjectDeferredBegin(pageObjectNumber, true);
      out("<</Type /Page");
      out("/Parent " + page.rootDictionaryObjId + " 0 R");
      out("/Resources " + page.resourceDictionaryObjId + " 0 R");
      out(
        "/MediaBox [" +
          parseFloat(hpf(page.mediaBox.bottomLeftX)) +
          " " +
          parseFloat(hpf(page.mediaBox.bottomLeftY)) +
          " " +
          hpf(page.mediaBox.topRightX) +
          " " +
          hpf(page.mediaBox.topRightY) +
          "]"
      );
      if (page.cropBox !== null) {
        out(
          "/CropBox [" +
            hpf(page.cropBox.bottomLeftX) +
            " " +
            hpf(page.cropBox.bottomLeftY) +
            " " +
            hpf(page.cropBox.topRightX) +
            " " +
            hpf(page.cropBox.topRightY) +
            "]"
        );
      }

      if (page.bleedBox !== null) {
        out(
          "/BleedBox [" +
            hpf(page.bleedBox.bottomLeftX) +
            " " +
            hpf(page.bleedBox.bottomLeftY) +
            " " +
            hpf(page.bleedBox.topRightX) +
            " " +
            hpf(page.bleedBox.topRightY) +
            "]"
        );
      }

      if (page.trimBox !== null) {
        out(
          "/TrimBox [" +
            hpf(page.trimBox.bottomLeftX) +
            " " +
            hpf(page.trimBox.bottomLeftY) +
            " " +
            hpf(page.trimBox.topRightX) +
            " " +
            hpf(page.trimBox.topRightY) +
            "]"
        );
      }

      if (page.artBox !== null) {
        out(
          "/ArtBox [" +
            hpf(page.artBox.bottomLeftX) +
            " " +
            hpf(page.artBox.bottomLeftY) +
            " " +
            hpf(page.artBox.topRightX) +
            " " +
            hpf(page.artBox.topRightY) +
            "]"
        );
      }

      if (typeof page.userUnit === "number" && page.userUnit !== 1.0) {
        out("/UserUnit " + page.userUnit);
      }

      events.publish("putPage", {
        objId: pageObjectNumber,
        pageContext: pagesContext[pageNumber],
        pageNumber: pageNumber,
        page: data
      });
      out("/Contents " + pageContentsObjId + " 0 R");
      out(">>");
      out("endobj");
      // Page content
      var pageContent = data.join("\n");

      if (apiMode === ApiMode.ADVANCED) {
        // if the user forgot to switch back to COMPAT mode, we must balance the graphics stack again
        pageContent += "\nQ";
      }

      newObjectDeferredBegin(pageContentsObjId, true);
      putStream({
        data: pageContent,
        filters: getFilters(),
        objectId: pageContentsObjId
      });
      out("endobj");
      return pageObjectNumber;
    });

    var putPages = (API.__private__.putPages = function() {
      var n,
        i,
        pageObjectNumbers = [];

      for (n = 1; n <= page; n++) {
        pagesContext[n].objId = newObjectDeferred();
        pagesContext[n].contentsObjId = newObjectDeferred();
      }

      for (n = 1; n <= page; n++) {
        pageObjectNumbers.push(
          putPage({
            number: n,
            data: pages[n],
            objId: pagesContext[n].objId,
            contentsObjId: pagesContext[n].contentsObjId,
            mediaBox: pagesContext[n].mediaBox,
            cropBox: pagesContext[n].cropBox,
            bleedBox: pagesContext[n].bleedBox,
            trimBox: pagesContext[n].trimBox,
            artBox: pagesContext[n].artBox,
            userUnit: pagesContext[n].userUnit,
            rootDictionaryObjId: rootDictionaryObjId,
            resourceDictionaryObjId: resourceDictionaryObjId
          })
        );
      }
      newObjectDeferredBegin(rootDictionaryObjId, true);
      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");
    });

    var putFont = function(font) {
      var pdfEscapeWithNeededParanthesis = function(text, flags) {
        var addParanthesis = text.indexOf(" ") !== -1; // no space in string
        return addParanthesis
          ? "(" + pdfEscape(text, flags) + ")"
          : pdfEscape(text, flags);
      };

      events.publish("putFont", {
        font: font,
        out: out,
        newObject: newObject,
        putStream: putStream,
        pdfEscapeWithNeededParanthesis: pdfEscapeWithNeededParanthesis
      });

      if (font.isAlreadyPutted !== true) {
        font.objectNumber = newObject();
        out("<<");
        out("/Type /Font");
        out("/BaseFont /" + pdfEscapeWithNeededParanthesis(font.postScriptName));
        out("/Subtype /Type1");
        if (typeof font.encoding === "string") {
          out("/Encoding /" + font.encoding);
        }
        out("/FirstChar 32");
        out("/LastChar 255");
        out(">>");
        out("endobj");
      }
    };

    var putFonts = function() {
      for (var fontKey in fonts) {
        if (fonts.hasOwnProperty(fontKey)) {
          if (
            putOnlyUsedFonts === false ||
            (putOnlyUsedFonts === true && usedFonts.hasOwnProperty(fontKey))
          ) {
            putFont(fonts[fontKey]);
          }
        }
      }
    };

    var putXObject = function(xObject) {
      xObject.objectNumber = newObject();

      var options = [];
      options.push({ key: "Type", value: "/XObject" });
      options.push({ key: "Subtype", value: "/Form" });
      options.push({
        key: "BBox",
        value:
          "[" +
          [
            hpf(xObject.x),
            hpf(xObject.y),
            hpf(xObject.x + xObject.width),
            hpf(xObject.y + xObject.height)
          ].join(" ") +
          "]"
      });
      options.push({
        key: "Matrix",
        value: "[" + xObject.matrix.toString() + "]"
      });
      // TODO: /Resources

      var stream = xObject.pages[1].join("\n");
      putStream({
        data: stream,
        additionalKeyValues: options,
        objectId: xObject.objectNumber
      });
      out("endobj");
    };

    var putXObjects = function() {
      for (var xObjectKey in renderTargets) {
        if (renderTargets.hasOwnProperty(xObjectKey)) {
          putXObject(renderTargets[xObjectKey]);
        }
      }
    };

    var interpolateAndEncodeRGBStream = function(colors, numberSamples) {
      var tValues = [];
      var t;
      var dT = 1.0 / (numberSamples - 1);
      for (t = 0.0; t < 1.0; t += dT) {
        tValues.push(t);
      }
      tValues.push(1.0);
      // add first and last control point if not present
      if (colors[0].offset != 0.0) {
        var c0 = {
          offset: 0.0,
          color: colors[0].color
        };
        colors.unshift(c0);
      }
      if (colors[colors.length - 1].offset != 1.0) {
        var c1 = {
          offset: 1.0,
          color: colors[colors.length - 1].color
        };
        colors.push(c1);
      }
      var out = "";
      var index = 0;

      for (var i = 0; i < tValues.length; i++) {
        t = tValues[i];
        while (t > colors[index + 1].offset) index++;
        var a = colors[index].offset;
        var b = colors[index + 1].offset;
        var d = (t - a) / (b - a);

        var aColor = colors[index].color;
        var bColor = colors[index + 1].color;

        out +=
          padd2Hex(Math.round((1 - d) * aColor[0] + d * bColor[0]).toString(16)) +
          padd2Hex(Math.round((1 - d) * aColor[1] + d * bColor[1]).toString(16)) +
          padd2Hex(Math.round((1 - d) * aColor[2] + d * bColor[2]).toString(16));
      }
      return out.trim();
    };

    var putShadingPattern = function(pattern, numberSamples) {
      /*
         Axial patterns shade between the two points specified in coords, radial patterns between the inner
         and outer circle.
         The user can specify an array (colors) that maps t-Values in [0, 1] to RGB colors. These are now
         interpolated to equidistant samples and written to pdf as a sample (type 0) function.
         */
      // The number of color samples that should be used to describe the shading.
      // The higher, the more accurate the gradient will be.
      numberSamples || (numberSamples = 21);
      var funcObjectNumber = newObject();
      var stream = interpolateAndEncodeRGBStream(pattern.colors, numberSamples);

      var options = [];
      options.push({ key: "FunctionType", value: "0" });
      options.push({ key: "Domain", value: "[0.0 1.0]" });
      options.push({ key: "Size", value: "[" + numberSamples + "]" });
      options.push({ key: "BitsPerSample", value: "8" });
      options.push({ key: "Range", value: "[0.0 1.0 0.0 1.0 0.0 1.0]" });
      options.push({ key: "Decode", value: "[0.0 1.0 0.0 1.0 0.0 1.0]" });

      putStream({
        data: stream,
        additionalKeyValues: options,
        alreadyAppliedFilters: ["/ASCIIHexDecode"],
        objectId: funcObjectNumber
      });
      out("endobj");

      pattern.objectNumber = newObject();
      out("<< /ShadingType " + pattern.type);
      out("/ColorSpace /DeviceRGB");
      var coords =
        "/Coords [" +
        hpf(parseFloat(pattern.coords[0])) +
        " " + // x1
        hpf(parseFloat(pattern.coords[1])) +
        " "; // y1
      if (pattern.type === 2) {
        // axial
        coords +=
          hpf(parseFloat(pattern.coords[2])) +
          " " + // x2
          hpf(parseFloat(pattern.coords[3])); // y2
      } else {
        // radial
        coords +=
          hpf(parseFloat(pattern.coords[2])) +
          " " + // r1
          hpf(parseFloat(pattern.coords[3])) +
          " " + // x2
          hpf(parseFloat(pattern.coords[4])) +
          " " + // y2
          hpf(parseFloat(pattern.coords[5])); // r2
      }
      coords += "]";
      out(coords);

      if (pattern.matrix) {
        out("/Matrix [" + pattern.matrix.toString() + "]");
      }
      out("/Function " + funcObjectNumber + " 0 R");
      out("/Extend [true true]");
      out(">>");
      out("endobj");
    };

    var putTilingPattern = function(pattern, deferredResourceDictionaryIds) {
      var resourcesObjectId = newObjectDeferred();
      var patternObjectId = newObject();

      deferredResourceDictionaryIds.push({
        resourcesOid: resourcesObjectId,
        objectOid: patternObjectId
      });

      pattern.objectNumber = patternObjectId;
      var options = [];
      options.push({ key: "Type", value: "/Pattern" });
      options.push({ key: "PatternType", value: "1" }); // tiling pattern
      options.push({ key: "PaintType", value: "1" }); // colored tiling pattern
      options.push({ key: "TilingType", value: "1" }); // constant spacing
      options.push({
        key: "BBox",
        value: "[" + pattern.boundingBox.map(hpf).join(" ") + "]"
      });
      options.push({ key: "XStep", value: hpf(pattern.xStep) });
      options.push({ key: "YStep", value: hpf(pattern.yStep) });
      options.push({ key: "Resources", value: resourcesObjectId + " 0 R" });
      if (pattern.matrix) {
        options.push({
          key: "Matrix",
          value: "[" + pattern.matrix.toString() + "]"
        });
      }

      putStream({
        data: pattern.stream,
        additionalKeyValues: options,
        objectId: pattern.objectNumber
      });
      out("endobj");
    };

    var putPatterns = function(deferredResourceDictionaryIds) {
      var patternKey;
      for (patternKey in patterns) {
        if (patterns.hasOwnProperty(patternKey)) {
          if (patterns[patternKey] instanceof ShadingPattern) {
            putShadingPattern(patterns[patternKey]);
          } else if (patterns[patternKey] instanceof TilingPattern) {
            putTilingPattern(patterns[patternKey], deferredResourceDictionaryIds);
          }
        }
      }
    };

    var putGState = function(gState) {
      gState.objectNumber = newObject();
      out("<<");
      for (var p in gState) {
        switch (p) {
          case "opacity":
            out("/ca " + f2(gState[p]));
            break;
          case "stroke-opacity":
            out("/CA " + f2(gState[p]));
            break;
        }
      }
      out(">>");
      out("endobj");
    };

    var putGStates = function() {
      var gStateKey;
      for (gStateKey in gStates) {
        if (gStates.hasOwnProperty(gStateKey)) {
          putGState(gStates[gStateKey]);
        }
      }
    };

    var putXobjectDict = function() {
      out("/XObject <<");
      for (var xObjectKey in renderTargets) {
        if (
          renderTargets.hasOwnProperty(xObjectKey) &&
          renderTargets[xObjectKey].objectNumber >= 0
        ) {
          out(
            "/" +
              xObjectKey +
              " " +
              renderTargets[xObjectKey].objectNumber +
              " 0 R"
          );
        }
      }

      // Loop through images, or other data objects
      events.publish("putXobjectDict");
      out(">>");
    };

    var putEncryptionDict = function() {
      encryption.oid = newObject();
      out("<<");
      out("/Filter /Standard");
      out("/V " + encryption.v);
      out("/R " + encryption.r);
      out("/U <" + encryption.toHexString(encryption.U) + ">");
      out("/O <" + encryption.toHexString(encryption.O) + ">");
      out("/P " + encryption.P);
      out(">>");
      out("endobj");
    };

    var putFontDict = function() {
      out("/Font <<");

      for (var fontKey in fonts) {
        if (fonts.hasOwnProperty(fontKey)) {
          if (
            putOnlyUsedFonts === false ||
            (putOnlyUsedFonts === true && usedFonts.hasOwnProperty(fontKey))
          ) {
            out("/" + fontKey + " " + fonts[fontKey].objectNumber + " 0 R");
          }
        }
      }
      out(">>");
    };

    var putShadingPatternDict = function() {
      if (Object.keys(patterns).length > 0) {
        out("/Shading <<");
        for (var patternKey in patterns) {
          if (
            patterns.hasOwnProperty(patternKey) &&
            patterns[patternKey] instanceof ShadingPattern &&
            patterns[patternKey].objectNumber >= 0
          ) {
            out(
              "/" + patternKey + " " + patterns[patternKey].objectNumber + " 0 R"
            );
          }
        }

        events.publish("putShadingPatternDict");
        out(">>");
      }
    };

    var putTilingPatternDict = function(objectOid) {
      if (Object.keys(patterns).length > 0) {
        out("/Pattern <<");
        for (var patternKey in patterns) {
          if (
            patterns.hasOwnProperty(patternKey) &&
            patterns[patternKey] instanceof API.TilingPattern &&
            patterns[patternKey].objectNumber >= 0 &&
            patterns[patternKey].objectNumber < objectOid // prevent cyclic dependencies
          ) {
            out(
              "/" + patternKey + " " + patterns[patternKey].objectNumber + " 0 R"
            );
          }
        }
        events.publish("putTilingPatternDict");
        out(">>");
      }
    };

    var putGStatesDict = function() {
      if (Object.keys(gStates).length > 0) {
        var gStateKey;
        out("/ExtGState <<");
        for (gStateKey in gStates) {
          if (
            gStates.hasOwnProperty(gStateKey) &&
            gStates[gStateKey].objectNumber >= 0
          ) {
            out("/" + gStateKey + " " + gStates[gStateKey].objectNumber + " 0 R");
          }
        }

        events.publish("putGStateDict");
        out(">>");
      }
    };

    var putResourceDictionary = function(objectIds) {
      newObjectDeferredBegin(objectIds.resourcesOid, true);
      out("<<");
      out("/ProcSet [/PDF /Text /ImageB /ImageC /ImageI]");
      putFontDict();
      putShadingPatternDict();
      putTilingPatternDict(objectIds.objectOid);
      putGStatesDict();
      putXobjectDict();
      out(">>");
      out("endobj");
    };

    var putResources = function() {
      // FormObjects, Patterns etc. might use other FormObjects/Patterns/Images
      // which means their resource dictionaries must contain the already resolved
      // object ids. For this reason we defer the serialization of the resource
      // dicts until all objects have been serialized and have object ids.
      //
      // In order to prevent cyclic dependencies (which Adobe Reader doesn't like),
      // we only put all oids that are smaller than the oid of the object the
      // resource dict belongs to. This is correct behavior, since the streams
      // may only use other objects that have already been defined and thus appear
      // earlier in their respective collection.
      // Currently, this only affects tiling patterns, but a (more) correct
      // implementation of FormObjects would also define their own resource dicts.
      var deferredResourceDictionaryIds = [];

      putFonts();
      putGStates();
      putXObjects();
      putPatterns(deferredResourceDictionaryIds);

      events.publish("putResources");
      deferredResourceDictionaryIds.forEach(putResourceDictionary);
      putResourceDictionary({
        resourcesOid: resourceDictionaryObjId,
        objectOid: Number.MAX_SAFE_INTEGER // output all objects
      });
      events.publish("postPutResources");
    };

    var putAdditionalObjects = function() {
      events.publish("putAdditionalObjects");
      for (var i = 0; i < additionalObjects.length; i++) {
        var obj = additionalObjects[i];
        newObjectDeferredBegin(obj.objId, true);
        out(obj.content);
        out("endobj");
      }
      events.publish("postPutAdditionalObjects");
    };

    var addFontToFontDictionary = function(font) {
      fontmap[font.fontName] = fontmap[font.fontName] || {};
      fontmap[font.fontName][font.fontStyle] = font.id;
    };

    var addFont = function(
      postScriptName,
      fontName,
      fontStyle,
      encoding,
      isStandardFont
    ) {
      var font = {
        id: "F" + (Object.keys(fonts).length + 1).toString(10),
        postScriptName: postScriptName,
        fontName: fontName,
        fontStyle: fontStyle,
        encoding: encoding,
        isStandardFont: isStandardFont || false,
        metadata: {}
      };

      events.publish("addFont", {
        font: font,
        instance: this
      });

      fonts[font.id] = font;
      addFontToFontDictionary(font);
      return font.id;
    };

    var addFonts = function(arrayOfFonts) {
      for (var i = 0, l = standardFonts.length; i < l; i++) {
        var fontKey = addFont.call(
          this,
          arrayOfFonts[i][0],
          arrayOfFonts[i][1],
          arrayOfFonts[i][2],
          standardFonts[i][3],
          true
        );

        if (putOnlyUsedFonts === false) {
          usedFonts[fontKey] = true;
        }
        // adding aliases for standard fonts, this time matching the capitalization
        var parts = arrayOfFonts[i][0].split("-");
        addFontToFontDictionary({
          id: fontKey,
          fontName: parts[0],
          fontStyle: parts[1] || ""
        });
      }
      events.publish("addFonts", {
        fonts: fonts,
        dictionary: fontmap
      });
    };

    var 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 (globalObject.console) {
            globalObject.console.error(m, e);
            if (globalObject.alert) alert(m);
          } else {
            throw new Error(m);
          }
        }
      };
      fn.foo.bar = fn;
      return fn.foo;
    };

    var to8bitStream = function(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);
    };

    var pdfEscape = (API.__private__.pdfEscape = API.pdfEscape = function(
      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, "\\)");
    });

    var beginPage = (API.__private__.beginPage = function(format) {
      pages[++page] = [];
      pagesContext[page] = {
        objId: 0,
        contentsObjId: 0,
        userUnit: Number(userUnit),
        artBox: null,
        bleedBox: null,
        cropBox: null,
        trimBox: null,
        mediaBox: {
          bottomLeftX: 0,
          bottomLeftY: 0,
          topRightX: Number(format[0]),
          topRightY: Number(format[1])
        }
      };
      _setPage(page);
      setOutputDestination(pages[currentPage]);
    });

    var _addPage = function(parmFormat, parmOrientation) {
      var dimensions, width, height;

      orientation = parmOrientation || orientation;

      if (typeof parmFormat === "string") {
        dimensions = getPageFormat(parmFormat.toLowerCase());
        if (Array.isArray(dimensions)) {
          width = dimensions[0];
          height = dimensions[1];
        }
      }

      if (Array.isArray(parmFormat)) {
        width = parmFormat[0] * scaleFactor;
        height = parmFormat[1] * scaleFactor;
      }

      if (isNaN(width)) {
        width = format[0];
        height = format[1];
      }

      if (width > 14400 || height > 14400) {
        console.warn(
          "A page in a PDF can not be wider or taller than 14400 userUnit. jsPDF limits the width/height to 14400"
        );
        width = Math.min(14400, width);
        height = Math.min(14400, height);
      }

      format = [width, height];

      switch (orientation.substr(0, 1)) {
        case "l":
          if (height > width) {
            format = [height, width];
          }
          break;
        case "p":
          if (width > height) {
            format = [height, width];
          }
          break;
      }

      beginPage(format);

      // Set line width
      setLineWidth(lineWidth);
      // Set draw color
      out(strokeColor);
      // resurrecting non-default line caps, joins
      if (lineCapID !== 0) {
        out(lineCapID + " J");
      }
      if (lineJoinID !== 0) {
        out(lineJoinID + " j");
      }
      events.publish("addPage", {
        pageNumber: page
      });
    };

    var _deletePage = function(n) {
      if (n > 0 && n <= page) {
        pages.splice(n, 1);
        pagesContext.splice(n, 1);
        page--;
        if (currentPage > page) {
          currentPage = page;
        }
        this.setPage(currentPage);
      }
    };

    var _setPage = function(n) {
      if (n > 0 && n <= page) {
        currentPage = n;
      }
    };

    var getNumberOfPages = (API.__private__.getNumberOfPages = API.getNumberOfPages = function() {
      return pages.length - 1;
    });

    /**
     * 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.
     * @ignore
     */
    var getFont = function(fontName, fontStyle, options) {
      var key = undefined,
        fontNameLowerCase;
      options = options || {};

      fontName =
        fontName !== undefined ? fontName : fonts[activeFontKey].fontName;
      fontStyle =
        fontStyle !== undefined ? fontStyle : fonts[activeFontKey].fontStyle;
      fontNameLowerCase = fontName.toLowerCase();

      if (
        fontmap[fontNameLowerCase] !== undefined &&
        fontmap[fontNameLowerCase][fontStyle] !== undefined
      ) {
        key = fontmap[fontNameLowerCase][fontStyle];
      } else if (
        fontmap[fontName] !== undefined &&
        fontmap[fontName][fontStyle] !== undefined
      ) {
        key = fontmap[fontName][fontStyle];
      } else {
        if (options.disableWarning === false) {
          console.warn(
            "Unable to look up font label for font '" +
              fontName +
              "', '" +
              fontStyle +
              "'. Refer to getFontList() for available fonts."
          );
        }
      }

      if (!key && !options.noFallback) {
        key = fontmap["times"][fontStyle];
        if (key == null) {
          key = fontmap["times"]["normal"];
        }
      }
      return key;
    };

    var putInfo = (API.__private__.putInfo = function() {
      var objectId = newObject();
      var encryptor = function(data) {
        return data;
      };
      if (encryptionOptions !== null) {
        encryptor = encryption.encryptor(objectId, 0);
      }
      out("<<");
      out("/Producer (" + pdfEscape(encryptor("jsPDF " + jsPDF.version)) + ")");
      for (var key in documentProperties) {
        if (documentProperties.hasOwnProperty(key) && documentProperties[key]) {
          out(
            "/" +
              key.substr(0, 1).toUpperCase() +
              key.substr(1) +
              " (" +
              pdfEscape(encryptor(documentProperties[key])) +
              ")"
          );
        }
      }
      out("/CreationDate (" + pdfEscape(encryptor(creationDate)) + ")");
      out(">>");
      out("endobj");
    });

    var putCatalog = (API.__private__.putCatalog = function(options) {
      options = options || {};
      var tmpRootDictionaryObjId =
        options.rootDictionaryObjId || rootDictionaryObjId;
      newObject();
      out("<<");
      out("/Type /Catalog");
      out("/Pages " + tmpRootDictionaryObjId + " 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");
      out(">>");
      out("endobj");
    });

    var putTrailer = (API.__private__.putTrailer = function() {
      out("trailer");
      out("<<");
      out("/Size " + (objectNumber + 1));
      // Root and Info must be the last and second last objects written respectively
      out("/Root " + objectNumber + " 0 R");
      out("/Info " + (objectNumber - 1) + " 0 R");
      if (encryptionOptions !== null) {
        out("/Encrypt " + encryption.oid + " 0 R");
      }
      out("/ID [ <" + fileId + "> <" + fileId + "> ]");
      out(">>");
    });

    var putHeader = (API.__private__.putHeader = function() {
      out("%PDF-" + pdfVersion);
      out("%\xBA\xDF\xAC\xE0");
    });

    var putXRef = (API.__private__.putXRef = function() {
      var p = "0000000000";

      out("xref");
      out("0 " + (objectNumber + 1));
      out("0000000000 65535 f ");
      for (var i = 1; i <= objectNumber; i++) {
        var offset = offsets[i];
        if (typeof offset === "function") {
          out((p + offsets[i]()).slice(-10) + " 00000 n ");
        } else {
          if (typeof offsets[i] !== "undefined") {
            out((p + offsets[i]).slice(-10) + " 00000 n ");
          } else {
            out("0000000000 00000 n ");
          }
        }
      }
    });

    var buildDocument = (API.__private__.buildDocument = function() {
      resetDocument();
      setOutputDestination(content);

      events.publish("buildDocument");

      putHeader();
      putPages();
      putAdditionalObjects();
      putResources();
      if (encryptionOptions !== null) putEncryptionDict();
      putInfo();
      putCatalog();

      var offsetOfXRef = contentLength;
      putXRef();
      putTrailer();
      out("startxref");
      out("" + offsetOfXRef);
      out("%%EOF");

      setOutputDestination(pages[currentPage]);

      return content.join("\n");
    });

    var getBlob = (API.__private__.getBlob = function(data) {
      return new Blob([getArrayBuffer(data)], {
        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. Possible values are 'arraybuffer', 'blob', 'bloburi'/'bloburl', 'datauristring'/'dataurlstring', 'datauri'/'dataurl', 'dataurlnewwindow', 'pdfobjectnewwindow', 'pdfjsnewwindow'.
     * @param {Object} options An object providing some additional signalling to PDF generator. Possible options are 'filename'.
     *
     * @function
     * @instance
     * @returns {jsPDF}
     * @memberof jsPDF#
     * @name output
     */
    var output = (API.output = API.__private__.output = SAFE(function output(
      type,
      options
    ) {
      options = options || {};

      if (typeof options === "string") {
        options = {
          filename: options
        };
      } else {
        options.filename = options.filename || "generated.pdf";
      }

      switch (type) {
        case undefined:
          return buildDocument();
        case "save":
          API.save(options.filename);
          break;
        case "arraybuffer":
          return getArrayBuffer(buildDocument());
        case "blob":
          return getBlob(buildDocument());
        case "bloburi":
        case "bloburl":
          // Developer is responsible of calling revokeObjectURL
          if (
            typeof globalObject.URL !== "undefined" &&
            typeof globalObject.URL.createObjectURL === "function"
          ) {
            return (
              (globalObject.URL &&
                globalObject.URL.createObjectURL(getBlob(buildDocument()))) ||
              void 0
            );
          } else {
            console.warn(
              "bloburl is not supported by your system, because URL.createObjectURL is not supported by your browser."
            );
          }
          break;
        case "datauristring":
        case "dataurlstring":
          var dataURI = "";
          var pdfDocument = buildDocument();
          try {
            dataURI = btoa(pdfDocument);
          } catch (e) {
            dataURI = btoa(unescape(encodeURIComponent(pdfDocument)));
          }
          return (
            "data:application/pdf;filename=" +
            options.filename +
            ";base64," +
            dataURI
          );
        case "pdfobjectnewwindow":
          if (
            Object.prototype.toString.call(globalObject) === "[object Window]"
          ) {
            var pdfObjectUrl =
              options.pdfObjectUrl ||
              "https://cdnjs.cloudflare.com/ajax/libs/pdfobject/2.1.1/pdfobject.min.js";
            var htmlForNewWindow =
              "<html>" +
              '<style>html, body { padding: 0; margin: 0; } iframe { width: 100%; height: 100%; border: 0;}  </style><body><script src="' +
              pdfObjectUrl +
              '"></script><script >PDFObject.embed("' +
              this.output("dataurlstring") +
              '", ' +
              JSON.stringify(options) +
              ");</script></body></html>";
            var nW = globalObject.open();

            if (nW !== null) {
              nW.document.write(htmlForNewWindow);
            }
            return nW;
          } else {
            throw new Error(
              "The option pdfobjectnewwindow just works in a browser-environment."
            );
          }
        case "pdfjsnewwindow":
          if (
            Object.prototype.toString.call(globalObject) === "[object Window]"
          ) {
            var pdfJsUrl = options.pdfJsUrl || "examples/PDF.js/web/viewer.html";
            var htmlForPDFjsNewWindow =
              "<html>" +
              "<style>html, body { padding: 0; margin: 0; } iframe { width: 100%; height: 100%; border: 0;}  </style>" +
              '<body><iframe id="pdfViewer" src="' +
              pdfJsUrl +
              "?file=&downloadName=" +
              options.filename +
              '" width="500px" height="400px" />' +
              "</body></html>";
            var PDFjsNewWindow = globalObject.open();

            if (PDFjsNewWindow !== null) {
              PDFjsNewWindow.document.write(htmlForPDFjsNewWindow);
              var scope = this;
              PDFjsNewWindow.document.documentElement.querySelector(
                "#pdfViewer"
              ).onload = function() {
                PDFjsNewWindow.document.title = options.filename;
                PDFjsNewWindow.document.documentElement
                  .querySelector("#pdfViewer")
                  .contentWindow.PDFViewerApplication.open(
                    scope.output("bloburl")
                  );
              };
            }
            return PDFjsNewWindow;
          } else {
            throw new Error(
              "The option pdfjsnewwindow just works in a browser-environment."
            );
          }
        case "dataurlnewwindow":
          if (
            Object.prototype.toString.call(globalObject) === "[object Window]"
          ) {
            var htmlForDataURLNewWindow =
              "<html>" +
              "<style>html, body { padding: 0; margin: 0; } iframe { width: 100%; height: 100%; border: 0;}  </style>" +
              "<body>" +
              '<iframe src="' +
              this.output("datauristring", options) +
              '"></iframe>' +
              "</body></html>";
            var dataURLNewWindow = globalObject.open();
            if (dataURLNewWindow !== null) {
              dataURLNewWindow.document.write(htmlForDataURLNewWindow);
              dataURLNewWindow.document.title = options.filename;
            }
            if (dataURLNewWindow || typeof safari === "undefined")
              return dataURLNewWindow;
          } else {
            throw new Error(
              "The option dataurlnewwindow just works in a browser-environment."
            );
          }
          break;
        case "datauri":
        case "dataurl":
          return (globalObject.document.location.href = this.output(
            "datauristring",
            options
          ));
        default:
          return null;
      }
    }));

    /**
     * Used to see if a supplied hotfix was requested when the pdf instance was created.
     * @param {string} hotfixName - The name of the hotfix to check.
     * @returns {boolean}
     */
    var hasHotfix = function(hotfixName) {
      return (
        Array.isArray(hotfixes) === true && hotfixes.indexOf(hotfixName) > -1
      );
    };

    switch (unit) {
      case "pt":
        scaleFactor = 1;
        break;
      case "mm":
        scaleFactor = 72 / 25.4;
        break;
      case "cm":
        scaleFactor = 72 / 2.54;
        break;
      case "in":
        scaleFactor = 72;
        break;
      case "px":
        if (hasHotfix("px_scaling") == true) {
          scaleFactor = 72 / 96;
        } else {
          scaleFactor = 96 / 72;
        }
        break;
      case "pc":
        scaleFactor = 12;
        break;
      case "em":
        scaleFactor = 12;
        break;
      case "ex":
        scaleFactor = 6;
        break;
      default:
        throw new Error("Invalid unit: " + unit);
    }

    var encryption = null;
    setCreationDate();
    setFileId();

    var getEncryptor = function(objectId) {
      if (encryptionOptions !== null) {
        return encryption.encryptor(objectId, 0);
      }
      return function(data) {
        return data;
      };
    };

    //---------------------------------------
    // Public API

    var getPageInfo = (API.__private__.getPageInfo = API.getPageInfo = function(
      pageNumberOneBased
    ) {
      if (isNaN(pageNumberOneBased) || pageNumberOneBased % 1 !== 0) {
        throw new Error("Invalid argument passed to jsPDF.getPageInfo");
      }
      var objId = pagesContext[pageNumberOneBased].objId;
      return {
        objId: objId,
        pageNumber: pageNumberOneBased,
        pageContext: pagesContext[pageNumberOneBased]
      };
    });

    var getPageInfoByObjId = (API.__private__.getPageInfoByObjId = function(
      objId
    ) {
      if (isNaN(objId) || objId % 1 !== 0) {
        throw new Error("Invalid argument passed to jsPDF.getPageInfoByObjId");
      }
      for (var pageNumber in pagesContext) {
        if (pagesContext[pageNumber].objId === objId) {
          break;
        }
      }
      return getPageInfo(pageNumber);
    });

    var getCurrentPageInfo = (API.__private__.getCurrentPageInfo = API.getCurrentPageInfo = function() {
      return {
        objId: pagesContext[currentPage].objId,
        pageNumber: currentPage,
        pageContext: pagesContext[currentPage]
      };
    });

    /**
     * Adds (and transfers the focus to) new page to the PDF document.
     * @param format {String/Array} The format of the new page. Can be: <ul><li>a0 - a10</li><li>b0 - b10</li><li>c0 - c10</li><li>dl</li><li>letter</li><li>government-letter</li><li>legal</li><li>junior-legal</li><li>ledger</li><li>tabloid</li><li>credit-card</li></ul><br />
     * Default is "a4". If you want to use your own format just pass instead of one of the above predefined formats the size as an number-array, e.g. [595.28, 841.89]
     * @param orientation {string} Orientation of the new page. Possible values are "portrait" or "landscape" (or shortcuts "p" (Default), "l").
     * @function
     * @instance
     * @returns {jsPDF}
     *
     * @memberof 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
     * @instance
     * @returns {jsPDF}
     *
     * @memberof jsPDF#
     * @name setPage
     * @param {number} page Switch the active page to the page number specified (indexed starting at 1).
     * @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);
      setOutputDestination.call(this, pages[currentPage]);
      return this;
    };

    /**
     * @name insertPage
     * @memberof jsPDF#
     *
     * @function
     * @instance
     * @param {Object} beforePage
     * @returns {jsPDF}
     */
    API.insertPage = function(beforePage) {
      this.addPage();
      this.movePage(currentPage, beforePage);
      return this;
    };

    /**
     * @name movePage
     * @memberof jsPDF#
     * @function
     * @instance
     * @param {number} targetPage
     * @param {number} beforePage
     * @returns {jsPDF}
     */
    API.movePage = function(targetPage, beforePage) {
      var tmpPages, tmpPagesContext;
      if (targetPage > beforePage) {
        tmpPages = pages[targetPage];
        tmpPagesContext = pagesContext[targetPage];
        for (var i = targetPage; i > beforePage; i--) {
          pages[i] = pages[i - 1];
          pagesContext[i] = pagesContext[i - 1];
        }
        pages[beforePage] = tmpPages;
        pagesContext[beforePage] = tmpPagesContext;
        this.setPage(beforePage);
      } else if (targetPage < beforePage) {
        tmpPages = pages[targetPage];
        tmpPagesContext = pagesContext[targetPage];
        for (var j = targetPage; j < beforePage; j++) {
          pages[j] = pages[j + 1];
          pagesContext[j] = pagesContext[j + 1];
        }
        pages[beforePage] = tmpPages;
        pagesContext[beforePage] = tmpPagesContext;
        this.setPage(beforePage);
      }
      return this;
    };

    /**
     * Deletes a page from the PDF.
     * @name deletePage
     * @memberof jsPDF#
     * @function
     * @param {number} targetPage
     * @instance
     * @returns {jsPDF}
     */
    API.deletePage = function() {
      _deletePage.apply(this, arguments);
      return this;
    };

    /**
     * Adds text to page. Supports adding multiline text when 'text' argument is an Array of Strings.
     *
     * @function
     * @instance
     * @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} [options] - Collection of settings signaling how the text must be encoded.
     * @param {string} [options.align=left] - The alignment of the text, possible values: left, center, right, justify.
     * @param {string} [options.baseline=alphabetic] - Sets text baseline used when drawing the text, possible values: alphabetic, ideographic, bottom, top, middle, hanging
     * @param {number|Matrix} [options.angle=0] - Rotate the text clockwise or counterclockwise. Expects the angle in degree.
     * @param {number} [options.rotationDirection=1] - Direction of the rotation. 0 = clockwise, 1 = counterclockwise.
     * @param {number} [options.charSpace=0] - The space between each letter.
     * @param {number} [options.lineHeightFactor=1.15] - The lineheight of each line.
     * @param {Object} [options.flags] - Flags for to8bitStream.
     * @param {boolean} [options.flags.noBOM=true] - Don't add BOM to Unicode-text.
     * @param {boolean} [options.flags.autoencode=true] - Autoencode the Text.
     * @param {number} [options.maxWidth=0] - Split the text by given width, 0 = no split.
     * @param {string} [options.renderingMode=fill] - Set how the text should be rendered, possible values: fill, stroke, fillThenStroke, invisible, fillAndAddForClipping, strokeAndAddPathForClipping, fillThenStrokeAndAddToPathForClipping, addToPathForClipping.
     * @param {boolean} [options.isInputVisual] - Option for the BidiEngine
     * @param {boolean} [options.isOutputVisual] - Option for the BidiEngine
     * @param {boolean} [options.isInputRtl] - Option for the BidiEngine
     * @param {boolean} [options.isOutputRtl] - Option for the BidiEngine
     * @param {boolean} [options.isSymmetricSwapping] - Option for the BidiEngine
     * @param {number|Matrix} transform If transform is a number the text will be rotated by this value around the anchor set by x and y.
     *
     * If it is a Matrix, this matrix gets directly applied to the text, which allows shearing
     * effects etc.; the x and y offsets are then applied AFTER the coordinate system has been established by this
     * matrix. This means passing a rotation matrix that is equivalent to some rotation angle will in general yield a
     * DIFFERENT result. A matrix is only allowed in "advanced" API mode.
     * @returns {jsPDF}
     * @memberof jsPDF#
     * @name text
     */
    API.__private__.text = API.text = function(text, x, y, options, transform) {
      /*
       * 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
       */
      options = options || {};
      var scope = options.scope || this;
      var payload, da, angle, align, charSpace, maxWidth, 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" &&
        typeof x === "number" &&
        (typeof y === "string" || Array.isArray(y))
      ) {
        var tmp = y;
        y = x;
        x = text;
        text = tmp;
      }

      var transformationMatrix;

      if (arguments[3] instanceof Matrix === false) {
        flags = arguments[3];
        angle = arguments[4];
        align = arguments[5];

        if (typeof flags !== "object" || flags === null) {
          if (typeof angle === "string") {
            align = angle;
            angle = null;
          }
          if (typeof flags === "string") {
            align = flags;
            flags = null;
          }
          if (typeof flags === "number") {
            angle = flags;
            flags = null;
          }
          options = {
            flags: flags,
            angle: angle,
            align: align
          };
        }
      } else {
        advancedApiModeTrap(
          "The transform parameter of text() with a Matrix value"
        );
        transformationMatrix = transform;
      }

      if (isNaN(x) || isNaN(y) || typeof text === "undefined" || text === null) {
        throw new Error("Invalid arguments passed to jsPDF.text");
      }

      if (text.length === 0) {
        return scope;
      }

      var xtra = "";
      var isHex = false;
      var lineHeight =
        typeof options.lineHeightFactor === "number"
          ? options.lineHeightFactor
          : lineHeightFactor;
      var scaleFactor = scope.internal.scaleFactor;

      function ESC(s) {
        s = s.split("\t").join(Array(options.TabLen || 9).join(" "));
        return pdfEscape(s, flags);
      }

      function transformTextToSpecialArray(text) {
        //we don't want to destroy original text array, so cloning it
        var sa = text.concat();
        var da = [];
        var len = sa.length;
        var curDa;
        //we do array.join('text that must not be PDFescaped")
        //thus, pdfEscape each component separately
        while (len--) {
          curDa = sa.shift();
          if (typeof curDa === "string") {
            da.push(curDa);
          } else {
            if (
              Array.isArray(text) &&
              (curDa.length === 1 ||
                (curDa[1] === undefined && curDa[2] === undefined))
            ) {
              da.push(curDa[0]);
            } else {
              da.push([curDa[0], curDa[1], curDa[2]]);
            }
          }
        }
        return da;
      }

      function processTextByFunction(text, processingFunction) {
        var result;
        if (typeof text === "string") {
          result = processingFunction(text)[0];
        } else if (Array.isArray(text)) {
          //we don't want to destroy original text array, so cloning it
          var sa = text.concat();
          var da = [];
          var len = sa.length;
          var curDa;
          var tmpResult;
          //we do array.join('text that must not be PDFescaped")
          //thus, pdfEscape each component separately
          while (len--) {
            curDa = sa.shift();
            if (typeof curDa === "string") {
              da.push(processingFunction(curDa)[0]);
            } else if (Array.isArray(curDa) && typeof curDa[0] === "string") {
              tmpResult = processingFunction(curDa[0], curDa[1], curDa[2]);
              da.push([tmpResult[0], tmpResult[1], tmpResult[2]]);
            }
          }
          result = da;
        }
        return result;
      }

      //Check if text is of type String
      var textIsOfTypeString = false;
      var tmpTextIsOfTypeString = true;

      if (typeof text === "string") {
        textIsOfTypeString = true;
      } else if (Array.isArray(text)) {
        //we don't want to destroy original text array, so cloning it
        var sa = text.concat();
        da = [];
        var len = sa.length;
        var curDa;
        //we do array.join('text that must not be PDFescaped")
        //thus, pdfEscape each component separately
        while (len--) {
          curDa = sa.shift();
          if (
            typeof curDa !== "string" ||
            (Array.isArray(curDa) && typeof curDa[0] !== "string")
          ) {
            tmpTextIsOfTypeString = false;
          }
        }
        textIsOfTypeString = tmpTextIsOfTypeString;
      }
      if (textIsOfTypeString === false) {
        throw new Error(
          'Type of text must be string or Array. "' +
            text +
            '" is not recognized.'
        );
      }

      //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(/[\r?\n]/)) {
          text = text.split(/\r\n|\r|\n/g);
        } else {
          text = [text];
        }
      }

      //baseline
      var height = activeFontSize / scope.internal.scaleFactor;
      var descent = height * (lineHeightFactor - 1);
      switch (options.baseline) {
        case "bottom":
          y -= descent;
          break;
        case "top":
          y += height - descent;
          break;
        case "hanging":
          y += height - 2 * descent;
          break;
        case "middle":
          y += height / 2 - descent;
          break;
      }

      //multiline
      maxWidth = options.maxWidth || 0;

      if (maxWidth > 0) {
        if (typeof text === "string") {
          text = scope.splitTextToSize(text, maxWidth);
        } else if (Object.prototype.toString.call(text) === "[object Array]") {
          text = text.reduce(function(acc, textLine) {
            return acc.concat(scope.splitTextToSize(textLine, maxWidth));
          }, []);
        }
      }

      //creating Payload-Object to make text byRef
      payload = {
        text: text,
        x: x,
        y: y,
        options: options,
        mutex: {
          pdfEscape: pdfEscape,
          activeFontKey: activeFontKey,
          fonts: fonts,
          activeFontSize: activeFontSize
        }
      };
      events.publish("preProcessText", payload);

      text = payload.text;
      options = payload.options;

      //angle
      angle = options.angle;

      if (
        transformationMatrix instanceof Matrix === false &&
        angle &&
        typeof angle === "number"
      ) {
        angle *= Math.PI / 180;

        if (options.rotationDirection === 0) {
          angle = -angle;
        }

        if (apiMode === ApiMode.ADVANCED) {
          angle = -angle;
        }

        var c = Math.cos(angle);
        var s = Math.sin(angle);
        transformationMatrix = new Matrix(c, s, -s, c, 0, 0);
      } else if (angle && angle instanceof Matrix) {
        transformationMatrix = angle;
      }

      if (apiMode === ApiMode.ADVANCED && !transformationMatrix) {
        transformationMatrix = identityMatrix;
      }

      //charSpace

      charSpace = options.charSpace || activeCharSpace;

      if (typeof charSpace !== "undefined") {
        xtra += hpf(scale(charSpace)) + " Tc\n";
        this.setCharSpace(this.getCharSpace() || 0);
      }

      //lang

      var lang = options.lang;

      //renderingMode
      var renderingMode = -1;
      var parmRenderingMode =
        typeof options.renderingMode !== "undefined"
          ? options.renderingMode
          : options.stroke;
      var pageContext = scope.internal.getCurrentPageInfo().pageContext;

      switch (parmRenderingMode) {
        case 0:
        case false:
        case "fill":
          renderingMode = 0;
          break;
        case 1:
        case true:
        case "stroke":
          renderingMode = 1;
          break;
        case 2:
        case "fillThenStroke":
          renderingMode = 2;
          break;
        case 3:
        case "invisible":
          renderingMode = 3;
          break;
        case 4:
        case "fillAndAddForClipping":
          renderingMode = 4;
          break;
        case 5:
        case "strokeAndAddPathForClipping":
          renderingMode = 5;
          break;
        case 6:
        case "fillThenStrokeAndAddToPathForClipping":
          renderingMode = 6;
          break;
        case 7:
        case "addToPathForClipping":
          renderingMode = 7;
          break;
      }

      var usedRenderingMode =
        typeof pageContext.usedRenderingMode !== "undefined"
          ? pageContext.usedRenderingMode
          : -1;

      //if the coder wrote it explicitly to use a specific
      //renderingMode, then use it
      if (renderingMode !== -1) {
        xtra += renderingMode + " Tr\n";
        //otherwise check if we used the rendering Mode already
        //if so then set the rendering Mode...
      } else if (usedRenderingMode !== -1) {
        xtra += "0 Tr\n";
      }

      if (renderingMode !== -1) {
        pageContext.usedRenderingMode = renderingMode;
      }

      //align
      align = options.align || "left";
      var leading = activeFontSize * lineHeight;
      var pageWidth = scope.internal.pageSize.getWidth();
      var activeFont = fonts[activeFontKey];
      charSpace = options.charSpace || activeCharSpace;
      maxWidth = options.maxWidth || 0;

      var lineWidths;
      flags = {};
      var wordSpacingPerLine = [];

      if (Object.prototype.toString.call(text) === "[object Array]") {
        da = transformTextToSpecialArray(text);
        var newY;
        if (align !== "left") {
          lineWidths = da.map(function(v) {
            return (
              (scope.getStringUnitWidth(v, {
                font: activeFont,
                charSpace: charSpace,
                fontSize: activeFontSize,
                doKerning: false
              }) *
                activeFontSize) /
              scaleFactor
            );
          });
        }
        //The first line uses the "main" Td setting,
        //and the subsequent lines are offset by the
        //previous line's x coordinate.
        var prevWidth = 0;
        var newX;
        if (align === "right") {
          //The passed in x coordinate defines the
          //rightmost point of the text.
          x -= lineWidths[0];
          text = [];
          len = da.length;
          for (var i = 0; i < len; i++) {
            if (i === 0) {
              newX = getHorizontalCoordinate(x);
              newY = getVerticalCoordinate(y);
            } else {
              newX = scale(prevWidth - lineWidths[i]);
              newY = -leading;
            }
            text.push([da[i], newX, newY]);
            prevWidth = lineWidths[i];
          }
        } else if (align === "center") {
          //The passed in x coordinate defines
          //the center point.
          x -= lineWidths[0] / 2;
          text = [];
          len = da.length;
          for (var j = 0; j < len; j++) {
            if (j === 0) {
              newX = getHorizontalCoordinate(x);
              newY = getVerticalCoordinate(y);
            } else {
              newX = scale((prevWidth - lineWidths[j]) / 2);
              newY = -leading;
            }
            text.push([da[j], newX, newY]);
            prevWidth = lineWidths[j];
          }
        } else if (align === "left") {
          text = [];
          len = da.length;
          for (var h = 0; h < len; h++) {
            text.push(da[h]);
          }
        } else if (align === "justify") {
          text = [];
          len = da.length;
          maxWidth = maxWidth !== 0 ? maxWidth : pageWidth;

          for (var l = 0; l < len; l++) {
            newY = l === 0 ? getVerticalCoordinate(y) : -leading;
            newX = l === 0 ? getHorizontalCoordinate(x) : 0;
            if (l < len - 1) {
              wordSpacingPerLine.push(
                hpf(
                  scale(
                    (maxWidth - lineWidths[l]) / (da[l].split(" ").length - 1)
                  )
                )
              );
            }
            text.push([da[l], newX, newY]);
          }
        } else {
          throw new Error(
            'Unrecognized alignment option, use "left", "center", "right" or "justify".'
          );
        }
      }

      //R2L
      var doReversing = typeof options.R2L === "boolean" ? options.R2L : R2L;
      if (doReversing === true) {
        text = processTextByFunction(text, function(text, posX, posY) {
          return [
            text
              .split("")
              .reverse()
              .join(""),
            posX,
            posY
          ];
        });
      }

      //creating Payload-Object to make text byRef
      payload = {
        text: text,
        x: x,
        y: y,
        options: options,
        mutex: {
          pdfEscape: pdfEscape,
          activeFontKey: activeFontKey,
          fonts: fonts,
          activeFontSize: activeFontSize
        }
      };
      events.publish("postProcessText", payload);

      text = payload.text;
      isHex = payload.mutex.isHex || false;

      //Escaping
      var activeFontEncoding = fonts[activeFontKey].encoding;

      if (
        activeFontEncoding === "WinAnsiEncoding" ||
        activeFontEncoding === "StandardEncoding"
      ) {
        text = processTextByFunction(text, function(text, posX, posY) {
          return [ESC(text), posX, posY];
        });
      }

      da = transformTextToSpecialArray(text);

      text = [];
      var STRING = 0;
      var ARRAY = 1;
      var variant = Array.isArray(da[0]) ? ARRAY : STRING;
      var posX;
      var posY;
      var content;
      var wordSpacing = "";

      var generatePosition = function(
        parmPosX,
        parmPosY,
        parmTransformationMatrix
      ) {
        var position = "";
        if (parmTransformationMatrix instanceof Matrix) {
          // It is kind of more intuitive to apply a plain rotation around the text anchor set by x and y
          // but when the user supplies an arbitrary transformation matrix, the x and y offsets should be applied
          // in the coordinate system established by this matrix
          if (typeof options.angle === "number") {
            parmTransformationMatrix = matrixMult(
              parmTransformationMatrix,
              new Matrix(1, 0, 0, 1, parmPosX, parmPosY)
            );
          } else {
            parmTransformationMatrix = matrixMult(
              new Matrix(1, 0, 0, 1, parmPosX, parmPosY),
              parmTransformationMatrix
            );
          }

          if (apiMode === ApiMode.ADVANCED) {
            parmTransformationMatrix = matrixMult(
              new Matrix(1, 0, 0, -1, 0, 0),
              parmTransformationMatrix
            );
          }

          position = parmTransformationMatrix.join(" ") + " Tm\n";
        } else {
          position = hpf(parmPosX) + " " + hpf(parmPosY) + " Td\n";
        }
        return position;
      };

      for (var lineIndex = 0; lineIndex < da.length; lineIndex++) {
        wordSpacing = "";

        switch (variant) {
          case ARRAY:
            content =
              (isHex ? "<" : "(") + da[lineIndex][0] + (isHex ? ">" : ")");
            posX = parseFloat(da[lineIndex][1]);
            posY = parseFloat(da[lineIndex][2]);
            break;
          case STRING:
            content = (isHex ? "<" : "(") + da[lineIndex] + (isHex ? ">" : ")");
            posX = getHorizontalCoordinate(x);
            posY = getVerticalCoordinate(y);
            break;
        }

        if (
          typeof wordSpacingPerLine !== "undefined" &&
          typeof wordSpacingPerLine[lineIndex] !== "undefined"
        ) {
          wordSpacing = wordSpacingPerLine[lineIndex] + " Tw\n";
        }

        if (lineIndex === 0) {
          text.push(
            wordSpacing +
              generatePosition(posX, posY, transformationMatrix) +
              content
          );
        } else if (variant === STRING) {
          text.push(wordSpacing + content);
        } else if (variant === ARRAY) {
          text.push(
            wordSpacing +
              generatePosition(posX, posY, transformationMatrix) +
              content
          );
        }
      }

      text = variant === STRING ? text.join(" Tj\nT* ") : text.join(" Tj\n");
      text += " Tj\n";

      var result = "BT\n/";
      result += activeFontKey + " " + activeFontSize + " Tf\n"; // font face, style, size
      result += hpf(activeFontSize * lineHeight) + " TL\n"; // line spacing
      result += textColor + "\n";
      result += xtra;
      result += text;
      result += "ET";

      out(result);
      usedFonts[activeFontKey] = true;
      return scope;
    };

    // PDF supports these path painting and clip path operators:
    //
    // S - stroke
    // s - close/stroke
    // f (F) - fill non-zero
    // f* - fill evenodd
    // B - fill stroke nonzero
    // B* - fill stroke evenodd
    // b - close fill stroke nonzero
    // b* - close fill stroke evenodd
    // n - nothing (consume path)
    // W - clip nonzero
    // W* - clip evenodd
    //
    // In order to keep the API small, we omit the close-and-fill/stroke operators and provide a separate close()
    // method.
    /**
     *
     * @name clip
     * @function
     * @instance
     * @param {string} rule Only possible value is 'evenodd'
     * @returns {jsPDF}
     * @memberof jsPDF#
     * @description All .clip() after calling drawing ops with a style argument of null.
     */
    var clip = (API.__private__.clip = API.clip = function(rule) {
      // Call .clip() after calling drawing ops with a style argument of null
      // W is the PDF clipping op
      if ("evenodd" === rule) {
        out("W*");
      } else {
        out("W");
      }
      return this;
    });

    /**
     * @name clipEvenOdd
     * @function
     * @instance
     * @returns {jsPDF}
     * @memberof jsPDF#
     * @description Modify the current clip path by intersecting it with the current path using the even-odd rule. Note
     * that this will NOT consume the current path. In order to only use this path for clipping call
     * {@link API.discardPath} afterwards.
     */
    API.clipEvenOdd = function() {
      return clip("evenodd");
    };

    /**
     * Consumes the current path without any effect. Mainly used in combination with {@link clip} or
     * {@link clipEvenOdd}. The PDF "n" operator.
     * @name discardPath
     * @function
     * @instance
     * @returns {jsPDF}
     * @memberof jsPDF#
     */
    API.__private__.discardPath = API.discardPath = function() {
      out("n");
      return this;
    };

    var isValidStyle = (API.__private__.isValidStyle = function(style) {
      var validStyleVariants = [
        undefined,
        null,
        "S",
        "D",
        "F",
        "DF",
        "FD",
        "f",
        "f*",
        "B",
        "B*",
        "n"
      ];
      var result = false;
      if (validStyleVariants.indexOf(style) !== -1) {
        result = true;
      }
      return result;
    });

    API.__private__.setDefaultPathOperation = API.setDefaultPathOperation = function(
      operator
    ) {
      if (isValidStyle(operator)) {
        defaultPathOperation = operator;
      }
      return this;
    };

    var getStyle = (API.__private__.getStyle = API.getStyle = function(style) {
      // see path-painting operators in PDF spec
      var op = defaultPathOperation; // stroke

      switch (style) {
        case "D":
        case "S":
          op = "S"; // stroke
          break;
        case "F":
          op = "f"; // fill
          break;
        case "FD":
        case "DF":
          op = "B";
          break;
        case "f":
        case "f*":
        case "B":
        case "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;
          break;
      }
      return op;
    });

    /**
     * Close the current path. The PDF "h" operator.
     * @name close
     * @function
     * @instance
     * @returns {jsPDF}
     * @memberof jsPDF#
     */
    var close = (API.close = function() {
      out("h");
      return this;
    });

    /**
     * Stroke the path. The PDF "S" operator.
     * @name stroke
     * @function
     * @instance
     * @returns {jsPDF}
     * @memberof jsPDF#
     */
    API.stroke = function() {
      out("S");
      return this;
    };

    /**
     * Fill the current path using the nonzero winding number rule. If a pattern is provided, the path will be filled
     * with this pattern, otherwise with the current fill color. Equivalent to the PDF "f" operator.
     * @name fill
     * @function
     * @instance
     * @param {PatternData=} pattern If provided the path will be filled with this pattern
     * @returns {jsPDF}
     * @memberof jsPDF#
     */
    API.fill = function(pattern) {
      fillWithOptionalPattern("f", pattern);
      return this;
    };

    /**
     * Fill the current path using the even-odd rule. The PDF f* operator.
     * @see API.fill
     * @name fillEvenOdd
     * @function
     * @instance
     * @param {PatternData=} pattern If provided the path will be filled with this pattern
     * @returns {jsPDF}
     * @memberof jsPDF#
     */
    API.fillEvenOdd = function(pattern) {
      fillWithOptionalPattern("f*", pattern);
      return this;
    };

    /**
     * Fill using the nonzero winding number rule and then stroke the current Path. The PDF "B" operator.
     * @see API.fill
     * @name fillStroke
     * @function
     * @instance
     * @param {PatternData=} pattern If provided the path will be stroked with this pattern
     * @returns {jsPDF}
     * @memberof jsPDF#
     */
    API.fillStroke = function(pattern) {
      fillWithOptionalPattern("B", pattern);
      return this;
    };

    /**
     * Fill using the even-odd rule and then stroke the current Path. The PDF "B" operator.
     * @see API.fill
     * @name fillStrokeEvenOdd
     * @function
     * @instance
     * @param {PatternData=} pattern If provided the path will be fill-stroked with this pattern
     * @returns {jsPDF}
     * @memberof jsPDF#
     */
    API.fillStrokeEvenOdd = function(pattern) {
      fillWithOptionalPattern("B*", pattern);
      return this;
    };

    var fillWithOptionalPattern = function(style, pattern) {
      if (typeof pattern === "object") {
        fillWithPattern(pattern, style);
      } else {
        out(style);
      }
    };

    var putStyle = function(style) {
      if (
        style === null ||
        (apiMode === ApiMode.ADVANCED && style === undefined)
      ) {
        return;
      }

      style = getStyle(style);

      // stroking / filling / both the path
      out(style);
    };

    function cloneTilingPattern(patternKey, boundingBox, xStep, yStep, matrix) {
      var clone = new TilingPattern(
        boundingBox || this.boundingBox,
        xStep || this.xStep,
        yStep || this.yStep,
        this.gState,
        matrix || this.matrix
      );
      clone.stream = this.stream;
      var key = patternKey + "$$" + this.cloneIndex++ + "$$";
      addPattern(key, clone);
      return clone;
    }

    var fillWithPattern = function(patternData, style) {
      var patternId = patternMap[patternData.key];
      var pattern = patterns[patternId];

      if (pattern instanceof ShadingPattern) {
        out("q");

        out(clipRuleFromStyle(style));

        if (pattern.gState) {
          API.setGState(pattern.gState);
        }
        out(patternData.matrix.toString() + " cm");
        out("/" + patternId + " sh");
        out("Q");
      } else if (pattern instanceof TilingPattern) {
        // pdf draws patterns starting at the bottom left corner and they are not affected by the global transformation,
        // so we must flip them
        var matrix = new Matrix(1, 0, 0, -1, 0, getPageHeight());

        if (patternData.matrix) {
          matrix = matrix.multiply(patternData.matrix || identityMatrix);
          // we cannot apply a matrix to the pattern on use so we must abuse the pattern matrix and create new instances
          // for each use
          patternId = cloneTilingPattern.call(
            pattern,
            patternData.key,
            patternData.boundingBox,
            patternData.xStep,
            patternData.yStep,
            matrix
          ).id;
        }

        out("q");
        out("/Pattern cs");
        out("/" + patternId + " scn");

        if (pattern.gState) {
          API.setGState(pattern.gState);
        }

        out(style);
        out("Q");
      }
    };

    var clipRuleFromStyle = function(style) {
      switch (style) {
        case "f":
        case "F":
          return "W n";
        case "f*":
          return "W* n";
        case "B":
          return "W S";
        case "B*":
          return "W* S";

        // these two are for compatibility reasons (in the past, calling any primitive method with a shading pattern
        // and "n"/"S" as style would still fill/fill and stroke the path)
        case "S":
          return "W S";
        case "n":
          return "W n";
      }
    };

    /**
     * Begin a new subpath by moving the current point to coordinates (x, y). The PDF "m" operator.
     * @param {number} x
     * @param {number} y
     * @name moveTo
     * @function
     * @instance
     * @memberof jsPDF#
     * @returns {jsPDF}
     */
    var moveTo = (API.moveTo = function(x, y) {
      out(hpf(scale(x)) + " " + hpf(transformScaleY(y)) + " m");
      return this;
    });

    /**
     * Append a straight line segment from the current point to the point (x, y). The PDF "l" operator.
     * @param {number} x
     * @param {number} y
     * @memberof jsPDF#
     * @name lineTo
     * @function
     * @instance
     * @memberof jsPDF#
     * @returns {jsPDF}
     */
    var lineTo = (API.lineTo = function(x, y) {
      out(hpf(scale(x)) + " " + hpf(transformScaleY(y)) + " l");
      return this;
    });

    /**
     * Append a cubic Bézier curve to the current path. The curve shall extend from the current point to the point
     * (x3, y3), using (x1, y1) and (x2, y2) as Bézier control points. The new current point shall be (x3, x3).
     * @param {number} x1
     * @param {number} y1
     * @param {number} x2
     * @param {number} y2
     * @param {number} x3
     * @param {number} y3
     * @memberof jsPDF#
     * @name curveTo
     * @function
     * @instance
     * @memberof jsPDF#
     * @returns {jsPDF}
     */
    var curveTo = (API.curveTo = function(x1, y1, x2, y2, x3, y3) {
      out(
        [
          hpf(scale(x1)),
          hpf(transformScaleY(y1)),
          hpf(scale(x2)),
          hpf(transformScaleY(y2)),
          hpf(scale(x3)),
          hpf(transformScaleY(y3)),
          "c"
        ].join(" ")
      );
      return this;
    });

    /**
     * Draw a line on the current page.
     *
     * @name line
     * @function
     * @instance
     * @param {number} x1
     * @param {number} y1
     * @param {number} x2
     * @param {number} y2
     * @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. default: 'S'
     * @returns {jsPDF}
     * @memberof jsPDF#
     */
    API.__private__.line = API.line = function(x1, y1, x2, y2, style) {
      if (
        isNaN(x1) ||
        isNaN(y1) ||
        isNaN(x2) ||
        isNaN(y2) ||
        !isValidStyle(style)
      ) {
        throw new Error("Invalid arguments passed to jsPDF.line");
      }
      if (apiMode === ApiMode.COMPAT) {
        return this.lines([[x2 - x1, y2 - y1]], x1, y1, [1, 1], style || "S");
      } else {
        return this.lines([[x2 - x1, y2 - y1]], x1, y1, [1, 1]).stroke();
      }
    };

    /**
     * @typedef {Object} PatternData
     * {Matrix|undefined} matrix
     * {Number|undefined} xStep
     * {Number|undefined} yStep
     * {Array.<Number>|undefined} boundingBox
     */

    /**
     * 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, [1,1], 'F', false) // 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.
     * In "compat" API mode, 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.
     *
     * In "advanced" API mode this parameter is deprecated.
     * @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
     * @instance
     * @returns {jsPDF}
     * @memberof jsPDF#
     * @name lines
     */
    API.__private__.lines = API.lines = function(
      lines,
      x,
      y,
      scale,
      style,
      closed
    ) {
      var scalex, scaley, i, l, leg, x2, y2, x3, y3, x4, y4, tmp;

      // 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];
      closed = closed || false;

      if (
        isNaN(x) ||
        isNaN(y) ||
        !Array.isArray(lines) ||
        !Array.isArray(scale) ||
        !isValidStyle(style) ||
        typeof closed !== "boolean"
      ) {
        throw new Error("Invalid arguments passed to jsPDF.lines");
      }

      // starting point
      moveTo(x, y);

      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
          lineTo(x4, y4);
        } 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
          curveTo(x2, y2, x3, y3, x4, y4);
        }
      }

      if (closed) {
        close();
      }

      putStyle(style);
      return this;
    };

    /**
     * Similar to {@link API.lines} but all coordinates are interpreted as absolute coordinates instead of relative.
     * @param {Array<Object>} lines An array of {op: operator, c: coordinates} object, where op is one of "m" (move to), "l" (line to)
     * "c" (cubic bezier curve) and "h" (close (sub)path)). c is an array of coordinates. "m" and "l" expect two, "c"
     * six and "h" an empty array (or undefined).
     * @function
     * @returns {jsPDF}
     * @memberof jsPDF#
     * @name path
     */
    API.path = function(lines) {
      for (var i = 0; i < lines.length; i++) {
        var leg = lines[i];
        var coords = leg.c;
        switch (leg.op) {
          case "m":
            moveTo(coords[0], coords[1]);
            break;
          case "l":
            lineTo(coords[0], coords[1]);
            break;
          case "c":
            curveTo.apply(this, coords);
            break;
          case "h":
            close();
            break;
        }
      }

      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.
     * In "compat" API mode, 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.
     *
     * In "advanced" API mode this parameter is deprecated.
     * @function
     * @instance
     * @returns {jsPDF}
     * @memberof jsPDF#
     * @name rect
     */
    API.__private__.rect = API.rect = function(x, y, w, h, style) {
      if (isNaN(x) || isNaN(y) || isNaN(w) || isNaN(h) || !isValidStyle(style)) {
        throw new Error("Invalid arguments passed to jsPDF.rect");
      }
      if (apiMode === ApiMode.COMPAT) {
        h = -h;
      }

      out(
        [
          hpf(scale(x)),
          hpf(transformScaleY(y)),
          hpf(scale(w)),
          hpf(scale(h)),
          "re"
        ].join(" ")
      );

      putStyle(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.
     * In "compat" API mode, 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.
     *
     * In "advanced" API mode this parameter is deprecated.
     * @function
     * @instance
     * @returns {jsPDF}
     * @memberof jsPDF#
     * @name triangle
     */
    API.__private__.triangle = API.triangle = function(
      x1,
      y1,
      x2,
      y2,
      x3,
      y3,
      style
    ) {
      if (
        isNaN(x1) ||
        isNaN(y1) ||
        isNaN(x2) ||
        isNaN(y2) ||
        isNaN(x3) ||
        isNaN(y3) ||
        !isValidStyle(style)
      ) {
        throw new Error("Invalid arguments passed to jsPDF.triangle");
      }
      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} ry 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.
     * In "compat" API mode, 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.
     *
     * In "advanced" API mode this parameter is deprecated.
     * @function
     * @instance
     * @returns {jsPDF}
     * @memberof jsPDF#
     * @name roundedRect
     */
    API.__private__.roundedRect = API.roundedRect = function(
      x,
      y,
      w,
      h,
      rx,
      ry,
      style
    ) {
      if (
        isNaN(x) ||
        isNaN(y) ||
        isNaN(w) ||
        isNaN(h) ||
        isNaN(rx) ||
        isNaN(ry) ||
        !isValidStyle(style)
      ) {
        throw new Error("Invalid arguments passed to jsPDF.roundedRect");
      }
      var MyArc = (4 / 3) * (Math.SQRT2 - 1);

      rx = Math.min(rx, w * 0.5);
      ry = Math.min(ry, h * 0.5);

      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,
        true
      );
      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} ry 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.
     * In "compat" API mode, 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.
     *
     * In "advanced" API mode this parameter is deprecated.
     * @function
     * @instance
     * @returns {jsPDF}
     * @memberof jsPDF#
     * @name ellipse
     */
    API.__private__.ellipse = API.ellipse = function(x, y, rx, ry, style) {
      if (
        isNaN(x) ||
        isNaN(y) ||
        isNaN(rx) ||
        isNaN(ry) ||
        !isValidStyle(style)
      ) {
        throw new Error("Invalid arguments passed to jsPDF.ellipse");
      }
      var lx = (4 / 3) * (Math.SQRT2 - 1) * rx,
        ly = (4 / 3) * (Math.SQRT2 - 1) * ry;

      moveTo(x + rx, y);
      curveTo(x + rx, y - ly, x + lx, y - ry, x, y - ry);
      curveTo(x - lx, y - ry, x - rx, y - ly, x - rx, y);
      curveTo(x - rx, y + ly, x - lx, y + ry, x, y + ry);
      curveTo(x + lx, y + ry, x + rx, y + ly, x + rx, y);

      putStyle(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.
     * In "compat" API mode, 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.
     *
     * In "advanced" API mode this parameter is deprecated.
     * @function
     * @instance
     * @returns {jsPDF}
     * @memberof jsPDF#
     * @name circle
     */
    API.__private__.circle = API.circle = function(x, y, r, style) {
      if (isNaN(x) || isNaN(y) || isNaN(r) || !isValidStyle(style)) {
        throw new Error("Invalid arguments passed to jsPDF.circle");
      }
      return this.ellipse(x, y, r, r, style);
    };

    /**
     * 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
     * @instance
     * @returns {jsPDF}
     * @memberof jsPDF#
     * @name setFont
     */
    API.setFont = function(fontName, fontStyle) {
      activeFontKey = getFont(fontName, fontStyle, {
        disableWarning: false
      });
      return this;
    };

    /**
     * Gets text font face, variant for upcoming text elements.
     *
     * @function
     * @instance
     * @returns {Object}
     * @memberof jsPDF#
     * @name getFont
     */
    var getFontEntry = (API.__private__.getFont = API.getFont = function() {
      return fonts[getFont.apply(API, arguments)];
    });

    /**
     * Returns an object - a tree of fontName to fontStyle relationships available to
     * active PDF document.
     *
     * @public
     * @function
     * @instance
     * @returns {Object} Like {'times':['normal', 'italic', ... ], 'arial':['normal', 'bold', ... ], ... }
     * @memberof jsPDF#
     * @name getFontList
     */
    API.__private__.getFontList = API.getFontList = function() {
      var list = {},
        fontName,
        fontStyle;

      for (fontName in fontmap) {
        if (fontmap.hasOwnProperty(fontName)) {
          list[fontName] = [];
          for (fontStyle in fontmap[fontName]) {
            if (fontmap[fontName].hasOwnProperty(fontStyle)) {
              list[fontName].push(fontStyle);
            }
          }
        }
      }
      return list;
    };

    /**
     * Add a custom font to the current instance.
     *
     * @param {string} postScriptName PDF specification full name for the font.
     * @param {string} id PDF-document-instance-specific label assinged to the font.
     * @param {string} fontStyle Style of the Font.
     * @param {Object} encoding Encoding_name-to-Font_metrics_object mapping.
     * @function
     * @instance
     * @memberof jsPDF#
     * @name addFont
     * @returns {string} fontId
     */
    API.addFont = function(postScriptName, fontName, fontStyle, encoding) {
      encoding = encoding || "Identity-H";
      return addFont.call(this, postScriptName, fontName, fontStyle, encoding);
    };

    var lineWidth = options.lineWidth || 0.200025; // 2mm
    /**
     * Sets line width for upcoming lines.
     *
     * @param {number} width Line width (in units declared at inception of PDF document).
     * @function
     * @instance
     * @returns {jsPDF}
     * @memberof jsPDF#
     * @name setLineWidth
     */
    var setLineWidth = (API.__private__.setLineWidth = API.setLineWidth = function(
      width
    ) {
      out(hpf(scale(width)) + " w");
      return this;
    });

    /**
     * Sets the dash pattern for upcoming lines.
     *
     * To reset the settings simply call the method without any parameters.
     * @param {Array<number>} dashArray An array containing 0-2 numbers. The first number sets the length of the
     * dashes, the second number the length of the gaps. If the second number is missing, the gaps are considered
     * to be as long as the dashes. An empty array means solid, unbroken lines.
     * @param {number} dashPhase The phase lines start with.
     * @function
     * @instance
     * @returns {jsPDF}
     * @memberof jsPDF#
     * @name setLineDashPattern
     */
    API.__private__.setLineDash = jsPDF.API.setLineDash = jsPDF.API.setLineDashPattern = function(
      dashArray,
      dashPhase
    ) {
      dashArray = dashArray || [];
      dashPhase = dashPhase || 0;

      if (isNaN(dashPhase) || !Array.isArray(dashArray)) {
        throw new Error("Invalid arguments passed to jsPDF.setLineDash");
      }

      dashArray = dashArray
        .map(function(x) {
          return hpf(scale(x));
        })
        .join(" ");
      dashPhase = hpf(scale(dashPhase));

      out("[" + dashArray + "] " + dashPhase + " d");
      return this;
    };

    var lineHeightFactor;

    var getLineHeight = (API.__private__.getLineHeight = API.getLineHeight = function() {
      return activeFontSize * lineHeightFactor;
    });

    API.__private__.getLineHeight = API.getLineHeight = function() {
      return activeFontSize * lineHeightFactor;
    };

    /**
     * Sets the LineHeightFactor of proportion.
     *
     * @param {number} value LineHeightFactor value. Default: 1.15.
     * @function
     * @instance
     * @returns {jsPDF}
     * @memberof jsPDF#
     * @name setLineHeightFactor
     */
    var setLineHeightFactor = (API.__private__.setLineHeightFactor = API.setLineHeightFactor = function(
      value
    ) {
      value = value || 1.15;
      if (typeof value === "number") {
        lineHeightFactor = value;
      }
      return this;
    });

    /**
     * Gets the LineHeightFactor, default: 1.15.
     *
     * @function
     * @instance
     * @returns {number} lineHeightFactor
     * @memberof jsPDF#
     * @name getLineHeightFactor
     */
    var getLineHeightFactor = (API.__private__.getLineHeightFactor = API.getLineHeightFactor = function() {
      return lineHeightFactor;
    });

    setLineHeightFactor(options.lineHeight);

    var getHorizontalCoordinate = (API.__private__.getHorizontalCoordinate = function(
      value
    ) {
      return scale(value);
    });

    var getVerticalCoordinate = (API.__private__.getVerticalCoordinate = function(
      value
    ) {
      if (apiMode === ApiMode.ADVANCED) {
        return value;
      } else {
        var pageHeight =
          pagesContext[currentPage].mediaBox.topRightY -
          pagesContext[currentPage].mediaBox.bottomLeftY;
        return pageHeight - scale(value);
      }
    });

    var getHorizontalCoordinateString = (API.__private__.getHorizontalCoordinateString = API.getHorizontalCoordinateString = function(
      value
    ) {
      return hpf(getHorizontalCoordinate(value));
    });

    var getVerticalCoordinateString = (API.__private__.getVerticalCoordinateString = API.getVerticalCoordinateString = function(
      value
    ) {
      return hpf(getVerticalCoordinate(value));
    });

    var strokeColor = options.strokeColor || "0 G";

    /**
     *  Gets the stroke color for upcoming elements.
     *
     * @function
     * @instance
     * @returns {string} colorAsHex
     * @memberof jsPDF#
     * @name getDrawColor
     */
    API.__private__.getStrokeColor = API.getDrawColor = function() {
      return decodeColorString(strokeColor);
    };

    /**
     * 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 or {string} ch1 color value in hexadecimal, example: '#FFFFFF'.
     * @param {Number} ch2 Color channel value.
     * @param {Number} ch3 Color channel value.
     * @param {Number} ch4 Color channel value.
     *
     * @function
     * @instance
     * @returns {jsPDF}
     * @memberof jsPDF#
     * @name setDrawColor
     */
    API.__private__.setStrokeColor = API.setDrawColor = function(
      ch1,
      ch2,
      ch3,
      ch4
    ) {
      var options = {
        ch1: ch1,
        ch2: ch2,
        ch3: ch3,
        ch4: ch4,
        pdfColorType: "draw",
        precision: 2
      };

      strokeColor = encodeColorString(options);
      out(strokeColor);
      return this;
    };

    var fillColor = options.fillColor || "0 g";

    /**
     * Gets the fill color for upcoming elements.
     *
     * @function
     * @instance
     * @returns {string} colorAsHex
     * @memberof jsPDF#
     * @name getFillColor
     */
    API.__private__.getFillColor = API.getFillColor = function() {
      return decodeColorString(fillColor);
    };

    /**
     * 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 or {string} ch1 color value in hexadecimal, example: '#FFFFFF'.
     * @param {Number} ch2 Color channel value.
     * @param {Number} ch3 Color channel value.
     * @param {Number} ch4 Color channel value.
     *
     * @function
     * @instance
     * @returns {jsPDF}
     * @memberof jsPDF#
     * @name setFillColor
     */
    API.__private__.setFillColor = API.setFillColor = function(
      ch1,
      ch2,
      ch3,
      ch4
    ) {
      var options = {
        ch1: ch1,
        ch2: ch2,
        ch3: ch3,
        ch4: ch4,
        pdfColorType: "fill",
        precision: 2
      };

      fillColor = encodeColorString(options);
      out(fillColor);
      return this;
    };

    var textColor = options.textColor || "0 g";
    /**
     * Gets the text color for upcoming elements.
     *
     * @function
     * @instance
     * @returns {string} colorAsHex
     * @memberof jsPDF#
     * @name getTextColor
     */
    var getTextColor = (API.__private__.getTextColor = API.getTextColor = function() {
      return decodeColorString(textColor);
    });
    /**
     * Sets the text 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 or {string} ch1 color value in hexadecimal, example: '#FFFFFF'.
     * @param {Number} ch2 Color channel value.
     * @param {Number} ch3 Color channel value.
     * @param {Number} ch4 Color channel value.
     *
     * @function
     * @instance
     * @returns {jsPDF}
     * @memberof jsPDF#
     * @name setTextColor
     */
    API.__private__.setTextColor = API.setTextColor = function(
      ch1,
      ch2,
      ch3,
      ch4
    ) {
      var options = {
        ch1: ch1,
        ch2: ch2,
        ch3: ch3,
        ch4: ch4,
        pdfColorType: "text",
        precision: 3
      };
      textColor = encodeColorString(options);

      return this;
    };

    var activeCharSpace = options.charSpace;

    /**
     * Get global value of CharSpace.
     *
     * @function
     * @instance
     * @returns {number} charSpace
     * @memberof jsPDF#
     * @name getCharSpace
     */
    var getCharSpace = (API.__private__.getCharSpace = API.getCharSpace = function() {
      return parseFloat(activeCharSpace || 0);
    });

    /**
     * Set global value of CharSpace.
     *
     * @param {number} charSpace
     * @function
     * @instance
     * @returns {jsPDF} jsPDF-instance
     * @memberof jsPDF#
     * @name setCharSpace
     */
    API.__private__.setCharSpace = API.setCharSpace = function(charSpace) {
      if (isNaN(charSpace)) {
        throw new Error("Invalid argument passed to jsPDF.setCharSpace");
      }
      activeCharSpace = charSpace;
      return this;
    };

    var lineCapID = 0;
    /**
     * Is an Object providing a mapping from human-readable to
     * integer flag values designating the varieties of line cap
     * and join styles.
     *
     * @memberof 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
     * @instance
     * @returns {jsPDF}
     * @memberof jsPDF#
     * @name setLineCap
     */
    API.__private__.setLineCap = API.setLineCap = function(style) {
      var id = API.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;
    };

    var lineJoinID = 0;
    /**
     * 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
     * @instance
     * @returns {jsPDF}
     * @memberof jsPDF#
     * @name setLineJoin
     */
    API.__private__.setLineJoin = API.setLineJoin = function(style) {
      var id = API.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;
    };
    /**
     * Sets the miterLimit property, which effects the maximum miter length.
     *
     * @param {number} length The length of the miter
     * @function
     * @instance
     * @returns {jsPDF}
     * @memberof jsPDF#
     * @name setLineMiterLimit
     */
    API.__private__.setLineMiterLimit = API.__private__.setMiterLimit = API.setLineMiterLimit = API.setMiterLimit = function(
      length
    ) {
      length = length || 0;
      if (isNaN(length)) {
        throw new Error("Invalid argument passed to jsPDF.setLineMiterLimit");
      }
      out(hpf(scale(length)) + " M");

      return this;
    };

    /**
     * An object representing a pdf graphics state.
     * @class GState
     */

    /**
     *
     * @param parameters A parameter object that contains all properties this graphics state wants to set.
     * Supported are: opacity, stroke-opacity
     * @constructor
     */
    API.GState = GState;

    /**
     * Sets a either previously added {@link GState} (via {@link addGState}) or a new {@link GState}.
     * @param {String|GState} gState If type is string, a previously added GState is used, if type is GState
     * it will be added before use.
     * @function
     * @returns {jsPDF}
     * @memberof jsPDF#
     * @name setGState
     */
    API.setGState = function(gState) {
      if (typeof gState === "string") {
        gState = gStates[gStatesMap[gState]];
      } else {
        gState = addGState(null, gState);
      }

      if (!gState.equals(activeGState)) {
        out("/" + gState.id + " gs");
        activeGState = gState;
      }
    };

    /**
     * Adds a new Graphics State. Duplicates are automatically eliminated.
     * @param {String} key Might also be null, if no later reference to this gState is needed
     * @param {Object} gState The gState object
     */
    var addGState = function(key, gState) {
      // only add it if it is not already present (the keys provided by the user must be unique!)
      if (key && gStatesMap[key]) return;
      var duplicate = false;
      for (var s in gStates) {
        if (gStates.hasOwnProperty(s)) {
          if (gStates[s].equals(gState)) {
            duplicate = true;
            break;
          }
        }
      }

      if (duplicate) {
        gState = gStates[s];
      } else {
        var gStateKey = "GS" + (Object.keys(gStates).length + 1).toString(10);
        gStates[gStateKey] = gState;
        gState.id = gStateKey;
      }

      // several user keys may point to the same GState object
      key && (gStatesMap[key] = gState.id);

      events.publish("addGState", gState);

      return gState;
    };

    /**
     * Adds a new {@link GState} for later use. See {@link setGState}.
     * @param {String} key
     * @param {GState} gState
     * @function
     * @instance
     * @returns {jsPDF}
     *
     * @memberof jsPDF#
     * @name addGState
     */
    API.addGState = function(key, gState) {
      addGState(key, gState);
      return this;
    };

    /**
     * Saves the current graphics state ("pushes it on the stack"). It can be restored by {@link restoreGraphicsState}
     * later. Here, the general pdf graphics state is meant, also including the current transformation matrix,
     * fill and stroke colors etc.
     * @function
     * @returns {jsPDF}
     * @memberof jsPDF#
     * @name saveGraphicsState
     */
    API.saveGraphicsState = function() {
      out("q");
      // as we cannot set font key and size independently we must keep track of both
      fontStateStack.push({
        key: activeFontKey,
        size: activeFontSize,
        color: textColor
      });
      return this;
    };

    /**
     * Restores a previously saved graphics state saved by {@link saveGraphicsState} ("pops the stack").
     * @function
     * @returns {jsPDF}
     * @memberof jsPDF#
     * @name restoreGraphicsState
     */
    API.restoreGraphicsState = function() {
      out("Q");

      // restore previous font state
      var fontState = fontStateStack.pop();
      activeFontKey = fontState.key;
      activeFontSize = fontState.size;
      textColor = fontState.color;

      activeGState = null;

      return this;
    };

    /**
     * Appends this matrix to the left of all previously applied matrices.
     *
     * @param {Matrix} matrix
     * @function
     * @returns {jsPDF}
     * @memberof jsPDF#
     * @name setCurrentTransformationMatrix
     */
    API.setCurrentTransformationMatrix = function(matrix) {
      out(matrix.toString() + " cm");
      return this;
    };

    /**
     * Inserts a debug comment into the generated pdf.
     * @function
     * @instance
     * @param {String} text
     * @returns {jsPDF}
     * @memberof jsPDF#
     * @name comment
     */
    API.comment = function(text) {
      out("#" + text);
      return this;
    };

    /**
     * Point
     */
    var Point = function(x, y) {
      var _x = x || 0;
      Object.defineProperty(this, "x", {
        enumerable: true,
        get: function() {
          return _x;
        },
        set: function(value) {
          if (!isNaN(value)) {
            _x = parseFloat(value);
          }
        }
      });

      var _y = y || 0;
      Object.defineProperty(this, "y", {
        enumerable: true,
        get: function() {
          return _y;
        },
        set: function(value) {
          if (!isNaN(value)) {
            _y = parseFloat(value);
          }
        }
      });

      var _type = "pt";
      Object.defineProperty(this, "type", {
        enumerable: true,
        get: function() {
          return _type;
        },
        set: function(value) {
          _type = value.toString();
        }
      });
      return this;
    };

    /**
     * Rectangle
     */
    var Rectangle = function(x, y, w, h) {
      Point.call(this, x, y);
      this.type = "rect";

      var _w = w || 0;
      Object.defineProperty(this, "w", {
        enumerable: true,
        get: function() {
          return _w;
        },
        set: function(value) {
          if (!isNaN(value)) {
            _w = parseFloat(value);
          }
        }
      });

      var _h = h || 0;
      Object.defineProperty(this, "h", {
        enumerable: true,
        get: function() {
          return _h;
        },
        set: function(value) {
          if (!isNaN(value)) {
            _h = parseFloat(value);
          }
        }
      });

      return this;
    };

    /**
     * FormObject/RenderTarget
     */

    var RenderTarget = function() {
      this.page = page;
      this.currentPage = currentPage;
      this.pages = pages.slice(0);
      this.pagesContext = pagesContext.slice(0);
      this.x = pageX;
      this.y = pageY;
      this.matrix = pageMatrix;
      this.width = getPageWidth(currentPage);
      this.height = getPageHeight(currentPage);
      this.outputDestination = outputDestination;

      this.id = ""; // set by endFormObject()
      this.objectNumber = -1; // will be set by putXObject()
    };

    RenderTarget.prototype.restore = function() {
      page = this.page;
      currentPage = this.currentPage;
      pagesContext = this.pagesContext;
      pages = this.pages;
      pageX = this.x;
      pageY = this.y;
      pageMatrix = this.matrix;
      setPageWidth(currentPage, this.width);
      setPageHeight(currentPage, this.height);
      outputDestination = this.outputDestination;
    };

    var beginNewRenderTarget = function(x, y, width, height, matrix) {
      // save current state
      renderTargetStack.push(new RenderTarget());

      // clear pages
      page = currentPage = 0;
      pages = [];
      pageX = x;
      pageY = y;

      pageMatrix = matrix;

      beginPage([width, height]);
    };

    var endFormObject = function(key) {
      // only add it if it is not already present (the keys provided by the user must be unique!)
      if (renderTargetMap[key]) return;

      // save the created xObject
      var newXObject = new RenderTarget();

      var xObjectId = "Xo" + (Object.keys(renderTargets).length + 1).toString(10);
      newXObject.id = xObjectId;

      renderTargetMap[key] = xObjectId;
      renderTargets[xObjectId] = newXObject;

      events.publish("addFormObject", newXObject);

      // restore state from stack
      renderTargetStack.pop().restore();
    };

    /**
     * Starts a new pdf form object, which means that all consequent draw calls target a new independent object
     * until {@link endFormObject} is called. The created object can be referenced and drawn later using
     * {@link doFormObject}. Nested form objects are possible.
     * x, y, width, height set the bounding box that is used to clip the content.
     *
     * @param {number} x
     * @param {number} y
     * @param {number} width
     * @param {number} height
     * @param {Matrix} matrix The matrix that will be applied to convert the form objects coordinate system to
     * the parent's.
     * @function
     * @returns {jsPDF}
     * @memberof jsPDF#
     * @name beginFormObject
     */
    API.beginFormObject = function(x, y, width, height, matrix) {
      // The user can set the output target to a new form object. Nested form objects are possible.
      // Currently, they use the resource dictionary of the surrounding stream. This should be changed, as
      // the PDF-Spec states:
      // "In PDF 1.2 and later versions, form XObjects may be independent of the content streams in which
      // they appear, and this is strongly recommended although not requiredIn PDF 1.2 and later versions,
      // form XObjects may be independent of the content streams in which they appear, and this is strongly
      // recommended although not required"
      beginNewRenderTarget(x, y, width, height, matrix);
      return this;
    };

    /**
     * Completes and saves the form object.
     * @param {String} key The key by which this form object can be referenced.
     * @function
     * @returns {jsPDF}
     * @memberof jsPDF#
     * @name endFormObject
     */
    API.endFormObject = function(key) {
      endFormObject(key);
      return this;
    };

    /**
     * Draws the specified form object by referencing to the respective pdf XObject created with
     * {@link API.beginFormObject} and {@link endFormObject}.
     * The location is determined by matrix.
     *
     * @param {String} key The key to the form object.
     * @param {Matrix} matrix The matrix applied before drawing the form object.
     * @function
     * @returns {jsPDF}
     * @memberof jsPDF#
     * @name doFormObject
     */
    API.doFormObject = function(key, matrix) {
      var xObject = renderTargets[renderTargetMap[key]];
      out("q");
      out(matrix.toString() + " cm");
      out("/" + xObject.id + " Do");
      out("Q");
      return this;
    };

    /**
     * Returns the form object specified by key.
     * @param key {String}
     * @returns {{x: number, y: number, width: number, height: number, matrix: Matrix}}
     * @function
     * @returns {jsPDF}
     * @memberof jsPDF#
     * @name getFormObject
     */
    API.getFormObject = function(key) {
      var xObject = renderTargets[renderTargetMap[key]];
      return {
        x: xObject.x,
        y: xObject.y,
        width: xObject.width,
        height: xObject.height,
        matrix: xObject.matrix
      };
    };

    /**
     * Saves as PDF document. An alias of jsPDF.output('save', 'filename.pdf').
     * Uses FileSaver.js-method saveAs.
     *
     * @memberof jsPDF#
     * @name save
     * @function
     * @instance
     * @param  {string} filename The filename including extension.
     * @param  {Object} options An Object with additional options, possible options: 'returnPromise'.
     * @returns {jsPDF|Promise} jsPDF-instance     */
    API.save = function(filename, options) {
      filename = filename || "generated.pdf";

      options = options || {};
      options.returnPromise = options.returnPromise || false;

      if (options.returnPromise === false) {
        saveAs(getBlob(buildDocument()), filename);
        if (typeof saveAs.unload === "function") {
          if (globalObject.setTimeout) {
            setTimeout(saveAs.unload, 911);
          }
        }
        return this;
      } else {
        return new Promise(function(resolve, reject) {
          try {
            var result = saveAs(getBlob(buildDocument()), filename);
            if (typeof saveAs.unload === "function") {
              if (globalObject.setTimeout) {
                setTimeout(saveAs.unload, 911);
              }
            }
            resolve(result);
          } catch (e) {
            reject(e.message);
          }
        });
      }

    };

    // 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];
        }
      }
    }

    var getPageWidth = (API.getPageWidth = function(pageNumber) {
      pageNumber = pageNumber || currentPage;
      return (
        (pagesContext[pageNumber].mediaBox.topRightX -
          pagesContext[pageNumber].mediaBox.bottomLeftX) /
        scaleFactor
      );
    });

    var setPageWidth = (API.setPageWidth = function(pageNumber, value) {
      pagesContext[pageNumber].mediaBox.topRightX =
        value * scaleFactor + pagesContext[pageNumber].mediaBox.bottomLeftX;
    });

    var getPageHeight = (API.getPageHeight = function(pageNumber) {
      pageNumber = pageNumber || currentPage;
      return (
        (pagesContext[pageNumber].mediaBox.topRightY -
          pagesContext[pageNumber].mediaBox.bottomLeftY) /
        scaleFactor
      );
    });

    var setPageHeight = (API.setPageHeight = function(pageNumber, value) {
      pagesContext[pageNumber].mediaBox.topRightY =
        value * scaleFactor + pagesContext[pageNumber].mediaBox.bottomLeftY;
    });

    /**
     * Object exposing internal API to plugins
     * @public
     * @ignore
     */
    API.internal = {
      pdfEscape: pdfEscape,
      getStyle: getStyle,
      getFont: getFontEntry,
      getFontSize: getFontSize,
      getCharSpace: getCharSpace,
      getTextColor: getTextColor,
      getLineHeight: getLineHeight,
      getLineHeightFactor: getLineHeightFactor,
      write: write,
      getHorizontalCoordinate: getHorizontalCoordinate,
      getVerticalCoordinate: getVerticalCoordinate,
      getCoordinateString: getHorizontalCoordinateString,
      getVerticalCoordinateString: getVerticalCoordinateString,
      collections: {},
      newObject: newObject,
      newAdditionalObject: newAdditionalObject,
      newObjectDeferred: newObjectDeferred,
      newObjectDeferredBegin: newObjectDeferredBegin,
      getFilters: getFilters,
      putStream: putStream,
      events: events,
      scaleFactor: scaleFactor,
      pageSize: {
        getWidth: function() {
          return getPageWidth(currentPage);
        },
        setWidth: function(value) {
          setPageWidth(currentPage, value);
        },
        getHeight: function() {
          return getPageHeight(currentPage);
        },
        setHeight: function(value) {
          setPageHeight(currentPage, value);
        }
      },
      encryptionOptions: encryptionOptions,
      encryption: encryption,
      getEncryptor: getEncryptor,
      output: output,
      getNumberOfPages: getNumberOfPages,
      pages: pages,
      out: out,
      f2: f2,
      f3: f3,
      getPageInfo: getPageInfo,
      getPageInfoByObjId: getPageInfoByObjId,
      getCurrentPageInfo: getCurrentPageInfo,
      getPDFVersion: getPdfVersion,
      Point: Point,
      Rectangle: Rectangle,
      Matrix: Matrix,
      hasHotfix: hasHotfix //Expose the hasHotfix check so plugins can also check them.
    };

    Object.defineProperty(API.internal.pageSize, "width", {
      get: function() {
        return getPageWidth(currentPage);
      },
      set: function(value) {
        setPageWidth(currentPage, value);
      },
      enumerable: true,
      configurable: true
    });
    Object.defineProperty(API.internal.pageSize, "height", {
      get: function() {
        return getPageHeight(currentPage);
      },
      set: function(value) {
        setPageHeight(currentPage, value);
      },
      enumerable: true,
      configurable: true
    });

    //////////////////////////////////////////////////////
    // continuing initialization of jsPDF Document object
    //////////////////////////////////////////////////////
    // Add the first page automatically
    addFonts.call(API, standardFonts);
    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.
   *
   * @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: []
  };
  /**
   * The version of jsPDF.
   * @name version
   * @type {string}
   * @memberof jsPDF#
   */
  jsPDF.version = "2.2.0";

  /* global jsPDF */

  var jsPDFAPI = jsPDF.API;
  var scaleFactor = 1;

  var pdfEscape = function(value) {
    return value
      .replace(/\\/g, "\\\\")
      .replace(/\(/g, "\\(")
      .replace(/\)/g, "\\)");
  };
  var pdfUnescape = function(value) {
    return value
      .replace(/\\\\/g, "\\")
      .replace(/\\\(/g, "(")
      .replace(/\\\)/g, ")");
  };

  var f2 = function(number) {
    return number.toFixed(2); // Ie, %.2f
  };

  var f5 = function(number) {
    return number.toFixed(5); // Ie, %.2f
  };

  jsPDFAPI.__acroform__ = {};
  var inherit = function(child, parent) {
    child.prototype = Object.create(parent.prototype);
    child.prototype.constructor = child;
  };

  var scale = function(x) {
    return x * scaleFactor;
  };

  var createFormXObject = function(formObject) {
    var xobj = new AcroFormXObject();
    var height = AcroFormAppearance.internal.getHeight(formObject) || 0;
    var width = AcroFormAppearance.internal.getWidth(formObject) || 0;
    xobj.BBox = [0, 0, Number(f2(width)), Number(f2(height))];
    return xobj;
  };

  /**
   * Bit-Operations
   */
  var setBit = (jsPDFAPI.__acroform__.setBit = function(number, bitPosition) {
    number = number || 0;
    bitPosition = bitPosition || 0;

    if (isNaN(number) || isNaN(bitPosition)) {
      throw new Error(
        "Invalid arguments passed to jsPDF.API.__acroform__.setBit"
      );
    }
    var bitMask = 1 << bitPosition;

    number |= bitMask;

    return number;
  });

  var clearBit = (jsPDFAPI.__acroform__.clearBit = function(number, bitPosition) {
    number = number || 0;
    bitPosition = bitPosition || 0;

    if (isNaN(number) || isNaN(bitPosition)) {
      throw new Error(
        "Invalid arguments passed to jsPDF.API.__acroform__.clearBit"
      );
    }
    var bitMask = 1 << bitPosition;

    number &= ~bitMask;

    return number;
  });

  var getBit = (jsPDFAPI.__acroform__.getBit = function(number, bitPosition) {
    if (isNaN(number) || isNaN(bitPosition)) {
      throw new Error(
        "Invalid arguments passed to jsPDF.API.__acroform__.getBit"
      );
    }
    return (number & (1 << bitPosition)) === 0 ? 0 : 1;
  });

  /*
   * Ff starts counting the bit position at 1 and not like javascript at 0
   */
  var getBitForPdf = (jsPDFAPI.__acroform__.getBitForPdf = function(
    number,
    bitPosition
  ) {
    if (isNaN(number) || isNaN(bitPosition)) {
      throw new Error(
        "Invalid arguments passed to jsPDF.API.__acroform__.getBitForPdf"
      );
    }
    return getBit(number, bitPosition - 1);
  });

  var setBitForPdf = (jsPDFAPI.__acroform__.setBitForPdf = function(
    number,
    bitPosition
  ) {
    if (isNaN(number) || isNaN(bitPosition)) {
      throw new Error(
        "Invalid arguments passed to jsPDF.API.__acroform__.setBitForPdf"
      );
    }
    return setBit(number, bitPosition - 1);
  });

  var clearBitForPdf = (jsPDFAPI.__acroform__.clearBitForPdf = function(
    number,
    bitPosition
  ) {
    if (isNaN(number) || isNaN(bitPosition)) {
      throw new Error(
        "Invalid arguments passed to jsPDF.API.__acroform__.clearBitForPdf"
      );
    }
    return clearBit(number, bitPosition - 1);
  });

  var calculateCoordinates = (jsPDFAPI.__acroform__.calculateCoordinates = function(
    args,
    scope
  ) {
    var getHorizontalCoordinate = scope.internal.getHorizontalCoordinate;
    var getVerticalCoordinate = scope.internal.getVerticalCoordinate;
    var x = args[0];
    var y = args[1];
    var w = args[2];
    var h = args[3];

    var coordinates = {};

    coordinates.lowerLeft_X = getHorizontalCoordinate(x) || 0;
    coordinates.lowerLeft_Y = getVerticalCoordinate(y + h) || 0;
    coordinates.upperRight_X = getHorizontalCoordinate(x + w) || 0;
    coordinates.upperRight_Y = getVerticalCoordinate(y) || 0;

    return [
      Number(f2(coordinates.lowerLeft_X)),
      Number(f2(coordinates.lowerLeft_Y)),
      Number(f2(coordinates.upperRight_X)),
      Number(f2(coordinates.upperRight_Y))
    ];
  });

  var calculateAppearanceStream = function(formObject) {
    if (formObject.appearanceStreamContent) {
      return formObject.appearanceStreamContent;
    }

    if (!formObject.V && !formObject.DV) {
      return;
    }

    // else calculate it

    var stream = [];
    var text = formObject._V || formObject.DV;
    var calcRes = calculateX(formObject, text);
    var fontKey = formObject.scope.internal.getFont(
      formObject.fontName,
      formObject.fontStyle
    ).id;

    //PDF 32000-1:2008, page 444
    stream.push("/Tx BMC");
    stream.push("q");
    stream.push("BT"); // Begin Text
    stream.push(formObject.scope.__private__.encodeColorString(formObject.color));
    stream.push("/" + fontKey + " " + f2(calcRes.fontSize) + " Tf");
    stream.push("1 0 0 1 0 0 Tm"); // Transformation Matrix
    stream.push(calcRes.text);
    stream.push("ET"); // End Text
    stream.push("Q");
    stream.push("EMC");

    var appearanceStreamContent = createFormXObject(formObject);
    appearanceStreamContent.scope = formObject.scope;
    appearanceStreamContent.stream = stream.join("\n");
    return appearanceStreamContent;
  };

  var calculateX = function(formObject, text) {
    var maxFontSize =
      formObject.fontSize === 0 ? formObject.maxFontSize : formObject.fontSize;
    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(" ");

    var fontSize = maxFontSize; // The Starting fontSize (The Maximum)
    var lineSpacing = 2;
    var borderPadding = 2;

    var height = AcroFormAppearance.internal.getHeight(formObject) || 0;
    height = height < 0 ? -height : height;
    var width = AcroFormAppearance.internal.getWidth(formObject) || 0;
    width = width < 0 ? -width : width;

    var isSmallerThanWidth = function(i, lastLine, fontSize) {
      if (i + 1 < textSplit.length) {
        var tmp = lastLine + " " + textSplit[i + 1];
        var TextWidth = calculateFontSpace(tmp, formObject, fontSize).width;
        var FieldWidth = width - 2 * borderPadding;
        return TextWidth <= FieldWidth;
      } else {
        return false;
      }
    };

    fontSize++;
    FontSize: while (fontSize > 0) {
      text = "";
      fontSize--;
      var textHeight = calculateFontSpace("3", formObject, fontSize).height;
      var startY = formObject.multiline
        ? height - fontSize
        : (height - textHeight) / 2;
      startY += lineSpacing;
      var startX;

      var lastY = startY;
      var firstWordInLine = 0,
        lastWordInLine = 0;
      var lastLength;

      if (fontSize <= 0) {
        // In case, the Text doesn't fit at all
        fontSize = 12;
        text = "(...) Tj\n";
        text +=
          "% Width of Text: " +
          calculateFontSpace(text, formObject, fontSize).width +
          ", FieldWidth:" +
          width +
          "\n";
        break;
      }

      var lastLine = "";
      var lineCount = 0;
      Line: for (var i in textSplit) {
        if (textSplit.hasOwnProperty(i)) {
          lastLine += textSplit[i] + " ";
          // Remove last blank
          lastLine =
            lastLine.substr(lastLine.length - 1) == " "
              ? lastLine.substr(0, lastLine.length - 1)
              : lastLine;
          var key = parseInt(i);
          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 = calculateFontSpace(line, formObject, fontSize).width;

          // Calculate startX
          switch (formObject.textAlign) {
            case "right":
              startX = width - lastLength - borderPadding;
              break;
            case "center":
              startX = (width - lastLength) / 2;
              break;
            case "left":
            default:
              startX = borderPadding;
              break;
          }
          text += f2(startX) + " " + f2(lastY) + " Td\n";
          text += "(" + pdfEscape(line) + ") Tj\n";
          // reset X in PDF
          text += -f2(startX) + " 0 Td\n";

          // After a Line, adjust y position
          lastY = -(fontSize + lineSpacing);

          // Reset for next iteration step
          lastLength = 0;
          firstWordInLine = lastWordInLine + 1;
          lineCount++;

          lastLine = "";
          continue Line;
        }
      }
      break;
    }

    returnValue.text = text;
    returnValue.fontSize = fontSize;

    return returnValue;
  };

  /**
   * Small workaround for calculating the TextMetric approximately.
   *
   * @param text
   * @param fontsize
   * @returns {TextMetrics} (Has Height and Width)
   */
  var calculateFontSpace = function(text, formObject, fontSize) {
    var font = formObject.scope.internal.getFont(
      formObject.fontName,
      formObject.fontStyle
    );
    var width =
      formObject.scope.getStringUnitWidth(text, {
        font: font,
        fontSize: parseFloat(fontSize),
        charSpace: 0
      }) * parseFloat(fontSize);
    var height =
      formObject.scope.getStringUnitWidth("3", {
        font: font,
        fontSize: parseFloat(fontSize),
        charSpace: 0
      }) *
      parseFloat(fontSize) *
      1.5;
    return { height: height, width: width };
  };

  var acroformPluginTemplate = {
    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,
    isInitialized: false
  };

  var annotReferenceCallback = function(scope) {
    //set objId to undefined and force it to get a new objId on buildDocument
    scope.internal.acroformPlugin.acroFormDictionaryRoot.objId = undefined;
    var fields = scope.internal.acroformPlugin.acroFormDictionaryRoot.Fields;
    for (var i in fields) {
      if (fields.hasOwnProperty(i)) {
        var formObject = fields[i];
        //set objId to undefined and force it to get a new objId on buildDocument
        formObject.objId = undefined;
        // add Annot Reference!
        if (formObject.hasAnnotation) {
          // If theres an Annotation Widget in the Form Object, put the
          // Reference in the /Annot array
          createAnnotationReference(formObject, scope);
        }
      }
    }
  };

  var putForm = function(formObject) {
    if (formObject.scope.internal.acroformPlugin.printedOut) {
      formObject.scope.internal.acroformPlugin.printedOut = false;
      formObject.scope.internal.acroformPlugin.acroFormDictionaryRoot = null;
    }
    formObject.scope.internal.acroformPlugin.acroFormDictionaryRoot.Fields.push(
      formObject
    );
  };
  /**
   * Create the Reference to the widgetAnnotation, so that it gets referenced
   * in the Annot[] int the+ (Requires the Annotation Plugin)
   */
  var createAnnotationReference = function(object, scope) {
    var options = {
      type: "reference",
      object: object
    };
    var findEntry = function(entry) {
      return entry.type === options.type && entry.object === options.object;
    };
    if (
      scope.internal
        .getPageInfo(object.page)
        .pageContext.annotations.find(findEntry) === undefined
    ) {
      scope.internal
        .getPageInfo(object.page)
        .pageContext.annotations.push(options);
    }
  };

  // Callbacks

  var putCatalogCallback = function(scope) {
    // Put reference to AcroForm to DocumentCatalog
    if (
      typeof scope.internal.acroformPlugin.acroFormDictionaryRoot !== "undefined"
    ) {
      // for safety, shouldn't normally be the case
      scope.internal.write(
        "/AcroForm " +
          scope.internal.acroformPlugin.acroFormDictionaryRoot.objId +
          " " +
          0 +
          " R"
      );
    } else {
      throw new Error("putCatalogCallback: Root missing.");
    }
  };

  /**
   * Adds /Acroform X 0 R to Document Catalog, and creates the AcroForm
   * Dictionary
   */
  var AcroFormDictionaryCallback = function(scope) {
    // Remove event
    scope.internal.events.unsubscribe(
      scope.internal.acroformPlugin.acroFormDictionaryRoot._eventID
    );
    delete scope.internal.acroformPlugin.acroFormDictionaryRoot._eventID;
    scope.internal.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(fieldArray, scope) {
    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
      scope.internal.newObjectDeferredBegin(
        scope.internal.acroformPlugin.acroFormDictionaryRoot.objId,
        true
      );
      scope.internal.acroformPlugin.acroFormDictionaryRoot.putStream();
    }

    fieldArray =
      fieldArray || scope.internal.acroformPlugin.acroFormDictionaryRoot.Kids;

    for (var i in fieldArray) {
      if (fieldArray.hasOwnProperty(i)) {
        var fieldObject = fieldArray[i];
        var keyValueList = [];
        var oldRect = fieldObject.Rect;

        if (fieldObject.Rect) {
          fieldObject.Rect = calculateCoordinates(fieldObject.Rect, scope);
        }

        // Start Writing the Object
        scope.internal.newObjectDeferredBegin(fieldObject.objId, true);

        fieldObject.DA = AcroFormAppearance.createDefaultAppearanceStream(
          fieldObject
        );

        if (
          typeof fieldObject === "object" &&
          typeof fieldObject.getKeyValueListForStream === "function"
        ) {
          keyValueList = fieldObject.getKeyValueListForStream();
        }

        fieldObject.Rect = oldRect;

        if (
          fieldObject.hasAppearanceStream &&
          !fieldObject.appearanceStreamContent
        ) {
          // Calculate Appearance
          var appearance = calculateAppearanceStream(fieldObject);
          keyValueList.push({ key: "AP", value: "<</N " + appearance + ">>" });

          scope.internal.acroformPlugin.xForms.push(appearance);
        }

        // Assume AppearanceStreamContent is a Array with N,R,D (at least
        // one of them!)
        if (fieldObject.appearanceStreamContent) {
          var appearanceStreamString = "";
          // Iterate over N,R and D
          for (var k in fieldObject.appearanceStreamContent) {
            if (fieldObject.appearanceStreamContent.hasOwnProperty(k)) {
              var value = fieldObject.appearanceStreamContent[k];
              appearanceStreamString += "/" + k + " ";
              appearanceStreamString += "<<";
              if (Object.keys(value).length >= 1 || Array.isArray(value)) {
                // appearanceStream is an Array or Object!
                for (var i in value) {
                  if (value.hasOwnProperty(i)) {
                    var obj = value[i];
                    if (typeof obj === "function") {
                      // if Function is referenced, call it in order
                      // to get the FormXObject
                      obj = obj.call(scope, fieldObject);
                    }
                    appearanceStreamString += "/" + i + " " + obj + " ";

                    // In case the XForm is already used, e.g. OffState
                    // of CheckBoxes, don't add it
                    if (!(scope.internal.acroformPlugin.xForms.indexOf(obj) >= 0))
                      scope.internal.acroformPlugin.xForms.push(obj);
                  }
                }
              } else {
                obj = value;
                if (typeof obj === "function") {
                  // if Function is referenced, call it in order to
                  // get the FormXObject
                  obj = obj.call(scope, fieldObject);
                }
                appearanceStreamString += "/" + i + " " + obj;
                if (!(scope.internal.acroformPlugin.xForms.indexOf(obj) >= 0))
                  scope.internal.acroformPlugin.xForms.push(obj);
              }
              appearanceStreamString += ">>";
            }
          }

          // appearance stream is a normal Object..
          keyValueList.push({
            key: "AP",
            value: "<<\n" + appearanceStreamString + ">>"
          });
        }

        scope.internal.putStream({
          additionalKeyValues: keyValueList,
          objectId: fieldObject.objId
        });

        scope.internal.out("endobj");
      }
    }
    if (standardFields) {
      createXFormObjectCallback(scope.internal.acroformPlugin.xForms, scope);
    }
  };

  var createXFormObjectCallback = function(fieldArray, scope) {
    for (var i in fieldArray) {
      if (fieldArray.hasOwnProperty(i)) {
        var key = i;
        var fieldObject = fieldArray[i];
        // Start Writing the Object
        scope.internal.newObjectDeferredBegin(fieldObject.objId, true);

        if (
          typeof fieldObject === "object" &&
          typeof fieldObject.putStream === "function"
        ) {
          fieldObject.putStream();
        }
        delete fieldArray[key];
      }
    }
  };

  var initializeAcroForm = function(scope, formObject) {
    formObject.scope = scope;
    if (
      scope.internal !== undefined &&
      (scope.internal.acroformPlugin === undefined ||
        scope.internal.acroformPlugin.isInitialized === false)
    ) {
      AcroFormField.FieldNum = 0;
      scope.internal.acroformPlugin = JSON.parse(
        JSON.stringify(acroformPluginTemplate)
      );
      if (scope.internal.acroformPlugin.acroFormDictionaryRoot) {
        throw new Error("Exception while creating AcroformDictionary");
      }
      scaleFactor = scope.internal.scaleFactor;
      // The Object Number of the AcroForm Dictionary
      scope.internal.acroformPlugin.acroFormDictionaryRoot = new AcroFormDictionary();
      scope.internal.acroformPlugin.acroFormDictionaryRoot.scope = scope;

      // add Callback for creating the AcroForm Dictionary
      scope.internal.acroformPlugin.acroFormDictionaryRoot._eventID = scope.internal.events.subscribe(
        "postPutResources",
        function() {
          AcroFormDictionaryCallback(scope);
        }
      );

      scope.internal.events.subscribe("buildDocument", function() {
        annotReferenceCallback(scope);
      }); // buildDocument

      // Register event, that is triggered when the DocumentCatalog is
      // written, in order to add /AcroForm

      scope.internal.events.subscribe("putCatalog", function() {
        putCatalogCallback(scope);
      });

      // Register event, that creates all Fields
      scope.internal.events.subscribe("postPutPages", function(fieldArray) {
        createFieldCallback(fieldArray, scope);
      });

      scope.internal.acroformPlugin.isInitialized = true;
    }
  };

  //PDF 32000-1:2008, page 26, 7.3.6
  var arrayToPdfArray = (jsPDFAPI.__acroform__.arrayToPdfArray = function(
    array,
    objId,
    scope
  ) {
    var encryptor = function(data) {
      return data;
    };
    if (Array.isArray(array)) {
      var content = "[";
      for (var i = 0; i < array.length; i++) {
        if (i !== 0) {
          content += " ";
        }
        switch (typeof array[i]) {
          case "boolean":
          case "number":
          case "object":
            content += array[i].toString();
            break;
          case "string":
            if (array[i].substr(0, 1) !== "/") {
              if (typeof objId !== "undefined" && scope)
                encryptor = scope.internal.getEncryptor(objId);
              content += "(" + pdfEscape(encryptor(array[i].toString())) + ")";
            } else {
              content += array[i].toString();
            }
            break;
        }
      }
      content += "]";
      return content;
    }
    throw new Error(
      "Invalid argument passed to jsPDF.__acroform__.arrayToPdfArray"
    );
  });
  function getMatches(string, regex, index) {
    index || (index = 1); // default to the first capturing group
    var matches = [];
    var match;
    while ((match = regex.exec(string))) {
      matches.push(match[index]);
    }
    return matches;
  }
  var pdfArrayToStringArray = function(array) {
    var result = [];
    if (typeof array === "string") {
      result = getMatches(array, /\((.*?)\)/g);
    }
    return result;
  };

  var toPdfString = function(string, objId, scope) {
    var encryptor = function(data) {
      return data;
    };
    if (typeof objId !== "undefined" && scope)
      encryptor = scope.internal.getEncryptor(objId);
    string = string || "";
    string.toString();
    string = "(" + pdfEscape(encryptor(string)) + ")";
    return string;
  };

  // ##########################
  // Classes
  // ##########################

  /**
   * @class AcroFormPDFObject
   * @classdesc A AcroFormPDFObject
   */
  var AcroFormPDFObject = function() {
    this._objId = undefined;
    this._scope = undefined;

    /**
     * @name AcroFormPDFObject#objId
     * @type {any}
     */
    Object.defineProperty(this, "objId", {
      get: function() {
        if (typeof this._objId === "undefined") {
          if (typeof this.scope === "undefined") {
            return undefined;
          }
          this._objId = this.scope.internal.newObjectDeferred();
        }
        return this._objId;
      },
      set: function(value) {
        this._objId = value;
      }
    });
    Object.defineProperty(this, "scope", {
      value: this._scope,
      writable: true
    });
  };

  /**
   * @function AcroFormPDFObject.toString
   */
  AcroFormPDFObject.prototype.toString = function() {
    return this.objId + " 0 R";
  };

  AcroFormPDFObject.prototype.putStream = function() {
    var keyValueList = this.getKeyValueListForStream();
    this.scope.internal.putStream({
      data: this.stream,
      additionalKeyValues: keyValueList,
      objectId: this.objId
    });
    this.scope.internal.out("endobj");
  };

  /**
   * Returns an key-value-List of all non-configurable Variables from the Object
   *
   * @name getKeyValueListForStream
   * @returns {string}
   */
  AcroFormPDFObject.prototype.getKeyValueListForStream = function() {
    var keyValueList = [];
    var keys = Object.getOwnPropertyNames(this).filter(function(key) {
      return (
        key != "content" &&
        key != "appearanceStreamContent" &&
        key != "scope" &&
        key != "objId" &&
        key.substring(0, 1) != "_"
      );
    });

    for (var i in keys) {
      if (Object.getOwnPropertyDescriptor(this, keys[i]).configurable === false) {
        var key = keys[i];
        var value = this[key];

        if (value) {
          if (Array.isArray(value)) {
            keyValueList.push({
              key: key,
              value: arrayToPdfArray(value, this.objId, this.scope)
            });
          } else if (value instanceof AcroFormPDFObject) {
            // In case it is a reference to another PDFObject,
            // take the reference number
            value.scope = this.scope;
            keyValueList.push({ key: key, value: value.objId + " 0 R" });
          } else if (typeof value !== "function") {
            keyValueList.push({ key: key, value: value });
          }
        }
      }
    }
    return keyValueList;
  };

  var AcroFormXObject = function() {
    AcroFormPDFObject.call(this);

    Object.defineProperty(this, "Type", {
      value: "/XObject",
      configurable: false,
      writable: true
    });

    Object.defineProperty(this, "Subtype", {
      value: "/Form",
      configurable: false,
      writable: true
    });

    Object.defineProperty(this, "FormType", {
      value: 1,
      configurable: false,
      writable: true
    });

    var _BBox = [];
    Object.defineProperty(this, "BBox", {
      configurable: false,
      get: function() {
        return _BBox;
      },
      set: function(value) {
        _BBox = value;
      }
    });

    Object.defineProperty(this, "Resources", {
      value: "2 0 R",
      configurable: false,
      writable: true
    });

    var _stream;
    Object.defineProperty(this, "stream", {
      enumerable: false,
      configurable: true,
      set: function(value) {
        _stream = value.trim();
      },
      get: function() {
        if (_stream) {
          return _stream;
        } else {
          return null;
        }
      }
    });
  };

  inherit(AcroFormXObject, AcroFormPDFObject);

  var AcroFormDictionary = function() {
    AcroFormPDFObject.call(this);

    var _Kids = [];

    Object.defineProperty(this, "Kids", {
      enumerable: false,
      configurable: true,
      get: function() {
        if (_Kids.length > 0) {
          return _Kids;
        } else {
          return undefined;
        }
      }
    });
    Object.defineProperty(this, "Fields", {
      enumerable: false,
      configurable: false,
      get: function() {
        return _Kids;
      }
    });

    // Default Appearance
    var _DA;
    Object.defineProperty(this, "DA", {
      enumerable: false,
      configurable: false,
      get: function() {
        if (!_DA) {
          return undefined;
        }
        var encryptor = function(data) {
          return data;
        };
        if (this.scope) encryptor = this.scope.internal.getEncryptor(this.objId);
        return "(" + pdfEscape(encryptor(_DA)) + ")";
      },
      set: function(value) {
        _DA = value;
      }
    });
  };

  inherit(AcroFormDictionary, AcroFormPDFObject);

  /**
   * The Field Object contains the Variables, that every Field needs
   *
   * @class AcroFormField
   * @classdesc An AcroForm FieldObject
   */
  var AcroFormField = function() {
    AcroFormPDFObject.call(this);

    //Annotation-Flag See Table 165
    var _F = 4;
    Object.defineProperty(this, "F", {
      enumerable: false,
      configurable: false,
      get: function() {
        return _F;
      },
      set: function(value) {
        if (!isNaN(value)) {
          _F = value;
        } else {
          throw new Error(
            'Invalid value "' + value + '" for attribute F supplied.'
          );
        }
      }
    });

    /**
     * (PDF 1.2) If set, print the annotation when the page is printed. If clear, never print the annotation, regardless of wether is is displayed on the screen.
     * NOTE 2 This can be useful for annotations representing interactive pushbuttons, which would serve no meaningful purpose on the printed page.
     *
     * @name AcroFormField#showWhenPrinted
     * @default true
     * @type {boolean}
     */
    Object.defineProperty(this, "showWhenPrinted", {
      enumerable: true,
      configurable: true,
      get: function() {
        return Boolean(getBitForPdf(_F, 3));
      },
      set: function(value) {
        if (Boolean(value) === true) {
          this.F = setBitForPdf(_F, 3);
        } else {
          this.F = clearBitForPdf(_F, 3);
        }
      }
    });

    var _Ff = 0;
    Object.defineProperty(this, "Ff", {
      enumerable: false,
      configurable: false,
      get: function() {
        return _Ff;
      },
      set: function(value) {
        if (!isNaN(value)) {
          _Ff = value;
        } else {
          throw new Error(
            'Invalid value "' + value + '" for attribute Ff supplied.'
          );
        }
      }
    });

    var _Rect = [];
    Object.defineProperty(this, "Rect", {
      enumerable: false,
      configurable: false,
      get: function() {
        if (_Rect.length === 0) {
          return undefined;
        }
        return _Rect;
      },
      set: function(value) {
        if (typeof value !== "undefined") {
          _Rect = value;
        } else {
          _Rect = [];
        }
      }
    });

    /**
     * The x-position of the field.
     *
     * @name AcroFormField#x
     * @default null
     * @type {number}
     */
    Object.defineProperty(this, "x", {
      enumerable: true,
      configurable: true,
      get: function() {
        if (!_Rect || isNaN(_Rect[0])) {
          return 0;
        }
        return _Rect[0];
      },
      set: function(value) {
        _Rect[0] = value;
      }
    });

    /**
     * The y-position of the field.
     *
     * @name AcroFormField#y
     * @default null
     * @type {number}
     */
    Object.defineProperty(this, "y", {
      enumerable: true,
      configurable: true,
      get: function() {
        if (!_Rect || isNaN(_Rect[1])) {
          return 0;
        }
        return _Rect[1];
      },
      set: function(value) {
        _Rect[1] = value;
      }
    });

    /**
     * The width of the field.
     *
     * @name AcroFormField#width
     * @default null
     * @type {number}
     */
    Object.defineProperty(this, "width", {
      enumerable: true,
      configurable: true,
      get: function() {
        if (!_Rect || isNaN(_Rect[2])) {
          return 0;
        }
        return _Rect[2];
      },
      set: function(value) {
        _Rect[2] = value;
      }
    });

    /**
     * The height of the field.
     *
     * @name AcroFormField#height
     * @default null
     * @type {number}
     */
    Object.defineProperty(this, "height", {
      enumerable: true,
      configurable: true,
      get: function() {
        if (!_Rect || isNaN(_Rect[3])) {
          return 0;
        }
        return _Rect[3];
      },
      set: function(value) {
        _Rect[3] = value;
      }
    });

    var _FT = "";
    Object.defineProperty(this, "FT", {
      enumerable: true,
      configurable: false,
      get: function() {
        return _FT;
      },
      set: function(value) {
        switch (value) {
          case "/Btn":
          case "/Tx":
          case "/Ch":
          case "/Sig":
            _FT = value;
            break;
          default:
            throw new Error(
              'Invalid value "' + value + '" for attribute FT supplied.'
            );
        }
      }
    });

    var _T = null;

    Object.defineProperty(this, "T", {
      enumerable: true,
      configurable: false,
      get: function() {
        if (!_T || _T.length < 1) {
          // In case of a Child from a Radio´Group, you don't need a FieldName
          if (this instanceof AcroFormChildClass) {
            return undefined;
          }
          _T = "FieldObject" + AcroFormField.FieldNum++;
        }
        var encryptor = function(data) {
          return data;
        };
        if (this.scope) encryptor = this.scope.internal.getEncryptor(this.objId);
        return "(" + pdfEscape(encryptor(_T)) + ")";
      },
      set: function(value) {
        _T = value.toString();
      }
    });

    /**
     * (Optional) The partial field name (see 12.7.3.2, “Field Names”).
     *
     * @name AcroFormField#fieldName
     * @default null
     * @type {string}
     */
    Object.defineProperty(this, "fieldName", {
      configurable: true,
      enumerable: true,
      get: function() {
        return _T;
      },
      set: function(value) {
        _T = value;
      }
    });

    var _fontName = "helvetica";
    /**
     * The fontName of the font to be used.
     *
     * @name AcroFormField#fontName
     * @default 'helvetica'
     * @type {string}
     */
    Object.defineProperty(this, "fontName", {
      enumerable: true,
      configurable: true,
      get: function() {
        return _fontName;
      },
      set: function(value) {
        _fontName = value;
      }
    });

    var _fontStyle = "normal";
    /**
     * The fontStyle of the font to be used.
     *
     * @name AcroFormField#fontStyle
     * @default 'normal'
     * @type {string}
     */
    Object.defineProperty(this, "fontStyle", {
      enumerable: true,
      configurable: true,
      get: function() {
        return _fontStyle;
      },
      set: function(value) {
        _fontStyle = value;
      }
    });

    var _fontSize = 0;
    /**
     * The fontSize of the font to be used.
     *
     * @name AcroFormField#fontSize
     * @default 0 (for auto)
     * @type {number}
     */
    Object.defineProperty(this, "fontSize", {
      enumerable: true,
      configurable: true,
      get: function() {
        return _fontSize;
      },
      set: function(value) {
        _fontSize = value;
      }
    });

    var _maxFontSize = undefined;
    /**
     * The maximum fontSize of the font to be used.
     *
     * @name AcroFormField#maxFontSize
     * @default 0 (for auto)
     * @type {number}
     */
    Object.defineProperty(this, "maxFontSize", {
      enumerable: true,
      configurable: true,
      get: function() {
        if (_maxFontSize === undefined) {
          // use the old default value here - the value is some kind of random as it depends on the scaleFactor (user unit)
          // ("50" is transformed to the "user space" but then used in "pdf space")
          return 50 / scaleFactor;
        } else {
          return _maxFontSize;
        }
      },
      set: function(value) {
        _maxFontSize = value;
      }
    });

    var _color = "black";
    /**
     * The color of the text
     *
     * @name AcroFormField#color
     * @default 'black'
     * @type {string|rgba}
     */
    Object.defineProperty(this, "color", {
      enumerable: true,
      configurable: true,
      get: function() {
        return _color;
      },
      set: function(value) {
        _color = value;
      }
    });

    var _DA = "/F1 0 Tf 0 g";
    // Defines the default appearance (Needed for variable Text)
    Object.defineProperty(this, "DA", {
      enumerable: true,
      configurable: false,
      get: function() {
        if (
          !_DA ||
          this instanceof AcroFormChildClass ||
          this instanceof AcroFormTextField
        ) {
          return undefined;
        }
        return toPdfString(_DA, this.objId, this.scope);
      },
      set: function(value) {
        value = value.toString();
        _DA = value;
      }
    });

    var _DV = null;
    Object.defineProperty(this, "DV", {
      enumerable: false,
      configurable: false,
      get: function() {
        if (!_DV) {
          return undefined;
        }
        if (this instanceof AcroFormButton === false) {
          return toPdfString(_DV, this.objId, this.scope);
        }
        return _DV;
      },
      set: function(value) {
        value = value.toString();
        if (this instanceof AcroFormButton === false) {
          if (value.substr(0, 1) === "(") {
            _DV = pdfUnescape(value.substr(1, value.length - 2));
          } else {
            _DV = pdfUnescape(value);
          }
        } else {
          _DV = value;
        }
      }
    });

    /**
     * (Optional; inheritable) The default value to which the field reverts when a reset-form action is executed (see 12.7.5.3, “Reset-Form Action”). The format of this value is the same as that of value.
     *
     * @name AcroFormField#defaultValue
     * @default null
     * @type {any}
     */
    Object.defineProperty(this, "defaultValue", {
      enumerable: true,
      configurable: true,
      get: function() {
        if (this instanceof AcroFormButton === true) {
          return pdfUnescape(_DV.substr(1, _DV.length - 1));
        } else {
          return _DV;
        }
      },
      set: function(value) {
        value = value.toString();
        if (this instanceof AcroFormButton === true) {
          _DV = "/" + value;
        } else {
          _DV = value;
        }
      }
    });

    var _V = null;
    Object.defineProperty(this, "_V", {
      enumerable: false,
      configurable: false,
      get: function() {
        if (!_V) {
          return undefined;
        }
        return _V;
      },
      set: function(value) {
        this.V = value;
      }
    });
    Object.defineProperty(this, "V", {
      enumerable: false,
      configurable: false,
      get: function() {
        if (!_V) {
          return undefined;
        }
        if (this instanceof AcroFormButton === false) {
          return toPdfString(_V, this.objId, this.scope);
        }
        return _V;
      },
      set: function(value) {
        value = value.toString();
        if (this instanceof AcroFormButton === false) {
          if (value.substr(0, 1) === "(") {
            _V = pdfUnescape(value.substr(1, value.length - 2));
          } else {
            _V = pdfUnescape(value);
          }
        } else {
          _V = value;
        }
      }
    });

    /**
     * (Optional; inheritable) The field’s value, whose format varies depending on the field type. See the descriptions of individual field types for further information.
     *
     * @name AcroFormField#value
     * @default null
     * @type {any}
     */
    Object.defineProperty(this, "value", {
      enumerable: true,
      configurable: true,
      get: function() {
        if (this instanceof AcroFormButton === true) {
          return pdfUnescape(_V.substr(1, _V.length - 1));
        } else {
          return _V;
        }
      },
      set: function(value) {
        value = value.toString();
        if (this instanceof AcroFormButton === true) {
          _V = "/" + value;
        } else {
          _V = value;
        }
      }
    });

    /**
     * Check if field has annotations
     *
     * @name AcroFormField#hasAnnotation
     * @readonly
     * @type {boolean}
     */
    Object.defineProperty(this, "hasAnnotation", {
      enumerable: true,
      configurable: true,
      get: function() {
        return this.Rect;
      }
    });

    Object.defineProperty(this, "Type", {
      enumerable: true,
      configurable: false,
      get: function() {
        return this.hasAnnotation ? "/Annot" : null;
      }
    });

    Object.defineProperty(this, "Subtype", {
      enumerable: true,
      configurable: false,
      get: function() {
        return this.hasAnnotation ? "/Widget" : null;
      }
    });

    var _hasAppearanceStream = false;
    /**
     * true if field has an appearanceStream
     *
     * @name AcroFormField#hasAppearanceStream
     * @readonly
     * @type {boolean}
     */
    Object.defineProperty(this, "hasAppearanceStream", {
      enumerable: true,
      configurable: true,
      get: function() {
        return _hasAppearanceStream;
      },
      set: function(value) {
        value = Boolean(value);
        _hasAppearanceStream = value;
      }
    });

    /**
     * The page on which the AcroFormField is placed
     *
     * @name AcroFormField#page
     * @type {number}
     */
    var _page;
    Object.defineProperty(this, "page", {
      enumerable: true,
      configurable: true,
      get: function() {
        if (!_page) {
          return undefined;
        }
        return _page;
      },
      set: function(value) {
        _page = value;
      }
    });

    /**
     * If set, the user may not change the value of the field. Any associated widget annotations will not interact with the user; that is, they will not respond to mouse clicks or change their appearance in response to mouse motions. This flag is useful for fields whose values are computed or imported from a database.
     *
     * @name AcroFormField#readOnly
     * @default false
     * @type {boolean}
     */
    Object.defineProperty(this, "readOnly", {
      enumerable: true,
      configurable: true,
      get: function() {
        return Boolean(getBitForPdf(this.Ff, 1));
      },
      set: function(value) {
        if (Boolean(value) === true) {
          this.Ff = setBitForPdf(this.Ff, 1);
        } else {
          this.Ff = clearBitForPdf(this.Ff, 1);
        }
      }
    });

    /**
     * If set, the field shall have a value at the time it is exported by a submitform action (see 12.7.5.2, “Submit-Form Action”).
     *
     * @name AcroFormField#required
     * @default false
     * @type {boolean}
     */
    Object.defineProperty(this, "required", {
      enumerable: true,
      configurable: true,
      get: function() {
        return Boolean(getBitForPdf(this.Ff, 2));
      },
      set: function(value) {
        if (Boolean(value) === true) {
          this.Ff = setBitForPdf(this.Ff, 2);
        } else {
          this.Ff = clearBitForPdf(this.Ff, 2);
        }
      }
    });

    /**
     * If set, the field shall not be exported by a submit-form action (see 12.7.5.2, “Submit-Form Action”)
     *
     * @name AcroFormField#noExport
     * @default false
     * @type {boolean}
     */
    Object.defineProperty(this, "noExport", {
      enumerable: true,
      configurable: true,
      get: function() {
        return Boolean(getBitForPdf(this.Ff, 3));
      },
      set: function(value) {
        if (Boolean(value) === true) {
          this.Ff = setBitForPdf(this.Ff, 3);
        } else {
          this.Ff = clearBitForPdf(this.Ff, 3);
        }
      }
    });

    var _Q = null;
    Object.defineProperty(this, "Q", {
      enumerable: true,
      configurable: false,
      get: function() {
        if (_Q === null) {
          return undefined;
        }
        return _Q;
      },
      set: function(value) {
        if ([0, 1, 2].indexOf(value) !== -1) {
          _Q = value;
        } else {
          throw new Error(
            'Invalid value "' + value + '" for attribute Q supplied.'
          );
        }
      }
    });

    /**
     * (Optional; inheritable) A code specifying the form of quadding (justification) that shall be used in displaying the text:
     * 'left', 'center', 'right'
     *
     * @name AcroFormField#textAlign
     * @default 'left'
     * @type {string}
     */
    Object.defineProperty(this, "textAlign", {
      get: function() {
        var result;
        switch (_Q) {
          case 0:
          default:
            result = "left";
            break;
          case 1:
            result = "center";
            break;
          case 2:
            result = "right";
            break;
        }
        return result;
      },
      configurable: true,
      enumerable: true,
      set: function(value) {
        switch (value) {
          case "right":
          case 2:
            _Q = 2;
            break;
          case "center":
          case 1:
            _Q = 1;
            break;
          case "left":
          case 0:
          default:
            _Q = 0;
        }
      }
    });
  };

  inherit(AcroFormField, AcroFormPDFObject);

  /**
   * @class AcroFormChoiceField
   * @extends AcroFormField
   */
  var AcroFormChoiceField = function() {
    AcroFormField.call(this);
    // Field Type = Choice Field
    this.FT = "/Ch";
    // options
    this.V = "()";

    this.fontName = "zapfdingbats";
    // Top Index
    var _TI = 0;

    Object.defineProperty(this, "TI", {
      enumerable: true,
      configurable: false,
      get: function() {
        return _TI;
      },
      set: function(value) {
        _TI = value;
      }
    });

    /**
     * (Optional) For scrollable list boxes, the top index (the index in the Opt array of the first option visible in the list). Default value: 0.
     *
     * @name AcroFormChoiceField#topIndex
     * @default 0
     * @type {number}
     */
    Object.defineProperty(this, "topIndex", {
      enumerable: true,
      configurable: true,
      get: function() {
        return _TI;
      },
      set: function(value) {
        _TI = value;
      }
    });

    var _Opt = [];
    Object.defineProperty(this, "Opt", {
      enumerable: true,
      configurable: false,
      get: function() {
        return arrayToPdfArray(_Opt, this.objId, this.scope);
      },
      set: function(value) {
        _Opt = pdfArrayToStringArray(value);
      }
    });

    /**
     * @memberof AcroFormChoiceField
     * @name getOptions
     * @function
     * @instance
     * @returns {array} array of Options
     */
    this.getOptions = function() {
      return _Opt;
    };

    /**
     * @memberof AcroFormChoiceField
     * @name setOptions
     * @function
     * @instance
     * @param {array} value
     */
    this.setOptions = function(value) {
      _Opt = value;
      if (this.sort) {
        _Opt.sort();
      }
    };

    /**
     * @memberof AcroFormChoiceField
     * @name addOption
     * @function
     * @instance
     * @param {string} value
     */
    this.addOption = function(value) {
      value = value || "";
      value = value.toString();
      _Opt.push(value);
      if (this.sort) {
        _Opt.sort();
      }
    };

    /**
     * @memberof AcroFormChoiceField
     * @name removeOption
     * @function
     * @instance
     * @param {string} value
     * @param {boolean} allEntries (default: false)
     */
    this.removeOption = function(value, allEntries) {
      allEntries = allEntries || false;
      value = value || "";
      value = value.toString();

      while (_Opt.indexOf(value) !== -1) {
        _Opt.splice(_Opt.indexOf(value), 1);
        if (allEntries === false) {
          break;
        }
      }
    };

    /**
     * If set, the field is a combo box; if clear, the field is a list box.
     *
     * @name AcroFormChoiceField#combo
     * @default false
     * @type {boolean}
     */
    Object.defineProperty(this, "combo", {
      enumerable: true,
      configurable: true,
      get: function() {
        return Boolean(getBitForPdf(this.Ff, 18));
      },
      set: function(value) {
        if (Boolean(value) === true) {
          this.Ff = setBitForPdf(this.Ff, 18);
        } else {
          this.Ff = clearBitForPdf(this.Ff, 18);
        }
      }
    });

    /**
     * If set, the combo box shall include an editable text box as well as a drop-down list; if clear, it shall include only a drop-down list. This flag shall be used only if the Combo flag is set.
     *
     * @name AcroFormChoiceField#edit
     * @default false
     * @type {boolean}
     */
    Object.defineProperty(this, "edit", {
      enumerable: true,
      configurable: true,
      get: function() {
        return Boolean(getBitForPdf(this.Ff, 19));
      },
      set: function(value) {
        //PDF 32000-1:2008, page 444
        if (this.combo === true) {
          if (Boolean(value) === true) {
            this.Ff = setBitForPdf(this.Ff, 19);
          } else {
            this.Ff = clearBitForPdf(this.Ff, 19);
          }
        }
      }
    });

    /**
     * If set, the field’s option items shall be sorted alphabetically. This flag is intended for use by writers, not by readers. Conforming readers shall display the options in the order in which they occur in the Opt array (see Table 231).
     *
     * @name AcroFormChoiceField#sort
     * @default false
     * @type {boolean}
     */
    Object.defineProperty(this, "sort", {
      enumerable: true,
      configurable: true,
      get: function() {
        return Boolean(getBitForPdf(this.Ff, 20));
      },
      set: function(value) {
        if (Boolean(value) === true) {
          this.Ff = setBitForPdf(this.Ff, 20);
          _Opt.sort();
        } else {
          this.Ff = clearBitForPdf(this.Ff, 20);
        }
      }
    });

    /**
     * (PDF 1.4) If set, more than one of the field’s option items may be selected simultaneously; if clear, at most one item shall be selected
     *
     * @name AcroFormChoiceField#multiSelect
     * @default false
     * @type {boolean}
     */
    Object.defineProperty(this, "multiSelect", {
      enumerable: true,
      configurable: true,
      get: function() {
        return Boolean(getBitForPdf(this.Ff, 22));
      },
      set: function(value) {
        if (Boolean(value) === true) {
          this.Ff = setBitForPdf(this.Ff, 22);
        } else {
          this.Ff = clearBitForPdf(this.Ff, 22);
        }
      }
    });

    /**
     * (PDF 1.4) If set, text entered in the field shall not be spellchecked. This flag shall not be used unless the Combo and Edit flags are both set.
     *
     * @name AcroFormChoiceField#doNotSpellCheck
     * @default false
     * @type {boolean}
     */
    Object.defineProperty(this, "doNotSpellCheck", {
      enumerable: true,
      configurable: true,
      get: function() {
        return Boolean(getBitForPdf(this.Ff, 23));
      },
      set: function(value) {
        if (Boolean(value) === true) {
          this.Ff = setBitForPdf(this.Ff, 23);
        } else {
          this.Ff = clearBitForPdf(this.Ff, 23);
        }
      }
    });

    /**
     * (PDF 1.5) If set, the new value shall be committed as soon as a selection is made (commonly with the pointing device). In this case, supplying a value for a field involves three actions: selecting the field for fill-in, selecting a choice for the fill-in value, and leaving that field, which finalizes or “commits” the data choice and triggers any actions associated with the entry or changing of this data. If this flag is on, then processing does not wait for leaving the field action to occur, but immediately proceeds to the third step.
     * This option enables applications to perform an action once a selection is made, without requiring the user to exit the field. If clear, the new value is not committed until the user exits the field.
     *
     * @name AcroFormChoiceField#commitOnSelChange
     * @default false
     * @type {boolean}
     */
    Object.defineProperty(this, "commitOnSelChange", {
      enumerable: true,
      configurable: true,
      get: function() {
        return Boolean(getBitForPdf(this.Ff, 27));
      },
      set: function(value) {
        if (Boolean(value) === true) {
          this.Ff = setBitForPdf(this.Ff, 27);
        } else {
          this.Ff = clearBitForPdf(this.Ff, 27);
        }
      }
    });

    this.hasAppearanceStream = false;
  };
  inherit(AcroFormChoiceField, AcroFormField);

  /**
   * @class AcroFormListBox
   * @extends AcroFormChoiceField
   * @extends AcroFormField
   */
  var AcroFormListBox = function() {
    AcroFormChoiceField.call(this);
    this.fontName = "helvetica";

    //PDF 32000-1:2008, page 444
    this.combo = false;
  };
  inherit(AcroFormListBox, AcroFormChoiceField);

  /**
   * @class AcroFormComboBox
   * @extends AcroFormListBox
   * @extends AcroFormChoiceField
   * @extends AcroFormField
   */
  var AcroFormComboBox = function() {
    AcroFormListBox.call(this);
    this.combo = true;
  };
  inherit(AcroFormComboBox, AcroFormListBox);

  /**
   * @class AcroFormEditBox
   * @extends AcroFormComboBox
   * @extends AcroFormListBox
   * @extends AcroFormChoiceField
   * @extends AcroFormField
   */
  var AcroFormEditBox = function() {
    AcroFormComboBox.call(this);
    this.edit = true;
  };
  inherit(AcroFormEditBox, AcroFormComboBox);

  /**
   * @class AcroFormButton
   * @extends AcroFormField
   */
  var AcroFormButton = function() {
    AcroFormField.call(this);
    this.FT = "/Btn";

    /**
     * (Radio buttons only) If set, exactly one radio button shall be selected at all times; selecting the currently selected button has no effect. If clear, clicking the selected button deselects it, leaving no button selected.
     *
     * @name AcroFormButton#noToggleToOff
     * @type {boolean}
     */
    Object.defineProperty(this, "noToggleToOff", {
      enumerable: true,
      configurable: true,
      get: function() {
        return Boolean(getBitForPdf(this.Ff, 15));
      },
      set: function(value) {
        if (Boolean(value) === true) {
          this.Ff = setBitForPdf(this.Ff, 15);
        } else {
          this.Ff = clearBitForPdf(this.Ff, 15);
        }
      }
    });

    /**
     * If set, the field is a set of radio buttons; if clear, the field is a checkbox. This flag may be set only if the Pushbutton flag is clear.
     *
     * @name AcroFormButton#radio
     * @type {boolean}
     */
    Object.defineProperty(this, "radio", {
      enumerable: true,
      configurable: true,
      get: function() {
        return Boolean(getBitForPdf(this.Ff, 16));
      },
      set: function(value) {
        if (Boolean(value) === true) {
          this.Ff = setBitForPdf(this.Ff, 16);
        } else {
          this.Ff = clearBitForPdf(this.Ff, 16);
        }
      }
    });

    /**
     * If set, the field is a pushbutton that does not retain a permanent value.
     *
     * @name AcroFormButton#pushButton
     * @type {boolean}
     */
    Object.defineProperty(this, "pushButton", {
      enumerable: true,
      configurable: true,
      get: function() {
        return Boolean(getBitForPdf(this.Ff, 17));
      },
      set: function(value) {
        if (Boolean(value) === true) {
          this.Ff = setBitForPdf(this.Ff, 17);
        } else {
          this.Ff = clearBitForPdf(this.Ff, 17);
        }
      }
    });

    /**
     * (PDF 1.5) If set, a group of radio buttons within a radio button field that use the same value for the on state will turn on and off in unison; that is if one is checked, they are all checked. If clear, the buttons are mutually exclusive (the same behavior as HTML radio buttons).
     *
     * @name AcroFormButton#radioIsUnison
     * @type {boolean}
     */
    Object.defineProperty(this, "radioIsUnison", {
      enumerable: true,
      configurable: true,
      get: function() {
        return Boolean(getBitForPdf(this.Ff, 26));
      },
      set: function(value) {
        if (Boolean(value) === true) {
          this.Ff = setBitForPdf(this.Ff, 26);
        } else {
          this.Ff = clearBitForPdf(this.Ff, 26);
        }
      }
    });

    var _MK = {};
    Object.defineProperty(this, "MK", {
      enumerable: false,
      configurable: false,
      get: function() {
        var encryptor = function(data) {
          return data;
        };
        if (this.scope) encryptor = this.scope.internal.getEncryptor(this.objId);
        if (Object.keys(_MK).length !== 0) {
          var result = [];
          result.push("<<");
          var key;
          for (key in _MK) {
            result.push("/" + key + " (" + pdfEscape(encryptor(_MK[key])) + ")");
          }
          result.push(">>");
          return result.join("\n");
        }
        return undefined;
      },
      set: function(value) {
        if (typeof value === "object") {
          _MK = value;
        }
      }
    });

    /**
     * From the PDF reference:
     * (Optional, button fields only) The widget annotation's normal caption which shall be displayed when it is not interacting with the user.
     * Unlike the remaining entries listed in this Table which apply only to widget annotations associated with pushbutton fields (see Pushbuttons in 12.7.4.2, "Button Fields"), the CA entry may be used with any type of button field, including check boxes (see Check Boxes in 12.7.4.2, "Button Fields") and radio buttons (Radio Buttons in 12.7.4.2, "Button Fields").
     *
     * - '8' = Cross,
     * - 'l' =  Circle,
     * - '' = nothing
     * @name AcroFormButton#caption
     * @type {string}
     */
    Object.defineProperty(this, "caption", {
      enumerable: true,
      configurable: true,
      get: function() {
        return _MK.CA || "";
      },
      set: function(value) {
        if (typeof value === "string") {
          _MK.CA = value;
        }
      }
    });

    var _AS;
    Object.defineProperty(this, "AS", {
      enumerable: false,
      configurable: false,
      get: function() {
        return _AS;
      },
      set: function(value) {
        _AS = value;
      }
    });

    /**
     * (Required if the appearance dictionary AP contains one or more subdictionaries; PDF 1.2) The annotation's appearance state, which selects the applicable appearance stream from an appearance subdictionary (see Section 12.5.5, "Appearance Streams")
     *
     * @name AcroFormButton#appearanceState
     * @type {any}
     */
    Object.defineProperty(this, "appearanceState", {
      enumerable: true,
      configurable: true,
      get: function() {
        return _AS.substr(1, _AS.length - 1);
      },
      set: function(value) {
        _AS = "/" + value;
      }
    });
  };
  inherit(AcroFormButton, AcroFormField);

  /**
   * @class AcroFormPushButton
   * @extends AcroFormButton
   * @extends AcroFormField
   */
  var AcroFormPushButton = function() {
    AcroFormButton.call(this);
    this.pushButton = true;
  };
  inherit(AcroFormPushButton, AcroFormButton);

  /**
   * @class AcroFormRadioButton
   * @extends AcroFormButton
   * @extends AcroFormField
   */
  var AcroFormRadioButton = function() {
    AcroFormButton.call(this);
    this.radio = true;
    this.pushButton = false;

    var _Kids = [];
    Object.defineProperty(this, "Kids", {
      enumerable: true,
      configurable: false,
      get: function() {
        return _Kids;
      },
      set: function(value) {
        if (typeof value !== "undefined") {
          _Kids = value;
        } else {
          _Kids = [];
        }
      }
    });
  };
  inherit(AcroFormRadioButton, AcroFormButton);

  /**
   * The Child class of a RadioButton (the radioGroup) -> The single Buttons
   *
   * @class AcroFormChildClass
   * @extends AcroFormField
   * @ignore
   */
  var AcroFormChildClass = function() {
    AcroFormField.call(this);

    var _parent;
    Object.defineProperty(this, "Parent", {
      enumerable: false,
      configurable: false,
      get: function() {
        return _parent;
      },
      set: function(value) {
        _parent = value;
      }
    });

    var _optionName;
    Object.defineProperty(this, "optionName", {
      enumerable: false,
      configurable: true,
      get: function() {
        return _optionName;
      },
      set: function(value) {
        _optionName = value;
      }
    });

    var _MK = {};
    Object.defineProperty(this, "MK", {
      enumerable: false,
      configurable: false,
      get: function() {
        var encryptor = function(data) {
          return data;
        };
        if (this.scope) encryptor = this.scope.internal.getEncryptor(this.objId);
        var result = [];
        result.push("<<");
        var key;
        for (key in _MK) {
          result.push("/" + key + " (" + pdfEscape(encryptor(_MK[key])) + ")");
        }
        result.push(">>");
        return result.join("\n");
      },
      set: function(value) {
        if (typeof value === "object") {
          _MK = value;
        }
      }
    });

    /**
     * From the PDF reference:
     * (Optional, button fields only) The widget annotation's normal caption which shall be displayed when it is not interacting with the user.
     * Unlike the remaining entries listed in this Table which apply only to widget annotations associated with pushbutton fields (see Pushbuttons in 12.7.4.2, "Button Fields"), the CA entry may be used with any type of button field, including check boxes (see Check Boxes in 12.7.4.2, "Button Fields") and radio buttons (Radio Buttons in 12.7.4.2, "Button Fields").
     *
     * - '8' = Cross,
     * - 'l' =  Circle,
     * - '' = nothing
     * @name AcroFormButton#caption
     * @type {string}
     */
    Object.defineProperty(this, "caption", {
      enumerable: true,
      configurable: true,
      get: function() {
        return _MK.CA || "";
      },
      set: function(value) {
        if (typeof value === "string") {
          _MK.CA = value;
        }
      }
    });

    var _AS;
    Object.defineProperty(this, "AS", {
      enumerable: false,
      configurable: false,
      get: function() {
        return _AS;
      },
      set: function(value) {
        _AS = value;
      }
    });

    /**
     * (Required if the appearance dictionary AP contains one or more subdictionaries; PDF 1.2) The annotation's appearance state, which selects the applicable appearance stream from an appearance subdictionary (see Section 12.5.5, "Appearance Streams")
     *
     * @name AcroFormButton#appearanceState
     * @type {any}
     */
    Object.defineProperty(this, "appearanceState", {
      enumerable: true,
      configurable: true,
      get: function() {
        return _AS.substr(1, _AS.length - 1);
      },
      set: function(value) {
        _AS = "/" + value;
      }
    });
    this.caption = "l";
    this.appearanceState = "Off";
    // todo: set AppearanceType as variable that can be set from the
    // outside...
    this._AppearanceType = AcroFormAppearance.RadioButton.Circle;
    // The Default appearanceType is the Circle
    this.appearanceStreamContent = this._AppearanceType.createAppearanceStream(
      this.optionName
    );
  };
  inherit(AcroFormChildClass, AcroFormField);

  AcroFormRadioButton.prototype.setAppearance = function(appearance) {
    if (!("createAppearanceStream" in appearance && "getCA" in appearance)) {
      throw new Error(
        "Couldn't assign Appearance to RadioButton. Appearance was Invalid!"
      );
    }
    for (var objId in this.Kids) {
      if (this.Kids.hasOwnProperty(objId)) {
        var child = this.Kids[objId];
        child.appearanceStreamContent = appearance.createAppearanceStream(
          child.optionName
        );
        child.caption = appearance.getCA();
      }
    }
  };

  AcroFormRadioButton.prototype.createOption = function(name) {
    // Create new Child for RadioGroup
    var child = new AcroFormChildClass();
    child.Parent = this;
    child.optionName = name;
    // Add to Parent
    this.Kids.push(child);

    addField.call(this.scope, child);

    return child;
  };

  /**
   * @class AcroFormCheckBox
   * @extends AcroFormButton
   * @extends AcroFormField
   */
  var AcroFormCheckBox = function() {
    AcroFormButton.call(this);

    this.fontName = "zapfdingbats";
    this.caption = "3";
    this.appearanceState = "On";
    this.value = "On";
    this.textAlign = "center";
    this.appearanceStreamContent = AcroFormAppearance.CheckBox.createAppearanceStream();
  };
  inherit(AcroFormCheckBox, AcroFormButton);

  /**
   * @class AcroFormTextField
   * @extends AcroFormField
   */
  var AcroFormTextField = function() {
    AcroFormField.call(this);
    this.FT = "/Tx";

    /**
     * If set, the field may contain multiple lines of text; if clear, the field’s text shall be restricted to a single line.
     *
     * @name AcroFormTextField#multiline
     * @type {boolean}
     */
    Object.defineProperty(this, "multiline", {
      enumerable: true,
      configurable: true,
      get: function() {
        return Boolean(getBitForPdf(this.Ff, 13));
      },
      set: function(value) {
        if (Boolean(value) === true) {
          this.Ff = setBitForPdf(this.Ff, 13);
        } else {
          this.Ff = clearBitForPdf(this.Ff, 13);
        }
      }
    });

    /**
     * (PDF 1.4) If set, the text entered in the field represents the pathname of a file whose contents shall be submitted as the value of the field.
     *
     * @name AcroFormTextField#fileSelect
     * @type {boolean}
     */
    Object.defineProperty(this, "fileSelect", {
      enumerable: true,
      configurable: true,
      get: function() {
        return Boolean(getBitForPdf(this.Ff, 21));
      },
      set: function(value) {
        if (Boolean(value) === true) {
          this.Ff = setBitForPdf(this.Ff, 21);
        } else {
          this.Ff = clearBitForPdf(this.Ff, 21);
        }
      }
    });

    /**
     * (PDF 1.4) If set, text entered in the field shall not be spell-checked.
     *
     * @name AcroFormTextField#doNotSpellCheck
     * @type {boolean}
     */
    Object.defineProperty(this, "doNotSpellCheck", {
      enumerable: true,
      configurable: true,
      get: function() {
        return Boolean(getBitForPdf(this.Ff, 23));
      },
      set: function(value) {
        if (Boolean(value) === true) {
          this.Ff = setBitForPdf(this.Ff, 23);
        } else {
          this.Ff = clearBitForPdf(this.Ff, 23);
        }
      }
    });

    /**
     * (PDF 1.4) If set, the field shall not scroll (horizontally for single-line fields, vertically for multiple-line fields) to accommodate more text than fits within its annotation rectangle. Once the field is full, no further text shall be accepted for interactive form filling; for noninteractive form filling, the filler should take care not to add more character than will visibly fit in the defined area.
     *
     * @name AcroFormTextField#doNotScroll
     * @type {boolean}
     */
    Object.defineProperty(this, "doNotScroll", {
      enumerable: true,
      configurable: true,
      get: function() {
        return Boolean(getBitForPdf(this.Ff, 24));
      },
      set: function(value) {
        if (Boolean(value) === true) {
          this.Ff = setBitForPdf(this.Ff, 24);
        } else {
          this.Ff = clearBitForPdf(this.Ff, 24);
        }
      }
    });

    /**
     * (PDF 1.5) May be set only if the MaxLen entry is present in the text field dictionary (see Table 229) and if the Multiline, Password, and FileSelect flags are clear. If set, the field shall be automatically divided into as many equally spaced positions, or combs, as the value of MaxLen, and the text is laid out into those combs.
     *
     * @name AcroFormTextField#comb
     * @type {boolean}
     */
    Object.defineProperty(this, "comb", {
      enumerable: true,
      configurable: true,
      get: function() {
        return Boolean(getBitForPdf(this.Ff, 25));
      },
      set: function(value) {
        if (Boolean(value) === true) {
          this.Ff = setBitForPdf(this.Ff, 25);
        } else {
          this.Ff = clearBitForPdf(this.Ff, 25);
        }
      }
    });

    /**
     * (PDF 1.5) If set, the value of this field shall be a rich text string (see 12.7.3.4, “Rich Text Strings”). If the field has a value, the RV entry of the field dictionary (Table 222) shall specify the rich text string.
     *
     * @name AcroFormTextField#richText
     * @type {boolean}
     */
    Object.defineProperty(this, "richText", {
      enumerable: true,
      configurable: true,
      get: function() {
        return Boolean(getBitForPdf(this.Ff, 26));
      },
      set: function(value) {
        if (Boolean(value) === true) {
          this.Ff = setBitForPdf(this.Ff, 26);
        } else {
          this.Ff = clearBitForPdf(this.Ff, 26);
        }
      }
    });

    var _MaxLen = null;
    Object.defineProperty(this, "MaxLen", {
      enumerable: true,
      configurable: false,
      get: function() {
        return _MaxLen;
      },
      set: function(value) {
        _MaxLen = value;
      }
    });

    /**
     * (Optional; inheritable) The maximum length of the field’s text, in characters.
     *
     * @name AcroFormTextField#maxLength
     * @type {number}
     */
    Object.defineProperty(this, "maxLength", {
      enumerable: true,
      configurable: true,
      get: function() {
        return _MaxLen;
      },
      set: function(value) {
        if (Number.isInteger(value)) {
          _MaxLen = value;
        }
      }
    });

    Object.defineProperty(this, "hasAppearanceStream", {
      enumerable: true,
      configurable: true,
      get: function() {
        return this.V || this.DV;
      }
    });
  };
  inherit(AcroFormTextField, AcroFormField);

  /**
   * @class AcroFormPasswordField
   * @extends AcroFormTextField
   * @extends AcroFormField
   */
  var AcroFormPasswordField = function() {
    AcroFormTextField.call(this);

    /**
     * If set, the field is intended for entering a secure password that should not be echoed visibly to the screen. Characters typed from the keyboard shall instead be echoed in some unreadable form, such as asterisks or bullet characters.
     * NOTE To protect password confidentiality, readers should never store the value of the text field in the PDF file if this flag is set.
     *
     * @name AcroFormTextField#password
     * @type {boolean}
     */
    Object.defineProperty(this, "password", {
      enumerable: true,
      configurable: true,
      get: function() {
        return Boolean(getBitForPdf(this.Ff, 14));
      },
      set: function(value) {
        if (Boolean(value) === true) {
          this.Ff = setBitForPdf(this.Ff, 14);
        } else {
          this.Ff = clearBitForPdf(this.Ff, 14);
        }
      }
    });
    this.password = true;
  };
  inherit(AcroFormPasswordField, AcroFormTextField);

  // Contains Methods for creating standard appearances
  var AcroFormAppearance = {
    CheckBox: {
      createAppearanceStream: function() {
        var appearance = {
          N: {
            On: AcroFormAppearance.CheckBox.YesNormal
          },
          D: {
            On: AcroFormAppearance.CheckBox.YesPushDown,
            Off: AcroFormAppearance.CheckBox.OffPushDown
          }
        };

        return appearance;
      },
      /**
       * Returns the standard On Appearance for a CheckBox
       *
       * @returns {AcroFormXObject}
       */
      YesPushDown: function(formObject) {
        var xobj = createFormXObject(formObject);
        xobj.scope = formObject.scope;
        var stream = [];
        var fontKey = formObject.scope.internal.getFont(
          formObject.fontName,
          formObject.fontStyle
        ).id;
        var encodedColor = formObject.scope.__private__.encodeColorString(
          formObject.color
        );
        var calcRes = calculateX(formObject, formObject.caption);
        stream.push("0.749023 g");
        stream.push(
          "0 0 " +
            f2(AcroFormAppearance.internal.getWidth(formObject)) +
            " " +
            f2(AcroFormAppearance.internal.getHeight(formObject)) +
            " re"
        );
        stream.push("f");
        stream.push("BMC");
        stream.push("q");
        stream.push("0 0 1 rg");
        stream.push(
          "/" + fontKey + " " + f2(calcRes.fontSize) + " Tf " + encodedColor
        );
        stream.push("BT");
        stream.push(calcRes.text);
        stream.push("ET");
        stream.push("Q");
        stream.push("EMC");
        xobj.stream = stream.join("\n");
        return xobj;
      },

      YesNormal: function(formObject) {
        var xobj = createFormXObject(formObject);
        xobj.scope = formObject.scope;
        var fontKey = formObject.scope.internal.getFont(
          formObject.fontName,
          formObject.fontStyle
        ).id;
        var encodedColor = formObject.scope.__private__.encodeColorString(
          formObject.color
        );
        var stream = [];
        var height = AcroFormAppearance.internal.getHeight(formObject);
        var width = AcroFormAppearance.internal.getWidth(formObject);
        var calcRes = calculateX(formObject, formObject.caption);
        stream.push("1 g");
        stream.push("0 0 " + f2(width) + " " + f2(height) + " re");
        stream.push("f");
        stream.push("q");
        stream.push("0 0 1 rg");
        stream.push("0 0 " + f2(width - 1) + " " + f2(height - 1) + " re");
        stream.push("W");
        stream.push("n");
        stream.push("0 g");
        stream.push("BT");
        stream.push(
          "/" + fontKey + " " + f2(calcRes.fontSize) + " Tf " + encodedColor
        );
        stream.push(calcRes.text);
        stream.push("ET");
        stream.push("Q");
        xobj.stream = stream.join("\n");
        return xobj;
      },

      /**
       * Returns the standard Off Appearance for a CheckBox
       *
       * @returns {AcroFormXObject}
       */
      OffPushDown: function(formObject) {
        var xobj = createFormXObject(formObject);
        xobj.scope = formObject.scope;
        var stream = [];
        stream.push("0.749023 g");
        stream.push(
          "0 0 " +
            f2(AcroFormAppearance.internal.getWidth(formObject)) +
            " " +
            f2(AcroFormAppearance.internal.getHeight(formObject)) +
            " re"
        );
        stream.push("f");
        xobj.stream = stream.join("\n");
        return xobj;
      }
    },

    RadioButton: {
      Circle: {
        createAppearanceStream: function(name) {
          var appearanceStreamContent = {
            D: {
              Off: AcroFormAppearance.RadioButton.Circle.OffPushDown
            },
            N: {}
          };
          appearanceStreamContent.N[name] =
            AcroFormAppearance.RadioButton.Circle.YesNormal;
          appearanceStreamContent.D[name] =
            AcroFormAppearance.RadioButton.Circle.YesPushDown;
          return appearanceStreamContent;
        },
        getCA: function() {
          return "l";
        },

        YesNormal: function(formObject) {
          var xobj = createFormXObject(formObject);
          xobj.scope = formObject.scope;
          var stream = [];
          // Make the Radius of the Circle relative to min(height, width) of formObject
          var DotRadius =
            AcroFormAppearance.internal.getWidth(formObject) <=
            AcroFormAppearance.internal.getHeight(formObject)
              ? AcroFormAppearance.internal.getWidth(formObject) / 4
              : AcroFormAppearance.internal.getHeight(formObject) / 4;
          // The Borderpadding...
          DotRadius = Number((DotRadius * 0.9).toFixed(5));
          var c = AcroFormAppearance.internal.Bezier_C;
          var DotRadiusBezier = Number((DotRadius * c).toFixed(5));
          /*
           * The Following is a Circle created with Bezier-Curves.
           */
          stream.push("q");
          stream.push(
            "1 0 0 1 " +
              f5(AcroFormAppearance.internal.getWidth(formObject) / 2) +
              " " +
              f5(AcroFormAppearance.internal.getHeight(formObject) / 2) +
              " cm"
          );
          stream.push(DotRadius + " 0 m");
          stream.push(
            DotRadius +
              " " +
              DotRadiusBezier +
              " " +
              DotRadiusBezier +
              " " +
              DotRadius +
              " 0 " +
              DotRadius +
              " c"
          );
          stream.push(
            "-" +
              DotRadiusBezier +
              " " +
              DotRadius +
              " -" +
              DotRadius +
              " " +
              DotRadiusBezier +
              " -" +
              DotRadius +
              " 0 c"
          );
          stream.push(
            "-" +
              DotRadius +
              " -" +
              DotRadiusBezier +
              " -" +
              DotRadiusBezier +
              " -" +
              DotRadius +
              " 0 -" +
              DotRadius +
              " c"
          );
          stream.push(
            DotRadiusBezier +
              " -" +
              DotRadius +
              " " +
              DotRadius +
              " -" +
              DotRadiusBezier +
              " " +
              DotRadius +
              " 0 c"
          );
          stream.push("f");
          stream.push("Q");
          xobj.stream = stream.join("\n");
          return xobj;
        },
        YesPushDown: function(formObject) {
          var xobj = createFormXObject(formObject);
          xobj.scope = formObject.scope;
          var stream = [];
          var DotRadius =
            AcroFormAppearance.internal.getWidth(formObject) <=
            AcroFormAppearance.internal.getHeight(formObject)
              ? AcroFormAppearance.internal.getWidth(formObject) / 4
              : AcroFormAppearance.internal.getHeight(formObject) / 4;
          // The Borderpadding...
          DotRadius = Number((DotRadius * 0.9).toFixed(5));
          // Save results for later use; no need to waste
          // processor ticks on doing math
          var k = Number((DotRadius * 2).toFixed(5));
          var kc = Number((k * AcroFormAppearance.internal.Bezier_C).toFixed(5));
          var dc = Number(
            (DotRadius * AcroFormAppearance.internal.Bezier_C).toFixed(5)
          );

          stream.push("0.749023 g");
          stream.push("q");
          stream.push(
            "1 0 0 1 " +
              f5(AcroFormAppearance.internal.getWidth(formObject) / 2) +
              " " +
              f5(AcroFormAppearance.internal.getHeight(formObject) / 2) +
              " cm"
          );
          stream.push(k + " 0 m");
          stream.push(k + " " + kc + " " + kc + " " + k + " 0 " + k + " c");
          stream.push(
            "-" + kc + " " + k + " -" + k + " " + kc + " -" + k + " 0 c"
          );
          stream.push(
            "-" + k + " -" + kc + " -" + kc + " -" + k + " 0 -" + k + " c"
          );
          stream.push(kc + " -" + k + " " + k + " -" + kc + " " + k + " 0 c");
          stream.push("f");
          stream.push("Q");
          stream.push("0 g");
          stream.push("q");
          stream.push(
            "1 0 0 1 " +
              f5(AcroFormAppearance.internal.getWidth(formObject) / 2) +
              " " +
              f5(AcroFormAppearance.internal.getHeight(formObject) / 2) +
              " cm"
          );
          stream.push(DotRadius + " 0 m");
          stream.push(
            "" +
              DotRadius +
              " " +
              dc +
              " " +
              dc +
              " " +
              DotRadius +
              " 0 " +
              DotRadius +
              " c"
          );
          stream.push(
            "-" +
              dc +
              " " +
              DotRadius +
              " -" +
              DotRadius +
              " " +
              dc +
              " -" +
              DotRadius +
              " 0 c"
          );
          stream.push(
            "-" +
              DotRadius +
              " -" +
              dc +
              " -" +
              dc +
              " -" +
              DotRadius +
              " 0 -" +
              DotRadius +
              " c"
          );
          stream.push(
            dc +
              " -" +
              DotRadius +
              " " +
              DotRadius +
              " -" +
              dc +
              " " +
              DotRadius +
              " 0 c"
          );
          stream.push("f");
          stream.push("Q");
          xobj.stream = stream.join("\n");
          return xobj;
        },
        OffPushDown: function(formObject) {
          var xobj = createFormXObject(formObject);
          xobj.scope = formObject.scope;
          var stream = [];
          var DotRadius =
            AcroFormAppearance.internal.getWidth(formObject) <=
            AcroFormAppearance.internal.getHeight(formObject)
              ? AcroFormAppearance.internal.getWidth(formObject) / 4
              : AcroFormAppearance.internal.getHeight(formObject) / 4;
          // The Borderpadding...
          DotRadius = Number((DotRadius * 0.9).toFixed(5));
          // Save results for later use; no need to waste
          // processor ticks on doing math
          var k = Number((DotRadius * 2).toFixed(5));
          var kc = Number((k * AcroFormAppearance.internal.Bezier_C).toFixed(5));

          stream.push("0.749023 g");
          stream.push("q");
          stream.push(
            "1 0 0 1 " +
              f5(AcroFormAppearance.internal.getWidth(formObject) / 2) +
              " " +
              f5(AcroFormAppearance.internal.getHeight(formObject) / 2) +
              " cm"
          );
          stream.push(k + " 0 m");
          stream.push(k + " " + kc + " " + kc + " " + k + " 0 " + k + " c");
          stream.push(
            "-" + kc + " " + k + " -" + k + " " + kc + " -" + k + " 0 c"
          );
          stream.push(
            "-" + k + " -" + kc + " -" + kc + " -" + k + " 0 -" + k + " c"
          );
          stream.push(kc + " -" + k + " " + k + " -" + kc + " " + k + " 0 c");
          stream.push("f");
          stream.push("Q");
          xobj.stream = stream.join("\n");
          return xobj;
        }
      },

      Cross: {
        /**
         * Creates the Actual AppearanceDictionary-References
         *
         * @param {string} name
         * @returns {Object}
         * @ignore
         */
        createAppearanceStream: function(name) {
          var appearanceStreamContent = {
            D: {
              Off: AcroFormAppearance.RadioButton.Cross.OffPushDown
            },
            N: {}
          };
          appearanceStreamContent.N[name] =
            AcroFormAppearance.RadioButton.Cross.YesNormal;
          appearanceStreamContent.D[name] =
            AcroFormAppearance.RadioButton.Cross.YesPushDown;
          return appearanceStreamContent;
        },
        getCA: function() {
          return "8";
        },

        YesNormal: function(formObject) {
          var xobj = createFormXObject(formObject);
          xobj.scope = formObject.scope;
          var stream = [];
          var cross = AcroFormAppearance.internal.calculateCross(formObject);
          stream.push("q");
          stream.push(
            "1 1 " +
              f2(AcroFormAppearance.internal.getWidth(formObject) - 2) +
              " " +
              f2(AcroFormAppearance.internal.getHeight(formObject) - 2) +
              " re"
          );
          stream.push("W");
          stream.push("n");
          stream.push(f2(cross.x1.x) + " " + f2(cross.x1.y) + " m");
          stream.push(f2(cross.x2.x) + " " + f2(cross.x2.y) + " l");
          stream.push(f2(cross.x4.x) + " " + f2(cross.x4.y) + " m");
          stream.push(f2(cross.x3.x) + " " + f2(cross.x3.y) + " l");
          stream.push("s");
          stream.push("Q");
          xobj.stream = stream.join("\n");
          return xobj;
        },
        YesPushDown: function(formObject) {
          var xobj = createFormXObject(formObject);
          xobj.scope = formObject.scope;
          var cross = AcroFormAppearance.internal.calculateCross(formObject);
          var stream = [];
          stream.push("0.749023 g");
          stream.push(
            "0 0 " +
              f2(AcroFormAppearance.internal.getWidth(formObject)) +
              " " +
              f2(AcroFormAppearance.internal.getHeight(formObject)) +
              " re"
          );
          stream.push("f");
          stream.push("q");
          stream.push(
            "1 1 " +
              f2(AcroFormAppearance.internal.getWidth(formObject) - 2) +
              " " +
              f2(AcroFormAppearance.internal.getHeight(formObject) - 2) +
              " re"
          );
          stream.push("W");
          stream.push("n");
          stream.push(f2(cross.x1.x) + " " + f2(cross.x1.y) + " m");
          stream.push(f2(cross.x2.x) + " " + f2(cross.x2.y) + " l");
          stream.push(f2(cross.x4.x) + " " + f2(cross.x4.y) + " m");
          stream.push(f2(cross.x3.x) + " " + f2(cross.x3.y) + " l");
          stream.push("s");
          stream.push("Q");
          xobj.stream = stream.join("\n");
          return xobj;
        },
        OffPushDown: function(formObject) {
          var xobj = createFormXObject(formObject);
          xobj.scope = formObject.scope;
          var stream = [];
          stream.push("0.749023 g");
          stream.push(
            "0 0 " +
              f2(AcroFormAppearance.internal.getWidth(formObject)) +
              " " +
              f2(AcroFormAppearance.internal.getHeight(formObject)) +
              " re"
          );
          stream.push("f");
          xobj.stream = stream.join("\n");
          return xobj;
        }
      }
    },

    /**
     * Returns the standard Appearance
     *
     * @returns {AcroFormXObject}
     */
    createDefaultAppearanceStream: function(formObject) {
      // Set Helvetica to Standard Font (size: auto)
      // Color: Black
      var fontKey = formObject.scope.internal.getFont(
        formObject.fontName,
        formObject.fontStyle
      ).id;
      var encodedColor = formObject.scope.__private__.encodeColorString(
        formObject.color
      );
      var fontSize = formObject.fontSize;
      var result = "/" + fontKey + " " + fontSize + " Tf " + encodedColor;
      return result;
    }
  };

  AcroFormAppearance.internal = {
    Bezier_C: 0.551915024494,

    calculateCross: function(formObject) {
      var width = AcroFormAppearance.internal.getWidth(formObject);
      var height = AcroFormAppearance.internal.getHeight(formObject);
      var a = Math.min(width, height);

      var cross = {
        x1: {
          // upperLeft
          x: (width - a) / 2,
          y: (height - a) / 2 + a // height - borderPadding
        },
        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 // height - borderPadding
        }
      };

      return cross;
    }
  };
  AcroFormAppearance.internal.getWidth = function(formObject) {
    var result = 0;
    if (typeof formObject === "object") {
      result = scale(formObject.Rect[2]);
    }
    return result;
  };
  AcroFormAppearance.internal.getHeight = function(formObject) {
    var result = 0;
    if (typeof formObject === "object") {
      result = scale(formObject.Rect[3]);
    }
    return result;
  };

  // Public:

  /**
   * Add an AcroForm-Field to the jsPDF-instance
   *
   * @name addField
   * @function
   * @instance
   * @param {Object} fieldObject
   * @returns {jsPDF}
   */
  var addField = (jsPDFAPI.addField = function(fieldObject) {
    initializeAcroForm(this, fieldObject);

    if (fieldObject instanceof AcroFormField) {
      putForm(fieldObject);
    } else {
      throw new Error("Invalid argument passed to jsPDF.addField.");
    }
    fieldObject.page = fieldObject.scope.internal.getCurrentPageInfo().pageNumber;
    return this;
  });

  jsPDFAPI.AcroFormChoiceField = AcroFormChoiceField;
  jsPDFAPI.AcroFormListBox = AcroFormListBox;
  jsPDFAPI.AcroFormComboBox = AcroFormComboBox;
  jsPDFAPI.AcroFormEditBox = AcroFormEditBox;
  jsPDFAPI.AcroFormButton = AcroFormButton;
  jsPDFAPI.AcroFormPushButton = AcroFormPushButton;
  jsPDFAPI.AcroFormRadioButton = AcroFormRadioButton;
  jsPDFAPI.AcroFormCheckBox = AcroFormCheckBox;
  jsPDFAPI.AcroFormTextField = AcroFormTextField;
  jsPDFAPI.AcroFormPasswordField = AcroFormPasswordField;
  jsPDFAPI.AcroFormAppearance = AcroFormAppearance;

  jsPDFAPI.AcroForm = {
    ChoiceField: AcroFormChoiceField,
    ListBox: AcroFormListBox,
    ComboBox: AcroFormComboBox,
    EditBox: AcroFormEditBox,
    Button: AcroFormButton,
    PushButton: AcroFormPushButton,
    RadioButton: AcroFormRadioButton,
    CheckBox: AcroFormCheckBox,
    TextField: AcroFormTextField,
    PasswordField: AcroFormPasswordField,
    Appearance: AcroFormAppearance
  };

  jsPDF.AcroForm = {
    ChoiceField: AcroFormChoiceField,
    ListBox: AcroFormListBox,
    ComboBox: AcroFormComboBox,
    EditBox: AcroFormEditBox,
    Button: AcroFormButton,
    PushButton: AcroFormPushButton,
    RadioButton: AcroFormRadioButton,
    CheckBox: AcroFormCheckBox,
    TextField: AcroFormTextField,
    PasswordField: AcroFormPasswordField,
    Appearance: AcroFormAppearance
  };

  var AcroForm = jsPDF.AcroForm;

  /** @license
   * 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
   *
   * 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(jsPDFAPI) {

    var namespace = "addImage_";
    jsPDFAPI.__addimage__ = {};

    var UNKNOWN = "UNKNOWN";

    var imageFileTypeHeaders = {
      PNG: [[0x89, 0x50, 0x4e, 0x47]],
      TIFF: [
        [0x4d, 0x4d, 0x00, 0x2a], //Motorola
        [0x49, 0x49, 0x2a, 0x00] //Intel
      ],
      JPEG: [
        [
          0xff,
          0xd8,
          0xff,
          0xe0,
          undefined,
          undefined,
          0x4a,
          0x46,
          0x49,
          0x46,
          0x00
        ], //JFIF
        [
          0xff,
          0xd8,
          0xff,
          0xe1,
          undefined,
          undefined,
          0x45,
          0x78,
          0x69,
          0x66,
          0x00,
          0x00
        ], //Exif
        [0xff, 0xd8, 0xff, 0xdb], //JPEG RAW
        [0xff, 0xd8, 0xff, 0xee] //EXIF RAW
      ],
      JPEG2000: [[0x00, 0x00, 0x00, 0x0c, 0x6a, 0x50, 0x20, 0x20]],
      GIF87a: [[0x47, 0x49, 0x46, 0x38, 0x37, 0x61]],
      GIF89a: [[0x47, 0x49, 0x46, 0x38, 0x39, 0x61]],
      WEBP: [
        [
          0x52,
          0x49,
          0x46,
          0x46,
          undefined,
          undefined,
          undefined,
          undefined,
          0x57,
          0x45,
          0x42,
          0x50
        ]
      ],
      BMP: [
        [0x42, 0x4d], //BM - Windows 3.1x, 95, NT, ... etc.
        [0x42, 0x41], //BA - OS/2 struct bitmap array
        [0x43, 0x49], //CI - OS/2 struct color icon
        [0x43, 0x50], //CP - OS/2 const color pointer
        [0x49, 0x43], //IC - OS/2 struct icon
        [0x50, 0x54] //PT - OS/2 pointer
      ]
    };

    /**
     * Recognize filetype of Image by magic-bytes
     *
     * https://en.wikipedia.org/wiki/List_of_file_signatures
     *
     * @name getImageFileTypeByImageData
     * @public
     * @function
     * @param {string|arraybuffer} imageData imageData as binary String or arraybuffer
     * @param {string} format format of file if filetype-recognition fails, e.g. 'JPEG'
     *
     * @returns {string} filetype of Image
     */
    var getImageFileTypeByImageData = (jsPDFAPI.__addimage__.getImageFileTypeByImageData = function(
      imageData,
      fallbackFormat
    ) {
      fallbackFormat = fallbackFormat || UNKNOWN;
      var i;
      var j;
      var result = UNKNOWN;
      var headerSchemata;
      var compareResult;
      var fileType;

      if (isArrayBufferView(imageData)) {
        for (fileType in imageFileTypeHeaders) {
          headerSchemata = imageFileTypeHeaders[fileType];
          for (i = 0; i < headerSchemata.length; i += 1) {
            compareResult = true;
            for (j = 0; j < headerSchemata[i].length; j += 1) {
              if (headerSchemata[i][j] === undefined) {
                continue;
              }
              if (headerSchemata[i][j] !== imageData[j]) {
                compareResult = false;
                break;
              }
            }
            if (compareResult === true) {
              result = fileType;
              break;
            }
          }
        }
      } else {
        for (fileType in imageFileTypeHeaders) {
          headerSchemata = imageFileTypeHeaders[fileType];
          for (i = 0; i < headerSchemata.length; i += 1) {
            compareResult = true;
            for (j = 0; j < headerSchemata[i].length; j += 1) {
              if (headerSchemata[i][j] === undefined) {
                continue;
              }
              if (headerSchemata[i][j] !== imageData.charCodeAt(j)) {
                compareResult = false;
                break;
              }
            }
            if (compareResult === true) {
              result = fileType;
              break;
            }
          }
        }
      }

      if (result === UNKNOWN && fallbackFormat !== UNKNOWN) {
        result = fallbackFormat;
      }
      return result;
    });

    // Image functionality ported from pdf.js
    var putImage = function(image) {
      var out = this.internal.write;
      var putStream = this.internal.putStream;
      var getFilters = this.internal.getFilters;

      var filter = getFilters();
      while (filter.indexOf("FlateEncode") !== -1) {
        filter.splice(filter.indexOf("FlateEncode"), 1);
      }

      image.objectId = this.internal.newObject();

      var additionalKeyValues = [];
      additionalKeyValues.push({ key: "Type", value: "/XObject" });
      additionalKeyValues.push({ key: "Subtype", value: "/Image" });
      additionalKeyValues.push({ key: "Width", value: image.width });
      additionalKeyValues.push({ key: "Height", value: image.height });

      if (image.colorSpace === color_spaces.INDEXED) {
        additionalKeyValues.push({
          key: "ColorSpace",
          value:
            "[/Indexed /DeviceRGB " +
            // if an indexed png defines more than one colour with transparency, we've created a sMask
            (image.palette.length / 3 - 1) +
            " " +
            ("sMask" in image && typeof image.sMask !== "undefined"
              ? image.objectId + 2
              : image.objectId + 1) +
            " 0 R]"
        });
      } else {
        additionalKeyValues.push({
          key: "ColorSpace",
          value: "/" + image.colorSpace
        });
        if (image.colorSpace === color_spaces.DEVICE_CMYK) {
          additionalKeyValues.push({ key: "Decode", value: "[1 0 1 0 1 0 1 0]" });
        }
      }
      additionalKeyValues.push({
        key: "BitsPerComponent",
        value: image.bitsPerComponent
      });
      if (
        "decodeParameters" in image &&
        typeof image.decodeParameters !== "undefined"
      ) {
        additionalKeyValues.push({
          key: "DecodeParms",
          value: "<<" + image.decodeParameters + ">>"
        });
      }
      if ("transparency" in image && Array.isArray(image.transparency)) {
        var transparency = "",
          i = 0,
          len = image.transparency.length;
        for (; i < len; i++)
          transparency +=
            image.transparency[i] + " " + image.transparency[i] + " ";

        additionalKeyValues.push({
          key: "Mask",
          value: "[" + transparency + "]"
        });
      }
      if (typeof image.sMask !== "undefined") {
        additionalKeyValues.push({
          key: "SMask",
          value: image.objectId + 1 + " 0 R"
        });
      }

      var alreadyAppliedFilters =
        typeof image.filter !== "undefined" ? ["/" + image.filter] : undefined;

      putStream({
        data: image.data,
        additionalKeyValues: additionalKeyValues,
        alreadyAppliedFilters: alreadyAppliedFilters,
        objectId: image.objectId
      });

      out("endobj");

      // Soft mask
      if ("sMask" in image && typeof image.sMask !== "undefined") {
        var decodeParameters =
          "/Predictor " +
          image.predictor +
          " /Colors 1 /BitsPerComponent " +
          image.bitsPerComponent +
          " /Columns " +
          image.width;
        var sMask = {
          width: image.width,
          height: image.height,
          colorSpace: "DeviceGray",
          bitsPerComponent: image.bitsPerComponent,
          decodeParameters: decodeParameters,
          data: image.sMask
        };
        if ("filter" in image) {
          sMask.filter = image.filter;
        }
        putImage.call(this, sMask);
      }

      //Palette
      if (image.colorSpace === color_spaces.INDEXED) {
        var objId = this.internal.newObject();
        //out('<< /Filter / ' + img['f'] +' /Length ' + img['pal'].length + '>>');
        //putStream(zlib.compress(img['pal']));
        putStream({
          data: arrayBufferToBinaryString(new Uint8Array(image.palette)),
          objectId: objId
        });
        out("endobj");
      }
    };
    var putResourcesCallback = function() {
      var images = this.internal.collections[namespace + "images"];
      for (var i in images) {
        putImage.call(this, images[i]);
      }
    };
    var putXObjectsDictCallback = function() {
      var images = this.internal.collections[namespace + "images"],
        out = this.internal.write,
        image;
      for (var i in images) {
        image = images[i];
        out("/I" + image.index, image.objectId, "0", "R");
      }
    };

    var checkCompressValue = function(value) {
      if (value && typeof value === "string") value = value.toUpperCase();
      return value in jsPDFAPI.image_compression ? value : image_compression.NONE;
    };

    var initialize = function() {
      if (!this.internal.collections[namespace + "images"]) {
        this.internal.collections[namespace + "images"] = {};
        this.internal.events.subscribe("putResources", putResourcesCallback);
        this.internal.events.subscribe("putXobjectDict", putXObjectsDictCallback);
      }
    };

    var getImages = function() {
      var images = this.internal.collections[namespace + "images"];
      initialize.call(this);
      return images;
    };
    var getImageIndex = function() {
      return Object.keys(this.internal.collections[namespace + "images"]).length;
    };
    var notDefined = function(value) {
      return typeof value === "undefined" || value === null || value.length === 0;
    };
    var generateAliasFromImageData = function(imageData) {
      if (typeof imageData === "string" || isArrayBufferView(imageData)) {
        return sHashCode(imageData);
      }

      return null;
    };

    var isImageTypeSupported = function(type) {
      return typeof jsPDFAPI["process" + type.toUpperCase()] === "function";
    };

    var isDOMElement = function(object) {
      return typeof object === "object" && object.nodeType === 1;
    };

    var getImageDataFromElement = function(element, format) {
      //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");

        //is base64 encoded dataUrl, directly process it
        if (src.indexOf("data:image/") === 0) {
          return atob(
            unescape(src)
              .split("base64,")
              .pop()
          );
        }

        //it is probably an url, try to load it
        var tmpImageData = jsPDFAPI.loadFile(src, true);
        if (tmpImageData !== undefined) {
          return tmpImageData;
        }
      }

      if (element.nodeName === "CANVAS") {
        var mimeType;
        switch (format) {
          case "PNG":
            mimeType = "image/png";
            break;
          case "WEBP":
            mimeType = "image/webp";
            break;
          case "JPEG":
          case "JPG":
          default:
            mimeType = "image/jpeg";
            break;
        }
        return atob(
          element
            .toDataURL(mimeType, 1.0)
            .split("base64,")
            .pop()
        );
      }
    };

    var checkImagesForAlias = function(alias) {
      var images = this.internal.collections[namespace + "images"];
      if (images) {
        for (var e in images) {
          if (alias === images[e].alias) {
            return images[e];
          }
        }
      }
    };

    var determineWidthAndHeight = function(width, height, image) {
      if (!width && !height) {
        width = -96;
        height = -96;
      }
      if (width < 0) {
        width = (-1 * image.width * 72) / width / this.internal.scaleFactor;
      }
      if (height < 0) {
        height = (-1 * image.height * 72) / height / this.internal.scaleFactor;
      }
      if (width === 0) {
        width = (height * image.width) / image.height;
      }
      if (height === 0) {
        height = (width * image.height) / image.width;
      }

      return [width, height];
    };

    var writeImageToPDF = function(x, y, width, height, image, rotation) {
      var dims = determineWidthAndHeight.call(this, width, height, image),
        coord = this.internal.getCoordinateString,
        vcoord = this.internal.getVerticalCoordinateString;

      var images = getImages.call(this);

      width = dims[0];
      height = dims[1];
      images[image.index] = image;

      if (rotation) {
        rotation *= Math.PI / 180;
        var c = Math.cos(rotation);
        var s = Math.sin(rotation);
        //like in pdf Reference do it 4 digits instead of 2
        var f4 = function(number) {
          return number.toFixed(4);
        };
        var rotationTransformationMatrix = [
          f4(c),
          f4(s),
          f4(s * -1),
          f4(c),
          0,
          0,
          "cm"
        ];
      }
      this.internal.write("q"); //Save graphics state
      if (rotation) {
        this.internal.write(
          [1, "0", "0", 1, coord(x), vcoord(y + height), "cm"].join(" ")
        ); //Translate
        this.internal.write(rotationTransformationMatrix.join(" ")); //Rotate
        this.internal.write(
          [coord(width), "0", "0", coord(height), "0", "0", "cm"].join(" ")
        ); //Scale
      } else {
        this.internal.write(
          [
            coord(width),
            "0",
            "0",
            coord(height),
            coord(x),
            vcoord(y + height),
            "cm"
          ].join(" ")
        ); //Translate and Scale
      }

      if (this.isAdvancedAPI()) {
        // draw image bottom up when in "advanced" API mode
        this.internal.write([1, 0, 0, -1, 0, 0, "cm"].join(" "));
      }

      this.internal.write("/I" + image.index + " Do"); //Paint Image
      this.internal.write("Q"); //Restore graphics state
    };

    /**
     * COLOR SPACES
     */
    var 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
     */
    var image_compression = (jsPDFAPI.image_compression = {
      NONE: "NONE",
      FAST: "FAST",
      MEDIUM: "MEDIUM",
      SLOW: "SLOW"
    });

    /**
     * @name sHashCode
     * @function
     * @param {string} data
     * @returns {string}
     */
    var sHashCode = (jsPDFAPI.__addimage__.sHashCode = function(data) {
      var hash = 0,
        i,
        len;

      if (typeof data === "string") {
        len = data.length;
        for (i = 0; i < len; i++) {
          hash = (hash << 5) - hash + data.charCodeAt(i);
          hash |= 0; // Convert to 32bit integer
        }
      } else if (isArrayBufferView(data)) {
        len = data.byteLength / 2;
        for (i = 0; i < len; i++) {
          hash = (hash << 5) - hash + data[i];
          hash |= 0; // Convert to 32bit integer
        }
      }
      return hash;
    });

    /**
     * Validates if given String is a valid Base64-String
     *
     * @name validateStringAsBase64
     * @public
     * @function
     * @param {String} possible Base64-String
     *
     * @returns {boolean}
     */
    var validateStringAsBase64 = (jsPDFAPI.__addimage__.validateStringAsBase64 = function(
      possibleBase64String
    ) {
      possibleBase64String = possibleBase64String || "";
      possibleBase64String.toString().trim();

      var result = true;

      if (possibleBase64String.length === 0) {
        result = false;
      }

      if (possibleBase64String.length % 4 !== 0) {
        result = false;
      }

      if (
        /^[A-Za-z0-9+/]+$/.test(
          possibleBase64String.substr(0, possibleBase64String.length - 2)
        ) === false
      ) {
        result = false;
      }

      if (
        /^[A-Za-z0-9/][A-Za-z0-9+/]|[A-Za-z0-9+/]=|==$/.test(
          possibleBase64String.substr(-2)
        ) === false
      ) {
        result = false;
      }
      return result;
    });

    /**
     * Strips out and returns info from a valid base64 data URI
     *
     * @name extractImageFromDataUrl
     * @function
     * @param {string} dataUrl a valid data URI of format 'data:[<MIME-type>][;base64],<data>'
     * @returns {Array}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>
     */
    var extractImageFromDataUrl = (jsPDFAPI.__addimage__.extractImageFromDataUrl = function(
      dataUrl
    ) {
      dataUrl = dataUrl || "";
      var dataUrlParts = dataUrl.split("base64,");
      var result = null;

      if (dataUrlParts.length === 2) {
        var extractedInfo = /^data:(\w*\/\w*);*(charset=[\w=-]*)*;*$/.exec(
          dataUrlParts[0]
        );
        if (Array.isArray(extractedInfo)) {
          result = {
            mimeType: extractedInfo[1],
            charset: extractedInfo[2],
            data: dataUrlParts[1]
          };
        }
      }
      return result;
    });

    /**
     * Check to see if ArrayBuffer is supported
     *
     * @name supportsArrayBuffer
     * @function
     * @returns {boolean}
     */
    var supportsArrayBuffer = (jsPDFAPI.__addimage__.supportsArrayBuffer = function() {
      return (
        typeof ArrayBuffer !== "undefined" && typeof Uint8Array !== "undefined"
      );
    });

    /**
     * Tests supplied object to determine if ArrayBuffer
     *
     * @name isArrayBuffer
     * @function
     * @param {Object} object an Object
     *
     * @returns {boolean}
     */
    jsPDFAPI.__addimage__.isArrayBuffer = function(object) {
      return supportsArrayBuffer() && object instanceof ArrayBuffer;
    };

    /**
     * Tests supplied object to determine if it implements the ArrayBufferView (TypedArray) interface
     *
     * @name isArrayBufferView
     * @function
     * @param {Object} object an Object
     * @returns {boolean}
     */
    var isArrayBufferView = (jsPDFAPI.__addimage__.isArrayBufferView = function(
      object
    ) {
      return (
        supportsArrayBuffer() &&
        typeof Uint32Array !== "undefined" &&
        (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)
      );
    });

    /**
     * Convert Binary String to ArrayBuffer
     *
     * @name binaryStringToUint8Array
     * @public
     * @function
     * @param {string} BinaryString with ImageData
     * @returns {Uint8Array}
     */
    var binaryStringToUint8Array = (jsPDFAPI.__addimage__.binaryStringToUint8Array = function(
      binary_string
    ) {
      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;
    });

    /**
     * Convert the Buffer to a Binary String
     *
     * @name arrayBufferToBinaryString
     * @public
     * @function
     * @param {ArrayBuffer} ArrayBuffer with ImageData
     *
     * @returns {String}
     */
    var arrayBufferToBinaryString = (jsPDFAPI.__addimage__.arrayBufferToBinaryString = function(
      buffer
    ) {
      try {
        return atob(btoa(String.fromCharCode.apply(null, buffer)));
      } catch (e) {
        if (
          typeof Uint8Array !== "undefined" &&
          typeof Uint8Array.prototype.reduce !== "undefined"
        ) {
          return new Uint8Array(buffer)
            .reduce(function(data, byte) {
              return data.push(String.fromCharCode(byte)), data;
            }, [])
            .join("");
        }
      }
    });

    /**
     * Adds an Image to the PDF.
     *
     * @name addImage
     * @public
     * @function
     * @param {string|HTMLImageElement|HTMLCanvasElement|Uint8Array} imageData imageData as base64 encoded DataUrl or Image-HTMLElement or Canvas-HTMLElement
     * @param {string} format format of file if filetype-recognition fails or in case of a Canvas-Element needs to be specified (default for Canvas is JPEG), e.g. 'JPEG', 'PNG', 'WEBP'
     * @param {number} x x Coordinate (in units declared at inception of PDF document) against left edge of the page
     * @param {number} y y Coordinate (in units declared at inception of PDF document) against upper edge of the page
     * @param {number} width width of the image (in units declared at inception of PDF document)
     * @param {number} height height of the Image (in units declared at inception of PDF document)
     * @param {string} alias alias of the image (if used multiple times)
     * @param {string} compression compression of the generated JPEG, can have the values 'NONE', 'FAST', 'MEDIUM' and 'SLOW'
     * @param {number} rotation rotation of the image in degrees (0-359)
     *
     * @returns jsPDF
     */
    jsPDFAPI.addImage = function() {
      var imageData, format, x, y, w, h, alias, compression, rotation;

      imageData = arguments[0];
      if (typeof arguments[1] === "number") {
        format = UNKNOWN;
        x = arguments[1];
        y = arguments[2];
        w = arguments[3];
        h = arguments[4];
        alias = arguments[5];
        compression = arguments[6];
        rotation = arguments[7];
      } else {
        format = arguments[1];
        x = arguments[2];
        y = arguments[3];
        w = arguments[4];
        h = arguments[5];
        alias = arguments[6];
        compression = arguments[7];
        rotation = arguments[8];
      }

      if (
        typeof imageData === "object" &&
        !isDOMElement(imageData) &&
        "imageData" in imageData
      ) {
        var options = imageData;

        imageData = options.imageData;
        format = options.format || format || UNKNOWN;
        x = options.x || x || 0;
        y = options.y || y || 0;
        w = options.w || options.width || w;
        h = options.h || options.height || h;
        alias = options.alias || alias;
        compression = options.compression || compression;
        rotation = options.rotation || options.angle || rotation;
      }

      //If compression is not explicitly set, determine if we should use compression
      var filter = this.internal.getFilters();
      if (compression === undefined && filter.indexOf("FlateEncode") !== -1) {
        compression = "SLOW";
      }

      if (isNaN(x) || isNaN(y)) {
        throw new Error("Invalid coordinates passed to jsPDF.addImage");
      }

      initialize.call(this);

      var image = processImageData.call(
        this,
        imageData,
        format,
        alias,
        compression
      );

      writeImageToPDF.call(this, x, y, w, h, image, rotation);

      return this;
    };

    var processImageData = function(imageData, format, alias, compression) {
      var result, dataAsBinaryString;

      if (
        typeof imageData === "string" &&
        getImageFileTypeByImageData(imageData) === UNKNOWN
      ) {
        imageData = unescape(imageData);
        var tmpImageData = convertBase64ToBinaryString(imageData, false);

        if (tmpImageData !== "") {
          imageData = tmpImageData;
        } else {
          tmpImageData = jsPDFAPI.loadFile(imageData, true);
          if (tmpImageData !== undefined) {
            imageData = tmpImageData;
          }
        }
      }

      if (isDOMElement(imageData)) {
        imageData = getImageDataFromElement(imageData, format);
      }

      format = getImageFileTypeByImageData(imageData, format);
      if (!isImageTypeSupported(format)) {
        throw new Error(
          "addImage does not support files of type '" +
            format +
            "', please ensure that a plugin for '" +
            format +
            "' support is added."
        );
      }

      // now do the heavy lifting

      if (notDefined(alias)) {
        alias = generateAliasFromImageData(imageData);
      }
      result = checkImagesForAlias.call(this, alias);

      if (!result) {
        if (supportsArrayBuffer()) {
          // no need to convert if imageData is already uint8array
          if (!(imageData instanceof Uint8Array)) {
            dataAsBinaryString = imageData;
            imageData = binaryStringToUint8Array(imageData);
          }
        }

        result = this["process" + format.toUpperCase()](
          imageData,
          getImageIndex.call(this),
          alias,
          checkCompressValue(compression),
          dataAsBinaryString
        );
      }

      if (!result) {
        throw new Error("An unknown error occurred whilst processing the image.");
      }
      return result;
    };

    /**
     * @name convertBase64ToBinaryString
     * @function
     * @param {string} stringData
     * @returns {string} binary string
     */
    var convertBase64ToBinaryString = (jsPDFAPI.__addimage__.convertBase64ToBinaryString = function(
      stringData,
      throwError
    ) {
      throwError = typeof throwError === "boolean" ? throwError : true;
      var base64Info;
      var imageData = "";
      var rawData;

      if (typeof stringData === "string") {
        base64Info = extractImageFromDataUrl(stringData);
        rawData = base64Info !== null ? base64Info.data : stringData;

        try {
          imageData = atob(rawData);
        } catch (e) {
          if (throwError) {
            if (!validateStringAsBase64(rawData)) {
              throw new Error(
                "Supplied Data is not a valid base64-String jsPDF.convertBase64ToBinaryString "
              );
            } else {
              throw new Error(
                "atob-Error in jsPDF.convertBase64ToBinaryString " + e.message
              );
            }
          }
        }
      }
      return imageData;
    });

    /**
     * @name getImageProperties
     * @function
     * @param {Object} imageData
     * @returns {Object}
     */
    jsPDFAPI.getImageProperties = function(imageData) {
      var image;
      var tmpImageData = "";
      var format;

      if (isDOMElement(imageData)) {
        imageData = getImageDataFromElement(imageData);
      }

      if (
        typeof imageData === "string" &&
        getImageFileTypeByImageData(imageData) === UNKNOWN
      ) {
        tmpImageData = convertBase64ToBinaryString(imageData, false);

        if (tmpImageData === "") {
          tmpImageData = jsPDFAPI.loadFile(imageData) || "";
        }
        imageData = tmpImageData;
      }

      format = getImageFileTypeByImageData(imageData);
      if (!isImageTypeSupported(format)) {
        throw new Error(
          "addImage does not support files of type '" +
            format +
            "', please ensure that a plugin for '" +
            format +
            "' support is added."
        );
      }

      if (supportsArrayBuffer() && !(imageData instanceof Uint8Array)) {
        imageData = binaryStringToUint8Array(imageData);
      }

      image = this["process" + format.toUpperCase()](imageData);

      if (!image) {
        throw new Error("An unknown error occurred whilst processing the image");
      }

      image.fileType = format;

      return image;
    };
  })(jsPDF.API);

  /**
   * @license
   * Copyright (c) 2014 Steven Spungin (TwelveTone LLC)  steven@twelvetone.tv
   *
   * Licensed under the MIT License.
   * http://opensource.org/licenses/mit-license
   */

  (function(jsPDFAPI) {

    var notEmpty = function(obj) {
      if (typeof obj != "undefined") {
        if (obj != "") {
          return true;
        }
      }
    };

    jsPDF.API.events.push([
      "addPage",
      function(addPageData) {
        var pageInfo = this.internal.getPageInfo(addPageData.pageNumber);
        pageInfo.pageContext.annotations = [];
      }
    ]);

    jsPDFAPI.events.push([
      "putPage",
      function(putPageData) {
        var getHorizontalCoordinateString = this.internal.getCoordinateString;
        var getVerticalCoordinateString = this.internal
          .getVerticalCoordinateString;
        var pageInfo = this.internal.getPageInfoByObjId(putPageData.objId);
        var pageAnnos = putPageData.pageContext.annotations;

        var anno, rect, line;
        var found = false;
        for (var a = 0; a < pageAnnos.length && !found; a++) {
          anno = pageAnnos[a];
          switch (anno.type) {
            case "link":
              if (
                notEmpty(anno.options.url) ||
                notEmpty(anno.options.pageNumber)
              ) {
                found = true;
              }
              break;
            case "reference":
            case "text":
            case "freetext":
              found = true;
              break;
          }
        }
        if (found == false) {
          return;
        }

        this.internal.write("/Annots [");
        for (var i = 0; i < pageAnnos.length; i++) {
          anno = pageAnnos[i];
          var escape = this.internal.pdfEscape;
          var encryptor = this.internal.getEncryptor(putPageData.objId);

          switch (anno.type) {
            case "reference":
              // References to Widget Annotations (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 encryptorText = this.internal.getEncryptor(objText.objId);

              var title = anno.title || "Note";
              rect =
                "/Rect [" +
                getHorizontalCoordinateString(anno.bounds.x) +
                " " +
                getVerticalCoordinateString(anno.bounds.y + anno.bounds.h) +
                " " +
                getHorizontalCoordinateString(anno.bounds.x + anno.bounds.w) +
                " " +
                getVerticalCoordinateString(anno.bounds.y) +
                "] ";

              line =
                "<</Type /Annot /Subtype /" +
                "Text" +
                " " +
                rect +
                "/Contents (" +
                escape(encryptorText(anno.contents)) +
                ")";
              line += " /Popup " + objPopup.objId + " 0 R";
              line += " /P " + pageInfo.objId + " 0 R";
              line += " /T (" + escape(encryptorText(title)) + ") >>";
              objText.content = line;

              var parent = objText.objId + " 0 R";
              var popoff = 30;
              rect =
                "/Rect [" +
                getHorizontalCoordinateString(anno.bounds.x + popoff) +
                " " +
                getVerticalCoordinateString(anno.bounds.y + anno.bounds.h) +
                " " +
                getHorizontalCoordinateString(
                  anno.bounds.x + anno.bounds.w + popoff
                ) +
                " " +
                getVerticalCoordinateString(anno.bounds.y) +
                "] ";
              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":
              rect =
                "/Rect [" +
                getHorizontalCoordinateString(anno.bounds.x) +
                " " +
                getVerticalCoordinateString(anno.bounds.y) +
                " " +
                getHorizontalCoordinateString(anno.bounds.x + anno.bounds.w) +
                " " +
                getVerticalCoordinateString(anno.bounds.y + anno.bounds.h) +
                "] ";
              var color = anno.color || "#000000";
              line =
                "<</Type /Annot /Subtype /" +
                "FreeText" +
                " " +
                rect +
                "/Contents (" +
                escape(encryptor(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;
                }
              }

              rect =
                "/Rect [" +
                anno.finalBounds.x +
                " " +
                anno.finalBounds.y +
                " " +
                anno.finalBounds.w +
                " " +
                anno.finalBounds.h +
                "] ";

              line = "";
              if (anno.options.url) {
                line =
                  "<</Type /Annot /Subtype /Link " +
                  rect +
                  "/Border [0 0 0] /A <</S /URI /URI (" +
                  escape(encryptor(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":
                    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 = getVerticalCoordinateString(anno.options.top);
                    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;
                }
              }

              if (line != "") {
                line += " >>";
                this.internal.write(line);
              }
              break;
          }
        }
        this.internal.write("]");
      }
    ]);

    /**
     * @name createAnnotation
     * @function
     * @param {Object} options
     */
    jsPDFAPI.createAnnotation = function(options) {
      var pageInfo = this.internal.getCurrentPageInfo();
      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":
          pageInfo.pageContext.annotations.push(options);
          break;
      }
    };

    /**
     * Create a link
     *
     * valid options
     * <li> pageNumber or url [required]
     * <p>If pageNumber is specified, top and zoom may also be specified</p>
     * @name link
     * @function
     * @param {number} x
     * @param {number} y
     * @param {number} w
     * @param {number} h
     * @param {Object} options
     */
    jsPDFAPI.link = function(x, y, w, h, options) {
      var pageInfo = this.internal.getCurrentPageInfo();
      var getHorizontalCoordinateString = this.internal.getCoordinateString;
      var getVerticalCoordinateString = this.internal.getVerticalCoordinateString;

      pageInfo.pageContext.annotations.push({
        finalBounds: {
          x: getHorizontalCoordinateString(x),
          y: getVerticalCoordinateString(y),
          w: getHorizontalCoordinateString(x + w),
          h: getVerticalCoordinateString(y + h)
        },
        options: options,
        type: "link"
      });
    };

    /**
     * Currently only supports single line text.
     * Returns the width of the text/link
     *
     * @name textWithLink
     * @function
     * @param {string} text
     * @param {number} x
     * @param {number} y
     * @param {Object} options
     * @returns {number} width the width of the text/link
     */
    jsPDFAPI.textWithLink = function(text, x, y, options) {
      var width = this.getTextWidth(text);
      var height = this.internal.getLineHeight() / this.internal.scaleFactor;
      this.text(text, x, y, options);
      //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 * 0.2;
      this.link(x, y - height, width, height, options);
      return width;
    };

    //TODO move into external library
    /**
     * @name getTextWidth
     * @function
     * @param {string} text
     * @returns {number} txtWidth
     */
    jsPDFAPI.getTextWidth = function(text) {
      var fontSize = this.internal.getFontSize();
      var txtWidth =
        (this.getStringUnitWidth(text) * fontSize) / this.internal.scaleFactor;
      return txtWidth;
    };

    return this;
  })(jsPDF.API);

  /**
   * @license
   * Copyright (c) 2017 Aras Abbasi
   *
   * Licensed under the MIT License.
   * http://opensource.org/licenses/mit-license
   */

  /**
   * jsPDF arabic parser PlugIn
   *
   * @name arabic
   * @module
   */
  (function(jsPDFAPI) {

    /**
     * Arabic shape substitutions: char code => (isolated, final, initial, medial).
     * Arabic Substition A
     */
    var arabicSubstitionA = {
      0x0621: [0xfe80], // ARABIC LETTER HAMZA
      0x0622: [0xfe81, 0xfe82], // ARABIC LETTER ALEF WITH MADDA ABOVE
      0x0623: [0xfe83, 0xfe84], // ARABIC LETTER ALEF WITH HAMZA ABOVE
      0x0624: [0xfe85, 0xfe86], // ARABIC LETTER WAW WITH HAMZA ABOVE
      0x0625: [0xfe87, 0xfe88], // ARABIC LETTER ALEF WITH HAMZA BELOW
      0x0626: [0xfe89, 0xfe8a, 0xfe8b, 0xfe8c], // ARABIC LETTER YEH WITH HAMZA ABOVE
      0x0627: [0xfe8d, 0xfe8e], // ARABIC LETTER ALEF
      0x0628: [0xfe8f, 0xfe90, 0xfe91, 0xfe92], // ARABIC LETTER BEH
      0x0629: [0xfe93, 0xfe94], // ARABIC LETTER TEH MARBUTA
      0x062a: [0xfe95, 0xfe96, 0xfe97, 0xfe98], // ARABIC LETTER TEH
      0x062b: [0xfe99, 0xfe9a, 0xfe9b, 0xfe9c], // ARABIC LETTER THEH
      0x062c: [0xfe9d, 0xfe9e, 0xfe9f, 0xfea0], // ARABIC LETTER JEEM
      0x062d: [0xfea1, 0xfea2, 0xfea3, 0xfea4], // ARABIC LETTER HAH
      0x062e: [0xfea5, 0xfea6, 0xfea7, 0xfea8], // ARABIC LETTER KHAH
      0x062f: [0xfea9, 0xfeaa], // ARABIC LETTER DAL
      0x0630: [0xfeab, 0xfeac], // ARABIC LETTER THAL
      0x0631: [0xfead, 0xfeae], // ARABIC LETTER REH
      0x0632: [0xfeaf, 0xfeb0], // ARABIC LETTER ZAIN
      0x0633: [0xfeb1, 0xfeb2, 0xfeb3, 0xfeb4], // ARABIC LETTER SEEN
      0x0634: [0xfeb5, 0xfeb6, 0xfeb7, 0xfeb8], // ARABIC LETTER SHEEN
      0x0635: [0xfeb9, 0xfeba, 0xfebb, 0xfebc], // ARABIC LETTER SAD
      0x0636: [0xfebd, 0xfebe, 0xfebf, 0xfec0], // ARABIC LETTER DAD
      0x0637: [0xfec1, 0xfec2, 0xfec3, 0xfec4], // ARABIC LETTER TAH
      0x0638: [0xfec5, 0xfec6, 0xfec7, 0xfec8], // ARABIC LETTER ZAH
      0x0639: [0xfec9, 0xfeca, 0xfecb, 0xfecc], // ARABIC LETTER AIN
      0x063a: [0xfecd, 0xfece, 0xfecf, 0xfed0], // ARABIC LETTER GHAIN
      0x0641: [0xfed1, 0xfed2, 0xfed3, 0xfed4], // ARABIC LETTER FEH
      0x0642: [0xfed5, 0xfed6, 0xfed7, 0xfed8], // ARABIC LETTER QAF
      0x0643: [0xfed9, 0xfeda, 0xfedb, 0xfedc], // ARABIC LETTER KAF
      0x0644: [0xfedd, 0xfede, 0xfedf, 0xfee0], // ARABIC LETTER LAM
      0x0645: [0xfee1, 0xfee2, 0xfee3, 0xfee4], // ARABIC LETTER MEEM
      0x0646: [0xfee5, 0xfee6, 0xfee7, 0xfee8], // ARABIC LETTER NOON
      0x0647: [0xfee9, 0xfeea, 0xfeeb, 0xfeec], // ARABIC LETTER HEH
      0x0648: [0xfeed, 0xfeee], // ARABIC LETTER WAW
      0x0649: [0xfeef, 0xfef0, 64488, 64489], // ARABIC LETTER ALEF MAKSURA
      0x064a: [0xfef1, 0xfef2, 0xfef3, 0xfef4], // ARABIC LETTER YEH
      0x0671: [0xfb50, 0xfb51], // ARABIC LETTER ALEF WASLA
      0x0677: [0xfbdd], // ARABIC LETTER U WITH HAMZA ABOVE
      0x0679: [0xfb66, 0xfb67, 0xfb68, 0xfb69], // ARABIC LETTER TTEH
      0x067a: [0xfb5e, 0xfb5f, 0xfb60, 0xfb61], // ARABIC LETTER TTEHEH
      0x067b: [0xfb52, 0xfb53, 0xfb54, 0xfb55], // ARABIC LETTER BEEH
      0x067e: [0xfb56, 0xfb57, 0xfb58, 0xfb59], // ARABIC LETTER PEH
      0x067f: [0xfb62, 0xfb63, 0xfb64, 0xfb65], // ARABIC LETTER TEHEH
      0x0680: [0xfb5a, 0xfb5b, 0xfb5c, 0xfb5d], // ARABIC LETTER BEHEH
      0x0683: [0xfb76, 0xfb77, 0xfb78, 0xfb79], // ARABIC LETTER NYEH
      0x0684: [0xfb72, 0xfb73, 0xfb74, 0xfb75], // ARABIC LETTER DYEH
      0x0686: [0xfb7a, 0xfb7b, 0xfb7c, 0xfb7d], // ARABIC LETTER TCHEH
      0x0687: [0xfb7e, 0xfb7f, 0xfb80, 0xfb81], // ARABIC LETTER TCHEHEH
      0x0688: [0xfb88, 0xfb89], // ARABIC LETTER DDAL
      0x068c: [0xfb84, 0xfb85], // ARABIC LETTER DAHAL
      0x068d: [0xfb82, 0xfb83], // ARABIC LETTER DDAHAL
      0x068e: [0xfb86, 0xfb87], // ARABIC LETTER DUL
      0x0691: [0xfb8c, 0xfb8d], // ARABIC LETTER RREH
      0x0698: [0xfb8a, 0xfb8b], // ARABIC LETTER JEH
      0x06a4: [0xfb6a, 0xfb6b, 0xfb6c, 0xfb6d], // ARABIC LETTER VEH
      0x06a6: [0xfb6e, 0xfb6f, 0xfb70, 0xfb71], // ARABIC LETTER PEHEH
      0x06a9: [0xfb8e, 0xfb8f, 0xfb90, 0xfb91], // ARABIC LETTER KEHEH
      0x06ad: [0xfbd3, 0xfbd4, 0xfbd5, 0xfbd6], // ARABIC LETTER NG
      0x06af: [0xfb92, 0xfb93, 0xfb94, 0xfb95], // ARABIC LETTER GAF
      0x06b1: [0xfb9a, 0xfb9b, 0xfb9c, 0xfb9d], // ARABIC LETTER NGOEH
      0x06b3: [0xfb96, 0xfb97, 0xfb98, 0xfb99], // ARABIC LETTER GUEH
      0x06ba: [0xfb9e, 0xfb9f], // ARABIC LETTER NOON GHUNNA
      0x06bb: [0xfba0, 0xfba1, 0xfba2, 0xfba3], // ARABIC LETTER RNOON
      0x06be: [0xfbaa, 0xfbab, 0xfbac, 0xfbad], // ARABIC LETTER HEH DOACHASHMEE
      0x06c0: [0xfba4, 0xfba5], // ARABIC LETTER HEH WITH YEH ABOVE
      0x06c1: [0xfba6, 0xfba7, 0xfba8, 0xfba9], // ARABIC LETTER HEH GOAL
      0x06c5: [0xfbe0, 0xfbe1], // ARABIC LETTER KIRGHIZ OE
      0x06c6: [0xfbd9, 0xfbda], // ARABIC LETTER OE
      0x06c7: [0xfbd7, 0xfbd8], // ARABIC LETTER U
      0x06c8: [0xfbdb, 0xfbdc], // ARABIC LETTER YU
      0x06c9: [0xfbe2, 0xfbe3], // ARABIC LETTER KIRGHIZ YU
      0x06cb: [0xfbde, 0xfbdf], // ARABIC LETTER VE
      0x06cc: [0xfbfc, 0xfbfd, 0xfbfe, 0xfbff], // ARABIC LETTER FARSI YEH
      0x06d0: [0xfbe4, 0xfbe5, 0xfbe6, 0xfbe7], //ARABIC LETTER E
      0x06d2: [0xfbae, 0xfbaf], // ARABIC LETTER YEH BARREE
      0x06d3: [0xfbb0, 0xfbb1] // ARABIC LETTER YEH BARREE WITH HAMZA ABOVE
    };

    /*
      var ligaturesSubstitutionA = {
          0xFBEA: []// ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH ALEF ISOLATED FORM
      };
      */

    var ligatures = {
      0xfedf: {
        0xfe82: 0xfef5, // ARABIC LIGATURE LAM WITH ALEF WITH MADDA ABOVE ISOLATED FORM
        0xfe84: 0xfef7, // ARABIC LIGATURE LAM WITH ALEF WITH HAMZA ABOVE ISOLATED FORM
        0xfe88: 0xfef9, // ARABIC LIGATURE LAM WITH ALEF WITH HAMZA BELOW ISOLATED FORM
        0xfe8e: 0xfefb // ARABIC LIGATURE LAM WITH ALEF ISOLATED FORM
      },
      0xfee0: {
        0xfe82: 0xfef6, // ARABIC LIGATURE LAM WITH ALEF WITH MADDA ABOVE FINAL FORM
        0xfe84: 0xfef8, // ARABIC LIGATURE LAM WITH ALEF WITH HAMZA ABOVE FINAL FORM
        0xfe88: 0xfefa, // ARABIC LIGATURE LAM WITH ALEF WITH HAMZA BELOW FINAL FORM
        0xfe8e: 0xfefc // ARABIC LIGATURE LAM WITH ALEF FINAL FORM
      },
      0xfe8d: { 0xfedf: { 0xfee0: { 0xfeea: 0xfdf2 } } }, // ALLAH
      0x0651: {
        0x064c: 0xfc5e, // Shadda + Dammatan
        0x064d: 0xfc5f, // Shadda + Kasratan
        0x064e: 0xfc60, // Shadda + Fatha
        0x064f: 0xfc61, // Shadda + Damma
        0x0650: 0xfc62 // Shadda + Kasra
      }
    };

    var arabic_diacritics = {
      1612: 64606, // Shadda + Dammatan
      1613: 64607, // Shadda + Kasratan
      1614: 64608, // Shadda + Fatha
      1615: 64609, // Shadda + Damma
      1616: 64610 // Shadda + Kasra
    };

    var alfletter = [1570, 1571, 1573, 1575];

    var noChangeInForm = -1;
    var isolatedForm = 0;
    var finalForm = 1;
    var initialForm = 2;
    var medialForm = 3;

    jsPDFAPI.__arabicParser__ = {};

    //private
    var isInArabicSubstitutionA = (jsPDFAPI.__arabicParser__.isInArabicSubstitutionA = function(
      letter
    ) {
      return typeof arabicSubstitionA[letter.charCodeAt(0)] !== "undefined";
    });

    var isArabicLetter = (jsPDFAPI.__arabicParser__.isArabicLetter = function(
      letter
    ) {
      return (
        typeof letter === "string" &&
        /^[\u0600-\u06FF\u0750-\u077F\u08A0-\u08FF\uFB50-\uFDFF\uFE70-\uFEFF]+$/.test(
          letter
        )
      );
    });

    var isArabicEndLetter = (jsPDFAPI.__arabicParser__.isArabicEndLetter = function(
      letter
    ) {
      return (
        isArabicLetter(letter) &&
        isInArabicSubstitutionA(letter) &&
        arabicSubstitionA[letter.charCodeAt(0)].length <= 2
      );
    });

    var isArabicAlfLetter = (jsPDFAPI.__arabicParser__.isArabicAlfLetter = function(
      letter
    ) {
      return (
        isArabicLetter(letter) && alfletter.indexOf(letter.charCodeAt(0)) >= 0
      );
    });

    jsPDFAPI.__arabicParser__.arabicLetterHasIsolatedForm = function(letter) {
      return (
        isArabicLetter(letter) &&
        isInArabicSubstitutionA(letter) &&
        arabicSubstitionA[letter.charCodeAt(0)].length >= 1
      );
    };

    var arabicLetterHasFinalForm = (jsPDFAPI.__arabicParser__.arabicLetterHasFinalForm = function(
      letter
    ) {
      return (
        isArabicLetter(letter) &&
        isInArabicSubstitutionA(letter) &&
        arabicSubstitionA[letter.charCodeAt(0)].length >= 2
      );
    });

    jsPDFAPI.__arabicParser__.arabicLetterHasInitialForm = function(letter) {
      return (
        isArabicLetter(letter) &&
        isInArabicSubstitutionA(letter) &&
        arabicSubstitionA[letter.charCodeAt(0)].length >= 3
      );
    };

    var arabicLetterHasMedialForm = (jsPDFAPI.__arabicParser__.arabicLetterHasMedialForm = function(
      letter
    ) {
      return (
        isArabicLetter(letter) &&
        isInArabicSubstitutionA(letter) &&
        arabicSubstitionA[letter.charCodeAt(0)].length == 4
      );
    });

    var resolveLigatures = (jsPDFAPI.__arabicParser__.resolveLigatures = function(
      letters
    ) {
      var i = 0;
      var tmpLigatures = ligatures;
      var result = "";
      var effectedLetters = 0;

      for (i = 0; i < letters.length; i += 1) {
        if (typeof tmpLigatures[letters.charCodeAt(i)] !== "undefined") {
          effectedLetters++;
          tmpLigatures = tmpLigatures[letters.charCodeAt(i)];

          if (typeof tmpLigatures === "number") {
            result += String.fromCharCode(tmpLigatures);
            tmpLigatures = ligatures;
            effectedLetters = 0;
          }
          if (i === letters.length - 1) {
            tmpLigatures = ligatures;
            result += letters.charAt(i - (effectedLetters - 1));
            i = i - (effectedLetters - 1);
            effectedLetters = 0;
          }
        } else {
          tmpLigatures = ligatures;
          result += letters.charAt(i - effectedLetters);
          i = i - effectedLetters;
          effectedLetters = 0;
        }
      }

      return result;
    });

    jsPDFAPI.__arabicParser__.isArabicDiacritic = function(letter) {
      return (
        letter !== undefined &&
        arabic_diacritics[letter.charCodeAt(0)] !== undefined
      );
    };

    var getCorrectForm = (jsPDFAPI.__arabicParser__.getCorrectForm = function(
      currentChar,
      beforeChar,
      nextChar
    ) {
      if (!isArabicLetter(currentChar)) {
        return -1;
      }

      if (isInArabicSubstitutionA(currentChar) === false) {
        return noChangeInForm;
      }
      if (
        !arabicLetterHasFinalForm(currentChar) ||
        (!isArabicLetter(beforeChar) && !isArabicLetter(nextChar)) ||
        (!isArabicLetter(nextChar) && isArabicEndLetter(beforeChar)) ||
        (isArabicEndLetter(currentChar) && !isArabicLetter(beforeChar)) ||
        (isArabicEndLetter(currentChar) && isArabicAlfLetter(beforeChar)) ||
        (isArabicEndLetter(currentChar) && isArabicEndLetter(beforeChar))
      ) {
        return isolatedForm;
      }

      if (
        arabicLetterHasMedialForm(currentChar) &&
        isArabicLetter(beforeChar) &&
        !isArabicEndLetter(beforeChar) &&
        isArabicLetter(nextChar) &&
        arabicLetterHasFinalForm(nextChar)
      ) {
        return medialForm;
      }

      if (isArabicEndLetter(currentChar) || !isArabicLetter(nextChar)) {
        return finalForm;
      }
      return initialForm;
    });

    /**
     * @name processArabic
     * @function
     * @param {string} text
     * @returns {string}
     */
    var parseArabic = function(text) {
      text = text || "";

      var result = "";
      var i = 0;
      var j = 0;
      var position = 0;
      var currentLetter = "";
      var prevLetter = "";
      var nextLetter = "";

      var words = text.split("\\s+");
      var newWords = [];
      for (i = 0; i < words.length; i += 1) {
        newWords.push("");
        for (j = 0; j < words[i].length; j += 1) {
          currentLetter = words[i][j];
          prevLetter = words[i][j - 1];
          nextLetter = words[i][j + 1];
          if (isArabicLetter(currentLetter)) {
            position = getCorrectForm(currentLetter, prevLetter, nextLetter);
            if (position !== -1) {
              newWords[i] += String.fromCharCode(
                arabicSubstitionA[currentLetter.charCodeAt(0)][position]
              );
            } else {
              newWords[i] += currentLetter;
            }
          } else {
            newWords[i] += currentLetter;
          }
        }

        newWords[i] = resolveLigatures(newWords[i]);
      }
      result = newWords.join(" ");

      return result;
    };

    var processArabic = (jsPDFAPI.__arabicParser__.processArabic = jsPDFAPI.processArabic = function() {
      var text =
        typeof arguments[0] === "string" ? arguments[0] : arguments[0].text;
      var tmpText = [];
      var result;

      if (Array.isArray(text)) {
        var i = 0;
        tmpText = [];
        for (i = 0; i < text.length; i += 1) {
          if (Array.isArray(text[i])) {
            tmpText.push([parseArabic(text[i][0]), text[i][1], text[i][2]]);
          } else {
            tmpText.push([parseArabic(text[i])]);
          }
        }
        result = tmpText;
      } else {
        result = parseArabic(text);
      }
      if (typeof arguments[0] === "string") {
        return result;
      } else {
        arguments[0].text = result;
        return arguments[0];
      }
    });

    jsPDFAPI.events.push(["preProcessText", processArabic]);
  })(jsPDF.API);

  /** @license
   * jsPDF Autoprint Plugin
   *
   * Licensed under the MIT License.
   * http://opensource.org/licenses/mit-license
   */

  /**
   * @name autoprint
   * @module
   */
  (function(jsPDFAPI) {

    /**
     * Makes the PDF automatically open the print-Dialog when opened in a PDF-viewer.
     *
     * @name autoPrint
     * @function
     * @param {Object} options (optional) Set the attribute variant to 'non-conform' (default) or 'javascript' to activate different methods of automatic printing when opening in a PDF-viewer .
     * @returns {jsPDF}
     * @example
     * var doc = new jsPDF();
     * doc.text(10, 10, 'This is a test');
     * doc.autoPrint({variant: 'non-conform'});
     * doc.save('autoprint.pdf');
     */
    jsPDFAPI.autoPrint = function(options) {
      var refAutoPrintTag;
      options = options || {};
      options.variant = options.variant || "non-conform";

      switch (options.variant) {
        case "javascript":
          //https://github.com/Rob--W/pdf.js/commit/c676ecb5a0f54677b9f3340c3ef2cf42225453bb
          this.addJS("print({});");
          break;
        case "non-conform":
        default:
          this.internal.events.subscribe("postPutResources", function() {
            refAutoPrintTag = this.internal.newObject();
            this.internal.out("<<");
            this.internal.out("/S /Named");
            this.internal.out("/Type /Action");
            this.internal.out("/N /Print");
            this.internal.out(">>");
            this.internal.out("endobj");
          });

          this.internal.events.subscribe("putCatalog", function() {
            this.internal.out("/OpenAction " + refAutoPrintTag + " 0 R");
          });
          break;
      }
      return this;
    };
  })(jsPDF.API);

  /**
   * @license
   * Copyright (c) 2014 Steven Spungin (TwelveTone LLC)  steven@twelvetone.tv
   *
   * Licensed under the MIT License.
   * http://opensource.org/licenses/mit-license
   */

  /**
   * jsPDF Canvas PlugIn
   * This plugin mimics the HTML5 Canvas
   *
   * The goal is to provide a way for current canvas users to print directly to a PDF.
   * @name canvas
   * @module
   */
  (function(jsPDFAPI) {

    /**
     * @class Canvas
     * @classdesc A Canvas Wrapper for jsPDF
     */
    var Canvas = function() {
      var jsPdfInstance = undefined;
      Object.defineProperty(this, "pdf", {
        get: function() {
          return jsPdfInstance;
        },
        set: function(value) {
          jsPdfInstance = value;
        }
      });

      var _width = 150;
      /**
       * The height property is a positive integer reflecting the height HTML attribute of the <canvas> element interpreted in CSS pixels. When the attribute is not specified, or if it is set to an invalid value, like a negative, the default value of 150 is used.
       * This is one of the two properties, the other being width, that controls the size of the canvas.
       *
       * @name width
       */
      Object.defineProperty(this, "width", {
        get: function() {
          return _width;
        },
        set: function(value) {
          if (isNaN(value) || Number.isInteger(value) === false || value < 0) {
            _width = 150;
          } else {
            _width = value;
          }
          if (this.getContext("2d").pageWrapXEnabled) {
            this.getContext("2d").pageWrapX = _width + 1;
          }
        }
      });

      var _height = 300;
      /**
       * The width property is a positive integer reflecting the width HTML attribute of the <canvas> element interpreted in CSS pixels. When the attribute is not specified, or if it is set to an invalid value, like a negative, the default value of 300 is used.
       * This is one of the two properties, the other being height, that controls the size of the canvas.
       *
       * @name height
       */
      Object.defineProperty(this, "height", {
        get: function() {
          return _height;
        },
        set: function(value) {
          if (isNaN(value) || Number.isInteger(value) === false || value < 0) {
            _height = 300;
          } else {
            _height = value;
          }
          if (this.getContext("2d").pageWrapYEnabled) {
            this.getContext("2d").pageWrapY = _height + 1;
          }
        }
      });

      var _childNodes = [];
      Object.defineProperty(this, "childNodes", {
        get: function() {
          return _childNodes;
        },
        set: function(value) {
          _childNodes = value;
        }
      });

      var _style = {};
      Object.defineProperty(this, "style", {
        get: function() {
          return _style;
        },
        set: function(value) {
          _style = value;
        }
      });

      Object.defineProperty(this, "parentNode", {});
    };

    /**
     * The getContext() method returns a drawing context on the canvas, or null if the context identifier is not supported.
     *
     * @name getContext
     * @function
     * @param {string} contextType Is a String containing the context identifier defining the drawing context associated to the canvas. Possible value is "2d", leading to the creation of a Context2D object representing a two-dimensional rendering context.
     * @param {object} contextAttributes
     */
    Canvas.prototype.getContext = function(contextType, contextAttributes) {
      contextType = contextType || "2d";
      var key;

      if (contextType !== "2d") {
        return null;
      }
      for (key in contextAttributes) {
        if (this.pdf.context2d.hasOwnProperty(key)) {
          this.pdf.context2d[key] = contextAttributes[key];
        }
      }
      this.pdf.context2d._canvas = this;
      return this.pdf.context2d;
    };

    /**
     * The toDataURL() method is just a stub to throw an error if accidently called.
     *
     * @name toDataURL
     * @function
     */
    Canvas.prototype.toDataURL = function() {
      throw new Error("toDataURL is not implemented.");
    };

    jsPDFAPI.events.push([
      "initialized",
      function() {
        this.canvas = new Canvas();
        this.canvas.pdf = this;
      }
    ]);

    return this;
  })(jsPDF.API);

  /**
   * @license
   * ====================================================================
   * 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
   *
   * 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.
   * ====================================================================
   */

  /**
   * @name cell
   * @module
   */
  (function(jsPDFAPI) {

    var NO_MARGINS = { left: 0, top: 0, bottom: 0, right: 0 };

    var px2pt = (0.264583 * 72) / 25.4;
    var printingHeaderRow = false;

    var _initialize = function() {
      if (typeof this.internal.__cell__ === "undefined") {
        this.internal.__cell__ = {};
        this.internal.__cell__.padding = 3;
        this.internal.__cell__.headerFunction = undefined;
        this.internal.__cell__.margins = Object.assign({}, NO_MARGINS);
        this.internal.__cell__.margins.width = this.getPageWidth();
        _reset.call(this);
      }
    };

    var _reset = function() {
      this.internal.__cell__.lastCell = new Cell();
      this.internal.__cell__.pages = 1;
    };

    var Cell = function() {
      var _x = arguments[0];
      Object.defineProperty(this, "x", {
        enumerable: true,
        get: function() {
          return _x;
        },
        set: function(value) {
          _x = value;
        }
      });
      var _y = arguments[1];
      Object.defineProperty(this, "y", {
        enumerable: true,
        get: function() {
          return _y;
        },
        set: function(value) {
          _y = value;
        }
      });
      var _width = arguments[2];
      Object.defineProperty(this, "width", {
        enumerable: true,
        get: function() {
          return _width;
        },
        set: function(value) {
          _width = value;
        }
      });
      var _height = arguments[3];
      Object.defineProperty(this, "height", {
        enumerable: true,
        get: function() {
          return _height;
        },
        set: function(value) {
          _height = value;
        }
      });
      var _text = arguments[4];
      Object.defineProperty(this, "text", {
        enumerable: true,
        get: function() {
          return _text;
        },
        set: function(value) {
          _text = value;
        }
      });
      var _lineNumber = arguments[5];
      Object.defineProperty(this, "lineNumber", {
        enumerable: true,
        get: function() {
          return _lineNumber;
        },
        set: function(value) {
          _lineNumber = value;
        }
      });
      var _align = arguments[6];
      Object.defineProperty(this, "align", {
        enumerable: true,
        get: function() {
          return _align;
        },
        set: function(value) {
          _align = value;
        }
      });

      return this;
    };

    Cell.prototype.clone = function() {
      return new Cell(
        this.x,
        this.y,
        this.width,
        this.height,
        this.text,
        this.lineNumber,
        this.align
      );
    };

    Cell.prototype.toArray = function() {
      return [
        this.x,
        this.y,
        this.width,
        this.height,
        this.text,
        this.lineNumber,
        this.align
      ];
    };

    /**
     * @name setHeaderFunction
     * @function
     * @param {function} func
     */
    jsPDFAPI.setHeaderFunction = function(func) {
      _initialize.call(this);
      this.internal.__cell__.headerFunction =
        typeof func === "function" ? func : undefined;
      return this;
    };

    /**
     * @name getTextDimensions
     * @function
     * @param {string} txt
     * @returns {Object} dimensions
     */
    jsPDFAPI.getTextDimensions = function(text, options) {
      _initialize.call(this);
      options = options || {};
      var fontSize = options.fontSize || this.getFontSize();
      var font = options.font || this.getFont();
      var scaleFactor = options.scaleFactor || this.internal.scaleFactor;
      var width = 0;
      var amountOfLines = 0;
      var height = 0;
      var tempWidth = 0;

      if (!Array.isArray(text) && typeof text !== "string") {
        if (typeof text === "number") {
          text = String(text);
        } else {
          throw new Error(
            "getTextDimensions expects text-parameter to be of type String or type Number or an Array of Strings."
          );
        }
      }

      const maxWidth = options.maxWidth;
      if (maxWidth > 0) {
        if (typeof text === "string") {
          text = this.splitTextToSize(text, maxWidth);
        } else if (Object.prototype.toString.call(text) === "[object Array]") {
          text = text.reduce(function(acc, textLine) {
            return acc.concat(scope.splitTextToSize(textLine, maxWidth));
          }, []);
        }
      } else {
        // Without the else clause, it will not work if you do not pass along maxWidth
        text = Array.isArray(text) ? text : [text];
      }

      for (var i = 0; i < text.length; i++) {
        tempWidth = this.getStringUnitWidth(text[i], { font: font }) * fontSize;
        if (width < tempWidth) {
          width = tempWidth;
        }
      }

      if (width !== 0) {
        amountOfLines = text.length;
      }

      width = width / scaleFactor;
      height = Math.max(
        (amountOfLines * fontSize * this.getLineHeightFactor() -
          fontSize * (this.getLineHeightFactor() - 1)) /
          scaleFactor,
        0
      );
      return { w: width, h: height };
    };

    /**
     * @name cellAddPage
     * @function
     */
    jsPDFAPI.cellAddPage = function() {
      _initialize.call(this);

      this.addPage();

      var margins = this.internal.__cell__.margins || NO_MARGINS;
      this.internal.__cell__.lastCell = new Cell(
        margins.left,
        margins.top,
        undefined,
        undefined
      );
      this.internal.__cell__.pages += 1;

      return this;
    };

    /**
     * @name cell
     * @function
     * @param {number} x
     * @param {number} y
     * @param {number} width
     * @param {number} height
     * @param {string} text
     * @param {number} lineNumber lineNumber
     * @param {string} align
     * @return {jsPDF} jsPDF-instance
     */
    var cell = (jsPDFAPI.cell = function() {
      var currentCell;

      if (arguments[0] instanceof Cell) {
        currentCell = arguments[0];
      } else {
        currentCell = new Cell(
          arguments[0],
          arguments[1],
          arguments[2],
          arguments[3],
          arguments[4],
          arguments[5]
        );
      }
      _initialize.call(this);
      var lastCell = this.internal.__cell__.lastCell;
      var padding = this.internal.__cell__.padding;
      var margins = this.internal.__cell__.margins || NO_MARGINS;
      var tableHeaderRow = this.internal.__cell__.tableHeaderRow;
      var printHeaders = this.internal.__cell__.printHeaders;
      // If this is not the first cell, we must change its position
      if (typeof lastCell.lineNumber !== "undefined") {
        if (lastCell.lineNumber === currentCell.lineNumber) {
          //Same line
          currentCell.x = (lastCell.x || 0) + (lastCell.width || 0);
          currentCell.y = lastCell.y || 0;
        } else {
          //New line
          if (
            lastCell.y + lastCell.height + currentCell.height + margins.bottom >
            this.getPageHeight()
          ) {
            this.cellAddPage();
            currentCell.y = margins.top;
            if (printHeaders && tableHeaderRow) {
              this.printHeaderRow(currentCell.lineNumber, true);
              currentCell.y += tableHeaderRow[0].height;
            }
          } else {
            currentCell.y = lastCell.y + lastCell.height || currentCell.y;
          }
        }
      }

      if (typeof currentCell.text[0] !== "undefined") {
        this.rect(
          currentCell.x,
          currentCell.y,
          currentCell.width,
          currentCell.height,
          printingHeaderRow === true ? "FD" : undefined
        );
        if (currentCell.align === "right") {
          this.text(
            currentCell.text,
            currentCell.x + currentCell.width - padding,
            currentCell.y + padding,
            { align: "right", baseline: "top" }
          );
        } else if (currentCell.align === "center") {
          this.text(
            currentCell.text,
            currentCell.x + currentCell.width / 2,
            currentCell.y + padding,
            {
              align: "center",
              baseline: "top",
              maxWidth: currentCell.width - padding - padding
            }
          );
        } else {
          this.text(
            currentCell.text,
            currentCell.x + padding,
            currentCell.y + padding,
            {
              align: "left",
              baseline: "top",
              maxWidth: currentCell.width - padding - padding
            }
          );
        }
      }
      this.internal.__cell__.lastCell = currentCell;
      return this;
    });

    /**
       * Create a table from a set of data.
       * @name table
       * @function
       * @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] An 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)
       * @param {Object} [config.padding] cell-padding in pt to use (optional)
       * @param {Object} [config.headerBackgroundColor] default is #c8c8c8 (optional)
       * @returns {jsPDF} jsPDF-instance
       */

    jsPDFAPI.table = function(x, y, data, headers, config) {
      _initialize.call(this);
      if (!data) {
        throw new Error("No data for PDF table.");
      }

      config = config || {};

      var headerNames = [],
        headerLabels = [],
        headerAligns = [],
        i,
        columnMatrix = {},
        columnWidths = {},
        column,
        columnMinWidths = [],
        j,
        tableHeaderConfigs = [],
        //set up defaults. If a value is provided in config, defaults will be overwritten:
        autoSize = config.autoSize || false,
        printHeaders = config.printHeaders === false ? false : true,
        fontSize =
          config.css && typeof config.css["font-size"] !== "undefined"
            ? config.css["font-size"] * 16
            : config.fontSize || 12,
        margins =
          config.margins ||
          Object.assign({ width: this.getPageWidth() }, NO_MARGINS),
        padding = typeof config.padding === "number" ? config.padding : 3,
        headerBackgroundColor = config.headerBackgroundColor || "#c8c8c8";

      _reset.call(this);

      this.internal.__cell__.printHeaders = printHeaders;
      this.internal.__cell__.margins = margins;
      this.internal.__cell__.table_font_size = fontSize;
      this.internal.__cell__.padding = padding;
      this.internal.__cell__.headerBackgroundColor = headerBackgroundColor;
      this.setFontSize(fontSize);

      // Set header values
      if (headers === undefined || headers === null) {
        // No headers defined so we derive from data
        headerNames = Object.keys(data[0]);
        headerLabels = headerNames;
        headerAligns = headerNames.map(function() {
          return "left";
        });
      } else if (Array.isArray(headers) && typeof headers[0] === "object") {
        headerNames = headers.map(function(header) {
          return header.name;
        });
        headerLabels = headers.map(function(header) {
          return header.prompt || header.name || "";
        });
        headerAligns = headerNames.map(function(header) {
          return header.align || "left";
        });
        // Split header configs into names and prompts
        for (i = 0; i < headers.length; i += 1) {
          columnWidths[headers[i].name] = headers[i].width * px2pt;
        }
      } else if (Array.isArray(headers) && typeof headers[0] === "string") {
        headerNames = headers;
        headerLabels = headerNames;
        headerAligns = headerNames.map(function() {
          return "left";
        });
      }

      if (autoSize) {
        var headerName;
        for (i = 0; i < headerNames.length; i += 1) {
          headerName = headerNames[i];

          // Create a matrix of columns e.g., {column_title: [row1_Record, row2_Record]}

          columnMatrix[headerName] = data.map(function(rec) {
            return rec[headerName];
          });

          // get header width
          this.setFont(undefined, "bold");
          columnMinWidths.push(
            this.getTextDimensions(headerLabels[i], {
              fontSize: this.internal.__cell__.table_font_size,
              scaleFactor: this.internal.scaleFactor
            }).w
          );
          column = columnMatrix[headerName];

          // get cell widths
          this.setFont(undefined, "normal");
          for (j = 0; j < column.length; j += 1) {
            columnMinWidths.push(
              this.getTextDimensions(column[j], {
                fontSize: this.internal.__cell__.table_font_size,
                scaleFactor: this.internal.scaleFactor
              }).w
            );
          }

          // get final column width
          columnWidths[headerName] =
            Math.max.apply(null, columnMinWidths) + padding + padding;

          //have to reset
          columnMinWidths = [];
        }
      }

      // -- Construct the table

      if (printHeaders) {
        var row = {};
        for (i = 0; i < headerNames.length; i += 1) {
          row[headerNames[i]] = {};
          row[headerNames[i]].text = headerLabels[i];
          row[headerNames[i]].align = headerAligns[i];
        }

        var rowHeight = calculateLineHeight.call(this, row, columnWidths);

        // Construct the header row
        tableHeaderConfigs = headerNames.map(function(value) {
          return new Cell(
            x,
            y,
            columnWidths[value],
            rowHeight,
            row[value].text,
            undefined,
            row[value].align
          );
        });

        // 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

      var align = headers.reduce(function(pv, cv) {
        pv[cv.name] = cv.align;
        return pv;
      }, {});
      for (i = 0; i < data.length; i += 1) {
        var lineHeight = calculateLineHeight.call(this, data[i], columnWidths);

        for (j = 0; j < headerNames.length; j += 1) {
          cell.call(
            this,
            new Cell(
              x,
              y,
              columnWidths[headerNames[j]],
              lineHeight,
              data[i][headerNames[j]],
              i + 2,
              align[headerNames[j]]
            )
          );
        }
      }
      this.internal.__cell__.table_x = x;
      this.internal.__cell__.table_y = y;
      return this;
    };

    /**
     * Calculate the height for containing the highest column
     *
     * @name calculateLineHeight
     * @function
     * @param {Object[]} model is the line of data we want to calculate the height of
     * @param {Integer[]} columnWidths is size of each column
     * @returns {number} lineHeight
     * @private
     */
    var calculateLineHeight = function calculateLineHeight(model, columnWidths) {
      var padding = this.internal.__cell__.padding;
      var fontSize = this.internal.__cell__.table_font_size;
      var scaleFactor = this.internal.scaleFactor;

      return Object.keys(model)
        .map(function(key) {
          var value = model[key];
          return this.splitTextToSize(
            value.hasOwnProperty("text") ? value.text : value,
            columnWidths[key] - padding - padding
          );
        }, this)
        .map(function(value) {
          return (
            (this.getLineHeightFactor() * value.length * fontSize) / scaleFactor +
            padding +
            padding
          );
        }, this)
        .reduce(function(pv, cv) {
          return Math.max(pv, cv);
        }, 0);
    };

    /**
     * Store the config for outputting a table header
     *
     * @name setTableHeaderRow
     * @function
     * @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 lineNumber parameter is excluded
     */
    jsPDFAPI.setTableHeaderRow = function(config) {
      _initialize.call(this);
      this.internal.__cell__.tableHeaderRow = config;
    };

    /**
     * Output the store header row
     *
     * @name printHeaderRow
     * @function
     * @param {number} lineNumber The line number to output the header at
     * @param {boolean} new_page
     */
    jsPDFAPI.printHeaderRow = function(lineNumber, new_page) {
      _initialize.call(this);
      if (!this.internal.__cell__.tableHeaderRow) {
        throw new Error("Property tableHeaderRow does not exist.");
      }

      var tableHeaderCell;

      printingHeaderRow = true;
      if (typeof this.internal.__cell__.headerFunction === "function") {
        var position = this.internal.__cell__.headerFunction(
          this,
          this.internal.__cell__.pages
        );
        this.internal.__cell__.lastCell = new Cell(
          position[0],
          position[1],
          position[2],
          position[3],
          undefined,
          -1
        );
      }
      this.setFont(undefined, "bold");

      var tempHeaderConf = [];
      for (var i = 0; i < this.internal.__cell__.tableHeaderRow.length; i += 1) {
        tableHeaderCell = this.internal.__cell__.tableHeaderRow[i].clone();
        if (new_page) {
          tableHeaderCell.y = this.internal.__cell__.margins.top || 0;
          tempHeaderConf.push(tableHeaderCell);
        }
        tableHeaderCell.lineNumber = lineNumber;
        this.setFillColor(this.internal.__cell__.headerBackgroundColor);
        cell.call(this, tableHeaderCell);
      }
      if (tempHeaderConf.length > 0) {
        this.setTableHeaderRow(tempHeaderConf);
      }
      this.setFont(undefined, "normal");
      printingHeaderRow = false;
    };
  })(jsPDF.API);

  /* eslint-disable no-fallthrough */

  /**
   * This plugin mimics the HTML5 CanvasRenderingContext2D.
   *
   * The goal is to provide a way for current canvas implementations to print directly to a PDF.
   *
   * @name context2d
   * @module
   */
  (function(jsPDFAPI) {
    var ContextLayer = function(ctx) {
      ctx = ctx || {};
      this.isStrokeTransparent = ctx.isStrokeTransparent || false;
      this.strokeOpacity = ctx.strokeOpacity || 1;
      this.strokeStyle = ctx.strokeStyle || "#000000";
      this.fillStyle = ctx.fillStyle || "#000000";
      this.isFillTransparent = ctx.isFillTransparent || false;
      this.fillOpacity = ctx.fillOpacity || 1;
      this.font = ctx.font || "10px sans-serif";
      this.textBaseline = ctx.textBaseline || "alphabetic";
      this.textAlign = ctx.textAlign || "left";
      this.lineWidth = ctx.lineWidth || 1;
      this.lineJoin = ctx.lineJoin || "miter";
      this.lineCap = ctx.lineCap || "butt";
      this.path = ctx.path || [];
      this.transform =
        typeof ctx.transform !== "undefined"
          ? ctx.transform.clone()
          : new Matrix();
      this.globalCompositeOperation = ctx.globalCompositeOperation || "normal";
      this.globalAlpha = ctx.globalAlpha || 1.0;
      this.clip_path = ctx.clip_path || [];
      this.currentPoint = ctx.currentPoint || new Point();
      this.miterLimit = ctx.miterLimit || 10.0;
      this.lastPoint = ctx.lastPoint || new Point();

      this.ignoreClearRect =
        typeof ctx.ignoreClearRect === "boolean" ? ctx.ignoreClearRect : true;
      return this;
    };

    //stub
    var f2,
      getHorizontalCoordinateString,
      getVerticalCoordinateString,
      getHorizontalCoordinate,
      getVerticalCoordinate,
      Point,
      Rectangle,
      Matrix,
      _ctx;
    jsPDFAPI.events.push([
      "initialized",
      function() {
        this.context2d = new Context2D(this);

        f2 = this.internal.f2;
        getHorizontalCoordinateString = this.internal.getCoordinateString;
        getVerticalCoordinateString = this.internal.getVerticalCoordinateString;
        getHorizontalCoordinate = this.internal.getHorizontalCoordinate;
        getVerticalCoordinate = this.internal.getVerticalCoordinate;
        Point = this.internal.Point;
        Rectangle = this.internal.Rectangle;
        Matrix = this.internal.Matrix;
        _ctx = new ContextLayer();
      }
    ]);

    var Context2D = function(pdf) {
      Object.defineProperty(this, "canvas", {
        get: function() {
          return { parentNode: false, style: false };
        }
      });

      var _pdf = pdf;
      Object.defineProperty(this, "pdf", {
        get: function() {
          return _pdf;
        }
      });

      var _pageWrapXEnabled = false;
      /**
       * @name pageWrapXEnabled
       * @type {boolean}
       * @default false
       */
      Object.defineProperty(this, "pageWrapXEnabled", {
        get: function() {
          return _pageWrapXEnabled;
        },
        set: function(value) {
          _pageWrapXEnabled = Boolean(value);
        }
      });

      var _pageWrapYEnabled = false;
      /**
       * @name pageWrapYEnabled
       * @type {boolean}
       * @default true
       */
      Object.defineProperty(this, "pageWrapYEnabled", {
        get: function() {
          return _pageWrapYEnabled;
        },
        set: function(value) {
          _pageWrapYEnabled = Boolean(value);
        }
      });

      var _posX = 0;
      /**
       * @name posX
       * @type {number}
       * @default 0
       */
      Object.defineProperty(this, "posX", {
        get: function() {
          return _posX;
        },
        set: function(value) {
          if (!isNaN(value)) {
            _posX = value;
          }
        }
      });

      var _posY = 0;
      /**
       * @name posY
       * @type {number}
       * @default 0
       */
      Object.defineProperty(this, "posY", {
        get: function() {
          return _posY;
        },
        set: function(value) {
          if (!isNaN(value)) {
            _posY = value;
          }
        }
      });

      var _autoPaging = false;
      /**
       * @name autoPaging
       * @type {boolean}
       * @default true
       */
      Object.defineProperty(this, "autoPaging", {
        get: function() {
          return _autoPaging;
        },
        set: function(value) {
          _autoPaging = Boolean(value);
        }
      });

      var lastBreak = 0;
      /**
       * @name lastBreak
       * @type {number}
       * @default 0
       */
      Object.defineProperty(this, "lastBreak", {
        get: function() {
          return lastBreak;
        },
        set: function(value) {
          lastBreak = value;
        }
      });

      var pageBreaks = [];
      /**
       * Y Position of page breaks.
       * @name pageBreaks
       * @type {number}
       * @default 0
       */
      Object.defineProperty(this, "pageBreaks", {
        get: function() {
          return pageBreaks;
        },
        set: function(value) {
          pageBreaks = value;
        }
      });

      /**
       * @name ctx
       * @type {object}
       * @default {}
       */
      Object.defineProperty(this, "ctx", {
        get: function() {
          return _ctx;
        },
        set: function(value) {
          if (value instanceof ContextLayer) {
            _ctx = value;
          }
        }
      });

      /**
       * @name path
       * @type {array}
       * @default []
       */
      Object.defineProperty(this, "path", {
        get: function() {
          return _ctx.path;
        },
        set: function(value) {
          _ctx.path = value;
        }
      });

      /**
       * @name ctxStack
       * @type {array}
       * @default []
       */
      var _ctxStack = [];
      Object.defineProperty(this, "ctxStack", {
        get: function() {
          return _ctxStack;
        },
        set: function(value) {
          _ctxStack = value;
        }
      });

      /**
       * Sets or returns the color, gradient, or pattern used to fill the drawing
       *
       * @name fillStyle
       * @default #000000
       * @property {(color|gradient|pattern)} value The color of the drawing. Default value is #000000<br />
       * A gradient object (linear or radial) used to fill the drawing (not supported by context2d)<br />
       * A pattern object to use to fill the drawing (not supported by context2d)
       */
      Object.defineProperty(this, "fillStyle", {
        get: function() {
          return this.ctx.fillStyle;
        },
        set: function(value) {
          var rgba;
          rgba = getRGBA(value);

          this.ctx.fillStyle = rgba.style;
          this.ctx.isFillTransparent = rgba.a === 0;
          this.ctx.fillOpacity = rgba.a;

          this.pdf.setFillColor(rgba.r, rgba.g, rgba.b, { a: rgba.a });
          this.pdf.setTextColor(rgba.r, rgba.g, rgba.b, { a: rgba.a });
        }
      });

      /**
       * Sets or returns the color, gradient, or pattern used for strokes
       *
       * @name strokeStyle
       * @default #000000
       * @property {color} color A CSS color value that indicates the stroke color of the drawing. Default value is #000000 (not supported by context2d)
       * @property {gradient} gradient A gradient object (linear or radial) used to create a gradient stroke (not supported by context2d)
       * @property {pattern} pattern A pattern object used to create a pattern stroke (not supported by context2d)
       */
      Object.defineProperty(this, "strokeStyle", {
        get: function() {
          return this.ctx.strokeStyle;
        },
        set: function(value) {
          var rgba = getRGBA(value);

          this.ctx.strokeStyle = rgba.style;
          this.ctx.isStrokeTransparent = rgba.a === 0;
          this.ctx.strokeOpacity = rgba.a;

          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);
          }
        }
      });

      /**
       * Sets or returns the style of the end caps for a line
       *
       * @name lineCap
       * @default butt
       * @property {(butt|round|square)} lineCap butt A flat edge is added to each end of the line <br/>
       * round A rounded end cap is added to each end of the line<br/>
       * square A square end cap is added to each end of the line<br/>
       */
      Object.defineProperty(this, "lineCap", {
        get: function() {
          return this.ctx.lineCap;
        },
        set: function(value) {
          if (["butt", "round", "square"].indexOf(value) !== -1) {
            this.ctx.lineCap = value;
            this.pdf.setLineCap(value);
          }
        }
      });

      /**
       * Sets or returns the current line width
       *
       * @name lineWidth
       * @default 1
       * @property {number} lineWidth The current line width, in pixels
       */
      Object.defineProperty(this, "lineWidth", {
        get: function() {
          return this.ctx.lineWidth;
        },
        set: function(value) {
          if (!isNaN(value)) {
            this.ctx.lineWidth = value;
            this.pdf.setLineWidth(value);
          }
        }
      });

      /**
       * Sets or returns the type of corner created, when two lines meet
       */
      Object.defineProperty(this, "lineJoin", {
        get: function() {
          return this.ctx.lineJoin;
        },
        set: function(value) {
          if (["bevel", "round", "miter"].indexOf(value) !== -1) {
            this.ctx.lineJoin = value;
            this.pdf.setLineJoin(value);
          }
        }
      });

      /**
       * A number specifying the miter limit ratio in coordinate space units. Zero, negative, Infinity, and NaN values are ignored. The default value is 10.0.
       *
       * @name miterLimit
       * @default 10
       */
      Object.defineProperty(this, "miterLimit", {
        get: function() {
          return this.ctx.miterLimit;
        },
        set: function(value) {
          if (!isNaN(value)) {
            this.ctx.miterLimit = value;
            this.pdf.setMiterLimit(value);
          }
        }
      });

      Object.defineProperty(this, "textBaseline", {
        get: function() {
          return this.ctx.textBaseline;
        },
        set: function(value) {
          this.ctx.textBaseline = value;
        }
      });

      Object.defineProperty(this, "textAlign", {
        get: function() {
          return this.ctx.textAlign;
        },
        set: function(value) {
          if (["right", "end", "center", "left", "start"].indexOf(value) !== -1) {
            this.ctx.textAlign = value;
          }
        }
      });

      Object.defineProperty(this, "font", {
        get: function() {
          return this.ctx.font;
        },
        set: function(value) {
          this.ctx.font = value;
          var rx, matches;

          //source: https://stackoverflow.com/a/10136041
          // eslint-disable-next-line no-useless-escape
          rx = /^\s*(?=(?:(?:[-a-z]+\s*){0,2}(italic|oblique))?)(?=(?:(?:[-a-z]+\s*){0,2}(small-caps))?)(?=(?:(?:[-a-z]+\s*){0,2}(bold(?:er)?|lighter|[1-9]00))?)(?:(?:normal|\1|\2|\3)\s*){0,3}((?:xx?-)?(?:small|large)|medium|smaller|larger|[.\d]+(?:\%|in|[cem]m|ex|p[ctx]))(?:\s*\/\s*(normal|[.\d]+(?:\%|in|[cem]m|ex|p[ctx])))?\s*([-_,\"\'\sa-z]+?)\s*$/i;
          matches = rx.exec(value);
          if (matches !== null) {
            var fontStyle = matches[1];
            var fontVariant = matches[2];
            var fontWeight = matches[3];
            var fontSize = matches[4];
            var lineHeight = matches[5];
            var fontFamily = matches[6];
          } else {
            return;
          }
          var rxFontSize = /^([.\d]+)((?:%|in|[cem]m|ex|p[ctx]))$/i;
          var fontSizeUnit = rxFontSize.exec(fontSize)[2];

          if ("px" === fontSizeUnit) {
            fontSize = Math.floor(
              parseFloat(fontSize) * this.pdf.internal.scaleFactor
            );
          } else if ("em" === fontSizeUnit) {
            fontSize = Math.floor(parseFloat(fontSize) * this.pdf.getFontSize());
          } else {
            fontSize = Math.floor(
              parseFloat(fontSize) * this.pdf.internal.scaleFactor
            );
          }

          this.pdf.setFontSize(fontSize);

          var style = "";
          if (
            fontWeight === "bold" ||
            parseInt(fontWeight, 10) >= 700 ||
            fontStyle === "bold"
          ) {
            style = "bold";
          }

          if (fontStyle === "italic") {
            style += "italic";
          }

          if (style.length === 0) {
            style = "normal";
          }

          var jsPdfFontName = "";
          var parts = fontFamily.replace(/"|'/g, "").split(/\s*,\s*/);

          var fallbackFonts = {
            arial: "Helvetica",
            Arial: "Helvetica",
            verdana: "Helvetica",
            Verdana: "Helvetica",
            helvetica: "Helvetica",
            Helvetica: "Helvetica",
            "sans-serif": "Helvetica",
            fixed: "Courier",
            monospace: "Courier",
            terminal: "Courier",
            cursive: "Times",
            fantasy: "Times",
            serif: "Times"
          };

          for (var i = 0; i < parts.length; i++) {
            if (
              this.pdf.internal.getFont(parts[i], style, {
                noFallback: true,
                disableWarning: true
              }) !== undefined
            ) {
              jsPdfFontName = parts[i];
              break;
            } else if (
              style === "bolditalic" &&
              this.pdf.internal.getFont(parts[i], "bold", {
                noFallback: true,
                disableWarning: true
              }) !== undefined
            ) {
              jsPdfFontName = parts[i];
              style = "bold";
            } else if (
              this.pdf.internal.getFont(parts[i], "normal", {
                noFallback: true,
                disableWarning: true
              }) !== undefined
            ) {
              jsPdfFontName = parts[i];
              style = "normal";
              break;
            }
          }
          if (jsPdfFontName === "") {
            for (var j = 0; j < parts.length; j++) {
              if (fallbackFonts[parts[j]]) {
                jsPdfFontName = fallbackFonts[parts[j]];
                break;
              }
            }
          }
          jsPdfFontName = jsPdfFontName === "" ? "Times" : jsPdfFontName;
          this.pdf.setFont(jsPdfFontName, style);
        }
      });

      Object.defineProperty(this, "globalCompositeOperation", {
        get: function() {
          return this.ctx.globalCompositeOperation;
        },
        set: function(value) {
          this.ctx.globalCompositeOperation = value;
        }
      });

      Object.defineProperty(this, "globalAlpha", {
        get: function() {
          return this.ctx.globalAlpha;
        },
        set: function(value) {
          this.ctx.globalAlpha = value;
        }
      });

      // Not HTML API
      Object.defineProperty(this, "ignoreClearRect", {
        get: function() {
          return this.ctx.ignoreClearRect;
        },
        set: function(value) {
          this.ctx.ignoreClearRect = Boolean(value);
        }
      });
    };

    Context2D.prototype.fill = function() {
      pathPreProcess.call(this, "fill", false);
    };

    /**
     * Actually draws the path you have defined
     *
     * @name stroke
     * @function
     * @description The stroke() method actually draws the path you have defined with all those moveTo() and lineTo() methods. The default color is black.
     */
    Context2D.prototype.stroke = function() {
      pathPreProcess.call(this, "stroke", false);
    };

    /**
     * Begins a path, or resets the current
     *
     * @name beginPath
     * @function
     * @description The beginPath() method begins a path, or resets the current path.
     */
    Context2D.prototype.beginPath = function() {
      this.path = [
        {
          type: "begin"
        }
      ];
    };

    /**
     * Moves the path to the specified point in the canvas, without creating a line
     *
     * @name moveTo
     * @function
     * @param x {Number} The x-coordinate of where to move the path to
     * @param y {Number} The y-coordinate of where to move the path to
     */
    Context2D.prototype.moveTo = function(x, y) {
      if (isNaN(x) || isNaN(y)) {
        console.error("jsPDF.context2d.moveTo: Invalid arguments", arguments);
        throw new Error("Invalid arguments passed to jsPDF.context2d.moveTo");
      }

      var pt = this.ctx.transform.applyToPoint(new Point(x, y));

      this.path.push({
        type: "mt",
        x: pt.x,
        y: pt.y
      });
      this.ctx.lastPoint = new Point(x, y);
    };

    /**
     * Creates a path from the current point back to the starting point
     *
     * @name closePath
     * @function
     * @description The closePath() method creates a path from the current point back to the starting point.
     */
    Context2D.prototype.closePath = function() {
      var pathBegin = new Point(0, 0);
      var i = 0;
      for (i = this.path.length - 1; i !== -1; i--) {
        if (this.path[i].type === "begin") {
          if (
            typeof this.path[i + 1] === "object" &&
            typeof this.path[i + 1].x === "number"
          ) {
            pathBegin = new Point(this.path[i + 1].x, this.path[i + 1].y);
            this.path.push({
              type: "lt",
              x: pathBegin.x,
              y: pathBegin.y
            });
            break;
          }
        }
      }
      if (
        typeof this.path[i + 2] === "object" &&
        typeof this.path[i + 2].x === "number"
      ) {
        this.path.push(JSON.parse(JSON.stringify(this.path[i + 2])));
      }
      this.path.push({
        type: "close"
      });
      this.ctx.lastPoint = new Point(pathBegin.x, pathBegin.y);
    };

    /**
     * Adds a new point and creates a line to that point from the last specified point in the canvas
     *
     * @name lineTo
     * @function
     * @param x The x-coordinate of where to create the line to
     * @param y The y-coordinate of where to create the line to
     * @description The lineTo() method adds a new point and creates a line TO that point FROM the last specified point in the canvas (this method does not draw the line).
     */
    Context2D.prototype.lineTo = function(x, y) {
      if (isNaN(x) || isNaN(y)) {
        console.error("jsPDF.context2d.lineTo: Invalid arguments", arguments);
        throw new Error("Invalid arguments passed to jsPDF.context2d.lineTo");
      }

      var pt = this.ctx.transform.applyToPoint(new Point(x, y));

      this.path.push({
        type: "lt",
        x: pt.x,
        y: pt.y
      });
      this.ctx.lastPoint = new Point(pt.x, pt.y);
    };

    /**
     * Clips a region of any shape and size from the original canvas
     *
     * @name clip
     * @function
     * @description The clip() method clips a region of any shape and size from the original canvas.
     */
    Context2D.prototype.clip = function() {
      this.ctx.clip_path = JSON.parse(JSON.stringify(this.path));
      pathPreProcess.call(this, null, true);
    };

    /**
     * Creates a cubic Bézier curve
     *
     * @name quadraticCurveTo
     * @function
     * @param cpx {Number} The x-coordinate of the Bézier control point
     * @param cpy {Number} The y-coordinate of the Bézier control point
     * @param x {Number} The x-coordinate of the ending point
     * @param y {Number} The y-coordinate of the ending point
     * @description The quadraticCurveTo() method adds a point to the current path by using the specified control points that represent a quadratic Bézier curve.<br /><br /> A quadratic Bézier curve requires two points. The first point is a control point that is used in the quadratic Bézier calculation and the second point is the ending point for the curve. The starting point for the curve is the last point in the current path. If a path does not exist, use the beginPath() and moveTo() methods to define a starting point.
     */
    Context2D.prototype.quadraticCurveTo = function(cpx, cpy, x, y) {
      if (isNaN(x) || isNaN(y) || isNaN(cpx) || isNaN(cpy)) {
        console.error(
          "jsPDF.context2d.quadraticCurveTo: Invalid arguments",
          arguments
        );
        throw new Error(
          "Invalid arguments passed to jsPDF.context2d.quadraticCurveTo"
        );
      }

      var pt0 = this.ctx.transform.applyToPoint(new Point(x, y));
      var pt1 = this.ctx.transform.applyToPoint(new Point(cpx, cpy));

      this.path.push({
        type: "qct",
        x1: pt1.x,
        y1: pt1.y,
        x: pt0.x,
        y: pt0.y
      });
      this.ctx.lastPoint = new Point(pt0.x, pt0.y);
    };

    /**
     * Creates a cubic Bézier curve
     *
     * @name bezierCurveTo
     * @function
     * @param cp1x {Number} The x-coordinate of the first Bézier control point
     * @param cp1y {Number} The y-coordinate of the first Bézier control point
     * @param cp2x {Number} The x-coordinate of the second Bézier control point
     * @param cp2y {Number} The y-coordinate of the second Bézier control point
     * @param x {Number} The x-coordinate of the ending point
     * @param y {Number} The y-coordinate of the ending point
     * @description The bezierCurveTo() method adds a point to the current path by using the specified control points that represent a cubic Bézier curve. <br /><br />A cubic bezier curve requires three points. The first two points are control points that are used in the cubic Bézier calculation and the last point is the ending point for the curve.  The starting point for the curve is the last point in the current path. If a path does not exist, use the beginPath() and moveTo() methods to define a starting point.
     */
    Context2D.prototype.bezierCurveTo = function(cp1x, cp1y, cp2x, cp2y, x, y) {
      if (
        isNaN(x) ||
        isNaN(y) ||
        isNaN(cp1x) ||
        isNaN(cp1y) ||
        isNaN(cp2x) ||
        isNaN(cp2y)
      ) {
        console.error(
          "jsPDF.context2d.bezierCurveTo: Invalid arguments",
          arguments
        );
        throw new Error(
          "Invalid arguments passed to jsPDF.context2d.bezierCurveTo"
        );
      }
      var pt0 = this.ctx.transform.applyToPoint(new Point(x, y));
      var pt1 = this.ctx.transform.applyToPoint(new Point(cp1x, cp1y));
      var pt2 = this.ctx.transform.applyToPoint(new Point(cp2x, cp2y));

      this.path.push({
        type: "bct",
        x1: pt1.x,
        y1: pt1.y,
        x2: pt2.x,
        y2: pt2.y,
        x: pt0.x,
        y: pt0.y
      });
      this.ctx.lastPoint = new Point(pt0.x, pt0.y);
    };

    /**
     * Creates an arc/curve (used to create circles, or parts of circles)
     *
     * @name arc
     * @function
     * @param x {Number} The x-coordinate of the center of the circle
     * @param y {Number} The y-coordinate of the center of the circle
     * @param radius {Number} The radius of the circle
     * @param startAngle {Number} The starting angle, in radians (0 is at the 3 o'clock position of the arc's circle)
     * @param endAngle {Number} The ending angle, in radians
     * @param counterclockwise {Boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise.
     * @description The arc() method creates an arc/curve (used to create circles, or parts of circles).
     */
    Context2D.prototype.arc = function(
      x,
      y,
      radius,
      startAngle,
      endAngle,
      counterclockwise
    ) {
      if (
        isNaN(x) ||
        isNaN(y) ||
        isNaN(radius) ||
        isNaN(startAngle) ||
        isNaN(endAngle)
      ) {
        console.error("jsPDF.context2d.arc: Invalid arguments", arguments);
        throw new Error("Invalid arguments passed to jsPDF.context2d.arc");
      }
      counterclockwise = Boolean(counterclockwise);

      if (!this.ctx.transform.isIdentity) {
        var xpt = this.ctx.transform.applyToPoint(new Point(x, y));
        x = xpt.x;
        y = xpt.y;

        var x_radPt = this.ctx.transform.applyToPoint(new Point(0, radius));
        var x_radPt0 = this.ctx.transform.applyToPoint(new Point(0, 0));
        radius = Math.sqrt(
          Math.pow(x_radPt.x - x_radPt0.x, 2) +
            Math.pow(x_radPt.y - x_radPt0.y, 2)
        );
      }
      if (Math.abs(endAngle - startAngle) >= 2 * Math.PI) {
        startAngle = 0;
        endAngle = 2 * Math.PI;
      }

      this.path.push({
        type: "arc",
        x: x,
        y: y,
        radius: radius,
        startAngle: startAngle,
        endAngle: endAngle,
        counterclockwise: counterclockwise
      });
      // this.ctx.lastPoint(new Point(pt.x,pt.y));
    };

    /**
     * Creates an arc/curve between two tangents
     *
     * @name arcTo
     * @function
     * @param x1 {Number} The x-coordinate of the first tangent
     * @param y1 {Number} The y-coordinate of the first tangent
     * @param x2 {Number} The x-coordinate of the second tangent
     * @param y2 {Number} The y-coordinate of the second tangent
     * @param radius The radius of the arc
     * @description The arcTo() method creates an arc/curve between two tangents on the canvas.
     */
    // eslint-disable-next-line no-unused-vars
    Context2D.prototype.arcTo = function(x1, y1, x2, y2, radius) {
      throw new Error("arcTo not implemented.");
    };

    /**
     * Creates a rectangle
     *
     * @name rect
     * @function
     * @param x {Number} The x-coordinate of the upper-left corner of the rectangle
     * @param y {Number} The y-coordinate of the upper-left corner of the rectangle
     * @param w {Number} The width of the rectangle, in pixels
     * @param h {Number} The height of the rectangle, in pixels
     * @description The rect() method creates a rectangle.
     */
    Context2D.prototype.rect = function(x, y, w, h) {
      if (isNaN(x) || isNaN(y) || isNaN(w) || isNaN(h)) {
        console.error("jsPDF.context2d.rect: Invalid arguments", arguments);
        throw new Error("Invalid arguments passed to jsPDF.context2d.rect");
      }
      this.moveTo(x, y);
      this.lineTo(x + w, y);
      this.lineTo(x + w, y + h);
      this.lineTo(x, y + h);
      this.lineTo(x, y);
      this.lineTo(x + w, y);
      this.lineTo(x, y);
    };

    /**
     * Draws a "filled" rectangle
     *
     * @name fillRect
     * @function
     * @param x {Number} The x-coordinate of the upper-left corner of the rectangle
     * @param y {Number} The y-coordinate of the upper-left corner of the rectangle
     * @param w {Number} The width of the rectangle, in pixels
     * @param h {Number} The height of the rectangle, in pixels
     * @description The fillRect() method draws a "filled" rectangle. The default color of the fill is black.
     */
    Context2D.prototype.fillRect = function(x, y, w, h) {
      if (isNaN(x) || isNaN(y) || isNaN(w) || isNaN(h)) {
        console.error("jsPDF.context2d.fillRect: Invalid arguments", arguments);
        throw new Error("Invalid arguments passed to jsPDF.context2d.fillRect");
      }
      if (isFillTransparent.call(this)) {
        return;
      }
      var tmp = {};
      if (this.lineCap !== "butt") {
        tmp.lineCap = this.lineCap;
        this.lineCap = "butt";
      }
      if (this.lineJoin !== "miter") {
        tmp.lineJoin = this.lineJoin;
        this.lineJoin = "miter";
      }

      this.beginPath();
      this.rect(x, y, w, h);
      this.fill();

      if (tmp.hasOwnProperty("lineCap")) {
        this.lineCap = tmp.lineCap;
      }
      if (tmp.hasOwnProperty("lineJoin")) {
        this.lineJoin = tmp.lineJoin;
      }
    };

    /**
     *     Draws a rectangle (no fill)
     *
     * @name strokeRect
     * @function
     * @param x {Number} The x-coordinate of the upper-left corner of the rectangle
     * @param y {Number} The y-coordinate of the upper-left corner of the rectangle
     * @param w {Number} The width of the rectangle, in pixels
     * @param h {Number} The height of the rectangle, in pixels
     * @description The strokeRect() method draws a rectangle (no fill). The default color of the stroke is black.
     */
    Context2D.prototype.strokeRect = function strokeRect(x, y, w, h) {
      if (isNaN(x) || isNaN(y) || isNaN(w) || isNaN(h)) {
        console.error("jsPDF.context2d.strokeRect: Invalid arguments", arguments);
        throw new Error("Invalid arguments passed to jsPDF.context2d.strokeRect");
      }
      if (isStrokeTransparent.call(this)) {
        return;
      }
      this.beginPath();
      this.rect(x, y, w, h);
      this.stroke();
    };

    /**
     * Clears the specified pixels within a given rectangle
     *
     * @name clearRect
     * @function
     * @param x {Number} The x-coordinate of the upper-left corner of the rectangle
     * @param y {Number} The y-coordinate of the upper-left corner of the rectangle
     * @param w {Number} The width of the rectangle to clear, in pixels
     * @param h {Number} The height of the rectangle to clear, in pixels
     * @description 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.
     *
     */
    Context2D.prototype.clearRect = function(x, y, w, h) {
      if (isNaN(x) || isNaN(y) || isNaN(w) || isNaN(h)) {
        console.error("jsPDF.context2d.clearRect: Invalid arguments", arguments);
        throw new Error("Invalid arguments passed to jsPDF.context2d.clearRect");
      }
      if (this.ignoreClearRect) {
        return;
      }

      this.fillStyle = "#ffffff";
      this.fillRect(x, y, w, h);
    };

    /**
     * Saves the state of the current context
     *
     * @name save
     * @function
     */
    Context2D.prototype.save = function(doStackPush) {
      doStackPush = typeof doStackPush === "boolean" ? doStackPush : true;
      var tmpPageNumber = this.pdf.internal.getCurrentPageInfo().pageNumber;
      for (var i = 0; i < this.pdf.internal.getNumberOfPages(); i++) {
        this.pdf.setPage(i + 1);
        this.pdf.internal.out("q");
      }
      this.pdf.setPage(tmpPageNumber);

      if (doStackPush) {
        this.ctx.fontSize = this.pdf.internal.getFontSize();
        var ctx = new ContextLayer(this.ctx);
        this.ctxStack.push(this.ctx);
        this.ctx = ctx;
      }
    };

    /**
     * Returns previously saved path state and attributes
     *
     * @name restore
     * @function
     */
    Context2D.prototype.restore = function(doStackPop) {
      doStackPop = typeof doStackPop === "boolean" ? doStackPop : true;
      var tmpPageNumber = this.pdf.internal.getCurrentPageInfo().pageNumber;
      for (var i = 0; i < this.pdf.internal.getNumberOfPages(); i++) {
        this.pdf.setPage(i + 1);
        this.pdf.internal.out("Q");
      }
      this.pdf.setPage(tmpPageNumber);

      if (doStackPop && this.ctxStack.length !== 0) {
        this.ctx = this.ctxStack.pop();
        this.fillStyle = this.ctx.fillStyle;
        this.strokeStyle = this.ctx.strokeStyle;
        this.font = this.ctx.font;
        this.lineCap = this.ctx.lineCap;
        this.lineWidth = this.ctx.lineWidth;
        this.lineJoin = this.ctx.lineJoin;
      }
    };

    /**
     * @name toDataURL
     * @function
     */
    Context2D.prototype.toDataURL = function() {
      throw new Error("toDataUrl not implemented.");
    };

    //helper functions

    /**
     * Get the decimal values of r, g, b and a
     *
     * @name getRGBA
     * @function
     * @private
     * @ignore
     */
    var getRGBA = function(style) {
      var rxRgb = /rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/;
      var rxRgba = /rgba\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*([\d.]+)\s*\)/;
      var rxTransparent = /transparent|rgba\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*0+\s*\)/;

      var r, g, b, a;

      if (style.isCanvasGradient === true) {
        style = style.getColor();
      }

      if (!style) {
        return { r: 0, g: 0, b: 0, a: 0, style: style };
      }

      if (rxTransparent.test(style)) {
        r = 0;
        g = 0;
        b = 0;
        a = 0;
      } else {
        var matches = rxRgb.exec(style);
        if (matches !== null) {
          r = parseInt(matches[1]);
          g = parseInt(matches[2]);
          b = parseInt(matches[3]);
          a = 1;
        } else {
          matches = rxRgba.exec(style);
          if (matches !== null) {
            r = parseInt(matches[1]);
            g = parseInt(matches[2]);
            b = parseInt(matches[3]);
            a = parseFloat(matches[4]);
          } else {
            a = 1;

            if (typeof style === "string" && style.charAt(0) !== "#") {
              var rgbColor = new RGBColor(style);
              if (rgbColor.ok) {
                style = rgbColor.toHex();
              } else {
                style = "#000000";
              }
            }

            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);
          }
        }
      }
      return { r: r, g: g, b: b, a: a, style: style };
    };

    /**
     * @name isFillTransparent
     * @function
     * @private
     * @ignore
     * @returns {Boolean}
     */
    var isFillTransparent = function() {
      return this.ctx.isFillTransparent || this.globalAlpha == 0;
    };

    /**
     * @name isStrokeTransparent
     * @function
     * @private
     * @ignore
     * @returns {Boolean}
     */
    var isStrokeTransparent = function() {
      return Boolean(this.ctx.isStrokeTransparent || this.globalAlpha == 0);
    };

    /**
     * Draws "filled" text on the canvas
     *
     * @name fillText
     * @function
     * @param text {String} Specifies the text that will be written on the canvas
     * @param x {Number} The x coordinate where to start painting the text (relative to the canvas)
     * @param y {Number} The y coordinate where to start painting the text (relative to the canvas)
     * @param maxWidth {Number} Optional. The maximum allowed width of the text, in pixels
     * @description The fillText() method draws filled text on the canvas. The default color of the text is black.
     */
    Context2D.prototype.fillText = function(text, x, y, maxWidth) {
      if (isNaN(x) || isNaN(y) || typeof text !== "string") {
        console.error("jsPDF.context2d.fillText: Invalid arguments", arguments);
        throw new Error("Invalid arguments passed to jsPDF.context2d.fillText");
      }
      maxWidth = isNaN(maxWidth) ? undefined : maxWidth;
      if (isFillTransparent.call(this)) {
        return;
      }

      y = getBaseline.call(this, y);
      var degs = rad2deg(this.ctx.transform.rotation);

      // We only use X axis as scale hint
      var scale = this.ctx.transform.scaleX;

      putText.call(this, {
        text: text,
        x: x,
        y: y,
        scale: scale,
        angle: degs,
        align: this.textAlign,
        maxWidth: maxWidth
      });
    };

    /**
     * Draws text on the canvas (no fill)
     *
     * @name strokeText
     * @function
     * @param text {String} Specifies the text that will be written on the canvas
     * @param x {Number} The x coordinate where to start painting the text (relative to the canvas)
     * @param y {Number} The y coordinate where to start painting the text (relative to the canvas)
     * @param maxWidth {Number} Optional. The maximum allowed width of the text, in pixels
     * @description The strokeText() method draws text (with no fill) on the canvas. The default color of the text is black.
     */
    Context2D.prototype.strokeText = function(text, x, y, maxWidth) {
      if (isNaN(x) || isNaN(y) || typeof text !== "string") {
        console.error("jsPDF.context2d.strokeText: Invalid arguments", arguments);
        throw new Error("Invalid arguments passed to jsPDF.context2d.strokeText");
      }
      if (isStrokeTransparent.call(this)) {
        return;
      }

      maxWidth = isNaN(maxWidth) ? undefined : maxWidth;
      y = getBaseline.call(this, y);

      var degs = rad2deg(this.ctx.transform.rotation);
      var scale = this.ctx.transform.scaleX;

      putText.call(this, {
        text: text,
        x: x,
        y: y,
        scale: scale,
        renderingMode: "stroke",
        angle: degs,
        align: this.textAlign,
        maxWidth: maxWidth
      });
    };

    /**
     * Returns an object that contains the width of the specified text
     *
     * @name measureText
     * @function
     * @param text {String} The text to be measured
     * @description The measureText() method returns an object that contains the width of the specified text, in pixels.
     * @returns {Number}
     */
    Context2D.prototype.measureText = function(text) {
      if (typeof text !== "string") {
        console.error(
          "jsPDF.context2d.measureText: Invalid arguments",
          arguments
        );
        throw new Error(
          "Invalid arguments passed to jsPDF.context2d.measureText"
        );
      }
      var pdf = this.pdf;
      var k = this.pdf.internal.scaleFactor;

      var fontSize = pdf.internal.getFontSize();
      var txtWidth =
        (pdf.getStringUnitWidth(text) * fontSize) / pdf.internal.scaleFactor;
      txtWidth *= Math.round(((k * 96) / 72) * 10000) / 10000;

      var TextMetrics = function(options) {
        options = options || {};
        var _width = options.width || 0;
        Object.defineProperty(this, "width", {
          get: function() {
            return _width;
          }
        });
        return this;
      };
      return new TextMetrics({ width: txtWidth });
    };

    //Transformations

    /**
     * Scales the current drawing bigger or smaller
     *
     * @name scale
     * @function
     * @param scalewidth {Number} Scales the width of the current drawing (1=100%, 0.5=50%, 2=200%, etc.)
     * @param scaleheight {Number} Scales the height of the current drawing (1=100%, 0.5=50%, 2=200%, etc.)
     * @description The scale() method scales the current drawing, bigger or smaller.
     */
    Context2D.prototype.scale = function(scalewidth, scaleheight) {
      if (isNaN(scalewidth) || isNaN(scaleheight)) {
        console.error("jsPDF.context2d.scale: Invalid arguments", arguments);
        throw new Error("Invalid arguments passed to jsPDF.context2d.scale");
      }
      var matrix = new Matrix(scalewidth, 0.0, 0.0, scaleheight, 0.0, 0.0);
      this.ctx.transform = this.ctx.transform.multiply(matrix);
    };

    /**
     * Rotates the current drawing
     *
     * @name rotate
     * @function
     * @param angle {Number} The rotation angle, in radians.
     * @description To calculate from degrees to radians: degrees*Math.PI/180. <br />
     * Example: to rotate 5 degrees, specify the following: 5*Math.PI/180
     */
    Context2D.prototype.rotate = function(angle) {
      if (isNaN(angle)) {
        console.error("jsPDF.context2d.rotate: Invalid arguments", arguments);
        throw new Error("Invalid arguments passed to jsPDF.context2d.rotate");
      }
      var matrix = new Matrix(
        Math.cos(angle),
        Math.sin(angle),
        -Math.sin(angle),
        Math.cos(angle),
        0.0,
        0.0
      );
      this.ctx.transform = this.ctx.transform.multiply(matrix);
    };

    /**
     * Remaps the (0,0) position on the canvas
     *
     * @name translate
     * @function
     * @param x {Number} The value to add to horizontal (x) coordinates
     * @param y {Number} The value to add to vertical (y) coordinates
     * @description The translate() method remaps the (0,0) position on the canvas.
     */
    Context2D.prototype.translate = function(x, y) {
      if (isNaN(x) || isNaN(y)) {
        console.error("jsPDF.context2d.translate: Invalid arguments", arguments);
        throw new Error("Invalid arguments passed to jsPDF.context2d.translate");
      }
      var matrix = new Matrix(1.0, 0.0, 0.0, 1.0, x, y);
      this.ctx.transform = this.ctx.transform.multiply(matrix);
    };

    /**
     * Replaces the current transformation matrix for the drawing
     *
     * @name transform
     * @function
     * @param a {Number} Horizontal scaling
     * @param b {Number} Horizontal skewing
     * @param c {Number} Vertical skewing
     * @param d {Number} Vertical scaling
     * @param e {Number} Horizontal moving
     * @param f {Number} Vertical moving
     * @description Each object on the canvas has a current transformation matrix.<br /><br />The transform() method replaces the current transformation matrix. It multiplies the current transformation matrix with the matrix described by:<br /><br /><br /><br />a    c    e<br /><br />b    d    f<br /><br />0    0    1<br /><br />In other words, the transform() method lets you scale, rotate, move, and skew the current context.
     */
    Context2D.prototype.transform = function(a, b, c, d, e, f) {
      if (isNaN(a) || isNaN(b) || isNaN(c) || isNaN(d) || isNaN(e) || isNaN(f)) {
        console.error("jsPDF.context2d.transform: Invalid arguments", arguments);
        throw new Error("Invalid arguments passed to jsPDF.context2d.transform");
      }
      var matrix = new Matrix(a, b, c, d, e, f);
      this.ctx.transform = this.ctx.transform.multiply(matrix);
    };

    /**
     * Resets the current transform to the identity matrix. Then runs transform()
     *
     * @name setTransform
     * @function
     * @param a {Number} Horizontal scaling
     * @param b {Number} Horizontal skewing
     * @param c {Number} Vertical skewing
     * @param d {Number} Vertical scaling
     * @param e {Number} Horizontal moving
     * @param f {Number} Vertical moving
     * @description Each object on the canvas has a current transformation matrix. <br /><br />The setTransform() method resets the current transform to the identity matrix, and then runs transform() with the same arguments.<br /><br />In other words, the setTransform() method lets you scale, rotate, move, and skew the current context.
     */
    Context2D.prototype.setTransform = function(a, b, c, d, e, f) {
      a = isNaN(a) ? 1 : a;
      b = isNaN(b) ? 0 : b;
      c = isNaN(c) ? 0 : c;
      d = isNaN(d) ? 1 : d;
      e = isNaN(e) ? 0 : e;
      f = isNaN(f) ? 0 : f;
      this.ctx.transform = new Matrix(a, b, c, d, e, f);
    };

    /**
     * Draws an image, canvas, or video onto the canvas
     *
     * @function
     * @param img {} Specifies the image, canvas, or video element to use
     * @param sx {Number} Optional. The x coordinate where to start clipping
     * @param sy {Number} Optional. The y coordinate where to start clipping
     * @param swidth {Number} Optional. The width of the clipped image
     * @param sheight {Number} Optional. The height of the clipped image
     * @param x {Number} The x coordinate where to place the image on the canvas
     * @param y {Number} The y coordinate where to place the image on the canvas
     * @param width {Number} Optional. The width of the image to use (stretch or reduce the image)
     * @param height {Number} Optional. The height of the image to use (stretch or reduce the image)
     */
    Context2D.prototype.drawImage = function(
      img,
      sx,
      sy,
      swidth,
      sheight,
      x,
      y,
      width,
      height
    ) {
      var imageProperties = this.pdf.getImageProperties(img);
      var factorX = 1;
      var factorY = 1;

      var clipFactorX = 1;
      var clipFactorY = 1;

      if (typeof swidth !== "undefined" && typeof width !== "undefined") {
        clipFactorX = width / swidth;
        clipFactorY = height / sheight;
        factorX = ((imageProperties.width / swidth) * width) / swidth;
        factorY = ((imageProperties.height / sheight) * height) / sheight;
      }

      //is sx and sy are set and x and y not, set x and y with values of sx and sy
      if (typeof x === "undefined") {
        x = sx;
        y = sy;
        sx = 0;
        sy = 0;
      }

      if (typeof swidth !== "undefined" && typeof width === "undefined") {
        width = swidth;
        height = sheight;
      }
      if (typeof swidth === "undefined" && typeof width === "undefined") {
        width = imageProperties.width;
        height = imageProperties.height;
      }

      var decomposedTransformationMatrix = this.ctx.transform.decompose();
      var angle = rad2deg(decomposedTransformationMatrix.rotate.shx);
      var matrix = new Matrix();
      matrix = matrix.multiply(decomposedTransformationMatrix.translate);
      matrix = matrix.multiply(decomposedTransformationMatrix.skew);
      matrix = matrix.multiply(decomposedTransformationMatrix.scale);
      var xRect = matrix.applyToRectangle(
        new Rectangle(
          x - sx * clipFactorX,
          y - sy * clipFactorY,
          swidth * factorX,
          sheight * factorY
        )
      );
      var pageArray = getPagesByPath.call(this, xRect);
      var pages = [];
      for (var ii = 0; ii < pageArray.length; ii += 1) {
        if (pages.indexOf(pageArray[ii]) === -1) {
          pages.push(pageArray[ii]);
        }
      }

      sortPages(pages);

      var clipPath;
      if (this.autoPaging) {
        var min = pages[0];
        var max = pages[pages.length - 1];
        for (var i = min; i < max + 1; i++) {
          this.pdf.setPage(i);

          if (this.ctx.clip_path.length !== 0) {
            var tmpPaths = this.path;
            clipPath = JSON.parse(JSON.stringify(this.ctx.clip_path));
            this.path = pathPositionRedo(
              clipPath,
              this.posX,
              -1 * this.pdf.internal.pageSize.height * (i - 1) + this.posY
            );
            drawPaths.call(this, "fill", true);
            this.path = tmpPaths;
          }
          var tmpRect = JSON.parse(JSON.stringify(xRect));
          tmpRect = pathPositionRedo(
            [tmpRect],
            this.posX,
            -1 * this.pdf.internal.pageSize.height * (i - 1) + this.posY
          )[0];
          this.pdf.addImage(
            img,
            "JPEG",
            tmpRect.x,
            tmpRect.y,
            tmpRect.w,
            tmpRect.h,
            null,
            null,
            angle
          );
        }
      } else {
        this.pdf.addImage(
          img,
          "JPEG",
          xRect.x,
          xRect.y,
          xRect.w,
          xRect.h,
          null,
          null,
          angle
        );
      }
    };

    var getPagesByPath = function(path, pageWrapX, pageWrapY) {
      var result = [];
      pageWrapX = pageWrapX || this.pdf.internal.pageSize.width;
      pageWrapY = pageWrapY || this.pdf.internal.pageSize.height;

      switch (path.type) {
        default:
        case "mt":
        case "lt":
          result.push(Math.floor((path.y + this.posY) / pageWrapY) + 1);
          break;
        case "arc":
          result.push(
            Math.floor((path.y + this.posY - path.radius) / pageWrapY) + 1
          );
          result.push(
            Math.floor((path.y + this.posY + path.radius) / pageWrapY) + 1
          );
          break;
        case "qct":
          var rectOfQuadraticCurve = getQuadraticCurveBoundary(
            this.ctx.lastPoint.x,
            this.ctx.lastPoint.y,
            path.x1,
            path.y1,
            path.x,
            path.y
          );
          result.push(Math.floor(rectOfQuadraticCurve.y / pageWrapY) + 1);
          result.push(
            Math.floor(
              (rectOfQuadraticCurve.y + rectOfQuadraticCurve.h) / pageWrapY
            ) + 1
          );
          break;
        case "bct":
          var rectOfBezierCurve = getBezierCurveBoundary(
            this.ctx.lastPoint.x,
            this.ctx.lastPoint.y,
            path.x1,
            path.y1,
            path.x2,
            path.y2,
            path.x,
            path.y
          );
          result.push(Math.floor(rectOfBezierCurve.y / pageWrapY) + 1);
          result.push(
            Math.floor((rectOfBezierCurve.y + rectOfBezierCurve.h) / pageWrapY) +
              1
          );
          break;
        case "rect":
          result.push(Math.floor((path.y + this.posY) / pageWrapY) + 1);
          result.push(Math.floor((path.y + path.h + this.posY) / pageWrapY) + 1);
      }

      for (var i = 0; i < result.length; i += 1) {
        while (this.pdf.internal.getNumberOfPages() < result[i]) {
          addPage.call(this);
        }
      }
      return result;
    };

    var addPage = function() {
      var fillStyle = this.fillStyle;
      var strokeStyle = this.strokeStyle;
      var font = this.font;
      var lineCap = this.lineCap;
      var lineWidth = this.lineWidth;
      var lineJoin = this.lineJoin;
      this.pdf.addPage();
      this.fillStyle = fillStyle;
      this.strokeStyle = strokeStyle;
      this.font = font;
      this.lineCap = lineCap;
      this.lineWidth = lineWidth;
      this.lineJoin = lineJoin;
    };

    var pathPositionRedo = function(paths, x, y) {
      for (var i = 0; i < paths.length; i++) {
        switch (paths[i].type) {
          case "bct":
            paths[i].x2 += x;
            paths[i].y2 += y;
          case "qct":
            paths[i].x1 += x;
            paths[i].y1 += y;
          case "mt":
          case "lt":
          case "arc":
          default:
            paths[i].x += x;
            paths[i].y += y;
        }
      }
      return paths;
    };

    var sortPages = function(pages) {
      return pages.sort(function(a, b) {
        return a - b;
      });
    };

    var pathPreProcess = function(rule, isClip) {
      var fillStyle = this.fillStyle;
      var strokeStyle = this.strokeStyle;
      var lineCap = this.lineCap;
      var oldLineWidth = this.lineWidth;
      var lineWidth = oldLineWidth * this.ctx.transform.scaleX;
      var lineJoin = this.lineJoin;

      var origPath = JSON.parse(JSON.stringify(this.path));
      var xPath = JSON.parse(JSON.stringify(this.path));
      var clipPath;
      var tmpPath;
      var pages = [];

      for (var i = 0; i < xPath.length; i++) {
        if (typeof xPath[i].x !== "undefined") {
          var page = getPagesByPath.call(this, xPath[i]);

          for (var ii = 0; ii < page.length; ii += 1) {
            if (pages.indexOf(page[ii]) === -1) {
              pages.push(page[ii]);
            }
          }
        }
      }

      for (var j = 0; j < pages.length; j++) {
        while (this.pdf.internal.getNumberOfPages() < pages[j]) {
          addPage.call(this);
        }
      }
      sortPages(pages);

      if (this.autoPaging) {
        var min = pages[0];
        var max = pages[pages.length - 1];
        for (var k = min; k < max + 1; k++) {
          this.pdf.setPage(k);

          this.fillStyle = fillStyle;
          this.strokeStyle = strokeStyle;
          this.lineCap = lineCap;
          this.lineWidth = lineWidth;
          this.lineJoin = lineJoin;

          if (this.ctx.clip_path.length !== 0) {
            var tmpPaths = this.path;
            clipPath = JSON.parse(JSON.stringify(this.ctx.clip_path));
            this.path = pathPositionRedo(
              clipPath,
              this.posX,
              -1 * this.pdf.internal.pageSize.height * (k - 1) + this.posY
            );
            drawPaths.call(this, rule, true);
            this.path = tmpPaths;
          }
          tmpPath = JSON.parse(JSON.stringify(origPath));
          this.path = pathPositionRedo(
            tmpPath,
            this.posX,
            -1 * this.pdf.internal.pageSize.height * (k - 1) + this.posY
          );
          if (isClip === false || k === 0) {
            drawPaths.call(this, rule, isClip);
          }
          this.lineWidth = oldLineWidth;
        }
      } else {
        this.lineWidth = lineWidth;
        drawPaths.call(this, rule, isClip);
        this.lineWidth = oldLineWidth;
      }
      this.path = origPath;
    };

    /**
     * Processes the paths
     *
     * @function
     * @param rule {String}
     * @param isClip {Boolean}
     * @private
     * @ignore
     */
    var drawPaths = function(rule, isClip) {
      if (rule === "stroke" && !isClip && isStrokeTransparent.call(this)) {
        return;
      }

      if (rule !== "stroke" && !isClip && isFillTransparent.call(this)) {
        return;
      }

      var moves = [];

      //var alpha = (this.ctx.fillOpacity < 1) ? this.ctx.fillOpacity : this.ctx.globalAlpha;
      var delta;
      var xPath = this.path;
      for (var i = 0; i < xPath.length; i++) {
        var pt = xPath[i];

        switch (pt.type) {
          case "begin":
            moves.push({
              begin: true
            });
            break;

          case "close":
            moves.push({
              close: true
            });
            break;

          case "mt":
            moves.push({
              start: pt,
              deltas: [],
              abs: []
            });
            break;

          case "lt":
            var iii = moves.length;
            if (!isNaN(xPath[i - 1].x)) {
              delta = [pt.x - xPath[i - 1].x, pt.y - xPath[i - 1].y];
              if (iii > 0) {
                for (iii; iii >= 0; iii--) {
                  if (
                    moves[iii - 1].close !== true &&
                    moves[iii - 1].begin !== true
                  ) {
                    moves[iii - 1].deltas.push(delta);
                    moves[iii - 1].abs.push(pt);
                    break;
                  }
                }
              }
            }
            break;

          case "bct":
            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":
            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;
            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":
            moves.push({
              deltas: [],
              abs: [],
              arc: true
            });

            if (Array.isArray(moves[moves.length - 1].abs)) {
              moves[moves.length - 1].abs.push(pt);
            }
            break;
        }
      }
      var style;
      if (!isClip) {
        if (rule === "stroke") {
          style = "stroke";
        } else {
          style = "fill";
        }
      } else {
        style = null;
      }

      for (var k = 0; k < moves.length; k++) {
        if (moves[k].arc) {
          var arcs = moves[k].abs;

          for (var ii = 0; ii < arcs.length; ii++) {
            var arc = arcs[ii];

            if (arc.type === "arc") {
              drawArc.call(
                this,
                arc.x,
                arc.y,
                arc.radius,
                arc.startAngle,
                arc.endAngle,
                arc.counterclockwise,
                undefined,
                isClip
              );
            } else {
              drawLine.call(this, arc.x, arc.y);
            }
          }
          putStyle.call(this, style);
          this.pdf.internal.out("h");
        }
        if (!moves[k].arc) {
          if (moves[k].close !== true && moves[k].begin !== true) {
            var x = moves[k].start.x;
            var y = moves[k].start.y;
            drawLines.call(this, moves[k].deltas, x, y);
          }
        }
      }

      if (style) {
        putStyle.call(this, style);
      }
      if (isClip) {
        doClip.call(this);
      }
    };

    var getBaseline = function(y) {
      var height =
        this.pdf.internal.getFontSize() / this.pdf.internal.scaleFactor;
      var descent = height * (this.pdf.internal.getLineHeightFactor() - 1);
      switch (this.ctx.textBaseline) {
        case "bottom":
          return y - descent;
        case "top":
          return y + height - descent;
        case "hanging":
          return y + height - 2 * descent;
        case "middle":
          return y + height / 2 - descent;
        case "ideographic":
          // TODO not implemented
          return y;
        case "alphabetic":
        default:
          return y;
      }
    };

    Context2D.prototype.createLinearGradient = function createLinearGradient() {
      var canvasGradient = function canvasGradient() {};

      canvasGradient.colorStops = [];
      canvasGradient.addColorStop = function(offset, color) {
        this.colorStops.push([offset, color]);
      };

      canvasGradient.getColor = function() {
        if (this.colorStops.length === 0) {
          return "#000000";
        }

        return this.colorStops[0][1];
      };

      canvasGradient.isCanvasGradient = true;
      return canvasGradient;
    };
    Context2D.prototype.createPattern = function createPattern() {
      return this.createLinearGradient();
    };
    Context2D.prototype.createRadialGradient = function createRadialGradient() {
      return this.createLinearGradient();
    };

    /**
     *
     * @param x Edge point X
     * @param y Edge point Y
     * @param r Radius
     * @param a1 start angle
     * @param a2 end angle
     * @param counterclockwise
     * @param style
     * @param isClip
     */
    var drawArc = function(x, y, r, a1, a2, counterclockwise, style, isClip) {
      var curves = createArc.call(this, r, a1, a2, counterclockwise);

      for (var i = 0; i < curves.length; i++) {
        var curve = curves[i];
        if ( i === 0) {
          doMove.call(this, curve.x1 + x, curve.y1 + y);
        }
        drawCurve.call(
          this,
          x,
          y,
          curve.x2,
          curve.y2,
          curve.x3,
          curve.y3,
          curve.x4,
          curve.y4
        );
      }

      if (!isClip) {
        putStyle.call(this, style);
      } else {
        doClip.call(this);
      }
    };

    var putStyle = function(style) {
      switch (style) {
        case "stroke":
          this.pdf.internal.out("S");
          break;
        case "fill":
          this.pdf.internal.out("f");
          break;
      }
    };

    var doClip = function() {
      this.pdf.clip();
      this.pdf.discardPath();
    };

    var doMove = function(x, y) {
      this.pdf.internal.out(
        getHorizontalCoordinateString(x) +
          " " +
          getVerticalCoordinateString(y) +
          " m"
      );
    };

    var putText = function(options) {
      var textAlign;
      switch (options.align) {
        case "right":
        case "end":
          textAlign = "right";
          break;
        case "center":
          textAlign = "center";
          break;
        case "left":
        case "start":
        default:
          textAlign = "left";
          break;
      }

      var pt = this.ctx.transform.applyToPoint(new Point(options.x, options.y));
      var decomposedTransformationMatrix = this.ctx.transform.decompose();
      var matrix = new Matrix();
      matrix = matrix.multiply(decomposedTransformationMatrix.translate);
      matrix = matrix.multiply(decomposedTransformationMatrix.skew);
      matrix = matrix.multiply(decomposedTransformationMatrix.scale);

      var textDimensions = this.pdf.getTextDimensions(options.text);
      var textRect = this.ctx.transform.applyToRectangle(
        new Rectangle(options.x, options.y, textDimensions.w, textDimensions.h)
      );
      var textXRect = matrix.applyToRectangle(
        new Rectangle(
          options.x,
          options.y - textDimensions.h,
          textDimensions.w,
          textDimensions.h
        )
      );
      var pageArray = getPagesByPath.call(this, textXRect);
      var pages = [];
      for (var ii = 0; ii < pageArray.length; ii += 1) {
        if (pages.indexOf(pageArray[ii]) === -1) {
          pages.push(pageArray[ii]);
        }
      }

      sortPages(pages);

      var clipPath, oldSize, oldLineWidth;
      if (this.autoPaging === true) {
        var min = pages[0];
        var max = pages[pages.length - 1];
        for (var i = min; i < max + 1; i++) {
          this.pdf.setPage(i);

          if (this.ctx.clip_path.length !== 0) {
            var tmpPaths = this.path;
            clipPath = JSON.parse(JSON.stringify(this.ctx.clip_path));
            this.path = pathPositionRedo(
              clipPath,
              this.posX,
              -1 * this.pdf.internal.pageSize.height * (i - 1) + this.posY
            );
            drawPaths.call(this, "fill", true);
            this.path = tmpPaths;
          }
          var tmpRect = JSON.parse(JSON.stringify(textRect));
          tmpRect = pathPositionRedo(
            [tmpRect],
            this.posX,
            -1 * this.pdf.internal.pageSize.height * (i - 1) + this.posY
          )[0];

          if (options.scale >= 0.01) {
            oldSize = this.pdf.internal.getFontSize();
            this.pdf.setFontSize(oldSize * options.scale);
            oldLineWidth = this.lineWidth;
            this.lineWidth = oldLineWidth * options.scale;
          }
          this.pdf.text(options.text, tmpRect.x, tmpRect.y, {
            angle: options.angle,
            align: textAlign,
            renderingMode: options.renderingMode,
            maxWidth: options.maxWidth
          });

          if (options.scale >= 0.01) {
            this.pdf.setFontSize(oldSize);
            this.lineWidth = oldLineWidth;
          }
        }
      } else {
        if (options.scale >= 0.01) {
          oldSize = this.pdf.internal.getFontSize();
          this.pdf.setFontSize(oldSize * options.scale);
          oldLineWidth = this.lineWidth;
          this.lineWidth = oldLineWidth * options.scale;
        }
        this.pdf.text(options.text, pt.x + this.posX, pt.y + this.posY, {
          angle: options.angle,
          align: textAlign,
          renderingMode: options.renderingMode,
          maxWidth: options.maxWidth
        });

        if (options.scale >= 0.01) {
          this.pdf.setFontSize(oldSize);
          this.lineWidth = oldLineWidth;
        }
      }
    };

    var drawLine = function(x, y, prevX, prevY) {
      prevX = prevX || 0;
      prevY = prevY || 0;

      this.pdf.internal.out(
        getHorizontalCoordinateString(x + prevX) +
          " " +
          getVerticalCoordinateString(y + prevY) +
          " l"
      );
    };

    var drawLines = function(lines, x, y) {
      return this.pdf.lines(lines, x, y, null, null);
    };

    var drawCurve = function(x, y, x1, y1, x2, y2, x3, y3) {
      this.pdf.internal.out(
        [
          f2(getHorizontalCoordinate(x1 + x)),
          f2(getVerticalCoordinate(y1 + y)),
          f2(getHorizontalCoordinate(x2 + x)),
          f2(getVerticalCoordinate(y2 + y)),
          f2(getHorizontalCoordinate(x3 + x)),
          f2(getVerticalCoordinate(y3 + y)),
          "c"
        ].join(" ")
      );
    };

    /**
     * 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.
     * @function createArc
     */
    var createArc = function(radius, startAngle, endAngle, anticlockwise) {
      var EPSILON = 0.00001; // Roughly 1/1000th of a degree, see below
      var twoPi = Math.PI * 2;
      var halfPi = Math.PI / 2.0;

      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 = [];

      // clockwise or counterclockwise
      var sgn = anticlockwise ? -1 : +1;

      var a1 = startAngle;
      for (; totalAngle > EPSILON; ) {
        var remain = sgn * Math.min(totalAngle, halfPi);
        var a2 = a1 + remain;
        curves.push(createSmallArc.call(this, radius, a1, a2));
        totalAngle -= Math.abs(a2 - a1);
        a1 = a2;
      }

      return curves;
    };

    /**
     * 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.
     */
    var createSmallArc = function(r, a1, a2) {
      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;

      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)
      };
    };

    var rad2deg = function(value) {
      return (value * 180) / Math.PI;
    };

    var getQuadraticCurveBoundary = function(sx, sy, cpx, cpy, ex, ey) {
      var midX1 = sx + (cpx - sx) * 0.5;
      var midY1 = sy + (cpy - sy) * 0.5;
      var midX2 = ex + (cpx - ex) * 0.5;
      var midY2 = ey + (cpy - ey) * 0.5;
      var resultX1 = Math.min(sx, ex, midX1, midX2);
      var resultX2 = Math.max(sx, ex, midX1, midX2);
      var resultY1 = Math.min(sy, ey, midY1, midY2);
      var resultY2 = Math.max(sy, ey, midY1, midY2);
      return new Rectangle(
        resultX1,
        resultY1,
        resultX2 - resultX1,
        resultY2 - resultY1
      );
    };

    //De Casteljau algorithm
    var getBezierCurveBoundary = function(ax, ay, bx, by, cx, cy, dx, dy) {
      var tobx = bx - ax;
      var toby = by - ay;
      var tocx = cx - bx;
      var tocy = cy - by;
      var todx = dx - cx;
      var tody = dy - cy;
      var precision = 40;
      var d,
        i,
        px,
        py,
        qx,
        qy,
        rx,
        ry,
        tx,
        ty,
        sx,
        sy,
        x,
        y,
        minx,
        miny,
        maxx,
        maxy,
        toqx,
        toqy,
        torx,
        tory,
        totx,
        toty;
      for (i = 0; i < precision + 1; i++) {
        d = i / precision;
        px = ax + d * tobx;
        py = ay + d * toby;
        qx = bx + d * tocx;
        qy = by + d * tocy;
        rx = cx + d * todx;
        ry = cy + d * tody;
        toqx = qx - px;
        toqy = qy - py;
        torx = rx - qx;
        tory = ry - qy;

        sx = px + d * toqx;
        sy = py + d * toqy;
        tx = qx + d * torx;
        ty = qy + d * tory;
        totx = tx - sx;
        toty = ty - sy;

        x = sx + d * totx;
        y = sy + d * toty;
        if (i == 0) {
          minx = x;
          miny = y;
          maxx = x;
          maxy = y;
        } else {
          minx = Math.min(minx, x);
          miny = Math.min(miny, y);
          maxx = Math.max(maxx, x);
          maxy = Math.max(maxy, y);
        }
      }
      return new Rectangle(
        Math.round(minx),
        Math.round(miny),
        Math.round(maxx - minx),
        Math.round(maxy - miny)
      );
    };
  })(jsPDF.API);

  function createCommonjsModule(fn, module) {
  	return module = { exports: {} }, fn(module, module.exports), module.exports;
  }

  var common = createCommonjsModule(function (module, exports) {


  var TYPED_OK =  (typeof Uint8Array !== 'undefined') &&
                  (typeof Uint16Array !== 'undefined') &&
                  (typeof Int32Array !== 'undefined');

  function _has(obj, key) {
    return Object.prototype.hasOwnProperty.call(obj, key);
  }

  exports.assign = function (obj /*from1, from2, from3, ...*/) {
    var sources = Array.prototype.slice.call(arguments, 1);
    while (sources.length) {
      var source = sources.shift();
      if (!source) { continue; }

      if (typeof source !== 'object') {
        throw new TypeError(source + 'must be non-object');
      }

      for (var p in source) {
        if (_has(source, p)) {
          obj[p] = source[p];
        }
      }
    }

    return obj;
  };


  // reduce buffer size, avoiding mem copy
  exports.shrinkBuf = function (buf, size) {
    if (buf.length === size) { return buf; }
    if (buf.subarray) { return buf.subarray(0, size); }
    buf.length = size;
    return buf;
  };


  var fnTyped = {
    arraySet: function (dest, src, src_offs, len, dest_offs) {
      if (src.subarray && dest.subarray) {
        dest.set(src.subarray(src_offs, src_offs + len), dest_offs);
        return;
      }
      // Fallback to ordinary array
      for (var i = 0; i < len; i++) {
        dest[dest_offs + i] = src[src_offs + i];
      }
    },
    // Join array of chunks to single array.
    flattenChunks: function (chunks) {
      var i, l, len, pos, chunk, result;

      // calculate data length
      len = 0;
      for (i = 0, l = chunks.length; i < l; i++) {
        len += chunks[i].length;
      }

      // join chunks
      result = new Uint8Array(len);
      pos = 0;
      for (i = 0, l = chunks.length; i < l; i++) {
        chunk = chunks[i];
        result.set(chunk, pos);
        pos += chunk.length;
      }

      return result;
    }
  };

  var fnUntyped = {
    arraySet: function (dest, src, src_offs, len, dest_offs) {
      for (var i = 0; i < len; i++) {
        dest[dest_offs + i] = src[src_offs + i];
      }
    },
    // Join array of chunks to single array.
    flattenChunks: function (chunks) {
      return [].concat.apply([], chunks);
    }
  };


  // Enable/Disable typed arrays use, for testing
  //
  exports.setTyped = function (on) {
    if (on) {
      exports.Buf8  = Uint8Array;
      exports.Buf16 = Uint16Array;
      exports.Buf32 = Int32Array;
      exports.assign(exports, fnTyped);
    } else {
      exports.Buf8  = Array;
      exports.Buf16 = Array;
      exports.Buf32 = Array;
      exports.assign(exports, fnUntyped);
    }
  };

  exports.setTyped(TYPED_OK);
  });
  var common_1 = common.assign;
  var common_2 = common.shrinkBuf;
  var common_3 = common.setTyped;
  var common_4 = common.Buf8;
  var common_5 = common.Buf16;
  var common_6 = common.Buf32;

  // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  //
  // This software is provided 'as-is', without any express or implied
  // warranty. In no event will the authors be held liable for any damages
  // arising from the use of this software.
  //
  // Permission is granted to anyone to use this software for any purpose,
  // including commercial applications, and to alter it and redistribute it
  // freely, subject to the following restrictions:
  //
  // 1. The origin of this software must not be misrepresented; you must not
  //   claim that you wrote the original software. If you use this software
  //   in a product, an acknowledgment in the product documentation would be
  //   appreciated but is not required.
  // 2. Altered source versions must be plainly marked as such, and must not be
  //   misrepresented as being the original software.
  // 3. This notice may not be removed or altered from any source distribution.

  /* eslint-disable space-unary-ops */



  /* Public constants ==========================================================*/
  /* ===========================================================================*/


  //var Z_FILTERED          = 1;
  //var Z_HUFFMAN_ONLY      = 2;
  //var Z_RLE               = 3;
  var Z_FIXED               = 4;
  //var Z_DEFAULT_STRATEGY  = 0;

  /* Possible values of the data_type field (though see inflate()) */
  var Z_BINARY              = 0;
  var Z_TEXT                = 1;
  //var Z_ASCII             = 1; // = Z_TEXT
  var Z_UNKNOWN             = 2;

  /*============================================================================*/


  function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }

  // From zutil.h

  var STORED_BLOCK = 0;
  var STATIC_TREES = 1;
  var DYN_TREES    = 2;
  /* The three kinds of block type */

  var MIN_MATCH    = 3;
  var MAX_MATCH    = 258;
  /* The minimum and maximum match lengths */

  // From deflate.h
  /* ===========================================================================
   * Internal compression state.
   */

  var LENGTH_CODES  = 29;
  /* number of length codes, not counting the special END_BLOCK code */

  var LITERALS      = 256;
  /* number of literal bytes 0..255 */

  var L_CODES       = LITERALS + 1 + LENGTH_CODES;
  /* number of Literal or Length codes, including the END_BLOCK code */

  var D_CODES       = 30;
  /* number of distance codes */

  var BL_CODES      = 19;
  /* number of codes used to transfer the bit lengths */

  var HEAP_SIZE     = 2 * L_CODES + 1;
  /* maximum heap size */

  var MAX_BITS      = 15;
  /* All codes must not exceed MAX_BITS bits */

  var Buf_size      = 16;
  /* size of bit buffer in bi_buf */


  /* ===========================================================================
   * Constants
   */

  var MAX_BL_BITS = 7;
  /* Bit length codes must not exceed MAX_BL_BITS bits */

  var END_BLOCK   = 256;
  /* end of block literal code */

  var REP_3_6     = 16;
  /* repeat previous bit length 3-6 times (2 bits of repeat count) */

  var REPZ_3_10   = 17;
  /* repeat a zero length 3-10 times  (3 bits of repeat count) */

  var REPZ_11_138 = 18;
  /* repeat a zero length 11-138 times  (7 bits of repeat count) */

  /* eslint-disable comma-spacing,array-bracket-spacing */
  var extra_lbits =   /* extra bits for each length code */
    [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];

  var extra_dbits =   /* extra bits for each distance code */
    [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];

  var extra_blbits =  /* extra bits for each bit length code */
    [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];

  var bl_order =
    [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  /* eslint-enable comma-spacing,array-bracket-spacing */

  /* The lengths of the bit length codes are sent in order of decreasing
   * probability, to avoid transmitting the lengths for unused bit length codes.
   */

  /* ===========================================================================
   * Local data. These are initialized only once.
   */

  // We pre-fill arrays with 0 to avoid uninitialized gaps

  var DIST_CODE_LEN = 512; /* see definition of array dist_code below */

  // !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1
  var static_ltree  = new Array((L_CODES + 2) * 2);
  zero(static_ltree);
  /* The static literal tree. Since the bit lengths are imposed, there is no
   * need for the L_CODES extra codes used during heap construction. However
   * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
   * below).
   */

  var static_dtree  = new Array(D_CODES * 2);
  zero(static_dtree);
  /* The static distance tree. (Actually a trivial tree since all codes use
   * 5 bits.)
   */

  var _dist_code    = new Array(DIST_CODE_LEN);
  zero(_dist_code);
  /* Distance codes. The first 256 values correspond to the distances
   * 3 .. 258, the last 256 values correspond to the top 8 bits of
   * the 15 bit distances.
   */

  var _length_code  = new Array(MAX_MATCH - MIN_MATCH + 1);
  zero(_length_code);
  /* length code for each normalized match length (0 == MIN_MATCH) */

  var base_length   = new Array(LENGTH_CODES);
  zero(base_length);
  /* First normalized length for each code (0 = MIN_MATCH) */

  var base_dist     = new Array(D_CODES);
  zero(base_dist);
  /* First normalized distance for each code (0 = distance of 1) */


  function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) {

    this.static_tree  = static_tree;  /* static tree or NULL */
    this.extra_bits   = extra_bits;   /* extra bits for each code or NULL */
    this.extra_base   = extra_base;   /* base index for extra_bits */
    this.elems        = elems;        /* max number of elements in the tree */
    this.max_length   = max_length;   /* max bit length for the codes */

    // show if `static_tree` has data or dummy - needed for monomorphic objects
    this.has_stree    = static_tree && static_tree.length;
  }


  var static_l_desc;
  var static_d_desc;
  var static_bl_desc;


  function TreeDesc(dyn_tree, stat_desc) {
    this.dyn_tree = dyn_tree;     /* the dynamic tree */
    this.max_code = 0;            /* largest code with non zero frequency */
    this.stat_desc = stat_desc;   /* the corresponding static tree */
  }



  function d_code(dist) {
    return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  }


  /* ===========================================================================
   * Output a short LSB first on the stream.
   * IN assertion: there is enough room in pendingBuf.
   */
  function put_short(s, w) {
  //    put_byte(s, (uch)((w) & 0xff));
  //    put_byte(s, (uch)((ush)(w) >> 8));
    s.pending_buf[s.pending++] = (w) & 0xff;
    s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  }


  /* ===========================================================================
   * Send a value on a given number of bits.
   * IN assertion: length <= 16 and value fits in length bits.
   */
  function send_bits(s, value, length) {
    if (s.bi_valid > (Buf_size - length)) {
      s.bi_buf |= (value << s.bi_valid) & 0xffff;
      put_short(s, s.bi_buf);
      s.bi_buf = value >> (Buf_size - s.bi_valid);
      s.bi_valid += length - Buf_size;
    } else {
      s.bi_buf |= (value << s.bi_valid) & 0xffff;
      s.bi_valid += length;
    }
  }


  function send_code(s, c, tree) {
    send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/);
  }


  /* ===========================================================================
   * 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, len) {
    var res = 0;
    do {
      res |= code & 1;
      code >>>= 1;
      res <<= 1;
    } while (--len > 0);
    return res >>> 1;
  }


  /* ===========================================================================
   * Flush the bit buffer, keeping at most 7 bits in it.
   */
  function bi_flush(s) {
    if (s.bi_valid === 16) {
      put_short(s, s.bi_buf);
      s.bi_buf = 0;
      s.bi_valid = 0;

    } else if (s.bi_valid >= 8) {
      s.pending_buf[s.pending++] = s.bi_buf & 0xff;
      s.bi_buf >>= 8;
      s.bi_valid -= 8;
    }
  }


  /* ===========================================================================
   * 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, desc)
  //    deflate_state *s;
  //    tree_desc *desc;    /* the tree descriptor */
  {
    var tree            = desc.dyn_tree;
    var max_code        = desc.max_code;
    var stree           = desc.stat_desc.static_tree;
    var has_stree       = desc.stat_desc.has_stree;
    var extra           = desc.stat_desc.extra_bits;
    var base            = desc.stat_desc.extra_base;
    var max_length      = desc.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]/*.Len*/ = 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]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
      if (bits > max_length) {
        bits = max_length;
        overflow++;
      }
      tree[n * 2 + 1]/*.Len*/ = bits;
      /* We overwrite tree[n].Dad which is no longer needed */

      if (n > max_code) { continue; } /* not a leaf node */

      s.bl_count[bits]++;
      xbits = 0;
      if (n >= base) {
        xbits = extra[n - base];
      }
      f = tree[n * 2]/*.Freq*/;
      s.opt_len += f * (bits + xbits);
      if (has_stree) {
        s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits);
      }
    }
    if (overflow === 0) { return; }

    // Trace((stderr,"\nbit length overflow\n"));
    /* 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);

    /* Now recompute all bit lengths, scanning in increasing frequency.
     * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
     * lengths instead of fixing only the wrong ones. This idea is taken
     * from 'ar' written by Haruhiko Okumura.)
     */
    for (bits = max_length; bits !== 0; bits--) {
      n = s.bl_count[bits];
      while (n !== 0) {
        m = s.heap[--h];
        if (m > max_code) { continue; }
        if (tree[m * 2 + 1]/*.Len*/ !== bits) {
          // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
          s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/;
          tree[m * 2 + 1]/*.Len*/ = bits;
        }
        n--;
      }
    }
  }


  /* ===========================================================================
   * 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, max_code, bl_count)
  //    ct_data *tree;             /* the tree to decorate */
  //    int max_code;              /* largest code with non zero frequency */
  //    ushf *bl_count;            /* number of codes at each bit length */
  {
    var next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */
    var code = 0;              /* running code value */
    var bits;                  /* bit index */
    var n;                     /* code index */

    /* 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++) {
      var len = tree[n * 2 + 1]/*.Len*/;
      if (len === 0) { continue; }
      /* Now reverse the bits */
      tree[n * 2]/*.Code*/ = bi_reverse(next_code[len]++, len);

      //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
      //     n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
    }
  }


  /* ===========================================================================
   * Initialize the various 'constant' tables.
   */
  function tr_static_init() {
    var n;        /* iterates over tree elements */
    var bits;     /* bit counter */
    var length;   /* length value */
    var code;     /* code value */
    var dist;     /* distance index */
    var bl_count = new Array(MAX_BITS + 1);
    /* number of codes at each bit length for an optimal tree */

    // do check in _tr_init()
    //if (static_init_done) return;

    /* For some embedded targets, global variables are not initialized: */
  /*#ifdef NO_INIT_GLOBAL_POINTERS
    static_l_desc.static_tree = static_ltree;
    static_l_desc.extra_bits = extra_lbits;
    static_d_desc.static_tree = static_dtree;
    static_d_desc.extra_bits = extra_dbits;
    static_bl_desc.extra_bits = extra_blbits;
  #endif*/

    /* Initialize the mapping length (0..255) -> length code (0..28) */
    length = 0;
    for (code = 0; code < LENGTH_CODES - 1; code++) {
      base_length[code] = length;
      for (n = 0; n < (1 << extra_lbits[code]); n++) {
        _length_code[length++] = code;
      }
    }
    //Assert (length == 256, "tr_static_init: length != 256");
    /* Note that the length 255 (match length 258) can be represented
     * in two different ways: code 284 + 5 bits or code 285, so we
     * overwrite length_code[255] to use the best encoding:
     */
    _length_code[length - 1] = code;

    /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
    dist = 0;
    for (code = 0; code < 16; code++) {
      base_dist[code] = dist;
      for (n = 0; n < (1 << extra_dbits[code]); n++) {
        _dist_code[dist++] = code;
      }
    }
    //Assert (dist == 256, "tr_static_init: dist != 256");
    dist >>= 7; /* from now on, all distances are divided by 128 */
    for (; code < D_CODES; code++) {
      base_dist[code] = dist << 7;
      for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) {
        _dist_code[256 + dist++] = code;
      }
    }
    //Assert (dist == 256, "tr_static_init: 256+dist != 512");

    /* Construct the codes of the static literal tree */
    for (bits = 0; bits <= MAX_BITS; bits++) {
      bl_count[bits] = 0;
    }

    n = 0;
    while (n <= 143) {
      static_ltree[n * 2 + 1]/*.Len*/ = 8;
      n++;
      bl_count[8]++;
    }
    while (n <= 255) {
      static_ltree[n * 2 + 1]/*.Len*/ = 9;
      n++;
      bl_count[9]++;
    }
    while (n <= 279) {
      static_ltree[n * 2 + 1]/*.Len*/ = 7;
      n++;
      bl_count[7]++;
    }
    while (n <= 287) {
      static_ltree[n * 2 + 1]/*.Len*/ = 8;
      n++;
      bl_count[8]++;
    }
    /* Codes 286 and 287 do not exist, but we must include them in the
     * tree construction to get a canonical Huffman tree (longest code
     * all ones)
     */
    gen_codes(static_ltree, L_CODES + 1, bl_count);

    /* The static distance tree is trivial: */
    for (n = 0; n < D_CODES; n++) {
      static_dtree[n * 2 + 1]/*.Len*/ = 5;
      static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5);
    }

    // Now data ready and we can init static trees
    static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS);
    static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0,          D_CODES, MAX_BITS);
    static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0,         BL_CODES, MAX_BL_BITS);

    //static_init_done = true;
  }


  /* ===========================================================================
   * Initialize a new block.
   */
  function init_block(s) {
    var n; /* iterates over tree elements */

    /* Initialize the trees. */
    for (n = 0; n < L_CODES;  n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; }
    for (n = 0; n < D_CODES;  n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; }
    for (n = 0; n < BL_CODES; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; }

    s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1;
    s.opt_len = s.static_len = 0;
    s.last_lit = s.matches = 0;
  }


  /* ===========================================================================
   * Flush the bit buffer and align the output on a byte boundary
   */
  function bi_windup(s)
  {
    if (s.bi_valid > 8) {
      put_short(s, s.bi_buf);
    } else if (s.bi_valid > 0) {
      //put_byte(s, (Byte)s->bi_buf);
      s.pending_buf[s.pending++] = s.bi_buf;
    }
    s.bi_buf = 0;
    s.bi_valid = 0;
  }

  /* ===========================================================================
   * Copy a stored block, storing first the length and its
   * one's complement if requested.
   */
  function copy_block(s, buf, len, header)
  //DeflateState *s;
  //charf    *buf;    /* the input data */
  //unsigned len;     /* its length */
  //int      header;  /* true if block header must be written */
  {
    bi_windup(s);        /* align on byte boundary */

    if (header) {
      put_short(s, len);
      put_short(s, ~len);
    }
  //  while (len--) {
  //    put_byte(s, *buf++);
  //  }
    common.arraySet(s.pending_buf, s.window, buf, len, s.pending);
    s.pending += len;
  }

  /* ===========================================================================
   * Compares to subtrees, using the tree depth as tie breaker when
   * the subtrees have equal frequency. This minimizes the worst case length.
   */
  function smaller(tree, n, m, depth) {
    var _n2 = n * 2;
    var _m2 = m * 2;
    return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
           (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  }

  /* ===========================================================================
   * 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).
   */
  function pqdownheap(s, tree, k)
  //    deflate_state *s;
  //    ct_data *tree;  /* the tree to restore */
  //    int k;               /* node to move down */
  {
    var v = s.heap[k];
    var j = k << 1;  /* left son of k */
    while (j <= s.heap_len) {
      /* Set j to the smallest of the two sons: */
      if (j < s.heap_len &&
        smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) {
        j++;
      }
      /* Exit if v is smaller than both sons */
      if (smaller(tree, v, s.heap[j], s.depth)) { break; }

      /* Exchange v with the smallest son */
      s.heap[k] = s.heap[j];
      k = j;

      /* And continue down the tree, setting j to the left son of k */
      j <<= 1;
    }
    s.heap[k] = v;
  }


  // inlined manually
  // var SMALLEST = 1;

  /* ===========================================================================
   * Send the block data compressed using the given Huffman trees
   */
  function compress_block(s, ltree, dtree)
  //    deflate_state *s;
  //    const ct_data *ltree; /* literal tree */
  //    const ct_data *dtree; /* distance tree */
  {
    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 (s.last_lit !== 0) {
      do {
        dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]);
        lc = s.pending_buf[s.l_buf + lx];
        lx++;

        if (dist === 0) {
          send_code(s, lc, ltree); /* send a literal byte */
          //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
        } else {
          /* Here, lc is the match length - MIN_MATCH */
          code = _length_code[lc];
          send_code(s, code + LITERALS + 1, ltree); /* send the length code */
          extra = extra_lbits[code];
          if (extra !== 0) {
            lc -= base_length[code];
            send_bits(s, lc, extra);       /* send the extra length bits */
          }
          dist--; /* dist is now the match distance - 1 */
          code = d_code(dist);
          //Assert (code < D_CODES, "bad d_code");

          send_code(s, code, dtree);       /* send the distance code */
          extra = extra_dbits[code];
          if (extra !== 0) {
            dist -= base_dist[code];
            send_bits(s, 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: */
        //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
        //       "pendingBuf overflow");

      } while (lx < s.last_lit);
    }

    send_code(s, END_BLOCK, ltree);
  }


  /* ===========================================================================
   * 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.
   */
  function build_tree(s, desc)
  //    deflate_state *s;
  //    tree_desc *desc; /* the tree descriptor */
  {
    var tree     = desc.dyn_tree;
    var stree    = desc.stat_desc.static_tree;
    var has_stree = desc.stat_desc.has_stree;
    var elems    = desc.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[SMALLEST]. 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]/*.Freq*/ !== 0) {
        s.heap[++s.heap_len] = max_code = n;
        s.depth[n] = 0;

      } else {
        tree[n * 2 + 1]/*.Len*/ = 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]/*.Freq*/ = 1;
      s.depth[node] = 0;
      s.opt_len--;

      if (has_stree) {
        s.static_len -= stree[node * 2 + 1]/*.Len*/;
      }
      /* node is 0 or 1 so it does not have extra bits */
    }
    desc.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 = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }

    /* Construct the Huffman tree by repeatedly combining the least two
     * frequent nodes.
     */
    node = elems;              /* next internal node of the tree */
    do {
      //pqremove(s, tree, n);  /* n = node of least frequency */
      /*** pqremove ***/
      n = s.heap[1/*SMALLEST*/];
      s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
      pqdownheap(s, tree, 1/*SMALLEST*/);
      /***/

      m = s.heap[1/*SMALLEST*/]; /* 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]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
      s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
      tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node;

      /* and insert the new node in the heap */
      s.heap[1/*SMALLEST*/] = node++;
      pqdownheap(s, tree, 1/*SMALLEST*/);

    } while (s.heap_len >= 2);

    s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];

    /* At this point, the fields freq and dad are set. We can now
     * generate the bit lengths.
     */
    gen_bitlen(s, desc);

    /* The field len is now set, we can generate the bit codes */
    gen_codes(tree, max_code, s.bl_count);
  }


  /* ===========================================================================
   * Scan a literal or distance tree to determine the frequencies of the codes
   * in the bit length tree.
   */
  function scan_tree(s, tree, max_code)
  //    deflate_state *s;
  //    ct_data *tree;   /* the tree to be scanned */
  //    int 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]/*.Len*/; /* 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]/*.Len*/ = 0xffff; /* guard */

    for (n = 0; n <= max_code; n++) {
      curlen = nextlen;
      nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;

      if (++count < max_count && curlen === nextlen) {
        continue;

      } else if (count < min_count) {
        s.bl_tree[curlen * 2]/*.Freq*/ += count;

      } else if (curlen !== 0) {

        if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
        s.bl_tree[REP_3_6 * 2]/*.Freq*/++;

      } else if (count <= 10) {
        s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++;

      } else {
        s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++;
      }

      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 a literal or distance tree in compressed form, using the codes in
   * bl_tree.
   */
  function send_tree(s, tree, max_code)
  //    deflate_state *s;
  //    ct_data *tree; /* the tree to be scanned */
  //    int 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]/*.Len*/; /* 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 */

    /* tree[max_code+1].Len = -1; */  /* guard already set */
    if (nextlen === 0) {
      max_count = 138;
      min_count = 3;
    }

    for (n = 0; n <= max_code; n++) {
      curlen = nextlen;
      nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;

      if (++count < max_count && curlen === nextlen) {
        continue;

      } else if (count < min_count) {
        do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);

      } else if (curlen !== 0) {
        if (curlen !== prevlen) {
          send_code(s, curlen, s.bl_tree);
          count--;
        }
        //Assert(count >= 3 && count <= 6, " 3_6?");
        send_code(s, REP_3_6, s.bl_tree);
        send_bits(s, count - 3, 2);

      } else if (count <= 10) {
        send_code(s, REPZ_3_10, s.bl_tree);
        send_bits(s, count - 3, 3);

      } else {
        send_code(s, REPZ_11_138, s.bl_tree);
        send_bits(s, 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;
      }
    }
  }


  /* ===========================================================================
   * 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(s) {
    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(s, s.dyn_ltree, s.l_desc.max_code);
    scan_tree(s, s.dyn_dtree, s.d_desc.max_code);

    /* Build the bit length tree: */
    build_tree(s, s.bl_desc);
    /* 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 (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) {
        break;
      }
    }
    /* Update opt_len to include the bit length tree and counts */
    s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
    //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
    //        s->opt_len, s->static_len));

    return max_blindex;
  }


  /* ===========================================================================
   * 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(s, lcodes, dcodes, blcodes)
  //    deflate_state *s;
  //    int lcodes, dcodes, blcodes; /* number of codes for each tree */
  {
    var rank;                    /* index in bl_order */

    //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
    //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
    //        "too many codes");
    //Tracev((stderr, "\nbl counts: "));
    send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */
    send_bits(s, dcodes - 1,   5);
    send_bits(s, blcodes - 4,  4); /* not -3 as stated in appnote.txt */
    for (rank = 0; rank < blcodes; rank++) {
      //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
      send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3);
    }
    //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));

    send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */
    //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));

    send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */
    //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  }


  /* ===========================================================================
   * Check if the data type is TEXT or BINARY, using the following algorithm:
   * - TEXT if the two conditions below are satisfied:
   *    a) There are no non-portable control characters belonging to the
   *       "black list" (0..6, 14..25, 28..31).
   *    b) There is at least one printable character belonging to the
   *       "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
   * - BINARY otherwise.
   * - The following partially-portable control characters form a
   *   "gray list" that is ignored in this detection algorithm:
   *   (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
   * IN assertion: the fields Freq of dyn_ltree are set.
   */
  function detect_data_type(s) {
    /* black_mask is the bit mask of black-listed bytes
     * set bits 0..6, 14..25, and 28..31
     * 0xf3ffc07f = binary 11110011111111111100000001111111
     */
    var black_mask = 0xf3ffc07f;
    var n;

    /* Check for non-textual ("black-listed") bytes. */
    for (n = 0; n <= 31; n++, black_mask >>>= 1) {
      if ((black_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) {
        return Z_BINARY;
      }
    }

    /* Check for textual ("white-listed") bytes. */
    if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
        s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
      return Z_TEXT;
    }
    for (n = 32; n < LITERALS; n++) {
      if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
        return Z_TEXT;
      }
    }

    /* There are no "black-listed" or "white-listed" bytes:
     * this stream either is empty or has tolerated ("gray-listed") bytes only.
     */
    return Z_BINARY;
  }


  var static_init_done = false;

  /* ===========================================================================
   * Initialize the tree data structures for a new zlib stream.
   */
  function _tr_init(s)
  {

    if (!static_init_done) {
      tr_static_init();
      static_init_done = true;
    }

    s.l_desc  = new TreeDesc(s.dyn_ltree, static_l_desc);
    s.d_desc  = new TreeDesc(s.dyn_dtree, static_d_desc);
    s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);

    s.bi_buf = 0;
    s.bi_valid = 0;

    /* Initialize the first block of the first file: */
    init_block(s);
  }


  /* ===========================================================================
   * Send a stored block
   */
  function _tr_stored_block(s, buf, stored_len, last)
  //DeflateState *s;
  //charf *buf;       /* input block */
  //ulg stored_len;   /* length of input block */
  //int last;         /* one if this is the last block for a file */
  {
    send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3);    /* send block type */
    copy_block(s, buf, stored_len, true); /* with header */
  }


  /* ===========================================================================
   * Send one empty static block to give enough lookahead for inflate.
   * This takes 10 bits, of which 7 may remain in the bit buffer.
   */
  function _tr_align(s) {
    send_bits(s, STATIC_TREES << 1, 3);
    send_code(s, END_BLOCK, static_ltree);
    bi_flush(s);
  }


  /* ===========================================================================
   * 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(s, buf, stored_len, last)
  //DeflateState *s;
  //charf *buf;       /* input block, or NULL if too old */
  //ulg stored_len;   /* length of input block */
  //int last;         /* one 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 (s.level > 0) {

      /* Check if the file is binary or text */
      if (s.strm.data_type === Z_UNKNOWN) {
        s.strm.data_type = detect_data_type(s);
      }

      /* Construct the literal and distance trees */
      build_tree(s, s.l_desc);
      // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
      //        s->static_len));

      build_tree(s, s.d_desc);
      // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
      //        s->static_len));
      /* 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(s);

      /* Determine the best encoding. Compute the block lengths in bytes. */
      opt_lenb = (s.opt_len + 3 + 7) >>> 3;
      static_lenb = (s.static_len + 3 + 7) >>> 3;

      // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
      //        opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
      //        s->last_lit));

      if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }

    } else {
      // Assert(buf != (char*)0, "lost buf");
      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(s, buf, stored_len, last);

    } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {

      send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3);
      compress_block(s, static_ltree, static_dtree);

    } else {
      send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3);
      send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1);
      compress_block(s, s.dyn_ltree, s.dyn_dtree);
    }
    // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
    /* The above check is made mod 2^32, for files larger than 512 MB
     * and uLong implemented on 32 bits.
     */
    init_block(s);

    if (last) {
      bi_windup(s);
    }
    // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
    //       s->compressed_len-7*last));
  }

  /* ===========================================================================
   * Save the match info and tally the frequency counts. Return true if
   * the current block must be flushed.
   */
  function _tr_tally(s, dist, lc)
  //    deflate_state *s;
  //    unsigned dist;  /* distance of matched string */
  //    unsigned lc;    /* match length-MIN_MATCH or unmatched char (if dist==0) */
  {
    //var out_length, in_length, dcode;

    s.pending_buf[s.d_buf + s.last_lit * 2]     = (dist >>> 8) & 0xff;
    s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;

    s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
    s.last_lit++;

    if (dist === 0) {
      /* lc is the unmatched char */
      s.dyn_ltree[lc * 2]/*.Freq*/++;
    } else {
      s.matches++;
      /* Here, lc is the match length - MIN_MATCH */
      dist--;             /* dist = match distance - 1 */
      //Assert((ush)dist < (ush)MAX_DIST(s) &&
      //       (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
      //       (ush)d_code(dist) < (ush)D_CODES,  "_tr_tally: bad match");

      s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++;
      s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
    }

  // (!) This block is disabled in zlib defaults,
  // don't enable it for binary compatibility

  //#ifdef TRUNCATE_BLOCK
  //  /* Try to guess if it is profitable to stop the current block here */
  //  if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  //    /* Compute an upper bound for the compressed length */
  //    out_length = s.last_lit*8;
  //    in_length = s.strstart - s.block_start;
  //
  //    for (dcode = 0; dcode < D_CODES; dcode++) {
  //      out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  //    }
  //    out_length >>>= 3;
  //    //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  //    //       s->last_lit, in_length, out_length,
  //    //       100L - out_length*100L/in_length));
  //    if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  //      return true;
  //    }
  //  }
  //#endif

    return (s.last_lit === s.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.
     */
  }

  var _tr_init_1  = _tr_init;
  var _tr_stored_block_1 = _tr_stored_block;
  var _tr_flush_block_1  = _tr_flush_block;
  var _tr_tally_1 = _tr_tally;
  var _tr_align_1 = _tr_align;

  var trees = {
  	_tr_init: _tr_init_1,
  	_tr_stored_block: _tr_stored_block_1,
  	_tr_flush_block: _tr_flush_block_1,
  	_tr_tally: _tr_tally_1,
  	_tr_align: _tr_align_1
  };

  // Note: adler32 takes 12% for level 0 and 2% for level 6.
  // It isn't worth it to make additional optimizations as in original.
  // Small size is preferable.

  // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  //
  // This software is provided 'as-is', without any express or implied
  // warranty. In no event will the authors be held liable for any damages
  // arising from the use of this software.
  //
  // Permission is granted to anyone to use this software for any purpose,
  // including commercial applications, and to alter it and redistribute it
  // freely, subject to the following restrictions:
  //
  // 1. The origin of this software must not be misrepresented; you must not
  //   claim that you wrote the original software. If you use this software
  //   in a product, an acknowledgment in the product documentation would be
  //   appreciated but is not required.
  // 2. Altered source versions must be plainly marked as such, and must not be
  //   misrepresented as being the original software.
  // 3. This notice may not be removed or altered from any source distribution.

  function adler32(adler, buf, len, pos) {
    var s1 = (adler & 0xffff) |0,
        s2 = ((adler >>> 16) & 0xffff) |0,
        n = 0;

    while (len !== 0) {
      // Set limit ~ twice less than 5552, to keep
      // s2 in 31-bits, because we force signed ints.
      // in other case %= will fail.
      n = len > 2000 ? 2000 : len;
      len -= n;

      do {
        s1 = (s1 + buf[pos++]) |0;
        s2 = (s2 + s1) |0;
      } while (--n);

      s1 %= 65521;
      s2 %= 65521;
    }

    return (s1 | (s2 << 16)) |0;
  }


  var adler32_1 = adler32;

  // Note: we can't get significant speed boost here.
  // So write code to minimize size - no pregenerated tables
  // and array tools dependencies.

  // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  //
  // This software is provided 'as-is', without any express or implied
  // warranty. In no event will the authors be held liable for any damages
  // arising from the use of this software.
  //
  // Permission is granted to anyone to use this software for any purpose,
  // including commercial applications, and to alter it and redistribute it
  // freely, subject to the following restrictions:
  //
  // 1. The origin of this software must not be misrepresented; you must not
  //   claim that you wrote the original software. If you use this software
  //   in a product, an acknowledgment in the product documentation would be
  //   appreciated but is not required.
  // 2. Altered source versions must be plainly marked as such, and must not be
  //   misrepresented as being the original software.
  // 3. This notice may not be removed or altered from any source distribution.

  // Use ordinary array, since untyped makes no boost here
  function makeTable() {
    var c, table = [];

    for (var n = 0; n < 256; n++) {
      c = n;
      for (var k = 0; k < 8; k++) {
        c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
      }
      table[n] = c;
    }

    return table;
  }

  // Create table on load. Just 255 signed longs. Not a problem.
  var crcTable = makeTable();


  function crc32(crc, buf, len, pos) {
    var t = crcTable,
        end = pos + len;

    crc ^= -1;

    for (var i = pos; i < end; i++) {
      crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
    }

    return (crc ^ (-1)); // >>> 0;
  }


  var crc32_1 = crc32;

  // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  //
  // This software is provided 'as-is', without any express or implied
  // warranty. In no event will the authors be held liable for any damages
  // arising from the use of this software.
  //
  // Permission is granted to anyone to use this software for any purpose,
  // including commercial applications, and to alter it and redistribute it
  // freely, subject to the following restrictions:
  //
  // 1. The origin of this software must not be misrepresented; you must not
  //   claim that you wrote the original software. If you use this software
  //   in a product, an acknowledgment in the product documentation would be
  //   appreciated but is not required.
  // 2. Altered source versions must be plainly marked as such, and must not be
  //   misrepresented as being the original software.
  // 3. This notice may not be removed or altered from any source distribution.

  var messages = {
    2:      'need dictionary',     /* Z_NEED_DICT       2  */
    1:      'stream end',          /* Z_STREAM_END      1  */
    0:      '',                    /* Z_OK              0  */
    '-1':   'file error',          /* Z_ERRNO         (-1) */
    '-2':   'stream error',        /* Z_STREAM_ERROR  (-2) */
    '-3':   'data error',          /* Z_DATA_ERROR    (-3) */
    '-4':   'insufficient memory', /* Z_MEM_ERROR     (-4) */
    '-5':   'buffer error',        /* Z_BUF_ERROR     (-5) */
    '-6':   'incompatible version' /* Z_VERSION_ERROR (-6) */
  };

  // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  //
  // This software is provided 'as-is', without any express or implied
  // warranty. In no event will the authors be held liable for any damages
  // arising from the use of this software.
  //
  // Permission is granted to anyone to use this software for any purpose,
  // including commercial applications, and to alter it and redistribute it
  // freely, subject to the following restrictions:
  //
  // 1. The origin of this software must not be misrepresented; you must not
  //   claim that you wrote the original software. If you use this software
  //   in a product, an acknowledgment in the product documentation would be
  //   appreciated but is not required.
  // 2. Altered source versions must be plainly marked as such, and must not be
  //   misrepresented as being the original software.
  // 3. This notice may not be removed or altered from any source distribution.







  /* Public constants ==========================================================*/
  /* ===========================================================================*/


  /* Allowed flush values; see deflate() and inflate() below for details */
  var Z_NO_FLUSH      = 0;
  var Z_PARTIAL_FLUSH = 1;
  //var Z_SYNC_FLUSH    = 2;
  var Z_FULL_FLUSH    = 3;
  var Z_FINISH        = 4;
  var Z_BLOCK         = 5;
  //var Z_TREES         = 6;


  /* Return codes for the compression/decompression functions. Negative values
   * are errors, positive values are used for special but normal events.
   */
  var Z_OK            = 0;
  var Z_STREAM_END    = 1;
  //var Z_NEED_DICT     = 2;
  //var Z_ERRNO         = -1;
  var Z_STREAM_ERROR  = -2;
  var Z_DATA_ERROR    = -3;
  //var Z_MEM_ERROR     = -4;
  var Z_BUF_ERROR     = -5;
  //var Z_VERSION_ERROR = -6;


  /* compression levels */
  //var Z_NO_COMPRESSION      = 0;
  //var Z_BEST_SPEED          = 1;
  //var Z_BEST_COMPRESSION    = 9;
  var Z_DEFAULT_COMPRESSION = -1;


  var Z_FILTERED            = 1;
  var Z_HUFFMAN_ONLY        = 2;
  var Z_RLE                 = 3;
  var Z_FIXED$1               = 4;
  var Z_DEFAULT_STRATEGY    = 0;

  /* Possible values of the data_type field (though see inflate()) */
  //var Z_BINARY              = 0;
  //var Z_TEXT                = 1;
  //var Z_ASCII               = 1; // = Z_TEXT
  var Z_UNKNOWN$1             = 2;


  /* The deflate compression method */
  var Z_DEFLATED  = 8;

  /*============================================================================*/


  var MAX_MEM_LEVEL = 9;
  /* Maximum value for memLevel in deflateInit2 */
  var MAX_WBITS = 15;
  /* 32K LZ77 window */
  var DEF_MEM_LEVEL = 8;


  var LENGTH_CODES$1  = 29;
  /* number of length codes, not counting the special END_BLOCK code */
  var LITERALS$1      = 256;
  /* number of literal bytes 0..255 */
  var L_CODES$1       = LITERALS$1 + 1 + LENGTH_CODES$1;
  /* number of Literal or Length codes, including the END_BLOCK code */
  var D_CODES$1       = 30;
  /* number of distance codes */
  var BL_CODES$1      = 19;
  /* number of codes used to transfer the bit lengths */
  var HEAP_SIZE$1     = 2 * L_CODES$1 + 1;
  /* maximum heap size */
  var MAX_BITS$1  = 15;
  /* All codes must not exceed MAX_BITS bits */

  var MIN_MATCH$1 = 3;
  var MAX_MATCH$1 = 258;
  var MIN_LOOKAHEAD = (MAX_MATCH$1 + MIN_MATCH$1 + 1);

  var PRESET_DICT = 0x20;

  var INIT_STATE = 42;
  var EXTRA_STATE = 69;
  var NAME_STATE = 73;
  var COMMENT_STATE = 91;
  var HCRC_STATE = 103;
  var BUSY_STATE = 113;
  var FINISH_STATE = 666;

  var BS_NEED_MORE      = 1; /* block not completed, need more input or more output */
  var BS_BLOCK_DONE     = 2; /* block flush performed */
  var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  var BS_FINISH_DONE    = 4; /* finish done, accept no more input or output */

  var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.

  function err(strm, errorCode) {
    strm.msg = messages[errorCode];
    return errorCode;
  }

  function rank(f) {
    return ((f) << 1) - ((f) > 4 ? 9 : 0);
  }

  function zero$1(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }


  /* =========================================================================
   * 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->output buffer and copying into it.
   * (See also read_buf()).
   */
  function flush_pending(strm) {
    var s = strm.state;

    //_tr_flush_bits(s);
    var len = s.pending;
    if (len > strm.avail_out) {
      len = strm.avail_out;
    }
    if (len === 0) { return; }

    common.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
    strm.next_out += len;
    s.pending_out += len;
    strm.total_out += len;
    strm.avail_out -= len;
    s.pending -= len;
    if (s.pending === 0) {
      s.pending_out = 0;
    }
  }


  function flush_block_only(s, last) {
    trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
    s.block_start = s.strstart;
    flush_pending(s.strm);
  }


  function put_byte(s, b) {
    s.pending_buf[s.pending++] = b;
  }


  /* =========================================================================
   * Put a short in the pending buffer. The 16-bit value is put in MSB order.
   * IN assertion: the stream state is correct and there is enough room in
   * pending_buf.
   */
  function putShortMSB(s, b) {
  //  put_byte(s, (Byte)(b >> 8));
  //  put_byte(s, (Byte)(b & 0xff));
    s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
    s.pending_buf[s.pending++] = b & 0xff;
  }


  /* ===========================================================================
   * Read a new buffer from the current input stream, update the adler32
   * and 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->input buffer and copying from it.
   * (See also flush_pending()).
   */
  function read_buf(strm, buf, start, size) {
    var len = strm.avail_in;

    if (len > size) { len = size; }
    if (len === 0) { return 0; }

    strm.avail_in -= len;

    // zmemcpy(buf, strm->next_in, len);
    common.arraySet(buf, strm.input, strm.next_in, len, start);
    if (strm.state.wrap === 1) {
      strm.adler = adler32_1(strm.adler, buf, len, start);
    }

    else if (strm.state.wrap === 2) {
      strm.adler = crc32_1(strm.adler, buf, len, start);
    }

    strm.next_in += len;
    strm.total_in += len;

    return len;
  }


  /* ===========================================================================
   * Set match_start to the longest match starting at the given string and
   * return its length. Matches shorter or equal to prev_length are discarded,
   * in which case the result is equal to prev_length and match_start is
   * garbage.
   * IN assertions: cur_match is the head of the hash chain for the current
   *   string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
   * OUT assertion: the match length is not greater than s->lookahead.
   */
  function longest_match(s, cur_match) {
    var chain_length = s.max_chain_length;      /* max hash chain length */
    var scan = s.strstart; /* current string */
    var match;                       /* matched string */
    var len;                           /* length of current match */
    var best_len = s.prev_length;              /* best match length so far */
    var nice_match = s.nice_match;             /* stop if match long enough */
    var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
        s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;

    var _win = s.window; // shortcut

    var wmask = s.w_mask;
    var prev  = s.prev;

    /* Stop when cur_match becomes <= limit. To simplify the code,
     * we prevent matches with the string of window index 0.
     */

    var strend = s.strstart + MAX_MATCH$1;
    var scan_end1  = _win[scan + best_len - 1];
    var scan_end   = _win[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.
     */
    // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");

    /* Do not waste too much time if we already have a good match: */
    if (s.prev_length >= s.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 > s.lookahead) { nice_match = s.lookahead; }

    // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");

    do {
      // Assert(cur_match < s->strstart, "no future");
      match = cur_match;

      /* Skip to next match if the match length cannot increase
       * or if the match length is less than 2.  Note that the checks below
       * for insufficient lookahead only occur occasionally for performance
       * reasons.  Therefore uninitialized memory will be accessed, and
       * conditional jumps will be made that depend on those values.
       * However the length of the match is limited to the lookahead, so
       * the output of deflate is not affected by the uninitialized values.
       */

      if (_win[match + best_len]     !== scan_end  ||
          _win[match + best_len - 1] !== scan_end1 ||
          _win[match]                !== _win[scan] ||
          _win[++match]              !== _win[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++;
      // Assert(*scan == *match, "match[2]?");

      /* We check for insufficient lookahead only every 8th comparison;
       * the 256th check will be made at strstart+258.
       */
      do {
        /*jshint noempty:false*/
      } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
               _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
               _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
               _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
               scan < strend);

      // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");

      len = MAX_MATCH$1 - (strend - scan);
      scan = strend - MAX_MATCH$1;

      if (len > best_len) {
        s.match_start = cur_match;
        best_len = len;
        if (len >= nice_match) {
          break;
        }
        scan_end1  = _win[scan + best_len - 1];
        scan_end   = _win[scan + best_len];
      }
    } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);

    if (best_len <= s.lookahead) {
      return best_len;
    }
    return s.lookahead;
  }


  /* ===========================================================================
   * 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(s) {
    var _w_size = s.w_size;
    var p, n, m, more, str;

    //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");

    do {
      more = s.window_size - s.lookahead - s.strstart;

      // JS ints have 32 bit, block below not needed
      /* Deal with !@#$% 64K limit: */
      //if (sizeof(int) <= 2) {
      //    if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
      //        more = wsize;
      //
      //  } else if (more == (unsigned)(-1)) {
      //        /* Very unlikely, but possible on 16 bit machine if
      //         * strstart == 0 && lookahead == 1 (input done a 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.
       */
      if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {

        common.arraySet(s.window, s.window, _w_size, _w_size, 0);
        s.match_start -= _w_size;
        s.strstart -= _w_size;
        /* we now have strstart >= MAX_DIST */
        s.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 = s.hash_size;
        p = n;
        do {
          m = s.head[--p];
          s.head[p] = (m >= _w_size ? m - _w_size : 0);
        } while (--n);

        n = _w_size;
        p = n;
        do {
          m = s.prev[--p];
          s.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);

        more += _w_size;
      }
      if (s.strm.avail_in === 0) {
        break;
      }

      /* 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.
       */
      //Assert(more >= 2, "more < 2");
      n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
      s.lookahead += n;

      /* Initialize the hash value now that we have some input: */
      if (s.lookahead + s.insert >= MIN_MATCH$1) {
        str = s.strstart - s.insert;
        s.ins_h = s.window[str];

        /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
        s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  //#if MIN_MATCH != 3
  //        Call update_hash() MIN_MATCH-3 more times
  //#endif
        while (s.insert) {
          /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
          s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH$1 - 1]) & s.hash_mask;

          s.prev[str & s.w_mask] = s.head[s.ins_h];
          s.head[s.ins_h] = str;
          str++;
          s.insert--;
          if (s.lookahead + s.insert < MIN_MATCH$1) {
            break;
          }
        }
      }
      /* 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 (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);

    /* If the WIN_INIT bytes after the end of the current data have never been
     * written, then zero those bytes in order to avoid memory check reports of
     * the use of uninitialized (or uninitialised as Julian writes) bytes by
     * the longest match routines.  Update the high water mark for the next
     * time through here.  WIN_INIT is set to MAX_MATCH since the longest match
     * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
     */
  //  if (s.high_water < s.window_size) {
  //    var curr = s.strstart + s.lookahead;
  //    var init = 0;
  //
  //    if (s.high_water < curr) {
  //      /* Previous high water mark below current data -- zero WIN_INIT
  //       * bytes or up to end of window, whichever is less.
  //       */
  //      init = s.window_size - curr;
  //      if (init > WIN_INIT)
  //        init = WIN_INIT;
  //      zmemzero(s->window + curr, (unsigned)init);
  //      s->high_water = curr + init;
  //    }
  //    else if (s->high_water < (ulg)curr + WIN_INIT) {
  //      /* High water mark at or above current data, but below current data
  //       * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  //       * to end of window, whichever is less.
  //       */
  //      init = (ulg)curr + WIN_INIT - s->high_water;
  //      if (init > s->window_size - s->high_water)
  //        init = s->window_size - s->high_water;
  //      zmemzero(s->window + s->high_water, (unsigned)init);
  //      s->high_water += init;
  //    }
  //  }
  //
  //  Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  //    "not enough room for search");
  }

  /* ===========================================================================
   * 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(s, 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;

    if (max_block_size > s.pending_buf_size - 5) {
      max_block_size = s.pending_buf_size - 5;
    }

    /* Copy as much as possible from input to output: */
    for (;;) {
      /* Fill the window as much as possible: */
      if (s.lookahead <= 1) {

        //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
        //  s->block_start >= (long)s->w_size, "slide too late");
  //      if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  //        s.block_start >= s.w_size)) {
  //        throw  new Error("slide too late");
  //      }

        fill_window(s);
        if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
          return BS_NEED_MORE;
        }

        if (s.lookahead === 0) {
          break;
        }
        /* flush the current block */
      }
      //Assert(s->block_start >= 0L, "block gone");
  //    if (s.block_start < 0) throw new Error("block gone");

      s.strstart += s.lookahead;
      s.lookahead = 0;

      /* Emit a stored block if pending_buf will be full: */
      var max_start = s.block_start + max_block_size;

      if (s.strstart === 0 || s.strstart >= max_start) {
        /* strstart == 0 is possible when wraparound on 16-bit machine */
        s.lookahead = s.strstart - max_start;
        s.strstart = max_start;
        /*** FLUSH_BLOCK(s, 0); ***/
        flush_block_only(s, false);
        if (s.strm.avail_out === 0) {
          return BS_NEED_MORE;
        }
        /***/


      }
      /* Flush if we may have to slide, otherwise block_start may become
       * negative and the data will be gone:
       */
      if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
        /*** FLUSH_BLOCK(s, 0); ***/
        flush_block_only(s, false);
        if (s.strm.avail_out === 0) {
          return BS_NEED_MORE;
        }
        /***/
      }
    }

    s.insert = 0;

    if (flush === Z_FINISH) {
      /*** FLUSH_BLOCK(s, 1); ***/
      flush_block_only(s, true);
      if (s.strm.avail_out === 0) {
        return BS_FINISH_STARTED;
      }
      /***/
      return BS_FINISH_DONE;
    }

    if (s.strstart > s.block_start) {
      /*** FLUSH_BLOCK(s, 0); ***/
      flush_block_only(s, false);
      if (s.strm.avail_out === 0) {
        return BS_NEED_MORE;
      }
      /***/
    }

    return BS_NEED_MORE;
  }

  /* ===========================================================================
   * 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(s, flush) {
    var hash_head;        /* head of the hash chain */
    var bflush;           /* set if current block must be flushed */

    for (;;) {
      /* 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 (s.lookahead < MIN_LOOKAHEAD) {
        fill_window(s);
        if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
          return BS_NEED_MORE;
        }
        if (s.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:
       */
      hash_head = 0/*NIL*/;
      if (s.lookahead >= MIN_MATCH$1) {
        /*** INSERT_STRING(s, s.strstart, hash_head); ***/
        s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH$1 - 1]) & s.hash_mask;
        hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
        s.head[s.ins_h] = s.strstart;
        /***/
      }

      /* Find the longest match, discarding those <= prev_length.
       * At this point we have always match_length < MIN_MATCH
       */
      if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.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).
         */
        s.match_length = longest_match(s, hash_head);
        /* longest_match() sets match_start */
      }
      if (s.match_length >= MIN_MATCH$1) {
        // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only

        /*** _tr_tally_dist(s, s.strstart - s.match_start,
                       s.match_length - MIN_MATCH, bflush); ***/
        bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH$1);

        s.lookahead -= s.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 (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH$1) {
          s.match_length--; /* string at strstart already in table */
          do {
            s.strstart++;
            /*** INSERT_STRING(s, s.strstart, hash_head); ***/
            s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH$1 - 1]) & s.hash_mask;
            hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
            s.head[s.ins_h] = s.strstart;
            /***/
            /* strstart never exceeds WSIZE-MAX_MATCH, so there are
             * always MIN_MATCH bytes ahead.
             */
          } while (--s.match_length !== 0);
          s.strstart++;
        } else
        {
          s.strstart += s.match_length;
          s.match_length = 0;
          s.ins_h = s.window[s.strstart];
          /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
          s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;

  //#if MIN_MATCH != 3
  //                Call UPDATE_HASH() MIN_MATCH-3 more times
  //#endif
          /* 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 */
        //Tracevv((stderr,"%c", s.window[s.strstart]));
        /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
        bflush = trees._tr_tally(s, 0, s.window[s.strstart]);

        s.lookahead--;
        s.strstart++;
      }
      if (bflush) {
        /*** FLUSH_BLOCK(s, 0); ***/
        flush_block_only(s, false);
        if (s.strm.avail_out === 0) {
          return BS_NEED_MORE;
        }
        /***/
      }
    }
    s.insert = ((s.strstart < (MIN_MATCH$1 - 1)) ? s.strstart : MIN_MATCH$1 - 1);
    if (flush === Z_FINISH) {
      /*** FLUSH_BLOCK(s, 1); ***/
      flush_block_only(s, true);
      if (s.strm.avail_out === 0) {
        return BS_FINISH_STARTED;
      }
      /***/
      return BS_FINISH_DONE;
    }
    if (s.last_lit) {
      /*** FLUSH_BLOCK(s, 0); ***/
      flush_block_only(s, false);
      if (s.strm.avail_out === 0) {
        return BS_NEED_MORE;
      }
      /***/
    }
    return BS_BLOCK_DONE;
  }

  /* ===========================================================================
   * 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(s, flush) {
    var hash_head;          /* head of hash chain */
    var bflush;              /* set if current block must be flushed */

    var max_insert;

    /* Process the input block. */
    for (;;) {
      /* 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 (s.lookahead < MIN_LOOKAHEAD) {
        fill_window(s);
        if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
          return BS_NEED_MORE;
        }
        if (s.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:
       */
      hash_head = 0/*NIL*/;
      if (s.lookahead >= MIN_MATCH$1) {
        /*** INSERT_STRING(s, s.strstart, hash_head); ***/
        s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH$1 - 1]) & s.hash_mask;
        hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
        s.head[s.ins_h] = s.strstart;
        /***/
      }

      /* Find the longest match, discarding those <= prev_length.
       */
      s.prev_length = s.match_length;
      s.prev_match = s.match_start;
      s.match_length = MIN_MATCH$1 - 1;

      if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
          s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
        /* 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).
         */
        s.match_length = longest_match(s, hash_head);
        /* longest_match() sets match_start */

        if (s.match_length <= 5 &&
           (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH$1 && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {

          /* If prev_match is also MIN_MATCH, match_start is garbage
           * but we will ignore the current match anyway.
           */
          s.match_length = MIN_MATCH$1 - 1;
        }
      }
      /* If there was a match at the previous step and the current
       * match is not better, output the previous match:
       */
      if (s.prev_length >= MIN_MATCH$1 && s.match_length <= s.prev_length) {
        max_insert = s.strstart + s.lookahead - MIN_MATCH$1;
        /* Do not insert strings in hash table beyond this. */

        //check_match(s, s.strstart-1, s.prev_match, s.prev_length);

        /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
                       s.prev_length - MIN_MATCH, bflush);***/
        bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH$1);
        /* 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.
         */
        s.lookahead -= s.prev_length - 1;
        s.prev_length -= 2;
        do {
          if (++s.strstart <= max_insert) {
            /*** INSERT_STRING(s, s.strstart, hash_head); ***/
            s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH$1 - 1]) & s.hash_mask;
            hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
            s.head[s.ins_h] = s.strstart;
            /***/
          }
        } while (--s.prev_length !== 0);
        s.match_available = 0;
        s.match_length = MIN_MATCH$1 - 1;
        s.strstart++;

        if (bflush) {
          /*** FLUSH_BLOCK(s, 0); ***/
          flush_block_only(s, false);
          if (s.strm.avail_out === 0) {
            return BS_NEED_MORE;
          }
          /***/
        }

      } else if (s.match_available) {
        /* 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.
         */
        //Tracevv((stderr,"%c", s->window[s->strstart-1]));
        /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
        bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);

        if (bflush) {
          /*** FLUSH_BLOCK_ONLY(s, 0) ***/
          flush_block_only(s, false);
          /***/
        }
        s.strstart++;
        s.lookahead--;
        if (s.strm.avail_out === 0) {
          return BS_NEED_MORE;
        }
      } else {
        /* There is no previous match to compare with, wait for
         * the next step to decide.
         */
        s.match_available = 1;
        s.strstart++;
        s.lookahead--;
      }
    }
    //Assert (flush != Z_NO_FLUSH, "no flush?");
    if (s.match_available) {
      //Tracevv((stderr,"%c", s->window[s->strstart-1]));
      /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
      bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);

      s.match_available = 0;
    }
    s.insert = s.strstart < MIN_MATCH$1 - 1 ? s.strstart : MIN_MATCH$1 - 1;
    if (flush === Z_FINISH) {
      /*** FLUSH_BLOCK(s, 1); ***/
      flush_block_only(s, true);
      if (s.strm.avail_out === 0) {
        return BS_FINISH_STARTED;
      }
      /***/
      return BS_FINISH_DONE;
    }
    if (s.last_lit) {
      /*** FLUSH_BLOCK(s, 0); ***/
      flush_block_only(s, false);
      if (s.strm.avail_out === 0) {
        return BS_NEED_MORE;
      }
      /***/
    }

    return BS_BLOCK_DONE;
  }


  /* ===========================================================================
   * For Z_RLE, simply look for runs of bytes, generate matches only of distance
   * one.  Do not maintain a hash table.  (It will be regenerated if this run of
   * deflate switches away from Z_RLE.)
   */
  function deflate_rle(s, flush) {
    var bflush;            /* set if current block must be flushed */
    var prev;              /* byte at distance one to match */
    var scan, strend;      /* scan goes up to strend for length of run */

    var _win = s.window;

    for (;;) {
      /* Make sure that we always have enough lookahead, except
       * at the end of the input file. We need MAX_MATCH bytes
       * for the longest run, plus one for the unrolled loop.
       */
      if (s.lookahead <= MAX_MATCH$1) {
        fill_window(s);
        if (s.lookahead <= MAX_MATCH$1 && flush === Z_NO_FLUSH) {
          return BS_NEED_MORE;
        }
        if (s.lookahead === 0) { break; } /* flush the current block */
      }

      /* See how many times the previous byte repeats */
      s.match_length = 0;
      if (s.lookahead >= MIN_MATCH$1 && s.strstart > 0) {
        scan = s.strstart - 1;
        prev = _win[scan];
        if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
          strend = s.strstart + MAX_MATCH$1;
          do {
            /*jshint noempty:false*/
          } while (prev === _win[++scan] && prev === _win[++scan] &&
                   prev === _win[++scan] && prev === _win[++scan] &&
                   prev === _win[++scan] && prev === _win[++scan] &&
                   prev === _win[++scan] && prev === _win[++scan] &&
                   scan < strend);
          s.match_length = MAX_MATCH$1 - (strend - scan);
          if (s.match_length > s.lookahead) {
            s.match_length = s.lookahead;
          }
        }
        //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
      }

      /* Emit match if have run of MIN_MATCH or longer, else emit literal */
      if (s.match_length >= MIN_MATCH$1) {
        //check_match(s, s.strstart, s.strstart - 1, s.match_length);

        /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
        bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH$1);

        s.lookahead -= s.match_length;
        s.strstart += s.match_length;
        s.match_length = 0;
      } else {
        /* No match, output a literal byte */
        //Tracevv((stderr,"%c", s->window[s->strstart]));
        /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
        bflush = trees._tr_tally(s, 0, s.window[s.strstart]);

        s.lookahead--;
        s.strstart++;
      }
      if (bflush) {
        /*** FLUSH_BLOCK(s, 0); ***/
        flush_block_only(s, false);
        if (s.strm.avail_out === 0) {
          return BS_NEED_MORE;
        }
        /***/
      }
    }
    s.insert = 0;
    if (flush === Z_FINISH) {
      /*** FLUSH_BLOCK(s, 1); ***/
      flush_block_only(s, true);
      if (s.strm.avail_out === 0) {
        return BS_FINISH_STARTED;
      }
      /***/
      return BS_FINISH_DONE;
    }
    if (s.last_lit) {
      /*** FLUSH_BLOCK(s, 0); ***/
      flush_block_only(s, false);
      if (s.strm.avail_out === 0) {
        return BS_NEED_MORE;
      }
      /***/
    }
    return BS_BLOCK_DONE;
  }

  /* ===========================================================================
   * For Z_HUFFMAN_ONLY, do not look for matches.  Do not maintain a hash table.
   * (It will be regenerated if this run of deflate switches away from Huffman.)
   */
  function deflate_huff(s, flush) {
    var bflush;             /* set if current block must be flushed */

    for (;;) {
      /* Make sure that we have a literal to write. */
      if (s.lookahead === 0) {
        fill_window(s);
        if (s.lookahead === 0) {
          if (flush === Z_NO_FLUSH) {
            return BS_NEED_MORE;
          }
          break;      /* flush the current block */
        }
      }

      /* Output a literal byte */
      s.match_length = 0;
      //Tracevv((stderr,"%c", s->window[s->strstart]));
      /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
      bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
      s.lookahead--;
      s.strstart++;
      if (bflush) {
        /*** FLUSH_BLOCK(s, 0); ***/
        flush_block_only(s, false);
        if (s.strm.avail_out === 0) {
          return BS_NEED_MORE;
        }
        /***/
      }
    }
    s.insert = 0;
    if (flush === Z_FINISH) {
      /*** FLUSH_BLOCK(s, 1); ***/
      flush_block_only(s, true);
      if (s.strm.avail_out === 0) {
        return BS_FINISH_STARTED;
      }
      /***/
      return BS_FINISH_DONE;
    }
    if (s.last_lit) {
      /*** FLUSH_BLOCK(s, 0); ***/
      flush_block_only(s, false);
      if (s.strm.avail_out === 0) {
        return BS_NEED_MORE;
      }
      /***/
    }
    return BS_BLOCK_DONE;
  }

  /* Values for max_lazy_match, good_match and max_chain_length, depending on
   * the desired pack level (0..9). The values given below have been tuned to
   * exclude worst case performance for pathological files. Better values may be
   * found for specific files.
   */
  function Config(good_length, max_lazy, nice_length, max_chain, func) {
    this.good_length = good_length;
    this.max_lazy = max_lazy;
    this.nice_length = nice_length;
    this.max_chain = max_chain;
    this.func = func;
  }

  var configuration_table;

  configuration_table = [
    /*      good lazy nice chain */
    new Config(0, 0, 0, 0, deflate_stored),          /* 0 store only */
    new Config(4, 4, 8, 4, deflate_fast),            /* 1 max speed, no lazy matches */
    new Config(4, 5, 16, 8, deflate_fast),           /* 2 */
    new Config(4, 6, 32, 32, deflate_fast),          /* 3 */

    new Config(4, 4, 16, 16, deflate_slow),          /* 4 lazy matches */
    new Config(8, 16, 32, 32, deflate_slow),         /* 5 */
    new Config(8, 16, 128, 128, deflate_slow),       /* 6 */
    new Config(8, 32, 128, 256, deflate_slow),       /* 7 */
    new Config(32, 128, 258, 1024, deflate_slow),    /* 8 */
    new Config(32, 258, 258, 4096, deflate_slow)     /* 9 max compression */
  ];


  /* ===========================================================================
   * Initialize the "longest match" routines for a new zlib stream
   */
  function lm_init(s) {
    s.window_size = 2 * s.w_size;

    /*** CLEAR_HASH(s); ***/
    zero$1(s.head); // Fill with NIL (= 0);

    /* Set the default configuration parameters:
     */
    s.max_lazy_match = configuration_table[s.level].max_lazy;
    s.good_match = configuration_table[s.level].good_length;
    s.nice_match = configuration_table[s.level].nice_length;
    s.max_chain_length = configuration_table[s.level].max_chain;

    s.strstart = 0;
    s.block_start = 0;
    s.lookahead = 0;
    s.insert = 0;
    s.match_length = s.prev_length = MIN_MATCH$1 - 1;
    s.match_available = 0;
    s.ins_h = 0;
  }


  function DeflateState() {
    this.strm = null;            /* pointer back to this zlib stream */
    this.status = 0;            /* as the name implies */
    this.pending_buf = null;      /* output still pending */
    this.pending_buf_size = 0;  /* size of pending_buf */
    this.pending_out = 0;       /* next pending byte to output to the stream */
    this.pending = 0;           /* nb of bytes in the pending buffer */
    this.wrap = 0;              /* bit 0 true for zlib, bit 1 true for gzip */
    this.gzhead = null;         /* gzip header information to write */
    this.gzindex = 0;           /* where in extra, name, or comment */
    this.method = Z_DEFLATED; /* can only be DEFLATED */
    this.last_flush = -1;   /* value of flush param for previous deflate call */

    this.w_size = 0;  /* LZ77 window size (32K by default) */
    this.w_bits = 0;  /* log2(w_size)  (8..16) */
    this.w_mask = 0;  /* w_size - 1 */

    this.window = null;
    /* 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.
     */

    this.window_size = 0;
    /* Actual size of window: 2*wSize, except when the user input buffer
     * is directly used as sliding window.
     */

    this.prev = null;
    /* 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.
     */

    this.head = null;   /* Heads of the hash chains or NIL. */

    this.ins_h = 0;       /* hash index of string to be inserted */
    this.hash_size = 0;   /* number of elements in hash table */
    this.hash_bits = 0;   /* log2(hash_size) */
    this.hash_mask = 0;   /* hash_size-1 */

    this.hash_shift = 0;
    /* 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
     */

    this.block_start = 0;
    /* Window position at the beginning of the current output block. Gets
     * negative when the window is moved backwards.
     */

    this.match_length = 0;      /* length of best match */
    this.prev_match = 0;        /* previous match */
    this.match_available = 0;   /* set if previous match exists */
    this.strstart = 0;          /* start of string to insert */
    this.match_start = 0;       /* start of matching string */
    this.lookahead = 0;         /* number of valid bytes ahead in window */

    this.prev_length = 0;
    /* Length of the best match at previous step. Matches not greater than this
     * are discarded. This is used in the lazy match evaluation.
     */

    this.max_chain_length = 0;
    /* To speed up deflation, hash chains are never searched beyond this
     * length.  A higher limit improves compression ratio but degrades the
     * speed.
     */

    this.max_lazy_match = 0;
    /* 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.
     */
    // That's alias to max_lazy_match, don't use directly
    //this.max_insert_length = 0;
    /* 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.
     */

    this.level = 0;     /* compression level (1..9) */
    this.strategy = 0;  /* favor or force Huffman coding*/

    this.good_match = 0;
    /* Use a faster search when the previous match is longer than this */

    this.nice_match = 0; /* Stop searching when current match exceeds this */

                /* used by trees.c: */

    /* Didn't use ct_data typedef below to suppress compiler warning */

    // struct ct_data_s dyn_ltree[HEAP_SIZE];   /* literal and length tree */
    // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
    // struct ct_data_s bl_tree[2*BL_CODES+1];  /* Huffman tree for bit lengths */

    // Use flat array of DOUBLE size, with interleaved fata,
    // because JS does not support effective
    this.dyn_ltree  = new common.Buf16(HEAP_SIZE$1 * 2);
    this.dyn_dtree  = new common.Buf16((2 * D_CODES$1 + 1) * 2);
    this.bl_tree    = new common.Buf16((2 * BL_CODES$1 + 1) * 2);
    zero$1(this.dyn_ltree);
    zero$1(this.dyn_dtree);
    zero$1(this.bl_tree);

    this.l_desc   = null;         /* desc. for literal tree */
    this.d_desc   = null;         /* desc. for distance tree */
    this.bl_desc  = null;         /* desc. for bit length tree */

    //ush bl_count[MAX_BITS+1];
    this.bl_count = new common.Buf16(MAX_BITS$1 + 1);
    /* number of codes at each bit length for an optimal tree */

    //int heap[2*L_CODES+1];      /* heap used to build the Huffman trees */
    this.heap = new common.Buf16(2 * L_CODES$1 + 1);  /* heap used to build the Huffman trees */
    zero$1(this.heap);

    this.heap_len = 0;               /* number of elements in the heap */
    this.heap_max = 0;               /* 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.
     */

    this.depth = new common.Buf16(2 * L_CODES$1 + 1); //uch depth[2*L_CODES+1];
    zero$1(this.depth);
    /* Depth of each subtree used as tie breaker for trees of equal frequency
     */

    this.l_buf = 0;          /* buffer index for literals or lengths */

    this.lit_bufsize = 0;
    /* 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
     */

    this.last_lit = 0;      /* running index in l_buf */

    this.d_buf = 0;
    /* Buffer index 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.
     */

    this.opt_len = 0;       /* bit length of current block with optimal trees */
    this.static_len = 0;    /* bit length of current block with static trees */
    this.matches = 0;       /* number of string matches in current block */
    this.insert = 0;        /* bytes at end of window left to insert */


    this.bi_buf = 0;
    /* Output buffer. bits are inserted starting at the bottom (least
     * significant bits).
     */
    this.bi_valid = 0;
    /* Number of valid bits in bi_buf.  All bits above the last valid bit
     * are always zero.
     */

    // Used for window memory init. We safely ignore it for JS. That makes
    // sense only for pointers and memory check tools.
    //this.high_water = 0;
    /* High water mark offset in window for initialized bytes -- bytes above
     * this are set to zero in order to avoid memory check warnings when
     * longest match routines access bytes past the input.  This is then
     * updated to the new high water mark.
     */
  }


  function deflateResetKeep(strm) {
    var s;

    if (!strm || !strm.state) {
      return err(strm, Z_STREAM_ERROR);
    }

    strm.total_in = strm.total_out = 0;
    strm.data_type = Z_UNKNOWN$1;

    s = strm.state;
    s.pending = 0;
    s.pending_out = 0;

    if (s.wrap < 0) {
      s.wrap = -s.wrap;
      /* was made negative by deflate(..., Z_FINISH); */
    }
    s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
    strm.adler = (s.wrap === 2) ?
      0  // crc32(0, Z_NULL, 0)
    :
      1; // adler32(0, Z_NULL, 0)
    s.last_flush = Z_NO_FLUSH;
    trees._tr_init(s);
    return Z_OK;
  }


  function deflateReset(strm) {
    var ret = deflateResetKeep(strm);
    if (ret === Z_OK) {
      lm_init(strm.state);
    }
    return ret;
  }


  function deflateSetHeader(strm, head) {
    if (!strm || !strm.state) { return Z_STREAM_ERROR; }
    if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
    strm.state.gzhead = head;
    return Z_OK;
  }


  function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
    if (!strm) { // === Z_NULL
      return Z_STREAM_ERROR;
    }
    var wrap = 1;

    if (level === Z_DEFAULT_COMPRESSION) {
      level = 6;
    }

    if (windowBits < 0) { /* suppress zlib wrapper */
      wrap = 0;
      windowBits = -windowBits;
    }

    else if (windowBits > 15) {
      wrap = 2;           /* write gzip wrapper instead */
      windowBits -= 16;
    }


    if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
      windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
      strategy < 0 || strategy > Z_FIXED$1) {
      return err(strm, Z_STREAM_ERROR);
    }


    if (windowBits === 8) {
      windowBits = 9;
    }
    /* until 256-byte window bug fixed */

    var s = new DeflateState();

    strm.state = s;
    s.strm = strm;

    s.wrap = wrap;
    s.gzhead = null;
    s.w_bits = windowBits;
    s.w_size = 1 << s.w_bits;
    s.w_mask = s.w_size - 1;

    s.hash_bits = memLevel + 7;
    s.hash_size = 1 << s.hash_bits;
    s.hash_mask = s.hash_size - 1;
    s.hash_shift = ~~((s.hash_bits + MIN_MATCH$1 - 1) / MIN_MATCH$1);

    s.window = new common.Buf8(s.w_size * 2);
    s.head = new common.Buf16(s.hash_size);
    s.prev = new common.Buf16(s.w_size);

    // Don't need mem init magic for JS.
    //s.high_water = 0;  /* nothing written to s->window yet */

    s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */

    s.pending_buf_size = s.lit_bufsize * 4;

    //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
    //s->pending_buf = (uchf *) overlay;
    s.pending_buf = new common.Buf8(s.pending_buf_size);

    // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`)
    //s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
    s.d_buf = 1 * s.lit_bufsize;

    //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
    s.l_buf = (1 + 2) * s.lit_bufsize;

    s.level = level;
    s.strategy = strategy;
    s.method = method;

    return deflateReset(strm);
  }

  function deflateInit(strm, level) {
    return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  }


  function deflate(strm, flush) {
    var old_flush, s;
    var beg, val; // for gzip header write only

    if (!strm || !strm.state ||
      flush > Z_BLOCK || flush < 0) {
      return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
    }

    s = strm.state;

    if (!strm.output ||
        (!strm.input && strm.avail_in !== 0) ||
        (s.status === FINISH_STATE && flush !== Z_FINISH)) {
      return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
    }

    s.strm = strm; /* just in case */
    old_flush = s.last_flush;
    s.last_flush = flush;

    /* Write the header */
    if (s.status === INIT_STATE) {

      if (s.wrap === 2) { // GZIP header
        strm.adler = 0;  //crc32(0L, Z_NULL, 0);
        put_byte(s, 31);
        put_byte(s, 139);
        put_byte(s, 8);
        if (!s.gzhead) { // s->gzhead == Z_NULL
          put_byte(s, 0);
          put_byte(s, 0);
          put_byte(s, 0);
          put_byte(s, 0);
          put_byte(s, 0);
          put_byte(s, s.level === 9 ? 2 :
                      (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
                       4 : 0));
          put_byte(s, OS_CODE);
          s.status = BUSY_STATE;
        }
        else {
          put_byte(s, (s.gzhead.text ? 1 : 0) +
                      (s.gzhead.hcrc ? 2 : 0) +
                      (!s.gzhead.extra ? 0 : 4) +
                      (!s.gzhead.name ? 0 : 8) +
                      (!s.gzhead.comment ? 0 : 16)
          );
          put_byte(s, s.gzhead.time & 0xff);
          put_byte(s, (s.gzhead.time >> 8) & 0xff);
          put_byte(s, (s.gzhead.time >> 16) & 0xff);
          put_byte(s, (s.gzhead.time >> 24) & 0xff);
          put_byte(s, s.level === 9 ? 2 :
                      (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
                       4 : 0));
          put_byte(s, s.gzhead.os & 0xff);
          if (s.gzhead.extra && s.gzhead.extra.length) {
            put_byte(s, s.gzhead.extra.length & 0xff);
            put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
          }
          if (s.gzhead.hcrc) {
            strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending, 0);
          }
          s.gzindex = 0;
          s.status = EXTRA_STATE;
        }
      }
      else // DEFLATE header
      {
        var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
        var level_flags = -1;

        if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
          level_flags = 0;
        } else if (s.level < 6) {
          level_flags = 1;
        } else if (s.level === 6) {
          level_flags = 2;
        } else {
          level_flags = 3;
        }
        header |= (level_flags << 6);
        if (s.strstart !== 0) { header |= PRESET_DICT; }
        header += 31 - (header % 31);

        s.status = BUSY_STATE;
        putShortMSB(s, header);

        /* Save the adler32 of the preset dictionary: */
        if (s.strstart !== 0) {
          putShortMSB(s, strm.adler >>> 16);
          putShortMSB(s, strm.adler & 0xffff);
        }
        strm.adler = 1; // adler32(0L, Z_NULL, 0);
      }
    }

  //#ifdef GZIP
    if (s.status === EXTRA_STATE) {
      if (s.gzhead.extra/* != Z_NULL*/) {
        beg = s.pending;  /* start of bytes to update crc */

        while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
          if (s.pending === s.pending_buf_size) {
            if (s.gzhead.hcrc && s.pending > beg) {
              strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);
            }
            flush_pending(strm);
            beg = s.pending;
            if (s.pending === s.pending_buf_size) {
              break;
            }
          }
          put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
          s.gzindex++;
        }
        if (s.gzhead.hcrc && s.pending > beg) {
          strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);
        }
        if (s.gzindex === s.gzhead.extra.length) {
          s.gzindex = 0;
          s.status = NAME_STATE;
        }
      }
      else {
        s.status = NAME_STATE;
      }
    }
    if (s.status === NAME_STATE) {
      if (s.gzhead.name/* != Z_NULL*/) {
        beg = s.pending;  /* start of bytes to update crc */
        //int val;

        do {
          if (s.pending === s.pending_buf_size) {
            if (s.gzhead.hcrc && s.pending > beg) {
              strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);
            }
            flush_pending(strm);
            beg = s.pending;
            if (s.pending === s.pending_buf_size) {
              val = 1;
              break;
            }
          }
          // JS specific: little magic to add zero terminator to end of string
          if (s.gzindex < s.gzhead.name.length) {
            val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
          } else {
            val = 0;
          }
          put_byte(s, val);
        } while (val !== 0);

        if (s.gzhead.hcrc && s.pending > beg) {
          strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);
        }
        if (val === 0) {
          s.gzindex = 0;
          s.status = COMMENT_STATE;
        }
      }
      else {
        s.status = COMMENT_STATE;
      }
    }
    if (s.status === COMMENT_STATE) {
      if (s.gzhead.comment/* != Z_NULL*/) {
        beg = s.pending;  /* start of bytes to update crc */
        //int val;

        do {
          if (s.pending === s.pending_buf_size) {
            if (s.gzhead.hcrc && s.pending > beg) {
              strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);
            }
            flush_pending(strm);
            beg = s.pending;
            if (s.pending === s.pending_buf_size) {
              val = 1;
              break;
            }
          }
          // JS specific: little magic to add zero terminator to end of string
          if (s.gzindex < s.gzhead.comment.length) {
            val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
          } else {
            val = 0;
          }
          put_byte(s, val);
        } while (val !== 0);

        if (s.gzhead.hcrc && s.pending > beg) {
          strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);
        }
        if (val === 0) {
          s.status = HCRC_STATE;
        }
      }
      else {
        s.status = HCRC_STATE;
      }
    }
    if (s.status === HCRC_STATE) {
      if (s.gzhead.hcrc) {
        if (s.pending + 2 > s.pending_buf_size) {
          flush_pending(strm);
        }
        if (s.pending + 2 <= s.pending_buf_size) {
          put_byte(s, strm.adler & 0xff);
          put_byte(s, (strm.adler >> 8) & 0xff);
          strm.adler = 0; //crc32(0L, Z_NULL, 0);
          s.status = BUSY_STATE;
        }
      }
      else {
        s.status = BUSY_STATE;
      }
    }
  //#endif

    /* Flush as much pending output as possible */
    if (s.pending !== 0) {
      flush_pending(strm);
      if (strm.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:
         */
        s.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_BUF_ERROR.
       */
    } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
      flush !== Z_FINISH) {
      return err(strm, Z_BUF_ERROR);
    }

    /* User must not provide more input after the first FINISH: */
    if (s.status === FINISH_STATE && strm.avail_in !== 0) {
      return err(strm, Z_BUF_ERROR);
    }

    /* Start a new block or continue the current one.
     */
    if (strm.avail_in !== 0 || s.lookahead !== 0 ||
      (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
      var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
        (s.strategy === Z_RLE ? deflate_rle(s, flush) :
          configuration_table[s.level].func(s, flush));

      if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
        s.status = FINISH_STATE;
      }
      if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
        if (strm.avail_out === 0) {
          s.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 === BS_BLOCK_DONE) {
        if (flush === Z_PARTIAL_FLUSH) {
          trees._tr_align(s);
        }
        else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */

          trees._tr_stored_block(s, 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) {
            /*** CLEAR_HASH(s); ***/             /* forget history */
            zero$1(s.head); // Fill with NIL (= 0);

            if (s.lookahead === 0) {
              s.strstart = 0;
              s.block_start = 0;
              s.insert = 0;
            }
          }
        }
        flush_pending(strm);
        if (strm.avail_out === 0) {
          s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
          return Z_OK;
        }
      }
    }
    //Assert(strm->avail_out > 0, "bug2");
    //if (strm.avail_out <= 0) { throw new Error("bug2");}

    if (flush !== Z_FINISH) { return Z_OK; }
    if (s.wrap <= 0) { return Z_STREAM_END; }

    /* Write the trailer */
    if (s.wrap === 2) {
      put_byte(s, strm.adler & 0xff);
      put_byte(s, (strm.adler >> 8) & 0xff);
      put_byte(s, (strm.adler >> 16) & 0xff);
      put_byte(s, (strm.adler >> 24) & 0xff);
      put_byte(s, strm.total_in & 0xff);
      put_byte(s, (strm.total_in >> 8) & 0xff);
      put_byte(s, (strm.total_in >> 16) & 0xff);
      put_byte(s, (strm.total_in >> 24) & 0xff);
    }
    else
    {
      putShortMSB(s, strm.adler >>> 16);
      putShortMSB(s, strm.adler & 0xffff);
    }

    flush_pending(strm);
    /* If avail_out is zero, the application will call deflate again
     * to flush the rest.
     */
    if (s.wrap > 0) { s.wrap = -s.wrap; }
    /* write the trailer only once! */
    return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  }

  function deflateEnd(strm) {
    var status;

    if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
      return Z_STREAM_ERROR;
    }

    status = strm.state.status;
    if (status !== INIT_STATE &&
      status !== EXTRA_STATE &&
      status !== NAME_STATE &&
      status !== COMMENT_STATE &&
      status !== HCRC_STATE &&
      status !== BUSY_STATE &&
      status !== FINISH_STATE
    ) {
      return err(strm, Z_STREAM_ERROR);
    }

    strm.state = null;

    return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  }


  /* =========================================================================
   * Initializes the compression dictionary from the given byte
   * sequence without producing any compressed output.
   */
  function deflateSetDictionary(strm, dictionary) {
    var dictLength = dictionary.length;

    var s;
    var str, n;
    var wrap;
    var avail;
    var next;
    var input;
    var tmpDict;

    if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
      return Z_STREAM_ERROR;
    }

    s = strm.state;
    wrap = s.wrap;

    if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) {
      return Z_STREAM_ERROR;
    }

    /* when using zlib wrappers, compute Adler-32 for provided dictionary */
    if (wrap === 1) {
      /* adler32(strm->adler, dictionary, dictLength); */
      strm.adler = adler32_1(strm.adler, dictionary, dictLength, 0);
    }

    s.wrap = 0;   /* avoid computing Adler-32 in read_buf */

    /* if dictionary would fill window, just replace the history */
    if (dictLength >= s.w_size) {
      if (wrap === 0) {            /* already empty otherwise */
        /*** CLEAR_HASH(s); ***/
        zero$1(s.head); // Fill with NIL (= 0);
        s.strstart = 0;
        s.block_start = 0;
        s.insert = 0;
      }
      /* use the tail */
      // dictionary = dictionary.slice(dictLength - s.w_size);
      tmpDict = new common.Buf8(s.w_size);
      common.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0);
      dictionary = tmpDict;
      dictLength = s.w_size;
    }
    /* insert dictionary into window and hash */
    avail = strm.avail_in;
    next = strm.next_in;
    input = strm.input;
    strm.avail_in = dictLength;
    strm.next_in = 0;
    strm.input = dictionary;
    fill_window(s);
    while (s.lookahead >= MIN_MATCH$1) {
      str = s.strstart;
      n = s.lookahead - (MIN_MATCH$1 - 1);
      do {
        /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
        s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH$1 - 1]) & s.hash_mask;

        s.prev[str & s.w_mask] = s.head[s.ins_h];

        s.head[s.ins_h] = str;
        str++;
      } while (--n);
      s.strstart = str;
      s.lookahead = MIN_MATCH$1 - 1;
      fill_window(s);
    }
    s.strstart += s.lookahead;
    s.block_start = s.strstart;
    s.insert = s.lookahead;
    s.lookahead = 0;
    s.match_length = s.prev_length = MIN_MATCH$1 - 1;
    s.match_available = 0;
    strm.next_in = next;
    strm.input = input;
    strm.avail_in = avail;
    s.wrap = wrap;
    return Z_OK;
  }


  var deflateInit_1 = deflateInit;
  var deflateInit2_1 = deflateInit2;
  var deflateReset_1 = deflateReset;
  var deflateResetKeep_1 = deflateResetKeep;
  var deflateSetHeader_1 = deflateSetHeader;
  var deflate_2 = deflate;
  var deflateEnd_1 = deflateEnd;
  var deflateSetDictionary_1 = deflateSetDictionary;
  var deflateInfo = 'pako deflate (from Nodeca project)';

  /* Not implemented
  exports.deflateBound = deflateBound;
  exports.deflateCopy = deflateCopy;
  exports.deflateParams = deflateParams;
  exports.deflatePending = deflatePending;
  exports.deflatePrime = deflatePrime;
  exports.deflateTune = deflateTune;
  */

  var deflate_1 = {
  	deflateInit: deflateInit_1,
  	deflateInit2: deflateInit2_1,
  	deflateReset: deflateReset_1,
  	deflateResetKeep: deflateResetKeep_1,
  	deflateSetHeader: deflateSetHeader_1,
  	deflate: deflate_2,
  	deflateEnd: deflateEnd_1,
  	deflateSetDictionary: deflateSetDictionary_1,
  	deflateInfo: deflateInfo
  };

  // Quick check if we can use fast array to bin string conversion
  //
  // - apply(Array) can fail on Android 2.2
  // - apply(Uint8Array) can fail on iOS 5.1 Safari
  //
  var STR_APPLY_OK = true;
  var STR_APPLY_UIA_OK = true;

  try { String.fromCharCode.apply(null, [ 0 ]); } catch (__) { STR_APPLY_OK = false; }
  try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch (__) { STR_APPLY_UIA_OK = false; }


  // Table with utf8 lengths (calculated by first byte of sequence)
  // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  // because max possible codepoint is 0x10ffff
  var _utf8len = new common.Buf8(256);
  for (var q = 0; q < 256; q++) {
    _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
  }
  _utf8len[254] = _utf8len[254] = 1; // Invalid sequence start


  // convert string to array (typed, when possible)
  var string2buf = function (str) {
    var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;

    // count binary size
    for (m_pos = 0; m_pos < str_len; m_pos++) {
      c = str.charCodeAt(m_pos);
      if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {
        c2 = str.charCodeAt(m_pos + 1);
        if ((c2 & 0xfc00) === 0xdc00) {
          c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
          m_pos++;
        }
      }
      buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
    }

    // allocate buffer
    buf = new common.Buf8(buf_len);

    // convert
    for (i = 0, m_pos = 0; i < buf_len; m_pos++) {
      c = str.charCodeAt(m_pos);
      if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {
        c2 = str.charCodeAt(m_pos + 1);
        if ((c2 & 0xfc00) === 0xdc00) {
          c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
          m_pos++;
        }
      }
      if (c < 0x80) {
        /* one byte */
        buf[i++] = c;
      } else if (c < 0x800) {
        /* two bytes */
        buf[i++] = 0xC0 | (c >>> 6);
        buf[i++] = 0x80 | (c & 0x3f);
      } else if (c < 0x10000) {
        /* three bytes */
        buf[i++] = 0xE0 | (c >>> 12);
        buf[i++] = 0x80 | (c >>> 6 & 0x3f);
        buf[i++] = 0x80 | (c & 0x3f);
      } else {
        /* four bytes */
        buf[i++] = 0xf0 | (c >>> 18);
        buf[i++] = 0x80 | (c >>> 12 & 0x3f);
        buf[i++] = 0x80 | (c >>> 6 & 0x3f);
        buf[i++] = 0x80 | (c & 0x3f);
      }
    }

    return buf;
  };

  // Helper (used in 2 places)
  function buf2binstring(buf, len) {
    // On Chrome, the arguments in a function call that are allowed is `65534`.
    // If the length of the buffer is smaller than that, we can use this optimization,
    // otherwise we will take a slower path.
    if (len < 65534) {
      if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
        return String.fromCharCode.apply(null, common.shrinkBuf(buf, len));
      }
    }

    var result = '';
    for (var i = 0; i < len; i++) {
      result += String.fromCharCode(buf[i]);
    }
    return result;
  }


  // Convert byte array to binary string
  var buf2binstring_1 = function (buf) {
    return buf2binstring(buf, buf.length);
  };


  // Convert binary string (typed, when possible)
  var binstring2buf = function (str) {
    var buf = new common.Buf8(str.length);
    for (var i = 0, len = buf.length; i < len; i++) {
      buf[i] = str.charCodeAt(i);
    }
    return buf;
  };


  // convert array to string
  var buf2string = function (buf, max) {
    var i, out, c, c_len;
    var len = max || buf.length;

    // Reserve max possible length (2 words per char)
    // NB: by unknown reasons, Array is significantly faster for
    //     String.fromCharCode.apply than Uint16Array.
    var utf16buf = new Array(len * 2);

    for (out = 0, i = 0; i < len;) {
      c = buf[i++];
      // quick process ascii
      if (c < 0x80) { utf16buf[out++] = c; continue; }

      c_len = _utf8len[c];
      // skip 5 & 6 byte codes
      if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; }

      // apply mask on first byte
      c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
      // join the rest
      while (c_len > 1 && i < len) {
        c = (c << 6) | (buf[i++] & 0x3f);
        c_len--;
      }

      // terminated by end of string?
      if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }

      if (c < 0x10000) {
        utf16buf[out++] = c;
      } else {
        c -= 0x10000;
        utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
        utf16buf[out++] = 0xdc00 | (c & 0x3ff);
      }
    }

    return buf2binstring(utf16buf, out);
  };


  // Calculate max possible position in utf8 buffer,
  // that will not break sequence. If that's not possible
  // - (very small limits) return max size as is.
  //
  // buf[] - utf8 bytes array
  // max   - length limit (mandatory);
  var utf8border = function (buf, max) {
    var pos;

    max = max || buf.length;
    if (max > buf.length) { max = buf.length; }

    // go back from last position, until start of sequence found
    pos = max - 1;
    while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }

    // Very small and broken sequence,
    // return max, because we should return something anyway.
    if (pos < 0) { return max; }

    // If we came to start of buffer - that means buffer is too small,
    // return max too.
    if (pos === 0) { return max; }

    return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  };

  var strings = {
  	string2buf: string2buf,
  	buf2binstring: buf2binstring_1,
  	binstring2buf: binstring2buf,
  	buf2string: buf2string,
  	utf8border: utf8border
  };

  // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  //
  // This software is provided 'as-is', without any express or implied
  // warranty. In no event will the authors be held liable for any damages
  // arising from the use of this software.
  //
  // Permission is granted to anyone to use this software for any purpose,
  // including commercial applications, and to alter it and redistribute it
  // freely, subject to the following restrictions:
  //
  // 1. The origin of this software must not be misrepresented; you must not
  //   claim that you wrote the original software. If you use this software
  //   in a product, an acknowledgment in the product documentation would be
  //   appreciated but is not required.
  // 2. Altered source versions must be plainly marked as such, and must not be
  //   misrepresented as being the original software.
  // 3. This notice may not be removed or altered from any source distribution.

  function ZStream() {
    /* next input byte */
    this.input = null; // JS specific, because we have no pointers
    this.next_in = 0;
    /* number of bytes available at input */
    this.avail_in = 0;
    /* total number of input bytes read so far */
    this.total_in = 0;
    /* next output byte should be put there */
    this.output = null; // JS specific, because we have no pointers
    this.next_out = 0;
    /* remaining free space at output */
    this.avail_out = 0;
    /* total number of bytes output so far */
    this.total_out = 0;
    /* last error message, NULL if no error */
    this.msg = ''/*Z_NULL*/;
    /* not visible by applications */
    this.state = null;
    /* best guess about the data type: binary or text */
    this.data_type = 2/*Z_UNKNOWN*/;
    /* adler32 value of the uncompressed data */
    this.adler = 0;
  }

  var zstream = ZStream;

  var toString = Object.prototype.toString;

  /* Public constants ==========================================================*/
  /* ===========================================================================*/

  var Z_NO_FLUSH$1      = 0;
  var Z_FINISH$1        = 4;

  var Z_OK$1            = 0;
  var Z_STREAM_END$1    = 1;
  var Z_SYNC_FLUSH    = 2;

  var Z_DEFAULT_COMPRESSION$1 = -1;

  var Z_DEFAULT_STRATEGY$1    = 0;

  var Z_DEFLATED$1  = 8;

  /* ===========================================================================*/


  /**
   * class Deflate
   *
   * Generic JS-style wrapper for zlib calls. If you don't need
   * streaming behaviour - use more simple functions: [[deflate]],
   * [[deflateRaw]] and [[gzip]].
   **/

  /* internal
   * Deflate.chunks -> Array
   *
   * Chunks of output data, if [[Deflate#onData]] not overridden.
   **/

  /**
   * Deflate.result -> Uint8Array|Array
   *
   * Compressed result, generated by default [[Deflate#onData]]
   * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
   * (call [[Deflate#push]] with `Z_FINISH` / `true` param)  or if you
   * push a chunk with explicit flush (call [[Deflate#push]] with
   * `Z_SYNC_FLUSH` param).
   **/

  /**
   * Deflate.err -> Number
   *
   * Error code after deflate finished. 0 (Z_OK) on success.
   * You will not need it in real life, because deflate errors
   * are possible only on wrong options or bad `onData` / `onEnd`
   * custom handlers.
   **/

  /**
   * Deflate.msg -> String
   *
   * Error message, if [[Deflate.err]] != 0
   **/


  /**
   * new Deflate(options)
   * - options (Object): zlib deflate options.
   *
   * Creates new deflator instance with specified params. Throws exception
   * on bad params. Supported options:
   *
   * - `level`
   * - `windowBits`
   * - `memLevel`
   * - `strategy`
   * - `dictionary`
   *
   * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
   * for more information on these.
   *
   * Additional options, for internal needs:
   *
   * - `chunkSize` - size of generated data chunks (16K by default)
   * - `raw` (Boolean) - do raw deflate
   * - `gzip` (Boolean) - create gzip wrapper
   * - `to` (String) - if equal to 'string', then result will be "binary string"
   *    (each char code [0..255])
   * - `header` (Object) - custom header for gzip
   *   - `text` (Boolean) - true if compressed data believed to be text
   *   - `time` (Number) - modification time, unix timestamp
   *   - `os` (Number) - operation system code
   *   - `extra` (Array) - array of bytes with extra data (max 65536)
   *   - `name` (String) - file name (binary string)
   *   - `comment` (String) - comment (binary string)
   *   - `hcrc` (Boolean) - true if header crc should be added
   *
   * ##### Example:
   *
   * ```javascript
   * var pako = require('pako')
   *   , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
   *   , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
   *
   * var deflate = new pako.Deflate({ level: 3});
   *
   * deflate.push(chunk1, false);
   * deflate.push(chunk2, true);  // true -> last chunk
   *
   * if (deflate.err) { throw new Error(deflate.err); }
   *
   * console.log(deflate.result);
   * ```
   **/
  function Deflate(options) {
    if (!(this instanceof Deflate)) return new Deflate(options);

    this.options = common.assign({
      level: Z_DEFAULT_COMPRESSION$1,
      method: Z_DEFLATED$1,
      chunkSize: 16384,
      windowBits: 15,
      memLevel: 8,
      strategy: Z_DEFAULT_STRATEGY$1,
      to: ''
    }, options || {});

    var opt = this.options;

    if (opt.raw && (opt.windowBits > 0)) {
      opt.windowBits = -opt.windowBits;
    }

    else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
      opt.windowBits += 16;
    }

    this.err    = 0;      // error code, if happens (0 = Z_OK)
    this.msg    = '';     // error message
    this.ended  = false;  // used to avoid multiple onEnd() calls
    this.chunks = [];     // chunks of compressed data

    this.strm = new zstream();
    this.strm.avail_out = 0;

    var status = deflate_1.deflateInit2(
      this.strm,
      opt.level,
      opt.method,
      opt.windowBits,
      opt.memLevel,
      opt.strategy
    );

    if (status !== Z_OK$1) {
      throw new Error(messages[status]);
    }

    if (opt.header) {
      deflate_1.deflateSetHeader(this.strm, opt.header);
    }

    if (opt.dictionary) {
      var dict;
      // Convert data if needed
      if (typeof opt.dictionary === 'string') {
        // If we need to compress text, change encoding to utf8.
        dict = strings.string2buf(opt.dictionary);
      } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') {
        dict = new Uint8Array(opt.dictionary);
      } else {
        dict = opt.dictionary;
      }

      status = deflate_1.deflateSetDictionary(this.strm, dict);

      if (status !== Z_OK$1) {
        throw new Error(messages[status]);
      }

      this._dict_set = true;
    }
  }

  /**
   * Deflate#push(data[, mode]) -> Boolean
   * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
   *   converted to utf8 byte sequence.
   * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
   *   See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH.
   *
   * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
   * new compressed chunks. Returns `true` on success. The last data block must have
   * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
   * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
   * can use mode Z_SYNC_FLUSH, keeping the compression context.
   *
   * On fail call [[Deflate#onEnd]] with error code and return false.
   *
   * We strongly recommend to use `Uint8Array` on input for best speed (output
   * array format is detected automatically). Also, don't skip last param and always
   * use the same type in your code (boolean or number). That will improve JS speed.
   *
   * For regular `Array`-s make sure all elements are [0..255].
   *
   * ##### Example
   *
   * ```javascript
   * push(chunk, false); // push one of data chunks
   * ...
   * push(chunk, true);  // push last chunk
   * ```
   **/
  Deflate.prototype.push = function (data, mode) {
    var strm = this.strm;
    var chunkSize = this.options.chunkSize;
    var status, _mode;

    if (this.ended) { return false; }

    _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH$1 : Z_NO_FLUSH$1);

    // Convert data if needed
    if (typeof data === 'string') {
      // If we need to compress text, change encoding to utf8.
      strm.input = strings.string2buf(data);
    } else if (toString.call(data) === '[object ArrayBuffer]') {
      strm.input = new Uint8Array(data);
    } else {
      strm.input = data;
    }

    strm.next_in = 0;
    strm.avail_in = strm.input.length;

    do {
      if (strm.avail_out === 0) {
        strm.output = new common.Buf8(chunkSize);
        strm.next_out = 0;
        strm.avail_out = chunkSize;
      }
      status = deflate_1.deflate(strm, _mode);    /* no bad return value */

      if (status !== Z_STREAM_END$1 && status !== Z_OK$1) {
        this.onEnd(status);
        this.ended = true;
        return false;
      }
      if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH$1 || _mode === Z_SYNC_FLUSH))) {
        if (this.options.to === 'string') {
          this.onData(strings.buf2binstring(common.shrinkBuf(strm.output, strm.next_out)));
        } else {
          this.onData(common.shrinkBuf(strm.output, strm.next_out));
        }
      }
    } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END$1);

    // Finalize on the last chunk.
    if (_mode === Z_FINISH$1) {
      status = deflate_1.deflateEnd(this.strm);
      this.onEnd(status);
      this.ended = true;
      return status === Z_OK$1;
    }

    // callback interim results if Z_SYNC_FLUSH.
    if (_mode === Z_SYNC_FLUSH) {
      this.onEnd(Z_OK$1);
      strm.avail_out = 0;
      return true;
    }

    return true;
  };


  /**
   * Deflate#onData(chunk) -> Void
   * - chunk (Uint8Array|Array|String): output data. Type of array depends
   *   on js engine support. When string output requested, each chunk
   *   will be string.
   *
   * By default, stores data blocks in `chunks[]` property and glue
   * those in `onEnd`. Override this handler, if you need another behaviour.
   **/
  Deflate.prototype.onData = function (chunk) {
    this.chunks.push(chunk);
  };


  /**
   * Deflate#onEnd(status) -> Void
   * - status (Number): deflate status. 0 (Z_OK) on success,
   *   other if not.
   *
   * Called once after you tell deflate that the input stream is
   * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
   * or if an error happened. By default - join collected chunks,
   * free memory and fill `results` / `err` properties.
   **/
  Deflate.prototype.onEnd = function (status) {
    // On success - join
    if (status === Z_OK$1) {
      if (this.options.to === 'string') {
        this.result = this.chunks.join('');
      } else {
        this.result = common.flattenChunks(this.chunks);
      }
    }
    this.chunks = [];
    this.err = status;
    this.msg = this.strm.msg;
  };


  /**
   * deflate(data[, options]) -> Uint8Array|Array|String
   * - data (Uint8Array|Array|String): input data to compress.
   * - options (Object): zlib deflate options.
   *
   * Compress `data` with deflate algorithm and `options`.
   *
   * Supported options are:
   *
   * - level
   * - windowBits
   * - memLevel
   * - strategy
   * - dictionary
   *
   * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
   * for more information on these.
   *
   * Sugar (options):
   *
   * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
   *   negative windowBits implicitly.
   * - `to` (String) - if equal to 'string', then result will be "binary string"
   *    (each char code [0..255])
   *
   * ##### Example:
   *
   * ```javascript
   * var pako = require('pako')
   *   , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
   *
   * console.log(pako.deflate(data));
   * ```
   **/
  function deflate$1(input, options) {
    var deflator = new Deflate(options);

    deflator.push(input, true);

    // That will never happens, if you don't cheat with options :)
    if (deflator.err) { throw deflator.msg || messages[deflator.err]; }

    return deflator.result;
  }


  /**
   * deflateRaw(data[, options]) -> Uint8Array|Array|String
   * - data (Uint8Array|Array|String): input data to compress.
   * - options (Object): zlib deflate options.
   *
   * The same as [[deflate]], but creates raw data, without wrapper
   * (header and adler32 crc).
   **/
  function deflateRaw(input, options) {
    options = options || {};
    options.raw = true;
    return deflate$1(input, options);
  }


  /**
   * gzip(data[, options]) -> Uint8Array|Array|String
   * - data (Uint8Array|Array|String): input data to compress.
   * - options (Object): zlib deflate options.
   *
   * The same as [[deflate]], but create gzip wrapper instead of
   * deflate one.
   **/
  function gzip(input, options) {
    options = options || {};
    options.gzip = true;
    return deflate$1(input, options);
  }


  var Deflate_1 = Deflate;
  var deflate_2$1 = deflate$1;
  var deflateRaw_1 = deflateRaw;
  var gzip_1 = gzip;

  var deflate_1$1 = {
  	Deflate: Deflate_1,
  	deflate: deflate_2$1,
  	deflateRaw: deflateRaw_1,
  	gzip: gzip_1
  };

  // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  //
  // This software is provided 'as-is', without any express or implied
  // warranty. In no event will the authors be held liable for any damages
  // arising from the use of this software.
  //
  // Permission is granted to anyone to use this software for any purpose,
  // including commercial applications, and to alter it and redistribute it
  // freely, subject to the following restrictions:
  //
  // 1. The origin of this software must not be misrepresented; you must not
  //   claim that you wrote the original software. If you use this software
  //   in a product, an acknowledgment in the product documentation would be
  //   appreciated but is not required.
  // 2. Altered source versions must be plainly marked as such, and must not be
  //   misrepresented as being the original software.
  // 3. This notice may not be removed or altered from any source distribution.

  // See state defs from inflate.js
  var BAD = 30;       /* got a data error -- remain here until reset */
  var TYPE = 12;      /* i: waiting for type bits, including last-flag bit */

  /*
     Decode literal, length, and distance codes and write out the resulting
     literal and match bytes until either not enough input or output is
     available, an end-of-block is encountered, or a data error is encountered.
     When large enough input and output buffers are supplied to inflate(), for
     example, a 16K input buffer and a 64K output buffer, more than 95% of the
     inflate execution time is spent in this routine.

     Entry assumptions:

          state.mode === LEN
          strm.avail_in >= 6
          strm.avail_out >= 258
          start >= strm.avail_out
          state.bits < 8

     On return, state.mode is one of:

          LEN -- ran out of enough output space or enough available input
          TYPE -- reached end of block code, inflate() to interpret next block
          BAD -- error in block data

     Notes:

      - The maximum input bits used by a length/distance pair is 15 bits for the
        length code, 5 bits for the length extra, 15 bits for the distance code,
        and 13 bits for the distance extra.  This totals 48 bits, or six bytes.
        Therefore if strm.avail_in >= 6, then there is enough input to avoid
        checking for available input while decoding.

      - The maximum bytes that a single length/distance pair can output is 258
        bytes, which is the maximum length that can be coded.  inflate_fast()
        requires strm.avail_out >= 258 for each loop to avoid checking for
        output space.
   */
  var inffast = function inflate_fast(strm, start) {
    var state;
    var _in;                    /* local strm.input */
    var last;                   /* have enough input while in < last */
    var _out;                   /* local strm.output */
    var beg;                    /* inflate()'s initial strm.output */
    var end;                    /* while out < end, enough space available */
  //#ifdef INFLATE_STRICT
    var dmax;                   /* maximum distance from zlib header */
  //#endif
    var wsize;                  /* window size or zero if not using window */
    var whave;                  /* valid bytes in the window */
    var wnext;                  /* window write index */
    // Use `s_window` instead `window`, avoid conflict with instrumentation tools
    var s_window;               /* allocated sliding window, if wsize != 0 */
    var hold;                   /* local strm.hold */
    var bits;                   /* local strm.bits */
    var lcode;                  /* local strm.lencode */
    var dcode;                  /* local strm.distcode */
    var lmask;                  /* mask for first level of length codes */
    var dmask;                  /* mask for first level of distance codes */
    var here;                   /* retrieved table entry */
    var op;                     /* code bits, operation, extra bits, or */
                                /*  window position, window bytes to copy */
    var len;                    /* match length, unused bytes */
    var dist;                   /* match distance */
    var from;                   /* where to copy match from */
    var from_source;


    var input, output; // JS specific, because we have no pointers

    /* copy state to local variables */
    state = strm.state;
    //here = state.here;
    _in = strm.next_in;
    input = strm.input;
    last = _in + (strm.avail_in - 5);
    _out = strm.next_out;
    output = strm.output;
    beg = _out - (start - strm.avail_out);
    end = _out + (strm.avail_out - 257);
  //#ifdef INFLATE_STRICT
    dmax = state.dmax;
  //#endif
    wsize = state.wsize;
    whave = state.whave;
    wnext = state.wnext;
    s_window = state.window;
    hold = state.hold;
    bits = state.bits;
    lcode = state.lencode;
    dcode = state.distcode;
    lmask = (1 << state.lenbits) - 1;
    dmask = (1 << state.distbits) - 1;


    /* decode literals and length/distances until end-of-block or not enough
       input data or output space */

    top:
    do {
      if (bits < 15) {
        hold += input[_in++] << bits;
        bits += 8;
        hold += input[_in++] << bits;
        bits += 8;
      }

      here = lcode[hold & lmask];

      dolen:
      for (;;) { // Goto emulation
        op = here >>> 24/*here.bits*/;
        hold >>>= op;
        bits -= op;
        op = (here >>> 16) & 0xff/*here.op*/;
        if (op === 0) {                          /* literal */
          //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
          //        "inflate:         literal '%c'\n" :
          //        "inflate:         literal 0x%02x\n", here.val));
          output[_out++] = here & 0xffff/*here.val*/;
        }
        else if (op & 16) {                     /* length base */
          len = here & 0xffff/*here.val*/;
          op &= 15;                           /* number of extra bits */
          if (op) {
            if (bits < op) {
              hold += input[_in++] << bits;
              bits += 8;
            }
            len += hold & ((1 << op) - 1);
            hold >>>= op;
            bits -= op;
          }
          //Tracevv((stderr, "inflate:         length %u\n", len));
          if (bits < 15) {
            hold += input[_in++] << bits;
            bits += 8;
            hold += input[_in++] << bits;
            bits += 8;
          }
          here = dcode[hold & dmask];

          dodist:
          for (;;) { // goto emulation
            op = here >>> 24/*here.bits*/;
            hold >>>= op;
            bits -= op;
            op = (here >>> 16) & 0xff/*here.op*/;

            if (op & 16) {                      /* distance base */
              dist = here & 0xffff/*here.val*/;
              op &= 15;                       /* number of extra bits */
              if (bits < op) {
                hold += input[_in++] << bits;
                bits += 8;
                if (bits < op) {
                  hold += input[_in++] << bits;
                  bits += 8;
                }
              }
              dist += hold & ((1 << op) - 1);
  //#ifdef INFLATE_STRICT
              if (dist > dmax) {
                strm.msg = 'invalid distance too far back';
                state.mode = BAD;
                break top;
              }
  //#endif
              hold >>>= op;
              bits -= op;
              //Tracevv((stderr, "inflate:         distance %u\n", dist));
              op = _out - beg;                /* max distance in output */
              if (dist > op) {                /* see if copy from window */
                op = dist - op;               /* distance back in window */
                if (op > whave) {
                  if (state.sane) {
                    strm.msg = 'invalid distance too far back';
                    state.mode = BAD;
                    break top;
                  }

  // (!) This block is disabled in zlib defaults,
  // don't enable it for binary compatibility
  //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  //                if (len <= op - whave) {
  //                  do {
  //                    output[_out++] = 0;
  //                  } while (--len);
  //                  continue top;
  //                }
  //                len -= op - whave;
  //                do {
  //                  output[_out++] = 0;
  //                } while (--op > whave);
  //                if (op === 0) {
  //                  from = _out - dist;
  //                  do {
  //                    output[_out++] = output[from++];
  //                  } while (--len);
  //                  continue top;
  //                }
  //#endif
                }
                from = 0; // window index
                from_source = s_window;
                if (wnext === 0) {           /* very common case */
                  from += wsize - op;
                  if (op < len) {         /* some from window */
                    len -= op;
                    do {
                      output[_out++] = s_window[from++];
                    } while (--op);
                    from = _out - dist;  /* rest from output */
                    from_source = output;
                  }
                }
                else if (wnext < op) {      /* wrap around window */
                  from += wsize + wnext - op;
                  op -= wnext;
                  if (op < len) {         /* some from end of window */
                    len -= op;
                    do {
                      output[_out++] = s_window[from++];
                    } while (--op);
                    from = 0;
                    if (wnext < len) {  /* some from start of window */
                      op = wnext;
                      len -= op;
                      do {
                        output[_out++] = s_window[from++];
                      } while (--op);
                      from = _out - dist;      /* rest from output */
                      from_source = output;
                    }
                  }
                }
                else {                      /* contiguous in window */
                  from += wnext - op;
                  if (op < len) {         /* some from window */
                    len -= op;
                    do {
                      output[_out++] = s_window[from++];
                    } while (--op);
                    from = _out - dist;  /* rest from output */
                    from_source = output;
                  }
                }
                while (len > 2) {
                  output[_out++] = from_source[from++];
                  output[_out++] = from_source[from++];
                  output[_out++] = from_source[from++];
                  len -= 3;
                }
                if (len) {
                  output[_out++] = from_source[from++];
                  if (len > 1) {
                    output[_out++] = from_source[from++];
                  }
                }
              }
              else {
                from = _out - dist;          /* copy direct from output */
                do {                        /* minimum length is three */
                  output[_out++] = output[from++];
                  output[_out++] = output[from++];
                  output[_out++] = output[from++];
                  len -= 3;
                } while (len > 2);
                if (len) {
                  output[_out++] = output[from++];
                  if (len > 1) {
                    output[_out++] = output[from++];
                  }
                }
              }
            }
            else if ((op & 64) === 0) {          /* 2nd level distance code */
              here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
              continue dodist;
            }
            else {
              strm.msg = 'invalid distance code';
              state.mode = BAD;
              break top;
            }

            break; // need to emulate goto via "continue"
          }
        }
        else if ((op & 64) === 0) {              /* 2nd level length code */
          here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
          continue dolen;
        }
        else if (op & 32) {                     /* end-of-block */
          //Tracevv((stderr, "inflate:         end of block\n"));
          state.mode = TYPE;
          break top;
        }
        else {
          strm.msg = 'invalid literal/length code';
          state.mode = BAD;
          break top;
        }

        break; // need to emulate goto via "continue"
      }
    } while (_in < last && _out < end);

    /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
    len = bits >> 3;
    _in -= len;
    bits -= len << 3;
    hold &= (1 << bits) - 1;

    /* update state and return */
    strm.next_in = _in;
    strm.next_out = _out;
    strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
    strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
    state.hold = hold;
    state.bits = bits;
    return;
  };

  // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  //
  // This software is provided 'as-is', without any express or implied
  // warranty. In no event will the authors be held liable for any damages
  // arising from the use of this software.
  //
  // Permission is granted to anyone to use this software for any purpose,
  // including commercial applications, and to alter it and redistribute it
  // freely, subject to the following restrictions:
  //
  // 1. The origin of this software must not be misrepresented; you must not
  //   claim that you wrote the original software. If you use this software
  //   in a product, an acknowledgment in the product documentation would be
  //   appreciated but is not required.
  // 2. Altered source versions must be plainly marked as such, and must not be
  //   misrepresented as being the original software.
  // 3. This notice may not be removed or altered from any source distribution.



  var MAXBITS = 15;
  var ENOUGH_LENS = 852;
  var ENOUGH_DISTS = 592;
  //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);

  var CODES = 0;
  var LENS = 1;
  var DISTS = 2;

  var lbase = [ /* Length codes 257..285 base */
    3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
    35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  ];

  var lext = [ /* Length codes 257..285 extra */
    16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
    19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  ];

  var dbase = [ /* Distance codes 0..29 base */
    1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
    257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
    8193, 12289, 16385, 24577, 0, 0
  ];

  var dext = [ /* Distance codes 0..29 extra */
    16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
    23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
    28, 28, 29, 29, 64, 64
  ];

  var inftrees = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  {
    var bits = opts.bits;
        //here = opts.here; /* table entry for duplication */

    var len = 0;               /* a code's length in bits */
    var sym = 0;               /* index of code symbols */
    var min = 0, max = 0;          /* minimum and maximum code lengths */
    var root = 0;              /* number of index bits for root table */
    var curr = 0;              /* number of index bits for current table */
    var drop = 0;              /* code bits to drop for sub-table */
    var left = 0;                   /* number of prefix codes available */
    var used = 0;              /* code entries in table used */
    var huff = 0;              /* Huffman code */
    var incr;              /* for incrementing code, index */
    var fill;              /* index for replicating entries */
    var low;               /* low bits for current root entry */
    var mask;              /* mask for low root bits */
    var next;             /* next available space in table */
    var base = null;     /* base value table to use */
    var base_index = 0;
  //  var shoextra;    /* extra bits table to use */
    var end;                    /* use base and extra for symbol > end */
    var count = new common.Buf16(MAXBITS + 1); //[MAXBITS+1];    /* number of codes of each length */
    var offs = new common.Buf16(MAXBITS + 1); //[MAXBITS+1];     /* offsets in table for each length */
    var extra = null;
    var extra_index = 0;

    var here_bits, here_op, here_val;

    /*
     Process a set of code lengths to create a canonical Huffman code.  The
     code lengths are lens[0..codes-1].  Each length corresponds to the
     symbols 0..codes-1.  The Huffman code is generated by first sorting the
     symbols by length from short to long, and retaining the symbol order
     for codes with equal lengths.  Then the code starts with all zero bits
     for the first code of the shortest length, and the codes are integer
     increments for the same length, and zeros are appended as the length
     increases.  For the deflate format, these bits are stored backwards
     from their more natural integer increment ordering, and so when the
     decoding tables are built in the large loop below, the integer codes
     are incremented backwards.

     This routine assumes, but does not check, that all of the entries in
     lens[] are in the range 0..MAXBITS.  The caller must assure this.
     1..MAXBITS is interpreted as that code length.  zero means that that
     symbol does not occur in this code.

     The codes are sorted by computing a count of codes for each length,
     creating from that a table of starting indices for each length in the
     sorted table, and then entering the symbols in order in the sorted
     table.  The sorted table is work[], with that space being provided by
     the caller.

     The length counts are used for other purposes as well, i.e. finding
     the minimum and maximum length codes, determining if there are any
     codes at all, checking for a valid set of lengths, and looking ahead
     at length counts to determine sub-table sizes when building the
     decoding tables.
     */

    /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
    for (len = 0; len <= MAXBITS; len++) {
      count[len] = 0;
    }
    for (sym = 0; sym < codes; sym++) {
      count[lens[lens_index + sym]]++;
    }

    /* bound code lengths, force root to be within code lengths */
    root = bits;
    for (max = MAXBITS; max >= 1; max--) {
      if (count[max] !== 0) { break; }
    }
    if (root > max) {
      root = max;
    }
    if (max === 0) {                     /* no symbols to code at all */
      //table.op[opts.table_index] = 64;  //here.op = (var char)64;    /* invalid code marker */
      //table.bits[opts.table_index] = 1;   //here.bits = (var char)1;
      //table.val[opts.table_index++] = 0;   //here.val = (var short)0;
      table[table_index++] = (1 << 24) | (64 << 16) | 0;


      //table.op[opts.table_index] = 64;
      //table.bits[opts.table_index] = 1;
      //table.val[opts.table_index++] = 0;
      table[table_index++] = (1 << 24) | (64 << 16) | 0;

      opts.bits = 1;
      return 0;     /* no symbols, but wait for decoding to report error */
    }
    for (min = 1; min < max; min++) {
      if (count[min] !== 0) { break; }
    }
    if (root < min) {
      root = min;
    }

    /* check for an over-subscribed or incomplete set of lengths */
    left = 1;
    for (len = 1; len <= MAXBITS; len++) {
      left <<= 1;
      left -= count[len];
      if (left < 0) {
        return -1;
      }        /* over-subscribed */
    }
    if (left > 0 && (type === CODES || max !== 1)) {
      return -1;                      /* incomplete set */
    }

    /* generate offsets into symbol table for each length for sorting */
    offs[1] = 0;
    for (len = 1; len < MAXBITS; len++) {
      offs[len + 1] = offs[len] + count[len];
    }

    /* sort symbols by length, by symbol order within each length */
    for (sym = 0; sym < codes; sym++) {
      if (lens[lens_index + sym] !== 0) {
        work[offs[lens[lens_index + sym]]++] = sym;
      }
    }

    /*
     Create and fill in decoding tables.  In this loop, the table being
     filled is at next and has curr index bits.  The code being used is huff
     with length len.  That code is converted to an index by dropping drop
     bits off of the bottom.  For codes where len is less than drop + curr,
     those top drop + curr - len bits are incremented through all values to
     fill the table with replicated entries.

     root is the number of index bits for the root table.  When len exceeds
     root, sub-tables are created pointed to by the root entry with an index
     of the low root bits of huff.  This is saved in low to check for when a
     new sub-table should be started.  drop is zero when the root table is
     being filled, and drop is root when sub-tables are being filled.

     When a new sub-table is needed, it is necessary to look ahead in the
     code lengths to determine what size sub-table is needed.  The length
     counts are used for this, and so count[] is decremented as codes are
     entered in the tables.

     used keeps track of how many table entries have been allocated from the
     provided *table space.  It is checked for LENS and DIST tables against
     the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
     the initial root table size constants.  See the comments in inftrees.h
     for more information.

     sym increments through all symbols, and the loop terminates when
     all codes of length max, i.e. all codes, have been processed.  This
     routine permits incomplete codes, so another loop after this one fills
     in the rest of the decoding tables with invalid code markers.
     */

    /* set up for code type */
    // poor man optimization - use if-else instead of switch,
    // to avoid deopts in old v8
    if (type === CODES) {
      base = extra = work;    /* dummy value--not used */
      end = 19;

    } else if (type === LENS) {
      base = lbase;
      base_index -= 257;
      extra = lext;
      extra_index -= 257;
      end = 256;

    } else {                    /* DISTS */
      base = dbase;
      extra = dext;
      end = -1;
    }

    /* initialize opts for loop */
    huff = 0;                   /* starting code */
    sym = 0;                    /* starting code symbol */
    len = min;                  /* starting code length */
    next = table_index;              /* current table to fill in */
    curr = root;                /* current table index bits */
    drop = 0;                   /* current bits to drop from code for index */
    low = -1;                   /* trigger new sub-table when len > root */
    used = 1 << root;          /* use root table entries */
    mask = used - 1;            /* mask for comparing low */

    /* check available table space */
    if ((type === LENS && used > ENOUGH_LENS) ||
      (type === DISTS && used > ENOUGH_DISTS)) {
      return 1;
    }

    /* process all codes and make table entries */
    for (;;) {
      /* create table entry */
      here_bits = len - drop;
      if (work[sym] < end) {
        here_op = 0;
        here_val = work[sym];
      }
      else if (work[sym] > end) {
        here_op = extra[extra_index + work[sym]];
        here_val = base[base_index + work[sym]];
      }
      else {
        here_op = 32 + 64;         /* end of block */
        here_val = 0;
      }

      /* replicate for those indices with low len bits equal to huff */
      incr = 1 << (len - drop);
      fill = 1 << curr;
      min = fill;                 /* save offset to next table */
      do {
        fill -= incr;
        table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
      } while (fill !== 0);

      /* backwards increment the len-bit code huff */
      incr = 1 << (len - 1);
      while (huff & incr) {
        incr >>= 1;
      }
      if (incr !== 0) {
        huff &= incr - 1;
        huff += incr;
      } else {
        huff = 0;
      }

      /* go to next symbol, update count, len */
      sym++;
      if (--count[len] === 0) {
        if (len === max) { break; }
        len = lens[lens_index + work[sym]];
      }

      /* create new sub-table if needed */
      if (len > root && (huff & mask) !== low) {
        /* if first time, transition to sub-tables */
        if (drop === 0) {
          drop = root;
        }

        /* increment past last table */
        next += min;            /* here min is 1 << curr */

        /* determine length of next table */
        curr = len - drop;
        left = 1 << curr;
        while (curr + drop < max) {
          left -= count[curr + drop];
          if (left <= 0) { break; }
          curr++;
          left <<= 1;
        }

        /* check for enough space */
        used += 1 << curr;
        if ((type === LENS && used > ENOUGH_LENS) ||
          (type === DISTS && used > ENOUGH_DISTS)) {
          return 1;
        }

        /* point entry in root table to sub-table */
        low = huff & mask;
        /*table.op[low] = curr;
        table.bits[low] = root;
        table.val[low] = next - opts.table_index;*/
        table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
      }
    }

    /* fill in remaining table entry if code is incomplete (guaranteed to have
     at most one remaining entry, since if the code is incomplete, the
     maximum code length that was allowed to get this far is one bit) */
    if (huff !== 0) {
      //table.op[next + huff] = 64;            /* invalid code marker */
      //table.bits[next + huff] = len - drop;
      //table.val[next + huff] = 0;
      table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
    }

    /* set return parameters */
    //opts.table_index += used;
    opts.bits = root;
    return 0;
  };

  // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  //
  // This software is provided 'as-is', without any express or implied
  // warranty. In no event will the authors be held liable for any damages
  // arising from the use of this software.
  //
  // Permission is granted to anyone to use this software for any purpose,
  // including commercial applications, and to alter it and redistribute it
  // freely, subject to the following restrictions:
  //
  // 1. The origin of this software must not be misrepresented; you must not
  //   claim that you wrote the original software. If you use this software
  //   in a product, an acknowledgment in the product documentation would be
  //   appreciated but is not required.
  // 2. Altered source versions must be plainly marked as such, and must not be
  //   misrepresented as being the original software.
  // 3. This notice may not be removed or altered from any source distribution.







  var CODES$1 = 0;
  var LENS$1 = 1;
  var DISTS$1 = 2;

  /* Public constants ==========================================================*/
  /* ===========================================================================*/


  /* Allowed flush values; see deflate() and inflate() below for details */
  //var Z_NO_FLUSH      = 0;
  //var Z_PARTIAL_FLUSH = 1;
  //var Z_SYNC_FLUSH    = 2;
  //var Z_FULL_FLUSH    = 3;
  var Z_FINISH$2        = 4;
  var Z_BLOCK$1         = 5;
  var Z_TREES         = 6;


  /* Return codes for the compression/decompression functions. Negative values
   * are errors, positive values are used for special but normal events.
   */
  var Z_OK$2            = 0;
  var Z_STREAM_END$2    = 1;
  var Z_NEED_DICT     = 2;
  //var Z_ERRNO         = -1;
  var Z_STREAM_ERROR$1  = -2;
  var Z_DATA_ERROR$1    = -3;
  var Z_MEM_ERROR     = -4;
  var Z_BUF_ERROR$1     = -5;
  //var Z_VERSION_ERROR = -6;

  /* The deflate compression method */
  var Z_DEFLATED$2  = 8;


  /* STATES ====================================================================*/
  /* ===========================================================================*/


  var    HEAD = 1;       /* i: waiting for magic header */
  var    FLAGS = 2;      /* i: waiting for method and flags (gzip) */
  var    TIME = 3;       /* i: waiting for modification time (gzip) */
  var    OS = 4;         /* i: waiting for extra flags and operating system (gzip) */
  var    EXLEN = 5;      /* i: waiting for extra length (gzip) */
  var    EXTRA = 6;      /* i: waiting for extra bytes (gzip) */
  var    NAME = 7;       /* i: waiting for end of file name (gzip) */
  var    COMMENT = 8;    /* i: waiting for end of comment (gzip) */
  var    HCRC = 9;       /* i: waiting for header crc (gzip) */
  var    DICTID = 10;    /* i: waiting for dictionary check value */
  var    DICT = 11;      /* waiting for inflateSetDictionary() call */
  var        TYPE$1 = 12;      /* i: waiting for type bits, including last-flag bit */
  var        TYPEDO = 13;    /* i: same, but skip check to exit inflate on new block */
  var        STORED = 14;    /* i: waiting for stored size (length and complement) */
  var        COPY_ = 15;     /* i/o: same as COPY below, but only first time in */
  var        COPY = 16;      /* i/o: waiting for input or output to copy stored block */
  var        TABLE = 17;     /* i: waiting for dynamic block table lengths */
  var        LENLENS = 18;   /* i: waiting for code length code lengths */
  var        CODELENS = 19;  /* i: waiting for length/lit and distance code lengths */
  var            LEN_ = 20;      /* i: same as LEN below, but only first time in */
  var            LEN = 21;       /* i: waiting for length/lit/eob code */
  var            LENEXT = 22;    /* i: waiting for length extra bits */
  var            DIST = 23;      /* i: waiting for distance code */
  var            DISTEXT = 24;   /* i: waiting for distance extra bits */
  var            MATCH = 25;     /* o: waiting for output space to copy string */
  var            LIT = 26;       /* o: waiting for output space to write literal */
  var    CHECK = 27;     /* i: waiting for 32-bit check value */
  var    LENGTH = 28;    /* i: waiting for 32-bit length (gzip) */
  var    DONE = 29;      /* finished check, done -- remain here until reset */
  var    BAD$1 = 30;       /* got a data error -- remain here until reset */
  var    MEM = 31;       /* got an inflate() memory error -- remain here until reset */
  var    SYNC = 32;      /* looking for synchronization bytes to restart inflate() */

  /* ===========================================================================*/



  var ENOUGH_LENS$1 = 852;
  var ENOUGH_DISTS$1 = 592;
  //var ENOUGH =  (ENOUGH_LENS+ENOUGH_DISTS);

  var MAX_WBITS$1 = 15;
  /* 32K LZ77 window */
  var DEF_WBITS = MAX_WBITS$1;


  function zswap32(q) {
    return  (((q >>> 24) & 0xff) +
            ((q >>> 8) & 0xff00) +
            ((q & 0xff00) << 8) +
            ((q & 0xff) << 24));
  }


  function InflateState() {
    this.mode = 0;             /* current inflate mode */
    this.last = false;          /* true if processing last block */
    this.wrap = 0;              /* bit 0 true for zlib, bit 1 true for gzip */
    this.havedict = false;      /* true if dictionary provided */
    this.flags = 0;             /* gzip header method and flags (0 if zlib) */
    this.dmax = 0;              /* zlib header max distance (INFLATE_STRICT) */
    this.check = 0;             /* protected copy of check value */
    this.total = 0;             /* protected copy of output count */
    // TODO: may be {}
    this.head = null;           /* where to save gzip header information */

    /* sliding window */
    this.wbits = 0;             /* log base 2 of requested window size */
    this.wsize = 0;             /* window size or zero if not using window */
    this.whave = 0;             /* valid bytes in the window */
    this.wnext = 0;             /* window write index */
    this.window = null;         /* allocated sliding window, if needed */

    /* bit accumulator */
    this.hold = 0;              /* input bit accumulator */
    this.bits = 0;              /* number of bits in "in" */

    /* for string and stored block copying */
    this.length = 0;            /* literal or length of data to copy */
    this.offset = 0;            /* distance back to copy string from */

    /* for table and code decoding */
    this.extra = 0;             /* extra bits needed */

    /* fixed and dynamic code tables */
    this.lencode = null;          /* starting table for length/literal codes */
    this.distcode = null;         /* starting table for distance codes */
    this.lenbits = 0;           /* index bits for lencode */
    this.distbits = 0;          /* index bits for distcode */

    /* dynamic table building */
    this.ncode = 0;             /* number of code length code lengths */
    this.nlen = 0;              /* number of length code lengths */
    this.ndist = 0;             /* number of distance code lengths */
    this.have = 0;              /* number of code lengths in lens[] */
    this.next = null;              /* next available space in codes[] */

    this.lens = new common.Buf16(320); /* temporary storage for code lengths */
    this.work = new common.Buf16(288); /* work area for code table building */

    /*
     because we don't have pointers in js, we use lencode and distcode directly
     as buffers so we don't need codes
    */
    //this.codes = new utils.Buf32(ENOUGH);       /* space for code tables */
    this.lendyn = null;              /* dynamic table for length/literal codes (JS specific) */
    this.distdyn = null;             /* dynamic table for distance codes (JS specific) */
    this.sane = 0;                   /* if false, allow invalid distance too far */
    this.back = 0;                   /* bits back of last unprocessed length/lit */
    this.was = 0;                    /* initial length of match */
  }

  function inflateResetKeep(strm) {
    var state;

    if (!strm || !strm.state) { return Z_STREAM_ERROR$1; }
    state = strm.state;
    strm.total_in = strm.total_out = state.total = 0;
    strm.msg = ''; /*Z_NULL*/
    if (state.wrap) {       /* to support ill-conceived Java test suite */
      strm.adler = state.wrap & 1;
    }
    state.mode = HEAD;
    state.last = 0;
    state.havedict = 0;
    state.dmax = 32768;
    state.head = null/*Z_NULL*/;
    state.hold = 0;
    state.bits = 0;
    //state.lencode = state.distcode = state.next = state.codes;
    state.lencode = state.lendyn = new common.Buf32(ENOUGH_LENS$1);
    state.distcode = state.distdyn = new common.Buf32(ENOUGH_DISTS$1);

    state.sane = 1;
    state.back = -1;
    //Tracev((stderr, "inflate: reset\n"));
    return Z_OK$2;
  }

  function inflateReset(strm) {
    var state;

    if (!strm || !strm.state) { return Z_STREAM_ERROR$1; }
    state = strm.state;
    state.wsize = 0;
    state.whave = 0;
    state.wnext = 0;
    return inflateResetKeep(strm);

  }

  function inflateReset2(strm, windowBits) {
    var wrap;
    var state;

    /* get the state */
    if (!strm || !strm.state) { return Z_STREAM_ERROR$1; }
    state = strm.state;

    /* extract wrap request from windowBits parameter */
    if (windowBits < 0) {
      wrap = 0;
      windowBits = -windowBits;
    }
    else {
      wrap = (windowBits >> 4) + 1;
      if (windowBits < 48) {
        windowBits &= 15;
      }
    }

    /* set number of window bits, free window if different */
    if (windowBits && (windowBits < 8 || windowBits > 15)) {
      return Z_STREAM_ERROR$1;
    }
    if (state.window !== null && state.wbits !== windowBits) {
      state.window = null;
    }

    /* update state and reset the rest of it */
    state.wrap = wrap;
    state.wbits = windowBits;
    return inflateReset(strm);
  }

  function inflateInit2(strm, windowBits) {
    var ret;
    var state;

    if (!strm) { return Z_STREAM_ERROR$1; }
    //strm.msg = Z_NULL;                 /* in case we return an error */

    state = new InflateState();

    //if (state === Z_NULL) return Z_MEM_ERROR;
    //Tracev((stderr, "inflate: allocated\n"));
    strm.state = state;
    state.window = null/*Z_NULL*/;
    ret = inflateReset2(strm, windowBits);
    if (ret !== Z_OK$2) {
      strm.state = null/*Z_NULL*/;
    }
    return ret;
  }

  function inflateInit(strm) {
    return inflateInit2(strm, DEF_WBITS);
  }


  /*
   Return state with length and distance decoding tables and index sizes set to
   fixed code decoding.  Normally this returns fixed tables from inffixed.h.
   If BUILDFIXED is defined, then instead this routine builds the tables the
   first time it's called, and returns those tables the first time and
   thereafter.  This reduces the size of the code by about 2K bytes, in
   exchange for a little execution time.  However, BUILDFIXED should not be
   used for threaded applications, since the rewriting of the tables and virgin
   may not be thread-safe.
   */
  var virgin = true;

  var lenfix, distfix; // We have no pointers in JS, so keep tables separate

  function fixedtables(state) {
    /* build fixed huffman tables if first call (may not be thread safe) */
    if (virgin) {
      var sym;

      lenfix = new common.Buf32(512);
      distfix = new common.Buf32(32);

      /* literal/length table */
      sym = 0;
      while (sym < 144) { state.lens[sym++] = 8; }
      while (sym < 256) { state.lens[sym++] = 9; }
      while (sym < 280) { state.lens[sym++] = 7; }
      while (sym < 288) { state.lens[sym++] = 8; }

      inftrees(LENS$1,  state.lens, 0, 288, lenfix,   0, state.work, { bits: 9 });

      /* distance table */
      sym = 0;
      while (sym < 32) { state.lens[sym++] = 5; }

      inftrees(DISTS$1, state.lens, 0, 32,   distfix, 0, state.work, { bits: 5 });

      /* do this just once */
      virgin = false;
    }

    state.lencode = lenfix;
    state.lenbits = 9;
    state.distcode = distfix;
    state.distbits = 5;
  }


  /*
   Update the window with the last wsize (normally 32K) bytes written before
   returning.  If window does not exist yet, create it.  This is only called
   when a window is already in use, or when output has been written during this
   inflate call, but the end of the deflate stream has not been reached yet.
   It is also called to create a window for dictionary data when a dictionary
   is loaded.

   Providing output buffers larger than 32K to inflate() should provide a speed
   advantage, since only the last 32K of output is copied to the sliding window
   upon return from inflate(), and since all distances after the first 32K of
   output will fall in the output data, making match copies simpler and faster.
   The advantage may be dependent on the size of the processor's data caches.
   */
  function updatewindow(strm, src, end, copy) {
    var dist;
    var state = strm.state;

    /* if it hasn't been done already, allocate space for the window */
    if (state.window === null) {
      state.wsize = 1 << state.wbits;
      state.wnext = 0;
      state.whave = 0;

      state.window = new common.Buf8(state.wsize);
    }

    /* copy state->wsize or less output bytes into the circular window */
    if (copy >= state.wsize) {
      common.arraySet(state.window, src, end - state.wsize, state.wsize, 0);
      state.wnext = 0;
      state.whave = state.wsize;
    }
    else {
      dist = state.wsize - state.wnext;
      if (dist > copy) {
        dist = copy;
      }
      //zmemcpy(state->window + state->wnext, end - copy, dist);
      common.arraySet(state.window, src, end - copy, dist, state.wnext);
      copy -= dist;
      if (copy) {
        //zmemcpy(state->window, end - copy, copy);
        common.arraySet(state.window, src, end - copy, copy, 0);
        state.wnext = copy;
        state.whave = state.wsize;
      }
      else {
        state.wnext += dist;
        if (state.wnext === state.wsize) { state.wnext = 0; }
        if (state.whave < state.wsize) { state.whave += dist; }
      }
    }
    return 0;
  }

  function inflate(strm, flush) {
    var state;
    var input, output;          // input/output buffers
    var next;                   /* next input INDEX */
    var put;                    /* next output INDEX */
    var have, left;             /* available input and output */
    var hold;                   /* bit buffer */
    var bits;                   /* bits in bit buffer */
    var _in, _out;              /* save starting available input and output */
    var copy;                   /* number of stored or match bytes to copy */
    var from;                   /* where to copy match bytes from */
    var from_source;
    var here = 0;               /* current decoding table entry */
    var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
    //var last;                   /* parent table entry */
    var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
    var len;                    /* length to copy for repeats, bits to drop */
    var ret;                    /* return code */
    var hbuf = new common.Buf8(4);    /* buffer for gzip header crc calculation */
    var opts;

    var n; // temporary var for NEED_BITS

    var order = /* permutation of code lengths */
      [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];


    if (!strm || !strm.state || !strm.output ||
        (!strm.input && strm.avail_in !== 0)) {
      return Z_STREAM_ERROR$1;
    }

    state = strm.state;
    if (state.mode === TYPE$1) { state.mode = TYPEDO; }    /* skip check */


    //--- LOAD() ---
    put = strm.next_out;
    output = strm.output;
    left = strm.avail_out;
    next = strm.next_in;
    input = strm.input;
    have = strm.avail_in;
    hold = state.hold;
    bits = state.bits;
    //---

    _in = have;
    _out = left;
    ret = Z_OK$2;

    inf_leave: // goto emulation
    for (;;) {
      switch (state.mode) {
        case HEAD:
          if (state.wrap === 0) {
            state.mode = TYPEDO;
            break;
          }
          //=== NEEDBITS(16);
          while (bits < 16) {
            if (have === 0) { break inf_leave; }
            have--;
            hold += input[next++] << bits;
            bits += 8;
          }
          //===//
          if ((state.wrap & 2) && hold === 0x8b1f) {  /* gzip header */
            state.check = 0/*crc32(0L, Z_NULL, 0)*/;
            //=== CRC2(state.check, hold);
            hbuf[0] = hold & 0xff;
            hbuf[1] = (hold >>> 8) & 0xff;
            state.check = crc32_1(state.check, hbuf, 2, 0);
            //===//

            //=== INITBITS();
            hold = 0;
            bits = 0;
            //===//
            state.mode = FLAGS;
            break;
          }
          state.flags = 0;           /* expect zlib header */
          if (state.head) {
            state.head.done = false;
          }
          if (!(state.wrap & 1) ||   /* check if zlib header allowed */
            (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
            strm.msg = 'incorrect header check';
            state.mode = BAD$1;
            break;
          }
          if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED$2) {
            strm.msg = 'unknown compression method';
            state.mode = BAD$1;
            break;
          }
          //--- DROPBITS(4) ---//
          hold >>>= 4;
          bits -= 4;
          //---//
          len = (hold & 0x0f)/*BITS(4)*/ + 8;
          if (state.wbits === 0) {
            state.wbits = len;
          }
          else if (len > state.wbits) {
            strm.msg = 'invalid window size';
            state.mode = BAD$1;
            break;
          }
          state.dmax = 1 << len;
          //Tracev((stderr, "inflate:   zlib header ok\n"));
          strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
          state.mode = hold & 0x200 ? DICTID : TYPE$1;
          //=== INITBITS();
          hold = 0;
          bits = 0;
          //===//
          break;
        case FLAGS:
          //=== NEEDBITS(16); */
          while (bits < 16) {
            if (have === 0) { break inf_leave; }
            have--;
            hold += input[next++] << bits;
            bits += 8;
          }
          //===//
          state.flags = hold;
          if ((state.flags & 0xff) !== Z_DEFLATED$2) {
            strm.msg = 'unknown compression method';
            state.mode = BAD$1;
            break;
          }
          if (state.flags & 0xe000) {
            strm.msg = 'unknown header flags set';
            state.mode = BAD$1;
            break;
          }
          if (state.head) {
            state.head.text = ((hold >> 8) & 1);
          }
          if (state.flags & 0x0200) {
            //=== CRC2(state.check, hold);
            hbuf[0] = hold & 0xff;
            hbuf[1] = (hold >>> 8) & 0xff;
            state.check = crc32_1(state.check, hbuf, 2, 0);
            //===//
          }
          //=== INITBITS();
          hold = 0;
          bits = 0;
          //===//
          state.mode = TIME;
          /* falls through */
        case TIME:
          //=== NEEDBITS(32); */
          while (bits < 32) {
            if (have === 0) { break inf_leave; }
            have--;
            hold += input[next++] << bits;
            bits += 8;
          }
          //===//
          if (state.head) {
            state.head.time = hold;
          }
          if (state.flags & 0x0200) {
            //=== CRC4(state.check, hold)
            hbuf[0] = hold & 0xff;
            hbuf[1] = (hold >>> 8) & 0xff;
            hbuf[2] = (hold >>> 16) & 0xff;
            hbuf[3] = (hold >>> 24) & 0xff;
            state.check = crc32_1(state.check, hbuf, 4, 0);
            //===
          }
          //=== INITBITS();
          hold = 0;
          bits = 0;
          //===//
          state.mode = OS;
          /* falls through */
        case OS:
          //=== NEEDBITS(16); */
          while (bits < 16) {
            if (have === 0) { break inf_leave; }
            have--;
            hold += input[next++] << bits;
            bits += 8;
          }
          //===//
          if (state.head) {
            state.head.xflags = (hold & 0xff);
            state.head.os = (hold >> 8);
          }
          if (state.flags & 0x0200) {
            //=== CRC2(state.check, hold);
            hbuf[0] = hold & 0xff;
            hbuf[1] = (hold >>> 8) & 0xff;
            state.check = crc32_1(state.check, hbuf, 2, 0);
            //===//
          }
          //=== INITBITS();
          hold = 0;
          bits = 0;
          //===//
          state.mode = EXLEN;
          /* falls through */
        case EXLEN:
          if (state.flags & 0x0400) {
            //=== NEEDBITS(16); */
            while (bits < 16) {
              if (have === 0) { break inf_leave; }
              have--;
              hold += input[next++] << bits;
              bits += 8;
            }
            //===//
            state.length = hold;
            if (state.head) {
              state.head.extra_len = hold;
            }
            if (state.flags & 0x0200) {
              //=== CRC2(state.check, hold);
              hbuf[0] = hold & 0xff;
              hbuf[1] = (hold >>> 8) & 0xff;
              state.check = crc32_1(state.check, hbuf, 2, 0);
              //===//
            }
            //=== INITBITS();
            hold = 0;
            bits = 0;
            //===//
          }
          else if (state.head) {
            state.head.extra = null/*Z_NULL*/;
          }
          state.mode = EXTRA;
          /* falls through */
        case EXTRA:
          if (state.flags & 0x0400) {
            copy = state.length;
            if (copy > have) { copy = have; }
            if (copy) {
              if (state.head) {
                len = state.head.extra_len - state.length;
                if (!state.head.extra) {
                  // Use untyped array for more convenient processing later
                  state.head.extra = new Array(state.head.extra_len);
                }
                common.arraySet(
                  state.head.extra,
                  input,
                  next,
                  // extra field is limited to 65536 bytes
                  // - no need for additional size check
                  copy,
                  /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
                  len
                );
                //zmemcpy(state.head.extra + len, next,
                //        len + copy > state.head.extra_max ?
                //        state.head.extra_max - len : copy);
              }
              if (state.flags & 0x0200) {
                state.check = crc32_1(state.check, input, copy, next);
              }
              have -= copy;
              next += copy;
              state.length -= copy;
            }
            if (state.length) { break inf_leave; }
          }
          state.length = 0;
          state.mode = NAME;
          /* falls through */
        case NAME:
          if (state.flags & 0x0800) {
            if (have === 0) { break inf_leave; }
            copy = 0;
            do {
              // TODO: 2 or 1 bytes?
              len = input[next + copy++];
              /* use constant limit because in js we should not preallocate memory */
              if (state.head && len &&
                  (state.length < 65536 /*state.head.name_max*/)) {
                state.head.name += String.fromCharCode(len);
              }
            } while (len && copy < have);

            if (state.flags & 0x0200) {
              state.check = crc32_1(state.check, input, copy, next);
            }
            have -= copy;
            next += copy;
            if (len) { break inf_leave; }
          }
          else if (state.head) {
            state.head.name = null;
          }
          state.length = 0;
          state.mode = COMMENT;
          /* falls through */
        case COMMENT:
          if (state.flags & 0x1000) {
            if (have === 0) { break inf_leave; }
            copy = 0;
            do {
              len = input[next + copy++];
              /* use constant limit because in js we should not preallocate memory */
              if (state.head && len &&
                  (state.length < 65536 /*state.head.comm_max*/)) {
                state.head.comment += String.fromCharCode(len);
              }
            } while (len && copy < have);
            if (state.flags & 0x0200) {
              state.check = crc32_1(state.check, input, copy, next);
            }
            have -= copy;
            next += copy;
            if (len) { break inf_leave; }
          }
          else if (state.head) {
            state.head.comment = null;
          }
          state.mode = HCRC;
          /* falls through */
        case HCRC:
          if (state.flags & 0x0200) {
            //=== NEEDBITS(16); */
            while (bits < 16) {
              if (have === 0) { break inf_leave; }
              have--;
              hold += input[next++] << bits;
              bits += 8;
            }
            //===//
            if (hold !== (state.check & 0xffff)) {
              strm.msg = 'header crc mismatch';
              state.mode = BAD$1;
              break;
            }
            //=== INITBITS();
            hold = 0;
            bits = 0;
            //===//
          }
          if (state.head) {
            state.head.hcrc = ((state.flags >> 9) & 1);
            state.head.done = true;
          }
          strm.adler = state.check = 0;
          state.mode = TYPE$1;
          break;
        case DICTID:
          //=== NEEDBITS(32); */
          while (bits < 32) {
            if (have === 0) { break inf_leave; }
            have--;
            hold += input[next++] << bits;
            bits += 8;
          }
          //===//
          strm.adler = state.check = zswap32(hold);
          //=== INITBITS();
          hold = 0;
          bits = 0;
          //===//
          state.mode = DICT;
          /* falls through */
        case DICT:
          if (state.havedict === 0) {
            //--- RESTORE() ---
            strm.next_out = put;
            strm.avail_out = left;
            strm.next_in = next;
            strm.avail_in = have;
            state.hold = hold;
            state.bits = bits;
            //---
            return Z_NEED_DICT;
          }
          strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
          state.mode = TYPE$1;
          /* falls through */
        case TYPE$1:
          if (flush === Z_BLOCK$1 || flush === Z_TREES) { break inf_leave; }
          /* falls through */
        case TYPEDO:
          if (state.last) {
            //--- BYTEBITS() ---//
            hold >>>= bits & 7;
            bits -= bits & 7;
            //---//
            state.mode = CHECK;
            break;
          }
          //=== NEEDBITS(3); */
          while (bits < 3) {
            if (have === 0) { break inf_leave; }
            have--;
            hold += input[next++] << bits;
            bits += 8;
          }
          //===//
          state.last = (hold & 0x01)/*BITS(1)*/;
          //--- DROPBITS(1) ---//
          hold >>>= 1;
          bits -= 1;
          //---//

          switch ((hold & 0x03)/*BITS(2)*/) {
            case 0:                             /* stored block */
              //Tracev((stderr, "inflate:     stored block%s\n",
              //        state.last ? " (last)" : ""));
              state.mode = STORED;
              break;
            case 1:                             /* fixed block */
              fixedtables(state);
              //Tracev((stderr, "inflate:     fixed codes block%s\n",
              //        state.last ? " (last)" : ""));
              state.mode = LEN_;             /* decode codes */
              if (flush === Z_TREES) {
                //--- DROPBITS(2) ---//
                hold >>>= 2;
                bits -= 2;
                //---//
                break inf_leave;
              }
              break;
            case 2:                             /* dynamic block */
              //Tracev((stderr, "inflate:     dynamic codes block%s\n",
              //        state.last ? " (last)" : ""));
              state.mode = TABLE;
              break;
            case 3:
              strm.msg = 'invalid block type';
              state.mode = BAD$1;
          }
          //--- DROPBITS(2) ---//
          hold >>>= 2;
          bits -= 2;
          //---//
          break;
        case STORED:
          //--- BYTEBITS() ---// /* go to byte boundary */
          hold >>>= bits & 7;
          bits -= bits & 7;
          //---//
          //=== NEEDBITS(32); */
          while (bits < 32) {
            if (have === 0) { break inf_leave; }
            have--;
            hold += input[next++] << bits;
            bits += 8;
          }
          //===//
          if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
            strm.msg = 'invalid stored block lengths';
            state.mode = BAD$1;
            break;
          }
          state.length = hold & 0xffff;
          //Tracev((stderr, "inflate:       stored length %u\n",
          //        state.length));
          //=== INITBITS();
          hold = 0;
          bits = 0;
          //===//
          state.mode = COPY_;
          if (flush === Z_TREES) { break inf_leave; }
          /* falls through */
        case COPY_:
          state.mode = COPY;
          /* falls through */
        case COPY:
          copy = state.length;
          if (copy) {
            if (copy > have) { copy = have; }
            if (copy > left) { copy = left; }
            if (copy === 0) { break inf_leave; }
            //--- zmemcpy(put, next, copy); ---
            common.arraySet(output, input, next, copy, put);
            //---//
            have -= copy;
            next += copy;
            left -= copy;
            put += copy;
            state.length -= copy;
            break;
          }
          //Tracev((stderr, "inflate:       stored end\n"));
          state.mode = TYPE$1;
          break;
        case TABLE:
          //=== NEEDBITS(14); */
          while (bits < 14) {
            if (have === 0) { break inf_leave; }
            have--;
            hold += input[next++] << bits;
            bits += 8;
          }
          //===//
          state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
          //--- DROPBITS(5) ---//
          hold >>>= 5;
          bits -= 5;
          //---//
          state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
          //--- DROPBITS(5) ---//
          hold >>>= 5;
          bits -= 5;
          //---//
          state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
          //--- DROPBITS(4) ---//
          hold >>>= 4;
          bits -= 4;
          //---//
  //#ifndef PKZIP_BUG_WORKAROUND
          if (state.nlen > 286 || state.ndist > 30) {
            strm.msg = 'too many length or distance symbols';
            state.mode = BAD$1;
            break;
          }
  //#endif
          //Tracev((stderr, "inflate:       table sizes ok\n"));
          state.have = 0;
          state.mode = LENLENS;
          /* falls through */
        case LENLENS:
          while (state.have < state.ncode) {
            //=== NEEDBITS(3);
            while (bits < 3) {
              if (have === 0) { break inf_leave; }
              have--;
              hold += input[next++] << bits;
              bits += 8;
            }
            //===//
            state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
            //--- DROPBITS(3) ---//
            hold >>>= 3;
            bits -= 3;
            //---//
          }
          while (state.have < 19) {
            state.lens[order[state.have++]] = 0;
          }
          // We have separate tables & no pointers. 2 commented lines below not needed.
          //state.next = state.codes;
          //state.lencode = state.next;
          // Switch to use dynamic table
          state.lencode = state.lendyn;
          state.lenbits = 7;

          opts = { bits: state.lenbits };
          ret = inftrees(CODES$1, state.lens, 0, 19, state.lencode, 0, state.work, opts);
          state.lenbits = opts.bits;

          if (ret) {
            strm.msg = 'invalid code lengths set';
            state.mode = BAD$1;
            break;
          }
          //Tracev((stderr, "inflate:       code lengths ok\n"));
          state.have = 0;
          state.mode = CODELENS;
          /* falls through */
        case CODELENS:
          while (state.have < state.nlen + state.ndist) {
            for (;;) {
              here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
              here_bits = here >>> 24;
              here_op = (here >>> 16) & 0xff;
              here_val = here & 0xffff;

              if ((here_bits) <= bits) { break; }
              //--- PULLBYTE() ---//
              if (have === 0) { break inf_leave; }
              have--;
              hold += input[next++] << bits;
              bits += 8;
              //---//
            }
            if (here_val < 16) {
              //--- DROPBITS(here.bits) ---//
              hold >>>= here_bits;
              bits -= here_bits;
              //---//
              state.lens[state.have++] = here_val;
            }
            else {
              if (here_val === 16) {
                //=== NEEDBITS(here.bits + 2);
                n = here_bits + 2;
                while (bits < n) {
                  if (have === 0) { break inf_leave; }
                  have--;
                  hold += input[next++] << bits;
                  bits += 8;
                }
                //===//
                //--- DROPBITS(here.bits) ---//
                hold >>>= here_bits;
                bits -= here_bits;
                //---//
                if (state.have === 0) {
                  strm.msg = 'invalid bit length repeat';
                  state.mode = BAD$1;
                  break;
                }
                len = state.lens[state.have - 1];
                copy = 3 + (hold & 0x03);//BITS(2);
                //--- DROPBITS(2) ---//
                hold >>>= 2;
                bits -= 2;
                //---//
              }
              else if (here_val === 17) {
                //=== NEEDBITS(here.bits + 3);
                n = here_bits + 3;
                while (bits < n) {
                  if (have === 0) { break inf_leave; }
                  have--;
                  hold += input[next++] << bits;
                  bits += 8;
                }
                //===//
                //--- DROPBITS(here.bits) ---//
                hold >>>= here_bits;
                bits -= here_bits;
                //---//
                len = 0;
                copy = 3 + (hold & 0x07);//BITS(3);
                //--- DROPBITS(3) ---//
                hold >>>= 3;
                bits -= 3;
                //---//
              }
              else {
                //=== NEEDBITS(here.bits + 7);
                n = here_bits + 7;
                while (bits < n) {
                  if (have === 0) { break inf_leave; }
                  have--;
                  hold += input[next++] << bits;
                  bits += 8;
                }
                //===//
                //--- DROPBITS(here.bits) ---//
                hold >>>= here_bits;
                bits -= here_bits;
                //---//
                len = 0;
                copy = 11 + (hold & 0x7f);//BITS(7);
                //--- DROPBITS(7) ---//
                hold >>>= 7;
                bits -= 7;
                //---//
              }
              if (state.have + copy > state.nlen + state.ndist) {
                strm.msg = 'invalid bit length repeat';
                state.mode = BAD$1;
                break;
              }
              while (copy--) {
                state.lens[state.have++] = len;
              }
            }
          }

          /* handle error breaks in while */
          if (state.mode === BAD$1) { break; }

          /* check for end-of-block code (better have one) */
          if (state.lens[256] === 0) {
            strm.msg = 'invalid code -- missing end-of-block';
            state.mode = BAD$1;
            break;
          }

          /* build code tables -- note: do not change the lenbits or distbits
             values here (9 and 6) without reading the comments in inftrees.h
             concerning the ENOUGH constants, which depend on those values */
          state.lenbits = 9;

          opts = { bits: state.lenbits };
          ret = inftrees(LENS$1, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
          // We have separate tables & no pointers. 2 commented lines below not needed.
          // state.next_index = opts.table_index;
          state.lenbits = opts.bits;
          // state.lencode = state.next;

          if (ret) {
            strm.msg = 'invalid literal/lengths set';
            state.mode = BAD$1;
            break;
          }

          state.distbits = 6;
          //state.distcode.copy(state.codes);
          // Switch to use dynamic table
          state.distcode = state.distdyn;
          opts = { bits: state.distbits };
          ret = inftrees(DISTS$1, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
          // We have separate tables & no pointers. 2 commented lines below not needed.
          // state.next_index = opts.table_index;
          state.distbits = opts.bits;
          // state.distcode = state.next;

          if (ret) {
            strm.msg = 'invalid distances set';
            state.mode = BAD$1;
            break;
          }
          //Tracev((stderr, 'inflate:       codes ok\n'));
          state.mode = LEN_;
          if (flush === Z_TREES) { break inf_leave; }
          /* falls through */
        case LEN_:
          state.mode = LEN;
          /* falls through */
        case LEN:
          if (have >= 6 && left >= 258) {
            //--- RESTORE() ---
            strm.next_out = put;
            strm.avail_out = left;
            strm.next_in = next;
            strm.avail_in = have;
            state.hold = hold;
            state.bits = bits;
            //---
            inffast(strm, _out);
            //--- LOAD() ---
            put = strm.next_out;
            output = strm.output;
            left = strm.avail_out;
            next = strm.next_in;
            input = strm.input;
            have = strm.avail_in;
            hold = state.hold;
            bits = state.bits;
            //---

            if (state.mode === TYPE$1) {
              state.back = -1;
            }
            break;
          }
          state.back = 0;
          for (;;) {
            here = state.lencode[hold & ((1 << state.lenbits) - 1)];  /*BITS(state.lenbits)*/
            here_bits = here >>> 24;
            here_op = (here >>> 16) & 0xff;
            here_val = here & 0xffff;

            if (here_bits <= bits) { break; }
            //--- PULLBYTE() ---//
            if (have === 0) { break inf_leave; }
            have--;
            hold += input[next++] << bits;
            bits += 8;
            //---//
          }
          if (here_op && (here_op & 0xf0) === 0) {
            last_bits = here_bits;
            last_op = here_op;
            last_val = here_val;
            for (;;) {
              here = state.lencode[last_val +
                      ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
              here_bits = here >>> 24;
              here_op = (here >>> 16) & 0xff;
              here_val = here & 0xffff;

              if ((last_bits + here_bits) <= bits) { break; }
              //--- PULLBYTE() ---//
              if (have === 0) { break inf_leave; }
              have--;
              hold += input[next++] << bits;
              bits += 8;
              //---//
            }
            //--- DROPBITS(last.bits) ---//
            hold >>>= last_bits;
            bits -= last_bits;
            //---//
            state.back += last_bits;
          }
          //--- DROPBITS(here.bits) ---//
          hold >>>= here_bits;
          bits -= here_bits;
          //---//
          state.back += here_bits;
          state.length = here_val;
          if (here_op === 0) {
            //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
            //        "inflate:         literal '%c'\n" :
            //        "inflate:         literal 0x%02x\n", here.val));
            state.mode = LIT;
            break;
          }
          if (here_op & 32) {
            //Tracevv((stderr, "inflate:         end of block\n"));
            state.back = -1;
            state.mode = TYPE$1;
            break;
          }
          if (here_op & 64) {
            strm.msg = 'invalid literal/length code';
            state.mode = BAD$1;
            break;
          }
          state.extra = here_op & 15;
          state.mode = LENEXT;
          /* falls through */
        case LENEXT:
          if (state.extra) {
            //=== NEEDBITS(state.extra);
            n = state.extra;
            while (bits < n) {
              if (have === 0) { break inf_leave; }
              have--;
              hold += input[next++] << bits;
              bits += 8;
            }
            //===//
            state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
            //--- DROPBITS(state.extra) ---//
            hold >>>= state.extra;
            bits -= state.extra;
            //---//
            state.back += state.extra;
          }
          //Tracevv((stderr, "inflate:         length %u\n", state.length));
          state.was = state.length;
          state.mode = DIST;
          /* falls through */
        case DIST:
          for (;;) {
            here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/
            here_bits = here >>> 24;
            here_op = (here >>> 16) & 0xff;
            here_val = here & 0xffff;

            if ((here_bits) <= bits) { break; }
            //--- PULLBYTE() ---//
            if (have === 0) { break inf_leave; }
            have--;
            hold += input[next++] << bits;
            bits += 8;
            //---//
          }
          if ((here_op & 0xf0) === 0) {
            last_bits = here_bits;
            last_op = here_op;
            last_val = here_val;
            for (;;) {
              here = state.distcode[last_val +
                      ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
              here_bits = here >>> 24;
              here_op = (here >>> 16) & 0xff;
              here_val = here & 0xffff;

              if ((last_bits + here_bits) <= bits) { break; }
              //--- PULLBYTE() ---//
              if (have === 0) { break inf_leave; }
              have--;
              hold += input[next++] << bits;
              bits += 8;
              //---//
            }
            //--- DROPBITS(last.bits) ---//
            hold >>>= last_bits;
            bits -= last_bits;
            //---//
            state.back += last_bits;
          }
          //--- DROPBITS(here.bits) ---//
          hold >>>= here_bits;
          bits -= here_bits;
          //---//
          state.back += here_bits;
          if (here_op & 64) {
            strm.msg = 'invalid distance code';
            state.mode = BAD$1;
            break;
          }
          state.offset = here_val;
          state.extra = (here_op) & 15;
          state.mode = DISTEXT;
          /* falls through */
        case DISTEXT:
          if (state.extra) {
            //=== NEEDBITS(state.extra);
            n = state.extra;
            while (bits < n) {
              if (have === 0) { break inf_leave; }
              have--;
              hold += input[next++] << bits;
              bits += 8;
            }
            //===//
            state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
            //--- DROPBITS(state.extra) ---//
            hold >>>= state.extra;
            bits -= state.extra;
            //---//
            state.back += state.extra;
          }
  //#ifdef INFLATE_STRICT
          if (state.offset > state.dmax) {
            strm.msg = 'invalid distance too far back';
            state.mode = BAD$1;
            break;
          }
  //#endif
          //Tracevv((stderr, "inflate:         distance %u\n", state.offset));
          state.mode = MATCH;
          /* falls through */
        case MATCH:
          if (left === 0) { break inf_leave; }
          copy = _out - left;
          if (state.offset > copy) {         /* copy from window */
            copy = state.offset - copy;
            if (copy > state.whave) {
              if (state.sane) {
                strm.msg = 'invalid distance too far back';
                state.mode = BAD$1;
                break;
              }
  // (!) This block is disabled in zlib defaults,
  // don't enable it for binary compatibility
  //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  //          Trace((stderr, "inflate.c too far\n"));
  //          copy -= state.whave;
  //          if (copy > state.length) { copy = state.length; }
  //          if (copy > left) { copy = left; }
  //          left -= copy;
  //          state.length -= copy;
  //          do {
  //            output[put++] = 0;
  //          } while (--copy);
  //          if (state.length === 0) { state.mode = LEN; }
  //          break;
  //#endif
            }
            if (copy > state.wnext) {
              copy -= state.wnext;
              from = state.wsize - copy;
            }
            else {
              from = state.wnext - copy;
            }
            if (copy > state.length) { copy = state.length; }
            from_source = state.window;
          }
          else {                              /* copy from output */
            from_source = output;
            from = put - state.offset;
            copy = state.length;
          }
          if (copy > left) { copy = left; }
          left -= copy;
          state.length -= copy;
          do {
            output[put++] = from_source[from++];
          } while (--copy);
          if (state.length === 0) { state.mode = LEN; }
          break;
        case LIT:
          if (left === 0) { break inf_leave; }
          output[put++] = state.length;
          left--;
          state.mode = LEN;
          break;
        case CHECK:
          if (state.wrap) {
            //=== NEEDBITS(32);
            while (bits < 32) {
              if (have === 0) { break inf_leave; }
              have--;
              // Use '|' instead of '+' to make sure that result is signed
              hold |= input[next++] << bits;
              bits += 8;
            }
            //===//
            _out -= left;
            strm.total_out += _out;
            state.total += _out;
            if (_out) {
              strm.adler = state.check =
                  /*UPDATE(state.check, put - _out, _out);*/
                  (state.flags ? crc32_1(state.check, output, _out, put - _out) : adler32_1(state.check, output, _out, put - _out));

            }
            _out = left;
            // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too
            if ((state.flags ? hold : zswap32(hold)) !== state.check) {
              strm.msg = 'incorrect data check';
              state.mode = BAD$1;
              break;
            }
            //=== INITBITS();
            hold = 0;
            bits = 0;
            //===//
            //Tracev((stderr, "inflate:   check matches trailer\n"));
          }
          state.mode = LENGTH;
          /* falls through */
        case LENGTH:
          if (state.wrap && state.flags) {
            //=== NEEDBITS(32);
            while (bits < 32) {
              if (have === 0) { break inf_leave; }
              have--;
              hold += input[next++] << bits;
              bits += 8;
            }
            //===//
            if (hold !== (state.total & 0xffffffff)) {
              strm.msg = 'incorrect length check';
              state.mode = BAD$1;
              break;
            }
            //=== INITBITS();
            hold = 0;
            bits = 0;
            //===//
            //Tracev((stderr, "inflate:   length matches trailer\n"));
          }
          state.mode = DONE;
          /* falls through */
        case DONE:
          ret = Z_STREAM_END$2;
          break inf_leave;
        case BAD$1:
          ret = Z_DATA_ERROR$1;
          break inf_leave;
        case MEM:
          return Z_MEM_ERROR;
        case SYNC:
          /* falls through */
        default:
          return Z_STREAM_ERROR$1;
      }
    }

    // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"

    /*
       Return from inflate(), updating the total counts and the check value.
       If there was no progress during the inflate() call, return a buffer
       error.  Call updatewindow() to create and/or update the window state.
       Note: a memory error from inflate() is non-recoverable.
     */

    //--- RESTORE() ---
    strm.next_out = put;
    strm.avail_out = left;
    strm.next_in = next;
    strm.avail_in = have;
    state.hold = hold;
    state.bits = bits;
    //---

    if (state.wsize || (_out !== strm.avail_out && state.mode < BAD$1 &&
                        (state.mode < CHECK || flush !== Z_FINISH$2))) {
      if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) ;
    }
    _in -= strm.avail_in;
    _out -= strm.avail_out;
    strm.total_in += _in;
    strm.total_out += _out;
    state.total += _out;
    if (state.wrap && _out) {
      strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
        (state.flags ? crc32_1(state.check, output, _out, strm.next_out - _out) : adler32_1(state.check, output, _out, strm.next_out - _out));
    }
    strm.data_type = state.bits + (state.last ? 64 : 0) +
                      (state.mode === TYPE$1 ? 128 : 0) +
                      (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
    if (((_in === 0 && _out === 0) || flush === Z_FINISH$2) && ret === Z_OK$2) {
      ret = Z_BUF_ERROR$1;
    }
    return ret;
  }

  function inflateEnd(strm) {

    if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
      return Z_STREAM_ERROR$1;
    }

    var state = strm.state;
    if (state.window) {
      state.window = null;
    }
    strm.state = null;
    return Z_OK$2;
  }

  function inflateGetHeader(strm, head) {
    var state;

    /* check state */
    if (!strm || !strm.state) { return Z_STREAM_ERROR$1; }
    state = strm.state;
    if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR$1; }

    /* save header structure */
    state.head = head;
    head.done = false;
    return Z_OK$2;
  }

  function inflateSetDictionary(strm, dictionary) {
    var dictLength = dictionary.length;

    var state;
    var dictid;
    var ret;

    /* check state */
    if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR$1; }
    state = strm.state;

    if (state.wrap !== 0 && state.mode !== DICT) {
      return Z_STREAM_ERROR$1;
    }

    /* check for correct dictionary identifier */
    if (state.mode === DICT) {
      dictid = 1; /* adler32(0, null, 0)*/
      /* dictid = adler32(dictid, dictionary, dictLength); */
      dictid = adler32_1(dictid, dictionary, dictLength, 0);
      if (dictid !== state.check) {
        return Z_DATA_ERROR$1;
      }
    }
    /* copy dictionary to window using updatewindow(), which will amend the
     existing dictionary if appropriate */
    ret = updatewindow(strm, dictionary, dictLength, dictLength);
    if (ret) {
      state.mode = MEM;
      return Z_MEM_ERROR;
    }
    state.havedict = 1;
    // Tracev((stderr, "inflate:   dictionary set\n"));
    return Z_OK$2;
  }

  var inflateReset_1 = inflateReset;
  var inflateReset2_1 = inflateReset2;
  var inflateResetKeep_1 = inflateResetKeep;
  var inflateInit_1 = inflateInit;
  var inflateInit2_1 = inflateInit2;
  var inflate_2 = inflate;
  var inflateEnd_1 = inflateEnd;
  var inflateGetHeader_1 = inflateGetHeader;
  var inflateSetDictionary_1 = inflateSetDictionary;
  var inflateInfo = 'pako inflate (from Nodeca project)';

  /* Not implemented
  exports.inflateCopy = inflateCopy;
  exports.inflateGetDictionary = inflateGetDictionary;
  exports.inflateMark = inflateMark;
  exports.inflatePrime = inflatePrime;
  exports.inflateSync = inflateSync;
  exports.inflateSyncPoint = inflateSyncPoint;
  exports.inflateUndermine = inflateUndermine;
  */

  var inflate_1 = {
  	inflateReset: inflateReset_1,
  	inflateReset2: inflateReset2_1,
  	inflateResetKeep: inflateResetKeep_1,
  	inflateInit: inflateInit_1,
  	inflateInit2: inflateInit2_1,
  	inflate: inflate_2,
  	inflateEnd: inflateEnd_1,
  	inflateGetHeader: inflateGetHeader_1,
  	inflateSetDictionary: inflateSetDictionary_1,
  	inflateInfo: inflateInfo
  };

  // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  //
  // This software is provided 'as-is', without any express or implied
  // warranty. In no event will the authors be held liable for any damages
  // arising from the use of this software.
  //
  // Permission is granted to anyone to use this software for any purpose,
  // including commercial applications, and to alter it and redistribute it
  // freely, subject to the following restrictions:
  //
  // 1. The origin of this software must not be misrepresented; you must not
  //   claim that you wrote the original software. If you use this software
  //   in a product, an acknowledgment in the product documentation would be
  //   appreciated but is not required.
  // 2. Altered source versions must be plainly marked as such, and must not be
  //   misrepresented as being the original software.
  // 3. This notice may not be removed or altered from any source distribution.

  var constants = {

    /* Allowed flush values; see deflate() and inflate() below for details */
    Z_NO_FLUSH:         0,
    Z_PARTIAL_FLUSH:    1,
    Z_SYNC_FLUSH:       2,
    Z_FULL_FLUSH:       3,
    Z_FINISH:           4,
    Z_BLOCK:            5,
    Z_TREES:            6,

    /* Return codes for the compression/decompression functions. Negative values
    * are errors, positive values are used for special but normal events.
    */
    Z_OK:               0,
    Z_STREAM_END:       1,
    Z_NEED_DICT:        2,
    Z_ERRNO:           -1,
    Z_STREAM_ERROR:    -2,
    Z_DATA_ERROR:      -3,
    //Z_MEM_ERROR:     -4,
    Z_BUF_ERROR:       -5,
    //Z_VERSION_ERROR: -6,

    /* compression levels */
    Z_NO_COMPRESSION:         0,
    Z_BEST_SPEED:             1,
    Z_BEST_COMPRESSION:       9,
    Z_DEFAULT_COMPRESSION:   -1,


    Z_FILTERED:               1,
    Z_HUFFMAN_ONLY:           2,
    Z_RLE:                    3,
    Z_FIXED:                  4,
    Z_DEFAULT_STRATEGY:       0,

    /* Possible values of the data_type field (though see inflate()) */
    Z_BINARY:                 0,
    Z_TEXT:                   1,
    //Z_ASCII:                1, // = Z_TEXT (deprecated)
    Z_UNKNOWN:                2,

    /* The deflate compression method */
    Z_DEFLATED:               8
    //Z_NULL:                 null // Use -1 or null inline, depending on var type
  };

  // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  //
  // This software is provided 'as-is', without any express or implied
  // warranty. In no event will the authors be held liable for any damages
  // arising from the use of this software.
  //
  // Permission is granted to anyone to use this software for any purpose,
  // including commercial applications, and to alter it and redistribute it
  // freely, subject to the following restrictions:
  //
  // 1. The origin of this software must not be misrepresented; you must not
  //   claim that you wrote the original software. If you use this software
  //   in a product, an acknowledgment in the product documentation would be
  //   appreciated but is not required.
  // 2. Altered source versions must be plainly marked as such, and must not be
  //   misrepresented as being the original software.
  // 3. This notice may not be removed or altered from any source distribution.

  function GZheader() {
    /* true if compressed data believed to be text */
    this.text       = 0;
    /* modification time */
    this.time       = 0;
    /* extra flags (not used when writing a gzip file) */
    this.xflags     = 0;
    /* operating system */
    this.os         = 0;
    /* pointer to extra field or Z_NULL if none */
    this.extra      = null;
    /* extra field length (valid if extra != Z_NULL) */
    this.extra_len  = 0; // Actually, we don't need it in JS,
                         // but leave for few code modifications

    //
    // Setup limits is not necessary because in js we should not preallocate memory
    // for inflate use constant limit in 65536 bytes
    //

    /* space at extra (only when reading header) */
    // this.extra_max  = 0;
    /* pointer to zero-terminated file name or Z_NULL */
    this.name       = '';
    /* space at name (only when reading header) */
    // this.name_max   = 0;
    /* pointer to zero-terminated comment or Z_NULL */
    this.comment    = '';
    /* space at comment (only when reading header) */
    // this.comm_max   = 0;
    /* true if there was or will be a header crc */
    this.hcrc       = 0;
    /* true when done reading gzip header (not used when writing a gzip file) */
    this.done       = false;
  }

  var gzheader = GZheader;

  var toString$1 = Object.prototype.toString;

  /**
   * class Inflate
   *
   * Generic JS-style wrapper for zlib calls. If you don't need
   * streaming behaviour - use more simple functions: [[inflate]]
   * and [[inflateRaw]].
   **/

  /* internal
   * inflate.chunks -> Array
   *
   * Chunks of output data, if [[Inflate#onData]] not overridden.
   **/

  /**
   * Inflate.result -> Uint8Array|Array|String
   *
   * Uncompressed result, generated by default [[Inflate#onData]]
   * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
   * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
   * push a chunk with explicit flush (call [[Inflate#push]] with
   * `Z_SYNC_FLUSH` param).
   **/

  /**
   * Inflate.err -> Number
   *
   * Error code after inflate finished. 0 (Z_OK) on success.
   * Should be checked if broken data possible.
   **/

  /**
   * Inflate.msg -> String
   *
   * Error message, if [[Inflate.err]] != 0
   **/


  /**
   * new Inflate(options)
   * - options (Object): zlib inflate options.
   *
   * Creates new inflator instance with specified params. Throws exception
   * on bad params. Supported options:
   *
   * - `windowBits`
   * - `dictionary`
   *
   * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
   * for more information on these.
   *
   * Additional options, for internal needs:
   *
   * - `chunkSize` - size of generated data chunks (16K by default)
   * - `raw` (Boolean) - do raw inflate
   * - `to` (String) - if equal to 'string', then result will be converted
   *   from utf8 to utf16 (javascript) string. When string output requested,
   *   chunk length can differ from `chunkSize`, depending on content.
   *
   * By default, when no options set, autodetect deflate/gzip data format via
   * wrapper header.
   *
   * ##### Example:
   *
   * ```javascript
   * var pako = require('pako')
   *   , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
   *   , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
   *
   * var inflate = new pako.Inflate({ level: 3});
   *
   * inflate.push(chunk1, false);
   * inflate.push(chunk2, true);  // true -> last chunk
   *
   * if (inflate.err) { throw new Error(inflate.err); }
   *
   * console.log(inflate.result);
   * ```
   **/
  function Inflate(options) {
    if (!(this instanceof Inflate)) return new Inflate(options);

    this.options = common.assign({
      chunkSize: 16384,
      windowBits: 0,
      to: ''
    }, options || {});

    var opt = this.options;

    // Force window size for `raw` data, if not set directly,
    // because we have no header for autodetect.
    if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
      opt.windowBits = -opt.windowBits;
      if (opt.windowBits === 0) { opt.windowBits = -15; }
    }

    // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
    if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
        !(options && options.windowBits)) {
      opt.windowBits += 32;
    }

    // Gzip header has no info about windows size, we can do autodetect only
    // for deflate. So, if window size not set, force it to max when gzip possible
    if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
      // bit 3 (16) -> gzipped data
      // bit 4 (32) -> autodetect gzip/deflate
      if ((opt.windowBits & 15) === 0) {
        opt.windowBits |= 15;
      }
    }

    this.err    = 0;      // error code, if happens (0 = Z_OK)
    this.msg    = '';     // error message
    this.ended  = false;  // used to avoid multiple onEnd() calls
    this.chunks = [];     // chunks of compressed data

    this.strm   = new zstream();
    this.strm.avail_out = 0;

    var status  = inflate_1.inflateInit2(
      this.strm,
      opt.windowBits
    );

    if (status !== constants.Z_OK) {
      throw new Error(messages[status]);
    }

    this.header = new gzheader();

    inflate_1.inflateGetHeader(this.strm, this.header);

    // Setup dictionary
    if (opt.dictionary) {
      // Convert data if needed
      if (typeof opt.dictionary === 'string') {
        opt.dictionary = strings.string2buf(opt.dictionary);
      } else if (toString$1.call(opt.dictionary) === '[object ArrayBuffer]') {
        opt.dictionary = new Uint8Array(opt.dictionary);
      }
      if (opt.raw) { //In raw mode we need to set the dictionary early
        status = inflate_1.inflateSetDictionary(this.strm, opt.dictionary);
        if (status !== constants.Z_OK) {
          throw new Error(messages[status]);
        }
      }
    }
  }

  /**
   * Inflate#push(data[, mode]) -> Boolean
   * - data (Uint8Array|Array|ArrayBuffer|String): input data
   * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
   *   See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH.
   *
   * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
   * new output chunks. Returns `true` on success. The last data block must have
   * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
   * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
   * can use mode Z_SYNC_FLUSH, keeping the decompression context.
   *
   * On fail call [[Inflate#onEnd]] with error code and return false.
   *
   * We strongly recommend to use `Uint8Array` on input for best speed (output
   * format is detected automatically). Also, don't skip last param and always
   * use the same type in your code (boolean or number). That will improve JS speed.
   *
   * For regular `Array`-s make sure all elements are [0..255].
   *
   * ##### Example
   *
   * ```javascript
   * push(chunk, false); // push one of data chunks
   * ...
   * push(chunk, true);  // push last chunk
   * ```
   **/
  Inflate.prototype.push = function (data, mode) {
    var strm = this.strm;
    var chunkSize = this.options.chunkSize;
    var dictionary = this.options.dictionary;
    var status, _mode;
    var next_out_utf8, tail, utf8str;

    // Flag to properly process Z_BUF_ERROR on testing inflate call
    // when we check that all output data was flushed.
    var allowBufError = false;

    if (this.ended) { return false; }
    _mode = (mode === ~~mode) ? mode : ((mode === true) ? constants.Z_FINISH : constants.Z_NO_FLUSH);

    // Convert data if needed
    if (typeof data === 'string') {
      // Only binary strings can be decompressed on practice
      strm.input = strings.binstring2buf(data);
    } else if (toString$1.call(data) === '[object ArrayBuffer]') {
      strm.input = new Uint8Array(data);
    } else {
      strm.input = data;
    }

    strm.next_in = 0;
    strm.avail_in = strm.input.length;

    do {
      if (strm.avail_out === 0) {
        strm.output = new common.Buf8(chunkSize);
        strm.next_out = 0;
        strm.avail_out = chunkSize;
      }

      status = inflate_1.inflate(strm, constants.Z_NO_FLUSH);    /* no bad return value */

      if (status === constants.Z_NEED_DICT && dictionary) {
        status = inflate_1.inflateSetDictionary(this.strm, dictionary);
      }

      if (status === constants.Z_BUF_ERROR && allowBufError === true) {
        status = constants.Z_OK;
        allowBufError = false;
      }

      if (status !== constants.Z_STREAM_END && status !== constants.Z_OK) {
        this.onEnd(status);
        this.ended = true;
        return false;
      }

      if (strm.next_out) {
        if (strm.avail_out === 0 || status === constants.Z_STREAM_END || (strm.avail_in === 0 && (_mode === constants.Z_FINISH || _mode === constants.Z_SYNC_FLUSH))) {

          if (this.options.to === 'string') {

            next_out_utf8 = strings.utf8border(strm.output, strm.next_out);

            tail = strm.next_out - next_out_utf8;
            utf8str = strings.buf2string(strm.output, next_out_utf8);

            // move tail
            strm.next_out = tail;
            strm.avail_out = chunkSize - tail;
            if (tail) { common.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }

            this.onData(utf8str);

          } else {
            this.onData(common.shrinkBuf(strm.output, strm.next_out));
          }
        }
      }

      // When no more input data, we should check that internal inflate buffers
      // are flushed. The only way to do it when avail_out = 0 - run one more
      // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.
      // Here we set flag to process this error properly.
      //
      // NOTE. Deflate does not return error in this case and does not needs such
      // logic.
      if (strm.avail_in === 0 && strm.avail_out === 0) {
        allowBufError = true;
      }

    } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== constants.Z_STREAM_END);

    if (status === constants.Z_STREAM_END) {
      _mode = constants.Z_FINISH;
    }

    // Finalize on the last chunk.
    if (_mode === constants.Z_FINISH) {
      status = inflate_1.inflateEnd(this.strm);
      this.onEnd(status);
      this.ended = true;
      return status === constants.Z_OK;
    }

    // callback interim results if Z_SYNC_FLUSH.
    if (_mode === constants.Z_SYNC_FLUSH) {
      this.onEnd(constants.Z_OK);
      strm.avail_out = 0;
      return true;
    }

    return true;
  };


  /**
   * Inflate#onData(chunk) -> Void
   * - chunk (Uint8Array|Array|String): output data. Type of array depends
   *   on js engine support. When string output requested, each chunk
   *   will be string.
   *
   * By default, stores data blocks in `chunks[]` property and glue
   * those in `onEnd`. Override this handler, if you need another behaviour.
   **/
  Inflate.prototype.onData = function (chunk) {
    this.chunks.push(chunk);
  };


  /**
   * Inflate#onEnd(status) -> Void
   * - status (Number): inflate status. 0 (Z_OK) on success,
   *   other if not.
   *
   * Called either after you tell inflate that the input stream is
   * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
   * or if an error happened. By default - join collected chunks,
   * free memory and fill `results` / `err` properties.
   **/
  Inflate.prototype.onEnd = function (status) {
    // On success - join
    if (status === constants.Z_OK) {
      if (this.options.to === 'string') {
        // Glue & convert here, until we teach pako to send
        // utf8 aligned strings to onData
        this.result = this.chunks.join('');
      } else {
        this.result = common.flattenChunks(this.chunks);
      }
    }
    this.chunks = [];
    this.err = status;
    this.msg = this.strm.msg;
  };


  /**
   * inflate(data[, options]) -> Uint8Array|Array|String
   * - data (Uint8Array|Array|String): input data to decompress.
   * - options (Object): zlib inflate options.
   *
   * Decompress `data` with inflate/ungzip and `options`. Autodetect
   * format via wrapper header by default. That's why we don't provide
   * separate `ungzip` method.
   *
   * Supported options are:
   *
   * - windowBits
   *
   * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
   * for more information.
   *
   * Sugar (options):
   *
   * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
   *   negative windowBits implicitly.
   * - `to` (String) - if equal to 'string', then result will be converted
   *   from utf8 to utf16 (javascript) string. When string output requested,
   *   chunk length can differ from `chunkSize`, depending on content.
   *
   *
   * ##### Example:
   *
   * ```javascript
   * var pako = require('pako')
   *   , input = pako.deflate([1,2,3,4,5,6,7,8,9])
   *   , output;
   *
   * try {
   *   output = pako.inflate(input);
   * } catch (err)
   *   console.log(err);
   * }
   * ```
   **/
  function inflate$1(input, options) {
    var inflator = new Inflate(options);

    inflator.push(input, true);

    // That will never happens, if you don't cheat with options :)
    if (inflator.err) { throw inflator.msg || messages[inflator.err]; }

    return inflator.result;
  }


  /**
   * inflateRaw(data[, options]) -> Uint8Array|Array|String
   * - data (Uint8Array|Array|String): input data to decompress.
   * - options (Object): zlib inflate options.
   *
   * The same as [[inflate]], but creates raw data, without wrapper
   * (header and adler32 crc).
   **/
  function inflateRaw(input, options) {
    options = options || {};
    options.raw = true;
    return inflate$1(input, options);
  }


  /**
   * ungzip(data[, options]) -> Uint8Array|Array|String
   * - data (Uint8Array|Array|String): input data to decompress.
   * - options (Object): zlib inflate options.
   *
   * Just shortcut to [[inflate]], because it autodetects format
   * by header.content. Done for convenience.
   **/


  var Inflate_1 = Inflate;
  var inflate_2$1 = inflate$1;
  var inflateRaw_1 = inflateRaw;
  var ungzip  = inflate$1;

  var inflate_1$1 = {
  	Inflate: Inflate_1,
  	inflate: inflate_2$1,
  	inflateRaw: inflateRaw_1,
  	ungzip: ungzip
  };

  var assign    = common.assign;





  var pako = {};

  assign(pako, deflate_1$1, inflate_1$1, constants);

  var pako_1 = pako;

  /**
   * @license
   * jsPDF filters PlugIn
   * Copyright (c) 2014 Aras Abbasi
   *
   * Licensed under the MIT License.
   * http://opensource.org/licenses/mit-license
   */

  (function(jsPDFAPI) {

    var ASCII85Encode = function(a) {
      var b, c, d, e, f, g, h, i, j, k;
      // eslint-disable-next-line no-control-regex
      for (
        !/[^\x00-\xFF]/.test(a),
          b = "\x00\x00\x00\x00".slice(a.length % 4 || 4),
          a += b,
          c = [],
          d = 0,
          e = a.length;
        e > d;
        d += 4
      )
        (f =
          (a.charCodeAt(d) << 24) +
          (a.charCodeAt(d + 1) << 16) +
          (a.charCodeAt(d + 2) << 8) +
          a.charCodeAt(d + 3)),
          0 !== f
            ? ((k = f % 85),
              (f = (f - k) / 85),
              (j = f % 85),
              (f = (f - j) / 85),
              (i = f % 85),
              (f = (f - i) / 85),
              (h = f % 85),
              (f = (f - h) / 85),
              (g = f % 85),
              c.push(g + 33, h + 33, i + 33, j + 33, k + 33))
            : c.push(122);
      return (
        (function(a, b) {
          for (var c = b; c > 0; c--) a.pop();
        })(c, b.length),
        String.fromCharCode.apply(String, c) + "~>"
      );
    };

    var ASCII85Decode = function(a) {
      var c,
        d,
        e,
        f,
        g,
        h = String,
        l = "length",
        w = 255,
        x = "charCodeAt",
        y = "slice",
        z = "replace";
      for (
        "~>" === a[y](-2),
          a = a[y](0, -2)
            [z](/\s/g, "")
            [z]("z", "!!!!!"),
          c = "uuuuu"[y](a[l] % 5 || 5),
          a += c,
          e = [],
          f = 0,
          g = a[l];
        g > f;
        f += 5
      )
        (d =
          52200625 * (a[x](f) - 33) +
          614125 * (a[x](f + 1) - 33) +
          7225 * (a[x](f + 2) - 33) +
          85 * (a[x](f + 3) - 33) +
          (a[x](f + 4) - 33)),
          e.push(w & (d >> 24), w & (d >> 16), w & (d >> 8), w & d);
      return (
        (function(a, b) {
          for (var c = b; c > 0; c--) a.pop();
        })(e, c[l]),
        h.fromCharCode.apply(h, e)
      );
    };

    var ASCIIHexEncode = function(value) {
      return (
        value
          .split("")
          .map(function(value) {
            return ("0" + value.charCodeAt().toString(16)).slice(-2);
          })
          .join("") + ">"
      );
    };

    var ASCIIHexDecode = function(value) {
      var regexCheckIfHex = new RegExp(/^([0-9A-Fa-f]{2})+$/);
      value = value.replace(/\s/g, "");
      if (value.indexOf(">") !== -1) {
        value = value.substr(0, value.indexOf(">"));
      }
      if (value.length % 2) {
        value += "0";
      }
      if (regexCheckIfHex.test(value) === false) {
        return "";
      }
      var result = "";
      for (var i = 0; i < value.length; i += 2) {
        result += String.fromCharCode("0x" + (value[i] + value[i + 1]));
      }
      return result;
    };
    /*
    var FlatePredictors = {
        None: 1,
        TIFF: 2,
        PNG_None: 10,
        PNG_Sub: 11,
        PNG_Up: 12,
        PNG_Average: 13,
        PNG_Paeth: 14,
        PNG_Optimum: 15
    };
    */

    var FlateEncode = function(data) {
      var arr = [];
      var i = data.length;
      var adler32;

      while (i--) {
        arr[i] = data.charCodeAt(i);
      }
      adler32 = jsPDFAPI.adler32cs.from(data);
      data = pako_1.deflate(arr);
      arr = new Uint8Array(data.byteLength + 4);
      arr.set(data, 0);
      arr.set(
        new Uint8Array([
          adler32 & 0xff,
          (adler32 >> 8) & 0xff,
          (adler32 >> 16) & 0xff,
          (adler32 >> 24) & 0xff
        ]),
        data.byteLength
      );
      data = arr.reduce(function(data, byte) {
        return data + String.fromCharCode(byte);
      }, "");
      return data;
    };

    jsPDFAPI.processDataByFilters = function(origData, filterChain) {
      var i = 0;
      var data = origData || "";
      var reverseChain = [];
      filterChain = filterChain || [];

      if (typeof filterChain === "string") {
        filterChain = [filterChain];
      }

      for (i = 0; i < filterChain.length; i += 1) {
        switch (filterChain[i]) {
          case "ASCII85Decode":
          case "/ASCII85Decode":
            data = ASCII85Decode(data);
            reverseChain.push("/ASCII85Encode");
            break;
          case "ASCII85Encode":
          case "/ASCII85Encode":
            data = ASCII85Encode(data);
            reverseChain.push("/ASCII85Decode");
            break;
          case "ASCIIHexDecode":
          case "/ASCIIHexDecode":
            data = ASCIIHexDecode(data);
            reverseChain.push("/ASCIIHexEncode");
            break;
          case "ASCIIHexEncode":
          case "/ASCIIHexEncode":
            data = ASCIIHexEncode(data);
            reverseChain.push("/ASCIIHexDecode");
            break;
          case "FlateEncode":
          case "/FlateEncode":
            data = FlateEncode(data);
            reverseChain.push("/FlateDecode");
            break;
          default:
            throw new Error(
              'The filter: "' + filterChain[i] + '" is not implemented'
            );
        }
      }

      return { data: data, reverseChain: reverseChain.reverse().join(" ") };
    };
  })(jsPDF.API);

  /**
   * @license
   * jsPDF fileloading PlugIn
   * Copyright (c) 2018 Aras Abbasi (aras.abbasi@gmail.com)
   *
   * Licensed under the MIT License.
   * http://opensource.org/licenses/mit-license
   */

  /**
   * @name fileloading
   * @module
   */
  (function(jsPDFAPI) {

    /**
     * @name loadFile
     * @function
     * @param {string} url
     * @param {boolean} sync
     * @param {function} callback
     * @returns {string|undefined} result
     */
    jsPDFAPI.loadFile = function(url, sync, callback) {
      return browserRequest(url, sync, callback);

    };

    /**
     * @name loadImageFile
     * @function
     * @param {string} path
     * @param {boolean} sync
     * @param {function} callback
     */
    jsPDFAPI.loadImageFile = jsPDFAPI.loadFile;

    function browserRequest(url, sync, callback) {
      sync = sync === false ? false : true;
      callback = typeof callback === "function" ? callback : function() {};
      var result = undefined;

      var xhr = function(url, sync, callback) {
        var request = new XMLHttpRequest();
        var i = 0;

        var sanitizeUnicode = function(data) {
          var dataLength = data.length;
          var charArray = [];
          var StringFromCharCode = String.fromCharCode;

          //Transform Unicode to ASCII
          for (i = 0; i < dataLength; i += 1) {
            charArray.push(StringFromCharCode(data.charCodeAt(i) & 0xff));
          }
          return charArray.join("");
        };

        request.open("GET", url, !sync);
        // XHR binary charset opt by Marcus Granado 2006 [http://mgran.blogspot.com]
        request.overrideMimeType("text/plain; charset=x-user-defined");

        if (sync === false) {
          request.onload = function() {
            if (request.status === 200) {
              callback(sanitizeUnicode(this.responseText));
            } else {
              callback(undefined);
            }
          };
        }
        request.send(null);

        if (sync && request.status === 200) {
          return sanitizeUnicode(request.responseText);
        }
      };
      try {
        result = xhr(url, sync, callback);
        // eslint-disable-next-line no-empty
      } catch (e) {}
      return result;
    }
  })(jsPDF.API);

  /**
   * @license
   * Copyright (c) 2018 Erik Koopmans
   * Released under the MIT License.
   *
   * Licensed under the MIT License.
   * http://opensource.org/licenses/mit-license
   */

  /**
   * jsPDF html PlugIn
   *
   * @name html
   * @module
   */
  (function(jsPDFAPI) {

    function loadHtml2Canvas() {
      return (function() {
        if (globalObject["html2canvas"]) {
          return Promise.resolve(globalObject["html2canvas"]);
        }


        if (typeof exports === "object" && typeof module !== "undefined") {
          return new Promise(function(resolve, reject) {
            try {
              resolve(require("html2canvas"));
            } catch (e) {
              reject(e);
            }
          });
        }
        if (typeof define === "function" && define.amd) {
          return new Promise(function(resolve, reject) {
            try {
              require(["html2canvas"], resolve);
            } catch (e) {
              reject(e);
            }
          });
        }
        return Promise.reject(new Error("Could not load html2canvas"));
      })()
        .catch(function(e) {
          return Promise.reject(new Error("Could not load html2canvas: " + e));
        })
        .then(function(html2canvas) {
          return html2canvas.default ? html2canvas.default : html2canvas;
        });
    }

    function loadDomPurify() {
      return (function() {
        if (globalObject["DOMPurify"]) {
          return Promise.resolve(globalObject["DOMPurify"]);
        }


        if (typeof exports === "object" && typeof module !== "undefined") {
          return new Promise(function(resolve, reject) {
            try {
              resolve(require("dompurify"));
            } catch (e) {
              reject(e);
            }
          });
        }
        if (typeof define === "function" && define.amd) {
          return new Promise(function(resolve, reject) {
            try {
              require(["dompurify"], resolve);
            } catch (e) {
              reject(e);
            }
          });
        }
        return Promise.reject(new Error("Could not load dompurify"));
      })()
        .catch(function(e) {
          return Promise.reject(new Error("Could not load dompurify: " + e));
        })
        .then(function(dompurify) {
          return dompurify.default ? dompurify.default : dompurify;
        });
    }

    /**
     * Determine the type of a variable/object.
     *
     * @private
     * @ignore
     */
    var objType = function(obj) {
      var type = typeof obj;
      if (type === "undefined") return "undefined";
      else if (type === "string" || obj instanceof String) return "string";
      else if (type === "number" || obj instanceof Number) return "number";
      else if (type === "function" || obj instanceof Function) return "function";
      else if (!!obj && obj.constructor === Array) return "array";
      else if (obj && obj.nodeType === 1) return "element";
      else if (type === "object") return "object";
      else return "unknown";
    };

    /**
     * Create an HTML element with optional className, innerHTML, and style.
     *
     * @private
     * @ignore
     */
    var createElement = function(tagName, opt) {
      var el = document.createElement(tagName);
      if (opt.className) el.className = opt.className;
      if (opt.innerHTML && opt.dompurify) {
        el.innerHTML = opt.dompurify.sanitize(opt.innerHTML);
      }
      for (var key in opt.style) {
        el.style[key] = opt.style[key];
      }
      return el;
    };

    /**
     * Deep-clone a node and preserve contents/properties.
     *
     * @private
     * @ignore
     */
    var cloneNode = function(node, javascriptEnabled) {
      // Recursively clone the node.
      var clone =
        node.nodeType === 3
          ? document.createTextNode(node.nodeValue)
          : node.cloneNode(false);
      for (var child = node.firstChild; child; child = child.nextSibling) {
        if (
          javascriptEnabled === true ||
          child.nodeType !== 1 ||
          child.nodeName !== "SCRIPT"
        ) {
          clone.appendChild(cloneNode(child, javascriptEnabled));
        }
      }

      if (node.nodeType === 1) {
        // Preserve contents/properties of special nodes.
        if (node.nodeName === "CANVAS") {
          clone.width = node.width;
          clone.height = node.height;
          clone.getContext("2d").drawImage(node, 0, 0);
        } else if (node.nodeName === "TEXTAREA" || node.nodeName === "SELECT") {
          clone.value = node.value;
        }

        // Preserve the node's scroll position when it loads.
        clone.addEventListener(
          "load",
          function() {
            clone.scrollTop = node.scrollTop;
            clone.scrollLeft = node.scrollLeft;
          },
          true
        );
      }

      // Return the cloned node.
      return clone;
    };

    /* ----- CONSTRUCTOR ----- */

    var Worker = function Worker(opt) {
      // Create the root parent for the proto chain, and the starting Worker.
      var root = Object.assign(
        Worker.convert(Promise.resolve()),
        JSON.parse(JSON.stringify(Worker.template))
      );
      var self = Worker.convert(Promise.resolve(), root);

      // Set progress, optional settings, and return.
      self = self.setProgress(1, Worker, 1, [Worker]);
      self = self.set(opt);
      return self;
    };

    // Boilerplate for subclassing Promise.
    Worker.prototype = Object.create(Promise.prototype);
    Worker.prototype.constructor = Worker;

    // Converts/casts promises into Workers.
    Worker.convert = function convert(promise, inherit) {
      // Uses prototypal inheritance to receive changes made to ancestors' properties.
      promise.__proto__ = inherit || Worker.prototype;
      return promise;
    };

    Worker.template = {
      prop: {
        src: null,
        container: null,
        overlay: null,
        canvas: null,
        img: null,
        pdf: null,
        pageSize: null,
        callback: function() {}
      },
      progress: {
        val: 0,
        state: null,
        n: 0,
        stack: []
      },
      opt: {
        filename: "file.pdf",
        margin: [0, 0, 0, 0],
        enableLinks: true,
        x: 0,
        y: 0,
        html2canvas: {},
        jsPDF: {},
        backgroundColor: "transparent"
      }
    };

    /* ----- FROM / TO ----- */

    Worker.prototype.from = function from(src, type) {
      function getType(src) {
        switch (objType(src)) {
          case "string":
            return "string";
          case "element":
            return src.nodeName.toLowerCase === "canvas" ? "canvas" : "element";
          default:
            return "unknown";
        }
      }

      return this.then(function from_main() {
        type = type || getType(src);
        switch (type) {
          case "string":
            return this.then(loadDomPurify).then(function(dompurify) {
              return this.set({
                src: createElement("div", {
                  innerHTML: src,
                  dompurify: dompurify
                })
              });
            });
          case "element":
            return this.set({ src: src });
          case "canvas":
            return this.set({ canvas: src });
          case "img":
            return this.set({ img: src });
          default:
            return this.error("Unknown source type.");
        }
      });
    };

    Worker.prototype.to = function to(target) {
      // Route the 'to' request to the appropriate method.
      switch (target) {
        case "container":
          return this.toContainer();
        case "canvas":
          return this.toCanvas();
        case "img":
          return this.toImg();
        case "pdf":
          return this.toPdf();
        default:
          return this.error("Invalid target.");
      }
    };

    Worker.prototype.toContainer = function toContainer() {
      // Set up function prerequisites.
      var prereqs = [
        function checkSrc() {
          return (
            this.prop.src || this.error("Cannot duplicate - no source HTML.")
          );
        },
        function checkPageSize() {
          return this.prop.pageSize || this.setPageSize();
        }
      ];
      return this.thenList(prereqs).then(function toContainer_main() {
        // Define the CSS styles for the container and its overlay parent.
        var overlayCSS = {
          position: "fixed",
          overflow: "hidden",
          zIndex: 1000,
          left: "-100000px",
          right: 0,
          bottom: 0,
          top: 0
        };
        var containerCSS = {
          position: "relative",
          display: "inline-block",
          width:
            Math.max(
              this.prop.src.clientWidth,
              this.prop.src.scrollWidth,
              this.prop.src.offsetWidth
            ) + "px",
          left: 0,
          right: 0,
          top: 0,
          margin: "auto",
          backgroundColor: this.opt.backgroundColor
        }; // Set the overlay to hidden (could be changed in the future to provide a print preview).

        var source = cloneNode(
          this.prop.src,
          this.opt.html2canvas.javascriptEnabled
        );

        if (source.tagName === "BODY") {
          containerCSS.height =
            Math.max(
              document.body.scrollHeight,
              document.body.offsetHeight,
              document.documentElement.clientHeight,
              document.documentElement.scrollHeight,
              document.documentElement.offsetHeight
            ) + "px";
        }

        this.prop.overlay = createElement("div", {
          className: "html2pdf__overlay",
          style: overlayCSS
        });
        this.prop.container = createElement("div", {
          className: "html2pdf__container",
          style: containerCSS
        });
        this.prop.container.appendChild(source);
        this.prop.container.firstChild.appendChild(
          createElement("div", {
            style: {
              clear: "both",
              border: "0 none transparent",
              margin: 0,
              padding: 0,
              height: 0
            }
          })
        );
        this.prop.container.style.float = "none";
        this.prop.overlay.appendChild(this.prop.container);
        document.body.appendChild(this.prop.overlay);
        this.prop.container.firstChild.style.position = "relative";
        this.prop.container.height =
          Math.max(
            this.prop.container.firstChild.clientHeight,
            this.prop.container.firstChild.scrollHeight,
            this.prop.container.firstChild.offsetHeight
          ) + "px";
      });
    };

    Worker.prototype.toCanvas = function toCanvas() {
      // Set up function prerequisites.
      var prereqs = [
        function checkContainer() {
          return (
            document.body.contains(this.prop.container) || this.toContainer()
          );
        }
      ];

      // Fulfill prereqs then create the canvas.
      return this.thenList(prereqs)
        .then(loadHtml2Canvas)
        .then(function toCanvas_main(html2canvas) {
          // Handle old-fashioned 'onrendered' argument.
          var options = Object.assign({}, this.opt.html2canvas);
          delete options.onrendered;

          return html2canvas(this.prop.container, options);
        })
        .then(function toCanvas_post(canvas) {
          // Handle old-fashioned 'onrendered' argument.
          var onRendered = this.opt.html2canvas.onrendered || function() {};
          onRendered(canvas);

          this.prop.canvas = canvas;
          document.body.removeChild(this.prop.overlay);
        });
    };

    Worker.prototype.toContext2d = function toContext2d() {
      // Set up function prerequisites.
      var prereqs = [
        function checkContainer() {
          return (
            document.body.contains(this.prop.container) || this.toContainer()
          );
        }
      ];

      // Fulfill prereqs then create the canvas.
      return this.thenList(prereqs)
        .then(loadHtml2Canvas)
        .then(function toContext2d_main(html2canvas) {
          // Handle old-fashioned 'onrendered' argument.

          var pdf = this.opt.jsPDF;
          var options = Object.assign(
            {
              async: true,
              allowTaint: true,
              scale: 1,
              scrollX: this.opt.scrollX || 0,
              scrollY: this.opt.scrollY || 0,
              backgroundColor: "#ffffff",
              imageTimeout: 15000,
              logging: true,
              proxy: null,
              removeContainer: true,
              foreignObjectRendering: false,
              useCORS: false
            },
            this.opt.html2canvas
          );
          delete options.onrendered;

          pdf.context2d.autoPaging = true;
          pdf.context2d.posX = this.opt.x;
          pdf.context2d.posY = this.opt.y;

          options.windowHeight = options.windowHeight || 0;
          options.windowHeight =
            options.windowHeight == 0
              ? Math.max(
                  this.prop.container.clientHeight,
                  this.prop.container.scrollHeight,
                  this.prop.container.offsetHeight
                )
              : options.windowHeight;

          return html2canvas(this.prop.container, options);
        })
        .then(function toContext2d_post(canvas) {
          // Handle old-fashioned 'onrendered' argument.
          var onRendered = this.opt.html2canvas.onrendered || function() {};
          onRendered(canvas);

          this.prop.canvas = canvas;
          document.body.removeChild(this.prop.overlay);
        });
    };

    Worker.prototype.toImg = function toImg() {
      // Set up function prerequisites.
      var prereqs = [
        function checkCanvas() {
          return this.prop.canvas || this.toCanvas();
        }
      ];

      // Fulfill prereqs then create the image.
      return this.thenList(prereqs).then(function toImg_main() {
        var imgData = this.prop.canvas.toDataURL(
          "image/" + this.opt.image.type,
          this.opt.image.quality
        );
        this.prop.img = document.createElement("img");
        this.prop.img.src = imgData;
      });
    };

    Worker.prototype.toPdf = function toPdf() {
      // Set up function prerequisites.
      var prereqs = [
        function checkContext2d() {
          return this.toContext2d();
        }
        //function checkCanvas() { return this.prop.canvas || this.toCanvas(); }
      ];

      // Fulfill prereqs then create the image.
      return this.thenList(prereqs).then(function toPdf_main() {
        // Create local copies of frequently used properties.
        this.prop.pdf = this.prop.pdf || this.opt.jsPDF;
      });
    };

    /* ----- OUTPUT / SAVE ----- */

    Worker.prototype.output = function output(type, options, src) {
      // Redirect requests to the correct function (outputPdf / outputImg).
      src = src || "pdf";
      if (src.toLowerCase() === "img" || src.toLowerCase() === "image") {
        return this.outputImg(type, options);
      } else {
        return this.outputPdf(type, options);
      }
    };

    Worker.prototype.outputPdf = function outputPdf(type, options) {
      // Set up function prerequisites.
      var prereqs = [
        function checkPdf() {
          return this.prop.pdf || this.toPdf();
        }
      ];

      // Fulfill prereqs then perform the appropriate output.
      return this.thenList(prereqs).then(function outputPdf_main() {
        /* Currently implemented output types:
         *    https://rawgit.com/MrRio/jsPDF/master/docs/jspdf.js.html#line992
         *  save(options), arraybuffer, blob, bloburi/bloburl,
         *  datauristring/dataurlstring, dataurlnewwindow, datauri/dataurl
         */
        return this.prop.pdf.output(type, options);
      });
    };

    Worker.prototype.outputImg = function outputImg(type) {
      // Set up function prerequisites.
      var prereqs = [
        function checkImg() {
          return this.prop.img || this.toImg();
        }
      ];

      // Fulfill prereqs then perform the appropriate output.
      return this.thenList(prereqs).then(function outputImg_main() {
        switch (type) {
          case undefined:
          case "img":
            return this.prop.img;
          case "datauristring":
          case "dataurlstring":
            return this.prop.img.src;
          case "datauri":
          case "dataurl":
            return (document.location.href = this.prop.img.src);
          default:
            throw 'Image output type "' + type + '" is not supported.';
        }
      });
    };

    Worker.prototype.save = function save(filename) {
      // Set up function prerequisites.
      var prereqs = [
        function checkPdf() {
          return this.prop.pdf || this.toPdf();
        }
      ];

      // Fulfill prereqs, update the filename (if provided), and save the PDF.
      return this.thenList(prereqs)
        .set(filename ? { filename: filename } : null)
        .then(function save_main() {
          this.prop.pdf.save(this.opt.filename);
        });
    };

    Worker.prototype.doCallback = function doCallback() {
      // Set up function prerequisites.
      var prereqs = [
        function checkPdf() {
          return this.prop.pdf || this.toPdf();
        }
      ];

      // Fulfill prereqs, update the filename (if provided), and save the PDF.
      return this.thenList(prereqs).then(function doCallback_main() {
        this.prop.callback(this.prop.pdf);
      });
    };

    /* ----- SET / GET ----- */

    Worker.prototype.set = function set(opt) {
      // TODO: Implement ordered pairs?

      // Silently ignore invalid or empty input.
      if (objType(opt) !== "object") {
        return this;
      }

      // Build an array of setter functions to queue.
      var fns = Object.keys(opt || {}).map(function(key) {
        if (key in Worker.template.prop) {
          // Set pre-defined properties.
          return function set_prop() {
            this.prop[key] = opt[key];
          };
        } else {
          switch (key) {
            case "margin":
              return this.setMargin.bind(this, opt.margin);
            case "jsPDF":
              return function set_jsPDF() {
                this.opt.jsPDF = opt.jsPDF;
                return this.setPageSize();
              };
            case "pageSize":
              return this.setPageSize.bind(this, opt.pageSize);
            default:
              // Set any other properties in opt.
              return function set_opt() {
                this.opt[key] = opt[key];
              };
          }
        }
      }, this);

      // Set properties within the promise chain.
      return this.then(function set_main() {
        return this.thenList(fns);
      });
    };

    Worker.prototype.get = function get(key, cbk) {
      return this.then(function get_main() {
        // Fetch the requested property, either as a predefined prop or in opt.
        var val = key in Worker.template.prop ? this.prop[key] : this.opt[key];
        return cbk ? cbk(val) : val;
      });
    };

    Worker.prototype.setMargin = function setMargin(margin) {
      return this.then(function setMargin_main() {
        // Parse the margin property.
        switch (objType(margin)) {
          case "number":
            margin = [margin, margin, margin, margin];
          // eslint-disable-next-line no-fallthrough
          case "array":
            if (margin.length === 2) {
              margin = [margin[0], margin[1], margin[0], margin[1]];
            }
            if (margin.length === 4) {
              break;
            }
          // eslint-disable-next-line no-fallthrough
          default:
            return this.error("Invalid margin array.");
        }

        // Set the margin property, then update pageSize.
        this.opt.margin = margin;
      }).then(this.setPageSize);
    };

    Worker.prototype.setPageSize = function setPageSize(pageSize) {
      function toPx(val, k) {
        return Math.floor(((val * k) / 72) * 96);
      }

      return this.then(function setPageSize_main() {
        // Retrieve page-size based on jsPDF settings, if not explicitly provided.
        pageSize = pageSize || jsPDF.getPageSize(this.opt.jsPDF);

        // Add 'inner' field if not present.
        if (!pageSize.hasOwnProperty("inner")) {
          pageSize.inner = {
            width: pageSize.width - this.opt.margin[1] - this.opt.margin[3],
            height: pageSize.height - this.opt.margin[0] - this.opt.margin[2]
          };
          pageSize.inner.px = {
            width: toPx(pageSize.inner.width, pageSize.k),
            height: toPx(pageSize.inner.height, pageSize.k)
          };
          pageSize.inner.ratio = pageSize.inner.height / pageSize.inner.width;
        }

        // Attach pageSize to this.
        this.prop.pageSize = pageSize;
      });
    };

    Worker.prototype.setProgress = function setProgress(val, state, n, stack) {
      // Immediately update all progress values.
      if (val != null) this.progress.val = val;
      if (state != null) this.progress.state = state;
      if (n != null) this.progress.n = n;
      if (stack != null) this.progress.stack = stack;
      this.progress.ratio = this.progress.val / this.progress.state;

      // Return this for command chaining.
      return this;
    };

    Worker.prototype.updateProgress = function updateProgress(
      val,
      state,
      n,
      stack
    ) {
      // Immediately update all progress values, using setProgress.
      return this.setProgress(
        val ? this.progress.val + val : null,
        state ? state : null,
        n ? this.progress.n + n : null,
        stack ? this.progress.stack.concat(stack) : null
      );
    };

    /* ----- PROMISE MAPPING ----- */

    Worker.prototype.then = function then(onFulfilled, onRejected) {
      // Wrap `this` for encapsulation.
      var self = this;

      return this.thenCore(onFulfilled, onRejected, function then_main(
        onFulfilled,
        onRejected
      ) {
        // Update progress while queuing, calling, and resolving `then`.
        self.updateProgress(null, null, 1, [onFulfilled]);
        return Promise.prototype.then
          .call(this, function then_pre(val) {
            self.updateProgress(null, onFulfilled);
            return val;
          })
          .then(onFulfilled, onRejected)
          .then(function then_post(val) {
            self.updateProgress(1);
            return val;
          });
      });
    };

    Worker.prototype.thenCore = function thenCore(
      onFulfilled,
      onRejected,
      thenBase
    ) {
      // Handle optional thenBase parameter.
      thenBase = thenBase || Promise.prototype.then;

      // Wrap `this` for encapsulation and bind it to the promise handlers.
      var self = this;
      if (onFulfilled) {
        onFulfilled = onFulfilled.bind(self);
      }
      if (onRejected) {
        onRejected = onRejected.bind(self);
      }

      // Cast self into a Promise to avoid polyfills recursively defining `then`.
      var isNative =
        Promise.toString().indexOf("[native code]") !== -1 &&
        Promise.name === "Promise";
      var selfPromise = isNative
        ? self
        : Worker.convert(Object.assign({}, self), Promise.prototype);

      // Return the promise, after casting it into a Worker and preserving props.
      var returnVal = thenBase.call(selfPromise, onFulfilled, onRejected);
      return Worker.convert(returnVal, self.__proto__);
    };

    Worker.prototype.thenExternal = function thenExternal(
      onFulfilled,
      onRejected
    ) {
      // Call `then` and return a standard promise (exits the Worker chain).
      return Promise.prototype.then.call(this, onFulfilled, onRejected);
    };

    Worker.prototype.thenList = function thenList(fns) {
      // Queue a series of promise 'factories' into the promise chain.
      var self = this;
      fns.forEach(function thenList_forEach(fn) {
        self = self.thenCore(fn);
      });
      return self;
    };

    Worker.prototype["catch"] = function(onRejected) {
      // Bind `this` to the promise handler, call `catch`, and return a Worker.
      if (onRejected) {
        onRejected = onRejected.bind(this);
      }
      var returnVal = Promise.prototype["catch"].call(this, onRejected);
      return Worker.convert(returnVal, this);
    };

    Worker.prototype.catchExternal = function catchExternal(onRejected) {
      // Call `catch` and return a standard promise (exits the Worker chain).
      return Promise.prototype["catch"].call(this, onRejected);
    };

    Worker.prototype.error = function error(msg) {
      // Throw the error in the Promise chain.
      return this.then(function error_main() {
        throw new Error(msg);
      });
    };

    /* ----- ALIASES ----- */

    Worker.prototype.using = Worker.prototype.set;
    Worker.prototype.saveAs = Worker.prototype.save;
    Worker.prototype.export = Worker.prototype.output;
    Worker.prototype.run = Worker.prototype.then;

    // Get dimensions of a PDF page, as determined by jsPDF.
    jsPDF.getPageSize = function(orientation, unit, format) {
      // Decode options object
      if (typeof orientation === "object") {
        var options = orientation;
        orientation = options.orientation;
        unit = options.unit || unit;
        format = options.format || format;
      }

      // Default options
      unit = unit || "mm";
      format = format || "a4";
      orientation = ("" + (orientation || "P")).toLowerCase();
      var format_as_string = ("" + format).toLowerCase();

      // Size in pt of various paper formats
      var pageFormats = {
        a0: [2383.94, 3370.39],
        a1: [1683.78, 2383.94],
        a2: [1190.55, 1683.78],
        a3: [841.89, 1190.55],
        a4: [595.28, 841.89],
        a5: [419.53, 595.28],
        a6: [297.64, 419.53],
        a7: [209.76, 297.64],
        a8: [147.4, 209.76],
        a9: [104.88, 147.4],
        a10: [73.7, 104.88],
        b0: [2834.65, 4008.19],
        b1: [2004.09, 2834.65],
        b2: [1417.32, 2004.09],
        b3: [1000.63, 1417.32],
        b4: [708.66, 1000.63],
        b5: [498.9, 708.66],
        b6: [354.33, 498.9],
        b7: [249.45, 354.33],
        b8: [175.75, 249.45],
        b9: [124.72, 175.75],
        b10: [87.87, 124.72],
        c0: [2599.37, 3676.54],
        c1: [1836.85, 2599.37],
        c2: [1298.27, 1836.85],
        c3: [918.43, 1298.27],
        c4: [649.13, 918.43],
        c5: [459.21, 649.13],
        c6: [323.15, 459.21],
        c7: [229.61, 323.15],
        c8: [161.57, 229.61],
        c9: [113.39, 161.57],
        c10: [79.37, 113.39],
        dl: [311.81, 623.62],
        letter: [612, 792],
        "government-letter": [576, 756],
        legal: [612, 1008],
        "junior-legal": [576, 360],
        ledger: [1224, 792],
        tabloid: [792, 1224],
        "credit-card": [153, 243]
      };

      var k;
      // Unit conversion
      switch (unit) {
        case "pt":
          k = 1;
          break;
        case "mm":
          k = 72 / 25.4;
          break;
        case "cm":
          k = 72 / 2.54;
          break;
        case "in":
          k = 72;
          break;
        case "px":
          k = 72 / 96;
          break;
        case "pc":
          k = 12;
          break;
        case "em":
          k = 12;
          break;
        case "ex":
          k = 6;
          break;
        default:
          throw "Invalid unit: " + unit;
      }
      var pageHeight = 0;
      var pageWidth = 0;

      // Dimensions are stored as user units and converted to points on output
      if (pageFormats.hasOwnProperty(format_as_string)) {
        pageHeight = pageFormats[format_as_string][1] / k;
        pageWidth = pageFormats[format_as_string][0] / k;
      } else {
        try {
          pageHeight = format[1];
          pageWidth = format[0];
        } catch (err) {
          throw new Error("Invalid format: " + format);
        }
      }

      var tmp;
      // Handle page orientation
      if (orientation === "p" || orientation === "portrait") {
        orientation = "p";
        if (pageWidth > pageHeight) {
          tmp = pageWidth;
          pageWidth = pageHeight;
          pageHeight = tmp;
        }
      } else if (orientation === "l" || orientation === "landscape") {
        orientation = "l";
        if (pageHeight > pageWidth) {
          tmp = pageWidth;
          pageWidth = pageHeight;
          pageHeight = tmp;
        }
      } else {
        throw "Invalid orientation: " + orientation;
      }

      // Return information (k is the unit conversion ratio from pts)
      var info = {
        width: pageWidth,
        height: pageHeight,
        unit: unit,
        k: k,
        orientation: orientation
      };
      return info;
    };

    /**
     * Generate a PDF from an HTML element or string using.
     *
     * @name html
     * @function
     * @param {HTMLElement|string} source The source HTMLElement or a string containing HTML.
     * @param {Object} [options] Collection of settings
     * @param {function} [options.callback] The mandatory callback-function gets as first parameter the current jsPDF instance
     * @param {number|array} [options.margin] Array of margins [left, bottom, right, top]
     * @param {string} [options.filename] name of the file
     * @param {HTMLOptionImage} [options.image] image settings when converting HTML to image
     * @param {Html2CanvasOptions} [options.html2canvas] html2canvas options
     * @param {jsPDF} [options.jsPDF] jsPDF instance
     * @param {number} [options.x] x position on the PDF document
     * @param {number} [options.y] y position on the PDF document
     *
     * @example
     * var doc = new jsPDF();
     *
     * doc.html(document.body, {
     *    callback: function (doc) {
     *      doc.save();
     *    },
     *    x: 10,
     *    y: 10
     * });
     */
    jsPDFAPI.html = function(src, options) {

      options = options || {};
      options.callback = options.callback || function() {};
      options.html2canvas = options.html2canvas || {};
      options.html2canvas.canvas = options.html2canvas.canvas || this.canvas;
      options.jsPDF = options.jsPDF || this;
      // Create a new worker with the given options.
      var worker = new Worker(options);

      if (!options.worker) {
        // If worker is not set to true, perform the traditional 'simple' operation.
        return worker.from(src).doCallback();
      } else {
        // Otherwise, return the worker for new Promise-based operation.
        return worker;
      }
    };
  })(jsPDF.API);

  /**
   * @license
   * ====================================================================
   * Copyright (c) 2013 Youssef Beddad, youssef.beddad@gmail.com
   *
   * 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.
   * ====================================================================
   */

  /**
   * jsPDF JavaScript plugin
   *
   * @name javascript
   * @module
   */
  (function(jsPDFAPI) {
    var jsNamesObj, jsJsObj, text;
    /**
     * @name addJS
     * @function
     * @param {string} javascript The javascript to be embedded into the PDF-file.
     * @returns {jsPDF}
     */
    jsPDFAPI.addJS = function(javascript) {
      text = javascript;
      this.internal.events.subscribe("postPutResources", function() {
        jsNamesObj = this.internal.newObject();
        this.internal.out("<<");
        this.internal.out("/Names [(EmbeddedJS) " + (jsNamesObj + 1) + " 0 R]");
        this.internal.out(">>");
        this.internal.out("endobj");

        jsJsObj = this.internal.newObject();
        this.internal.out("<<");
        this.internal.out("/S /JavaScript");
        this.internal.out("/JS (" + text + ")");
        this.internal.out(">>");
        this.internal.out("endobj");
      });
      this.internal.events.subscribe("putCatalog", function() {
        if (jsNamesObj !== undefined && jsJsObj !== undefined) {
          this.internal.out("/Names <</JavaScript " + jsNamesObj + " 0 R>>");
        }
      });
      return this;
    };
  })(jsPDF.API);

  /**
   * @license
   * Copyright (c) 2014 Steven Spungin (TwelveTone LLC)  steven@twelvetone.tv
   *
   * Licensed under the MIT License.
   * http://opensource.org/licenses/mit-license
   */

  /**
   * jsPDF Outline PlugIn
   *
   * Generates a PDF Outline
   * @name outline
   * @module
   */
  (function(jsPDFAPI) {

    var namesOid;
    //var destsGoto = [];

    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, false);
            }
            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');

          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: []
          }
        };

        /**
         * 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) {
          var getVerticalCoordinateString = this.ctx.pdf.internal
            .getVerticalCoordinateString;
          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 " +
                    getVerticalCoordinateString(0) +
                    " 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.getHeight() + ' 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 z = 0; z < node.children.length; z++) {
            this.renderItems(node.children[z]);
          }
        };

        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() {
          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);

  /**
   * @license
   *
   * Licensed under the MIT License.
   * http://opensource.org/licenses/mit-license
   */

  /**
   * jsPDF jpeg Support PlugIn
   *
   * @name jpeg_support
   * @module
   */
  (function(jsPDFAPI) {

    /**
     * 0xc0 (SOF) Huffman  - Baseline DCT
     * 0xc1 (SOF) Huffman  - Extended sequential DCT
     * 0xc2 Progressive DCT (SOF2)
     * 0xc3 Spatial (sequential) lossless (SOF3)
     * 0xc4 Differential sequential DCT (SOF5)
     * 0xc5 Differential progressive DCT (SOF6)
     * 0xc6 Differential spatial (SOF7)
     * 0xc7
     */
    var markers = [0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7];

    //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 getJpegInfo = function(imgData) {
      var width, height, numcomponents;
      var blockLength = imgData.charCodeAt(4) * 256 + imgData.charCodeAt(5);
      var len = imgData.length;
      var result = { width: 0, height: 0, numcomponents: 1 };
      for (var i = 4; i < len; i += 2) {
        i += blockLength;
        if (markers.indexOf(imgData.charCodeAt(i + 1)) !== -1) {
          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);
          result = { width: width, height: height, numcomponents: numcomponents };
          break;
        } else {
          blockLength =
            imgData.charCodeAt(i + 2) * 256 + imgData.charCodeAt(i + 3);
        }
      }
      return result;
    };

    /**
     * @ignore
     */
    jsPDFAPI.processJPEG = function(
      data,
      index,
      alias,
      compression,
      dataAsBinaryString,
      colorSpace
    ) {
      var filter = this.decode.DCT_DECODE,
        bpc = 8,
        dims,
        result = null;

      if (
        typeof data === "string" ||
        this.__addimage__.isArrayBuffer(data) ||
        this.__addimage__.isArrayBufferView(data)
      ) {
        // if we already have a stored binary string rep use that
        data = dataAsBinaryString || data;
        data = this.__addimage__.isArrayBuffer(data)
          ? new Uint8Array(data)
          : data;
        data = this.__addimage__.isArrayBufferView(data)
          ? this.__addimage__.arrayBufferToBinaryString(data)
          : data;

        dims = getJpegInfo(data);
        switch (dims.numcomponents) {
          case 1:
            colorSpace = this.color_spaces.DEVICE_GRAY;
            break;
          case 4:
            colorSpace = this.color_spaces.DEVICE_CMYK;
            break;
          case 3:
            colorSpace = this.color_spaces.DEVICE_RGB;
            break;
        }

        result = {
          data: data,
          width: dims.width,
          height: dims.height,
          colorSpace: colorSpace,
          bitsPerComponent: bpc,
          filter: filter,
          index: index,
          alias: alias
        };
      }
      return result;
    };
  })(jsPDF.API);

  /**
   * @license
   * 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
   *
   * 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.
   */

  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 globalObject$1 =
    (typeof self !== "undefined" && self) ||
    (typeof window !== "undefined" && window) ||
    (typeof global !== "undefined" && global) ||
    Function('return typeof this === "object" && this.content')() ||
    Function("return this")();

  var FlateStream = (globalObject$1.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;
  })());

  // Generated by CoffeeScript 1.4.0

  var PNG = (function() {
    var APNG_BLEND_OP_SOURCE,
      APNG_DISPOSE_OP_BACKGROUND,
      APNG_DISPOSE_OP_PREVIOUS,
      makeImage,
      scratchCanvas,
      scratchCtx;

    APNG_DISPOSE_OP_BACKGROUND = 1;

    APNG_DISPOSE_OP_PREVIOUS = 2;

    APNG_BLEND_OP_SOURCE = 0;

    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");
        }
      }
    }

    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 pixelBytes = this.pixelBitlength / 8;
      var fullPixels = new Uint8Array(this.width * this.height * pixelBytes);
      var pos = 0;
      var _this = this;

      if (data == null) {
        data = this.imgData;
      }
      if (data.length === 0) {
        return new Uint8Array(0);
      }

      data = new FlateStream(data);
      data = data.getBytes();
      function pass(x0, y0, dx, dy) {
        var abyte,
          c,
          col,
          i,
          left,
          length,
          p,
          pa,
          paeth,
          pb,
          pc,
          pixels,
          row,
          scanlineLength,
          upper,
          upperLeft,
          _i,
          _j,
          _k,
          _l,
          _m;
        var w = Math.ceil((_this.width - x0) / dx),
          h = Math.ceil((_this.height - y0) / dy);
        var isFull = _this.width == w && _this.height == h;
        scanlineLength = pixelBytes * w;
        pixels = isFull ? fullPixels : new Uint8Array(scanlineLength * h);
        length = data.length;
        row = 0;
        c = 0;
        while (row < h && 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]);
          }
          if (!isFull) {
            var fullPos = ((y0 + row * dy) * _this.width + x0) * pixelBytes;
            var partPos = row * scanlineLength;
            for (i = 0; i < w; i += 1) {
              for (var j = 0; j < pixelBytes; j += 1)
                fullPixels[fullPos++] = pixels[partPos++];
              fullPos += (dx - 1) * pixelBytes;
            }
          }
          row++;
        }
      }
      if (_this.interlaceMethod == 1) {
        /*
            1 6 4 6 2 6 4 6
            7 7 7 7 7 7 7 7
            5 6 5 6 5 6 5 6
            7 7 7 7 7 7 7 7
            3 6 4 6 3 6 4 6
            7 7 7 7 7 7 7 7
            5 6 5 6 5 6 5 6
            7 7 7 7 7 7 7 7
          */
        pass(0, 0, 8, 8); // 1
        /* NOTE these seem to follow the pattern:
         * pass(x, 0, 2*x, 2*x);
         * pass(0, x,   x, 2*x);
         * with x being 4, 2, 1.
         */
        pass(4, 0, 8, 8); // 2
        pass(0, 4, 4, 8); // 3

        pass(2, 0, 4, 4); // 4
        pass(0, 2, 2, 4); // 5

        pass(1, 0, 2, 2); // 6
        pass(0, 1, 1, 2); // 7
      } else {
        pass(0, 0, 1, 1);
      }
      return fullPixels;
    };

    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 = 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;
    };

    var hasBrowserCanvas = function() {
      if (Object.prototype.toString.call(globalObject) === "[object Window]") {
        try {
          scratchCanvas = globalObject.document.createElement("canvas");
          scratchCtx = scratchCanvas.getContext("2d");
        } catch (e) {
          return false;
        }
        return true;
      }
      return false;
    };

    hasBrowserCanvas();

    makeImage = function(imageData) {
      if (hasBrowserCanvas() === true) {
        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;
      }
      throw new Error("This method requires a Browser with Canvas-capability.");
    };

    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;
  })();

  /**
   * @license
   *
   * Copyright (c) 2014 James Robb, https://github.com/jamesbrobb
   *
   * 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.
   * ====================================================================
   */

  /**
   * jsPDF PNG PlugIn
   * @name png_support
   * @module
   */
  (function(jsPDFAPI) {

    /*
     * @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 canCompress = function(value) {
      return value !== jsPDFAPI.image_compression.NONE && hasCompressionJS();
    };

    var hasCompressionJS = function() {
      return typeof pako_1.deflate === "function";
    };
    var compressBytes = function(bytes, lineLength, colorsPerPixel, compression) {
      var level = 5;
      var 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;
          break;
      }

      bytes = applyPngFilterMethod(
        bytes,
        lineLength,
        colorsPerPixel,
        filter_method
      );

      var checksum = jsPDF.API.adler32cs.fromBuffer(bytes.buffer);

      var deflater = new pako_1.Deflate({ level: level });
      deflater.push(bytes, true);
      var data = deflater.result;
      var len = data.length;
      var cmpd = new Uint8Array(data.length + 4);

      cmpd.set(data, 0);

      cmpd[len++] = (checksum >>> 24) & 0xff;
      cmpd[len++] = (checksum >>> 16) & 0xff;
      cmpd[len++] = (checksum >>> 8) & 0xff;
      cmpd[len++] = checksum & 0xff;

      return jsPDFAPI.__addimage__.arrayBufferToBinaryString(cmpd);
    };

    var applyPngFilterMethod = function(
      bytes,
      lineLength,
      colorsPerPixel,
      filter_method
    ) {
      var lines = bytes.length / lineLength,
        result = new Uint8Array(bytes.length + lines),
        filter_methods = getFilterMethods(),
        line,
        prevLine,
        offset;

      for (var i = 0; i < lines; i += 1) {
        offset = i * lineLength;
        line = bytes.subarray(offset, offset + lineLength);

        if (filter_method) {
          result.set(filter_method(line, colorsPerPixel, prevLine), offset + i);
        } else {
          var len = filter_methods.length,
            results = [];

          for (var j; j < len; j += 1) {
            results[j] = filter_methods[j](line, colorsPerPixel, prevLine);
          }

          var ind = getIndexOfSmallestSum(results.concat());

          result.set(results[ind], offset + i);
        }

        prevLine = line;
      }

      return result;
    };

    var filterNone = function(line) {
      /*var result = new Uint8Array(line.length + 1);
      result[0] = 0;
      result.set(line, 1);*/

      var result = Array.apply([], line);
      result.unshift(0);

      return result;
    };

    var filterSub = function(line, colorsPerPixel) {
      var result = [],
        len = line.length,
        left;

      result[0] = 1;

      for (var i = 0; i < len; i += 1) {
        left = line[i - colorsPerPixel] || 0;
        result[i + 1] = (line[i] - left + 0x0100) & 0xff;
      }

      return result;
    };

    var filterUp = function(line, colorsPerPixel, prevLine) {
      var result = [],
        len = line.length,
        up;

      result[0] = 2;

      for (var i = 0; i < len; i += 1) {
        up = (prevLine && prevLine[i]) || 0;
        result[i + 1] = (line[i] - up + 0x0100) & 0xff;
      }

      return result;
    };

    var filterAverage = function(line, colorsPerPixel, prevLine) {
      var result = [],
        len = line.length,
        left,
        up;

      result[0] = 3;

      for (var i = 0; i < len; i += 1) {
        left = line[i - colorsPerPixel] || 0;
        up = (prevLine && prevLine[i]) || 0;
        result[i + 1] = (line[i] + 0x0100 - ((left + up) >>> 1)) & 0xff;
      }

      return result;
    };

    var filterPaeth = function(line, colorsPerPixel, prevLine) {
      var result = [],
        len = line.length,
        left,
        up,
        upLeft,
        paeth;

      result[0] = 4;

      for (var i = 0; i < len; i += 1) {
        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;
    };

    var paethPredictor = function(left, up, upLeft) {
      if (left === up && up === upLeft) {
        return left;
      }
      var pLeft = Math.abs(up - upLeft),
        pUp = Math.abs(left - upLeft),
        pUpLeft = Math.abs(left + up - upLeft - upLeft);
      return pLeft <= pUp && pLeft <= pUpLeft
        ? left
        : pUp <= pUpLeft
        ? up
        : upLeft;
    };

    var getFilterMethods = function() {
      return [filterNone, filterSub, filterUp, filterAverage, filterPaeth];
    };

    var getIndexOfSmallestSum = function(arrays) {
      var sum = arrays.map(function(value) {
        return value.reduce(function(pv, cv) {
          return pv + Math.abs(cv);
        }, 0);
      });
      return sum.indexOf(Math.min.apply(null, sum));
    };

    var getPredictorFromCompression = function(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;
    };

    /**
     * @name processPNG
     * @function
     * @ignore
     */
    jsPDFAPI.processPNG = function(imageData, index, alias, compression) {

      var colorSpace,
        filter = this.decode.FLATE_DECODE,
        bitsPerComponent,
        image,
        decodeParameters = "",
        trns,
        colors,
        pal,
        smask,
        pixels,
        len,
        alphaData,
        imgData,
        hasColors,
        pixel,
        i,
        n;

      if (this.__addimage__.isArrayBuffer(imageData))
        imageData = new Uint8Array(imageData);

      if (this.__addimage__.isArrayBufferView(imageData)) {
        image = new PNG(imageData);
        imageData = image.imgData;
        bitsPerComponent = image.bits;
        colorSpace = image.colorSpace;
        colors = image.colors;

        /*
         * 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(image.colorType) !== -1) {
          /*
           * processes 8 bit RGBA and grayscale + alpha images
           */
          if (image.bits === 8) {
            pixels =
              image.pixelBitlength == 32
                ? new Uint32Array(image.decodePixels().buffer)
                : image.pixelBitlength == 16
                ? new Uint16Array(image.decodePixels().buffer)
                : new Uint8Array(image.decodePixels().buffer);
            len = pixels.length;
            imgData = new Uint8Array(len * image.colors);
            alphaData = new Uint8Array(len);
            var pDiff = image.pixelBitlength - image.bits;
            i = 0;
            n = 0;
            var pbl;

            for (; i < len; i++) {
              pixel = pixels[i];
              pbl = 0;

              while (pbl < pDiff) {
                imgData[n++] = (pixel >>> pbl) & 0xff;
                pbl = pbl + image.bits;
              }

              alphaData[i] = (pixel >>> pbl) & 0xff;
            }
          }

          /*
           * processes 16 bit RGBA and grayscale + alpha images
           */
          if (image.bits === 16) {
            pixels = new Uint32Array(image.decodePixels().buffer);
            len = pixels.length;
            imgData = new Uint8Array(
              len * (32 / image.pixelBitlength) * image.colors
            );
            alphaData = new Uint8Array(len * (32 / image.pixelBitlength));
            hasColors = image.colors > 1;
            i = 0;
            n = 0;
            var a = 0;

            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;
            }
            bitsPerComponent = 8;
          }

          if (canCompress(compression)) {
            imageData = compressBytes(
              imgData,
              image.width * image.colors,
              image.colors,
              compression
            );
            smask = compressBytes(alphaData, image.width, 1, compression);
          } else {
            imageData = imgData;
            smask = alphaData;
            filter = undefined;
          }
        }

        /*
         * Indexed png. Each pixel is a palette index.
         */
        if (image.colorType === 3) {
          colorSpace = this.color_spaces.INDEXED;
          pal = image.palette;

          if (image.transparency.indexed) {
            var trans = image.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) {
              pixels = image.decodePixels();
              alphaData = new Uint8Array(pixels.length);
              i = 0;
              len = pixels.length;

              for (; i < len; i++) {
                alphaData[i] = trans[pixels[i]];
              }

              smask = compressBytes(alphaData, image.width, 1);
            }
          }
        }

        var predictor = getPredictorFromCompression(compression);

        if (filter === this.decode.FLATE_DECODE) {
          decodeParameters = "/Predictor " + predictor + " ";
        }
        decodeParameters +=
          "/Colors " +
          colors +
          " /BitsPerComponent " +
          bitsPerComponent +
          " /Columns " +
          image.width;

        if (
          this.__addimage__.isArrayBuffer(imageData) ||
          this.__addimage__.isArrayBufferView(imageData)
        ) {
          imageData = this.__addimage__.arrayBufferToBinaryString(imageData);
        }

        if (
          (smask && this.__addimage__.isArrayBuffer(smask)) ||
          this.__addimage__.isArrayBufferView(smask)
        ) {
          smask = this.__addimage__.arrayBufferToBinaryString(smask);
        }

        return {
          alias: alias,
          data: imageData,
          index: index,
          filter: filter,
          decodeParameters: decodeParameters,
          transparency: trns,
          palette: pal,
          sMask: smask,
          predictor: predictor,
          width: image.width,
          height: image.height,
          bitsPerComponent: bitsPerComponent,
          colorSpace: colorSpace
        };
      }
    };
  })(jsPDF.API);

  /**
   * @license
   * (c) Dean McNamee <dean@gmail.com>, 2013.
   *
   * https://github.com/deanm/omggif
   *
   * 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.
   *
   * omggif is a JavaScript implementation of a GIF 89a encoder and decoder,
   * including animation and compression.  It does not rely on any specific
   * underlying system, so should run in the browser, Node, or Plask.
   */

  function GifReader(buf) {
    var p = 0;

    // - Header (GIF87a or GIF89a).
    if (
      buf[p++] !== 0x47 ||
      buf[p++] !== 0x49 ||
      buf[p++] !== 0x46 ||
      buf[p++] !== 0x38 ||
      ((buf[p++] + 1) & 0xfd) !== 0x38 ||
      buf[p++] !== 0x61
    ) {
      throw new Error("Invalid GIF 87a/89a header.");
    }

    // - Logical Screen Descriptor.
    var width = buf[p++] | (buf[p++] << 8);
    var height = buf[p++] | (buf[p++] << 8);
    var pf0 = buf[p++]; // <Packed Fields>.
    var global_palette_flag = pf0 >> 7;
    var num_global_colors_pow2 = pf0 & 0x7;
    var num_global_colors = 1 << (num_global_colors_pow2 + 1);
    var background = buf[p++];
    buf[p++]; // Pixel aspect ratio (unused?).

    var global_palette_offset = null;
    var global_palette_size = null;

    if (global_palette_flag) {
      global_palette_offset = p;
      global_palette_size = num_global_colors;
      p += num_global_colors * 3; // Seek past palette.
    }

    var no_eof = true;

    var frames = [];

    var delay = 0;
    var transparent_index = null;
    var disposal = 0; // 0 - No disposal specified.
    var loop_count = null;

    this.width = width;
    this.height = height;

    while (no_eof && p < buf.length) {
      switch (buf[p++]) {
        case 0x21: // Graphics Control Extension Block
          switch (buf[p++]) {
            case 0xff: // Application specific block
              // Try if it's a Netscape block (with animation loop counter).
              if (
                buf[p] !== 0x0b || // 21 FF already read, check block size.
                // NETSCAPE2.0
                (buf[p + 1] == 0x4e &&
                  buf[p + 2] == 0x45 &&
                  buf[p + 3] == 0x54 &&
                  buf[p + 4] == 0x53 &&
                  buf[p + 5] == 0x43 &&
                  buf[p + 6] == 0x41 &&
                  buf[p + 7] == 0x50 &&
                  buf[p + 8] == 0x45 &&
                  buf[p + 9] == 0x32 &&
                  buf[p + 10] == 0x2e &&
                  buf[p + 11] == 0x30 &&
                  // Sub-block
                  buf[p + 12] == 0x03 &&
                  buf[p + 13] == 0x01 &&
                  buf[p + 16] == 0)
              ) {
                p += 14;
                loop_count = buf[p++] | (buf[p++] << 8);
                p++; // Skip terminator.
              } else {
                // We don't know what it is, just try to get past it.
                p += 12;
                while (true) {
                  // Seek through subblocks.
                  var block_size = buf[p++];
                  // Bad block size (ex: undefined from an out of bounds read).
                  if (!(block_size >= 0)) throw Error("Invalid block size");
                  if (block_size === 0) break; // 0 size is terminator
                  p += block_size;
                }
              }
              break;

            case 0xf9: // Graphics Control Extension
              if (buf[p++] !== 0x4 || buf[p + 4] !== 0)
                throw new Error("Invalid graphics extension block.");
              var pf1 = buf[p++];
              delay = buf[p++] | (buf[p++] << 8);
              transparent_index = buf[p++];
              if ((pf1 & 1) === 0) transparent_index = null;
              disposal = (pf1 >> 2) & 0x7;
              p++; // Skip terminator.
              break;

            case 0xfe: // Comment Extension.
              while (true) {
                // Seek through subblocks.
                var block_size = buf[p++];
                // Bad block size (ex: undefined from an out of bounds read).
                if (!(block_size >= 0)) throw Error("Invalid block size");
                if (block_size === 0) break; // 0 size is terminator
                // console.log(buf.slice(p, p+block_size).toString('ascii'));
                p += block_size;
              }
              break;

            default:
              throw new Error(
                "Unknown graphic control label: 0x" + buf[p - 1].toString(16)
              );
          }
          break;

        case 0x2c: // Image Descriptor.
          var x = buf[p++] | (buf[p++] << 8);
          var y = buf[p++] | (buf[p++] << 8);
          var w = buf[p++] | (buf[p++] << 8);
          var h = buf[p++] | (buf[p++] << 8);
          var pf2 = buf[p++];
          var local_palette_flag = pf2 >> 7;
          var interlace_flag = (pf2 >> 6) & 1;
          var num_local_colors_pow2 = pf2 & 0x7;
          var num_local_colors = 1 << (num_local_colors_pow2 + 1);
          var palette_offset = global_palette_offset;
          var palette_size = global_palette_size;
          var has_local_palette = false;
          if (local_palette_flag) {
            var has_local_palette = true;
            palette_offset = p; // Override with local palette.
            palette_size = num_local_colors;
            p += num_local_colors * 3; // Seek past palette.
          }

          var data_offset = p;

          p++; // codesize
          while (true) {
            var block_size = buf[p++];
            // Bad block size (ex: undefined from an out of bounds read).
            if (!(block_size >= 0)) throw Error("Invalid block size");
            if (block_size === 0) break; // 0 size is terminator
            p += block_size;
          }

          frames.push({
            x: x,
            y: y,
            width: w,
            height: h,
            has_local_palette: has_local_palette,
            palette_offset: palette_offset,
            palette_size: palette_size,
            data_offset: data_offset,
            data_length: p - data_offset,
            transparent_index: transparent_index,
            interlaced: !!interlace_flag,
            delay: delay,
            disposal: disposal
          });
          break;

        case 0x3b: // Trailer Marker (end of file).
          no_eof = false;
          break;

        default:
          throw new Error("Unknown gif block: 0x" + buf[p - 1].toString(16));
      }
    }

    this.numFrames = function() {
      return frames.length;
    };

    this.loopCount = function() {
      return loop_count;
    };

    this.frameInfo = function(frame_num) {
      if (frame_num < 0 || frame_num >= frames.length)
        throw new Error("Frame index out of range.");
      return frames[frame_num];
    };

    this.decodeAndBlitFrameBGRA = function(frame_num, pixels) {
      var frame = this.frameInfo(frame_num);
      var num_pixels = frame.width * frame.height;
      var index_stream = new Uint8Array(num_pixels); // At most 8-bit indices.
      GifReaderLZWOutputIndexStream(
        buf,
        frame.data_offset,
        index_stream,
        num_pixels
      );
      var palette_offset = frame.palette_offset;

      // NOTE(deanm): It seems to be much faster to compare index to 256 than
      // to === null.  Not sure why, but CompareStub_EQ_STRICT shows up high in
      // the profile, not sure if it's related to using a Uint8Array.
      var trans = frame.transparent_index;
      if (trans === null) trans = 256;

      // We are possibly just blitting to a portion of the entire frame.
      // That is a subrect within the framerect, so the additional pixels
      // must be skipped over after we finished a scanline.
      var framewidth = frame.width;
      var framestride = width - framewidth;
      var xleft = framewidth; // Number of subrect pixels left in scanline.

      // Output indices of the top left and bottom right corners of the subrect.
      var opbeg = (frame.y * width + frame.x) * 4;
      var opend = ((frame.y + frame.height) * width + frame.x) * 4;
      var op = opbeg;

      var scanstride = framestride * 4;

      // Use scanstride to skip past the rows when interlacing.  This is skipping
      // 7 rows for the first two passes, then 3 then 1.
      if (frame.interlaced === true) {
        scanstride += width * 4 * 7; // Pass 1.
      }

      var interlaceskip = 8; // Tracking the row interval in the current pass.

      for (var i = 0, il = index_stream.length; i < il; ++i) {
        var index = index_stream[i];

        if (xleft === 0) {
          // Beginning of new scan line
          op += scanstride;
          xleft = framewidth;
          if (op >= opend) {
            // Catch the wrap to switch passes when interlacing.
            scanstride = framestride * 4 + width * 4 * (interlaceskip - 1);
            // interlaceskip / 2 * 4 is interlaceskip << 1.
            op = opbeg + (framewidth + framestride) * (interlaceskip << 1);
            interlaceskip >>= 1;
          }
        }

        if (index === trans) {
          op += 4;
        } else {
          var r = buf[palette_offset + index * 3];
          var g = buf[palette_offset + index * 3 + 1];
          var b = buf[palette_offset + index * 3 + 2];
          pixels[op++] = b;
          pixels[op++] = g;
          pixels[op++] = r;
          pixels[op++] = 255;
        }
        --xleft;
      }
    };

    // I will go to copy and paste hell one day...
    this.decodeAndBlitFrameRGBA = function(frame_num, pixels) {
      var frame = this.frameInfo(frame_num);
      var num_pixels = frame.width * frame.height;
      var index_stream = new Uint8Array(num_pixels); // At most 8-bit indices.
      GifReaderLZWOutputIndexStream(
        buf,
        frame.data_offset,
        index_stream,
        num_pixels
      );
      var palette_offset = frame.palette_offset;

      // NOTE(deanm): It seems to be much faster to compare index to 256 than
      // to === null.  Not sure why, but CompareStub_EQ_STRICT shows up high in
      // the profile, not sure if it's related to using a Uint8Array.
      var trans = frame.transparent_index;
      if (trans === null) trans = 256;

      // We are possibly just blitting to a portion of the entire frame.
      // That is a subrect within the framerect, so the additional pixels
      // must be skipped over after we finished a scanline.
      var framewidth = frame.width;
      var framestride = width - framewidth;
      var xleft = framewidth; // Number of subrect pixels left in scanline.

      // Output indices of the top left and bottom right corners of the subrect.
      var opbeg = (frame.y * width + frame.x) * 4;
      var opend = ((frame.y + frame.height) * width + frame.x) * 4;
      var op = opbeg;

      var scanstride = framestride * 4;

      // Use scanstride to skip past the rows when interlacing.  This is skipping
      // 7 rows for the first two passes, then 3 then 1.
      if (frame.interlaced === true) {
        scanstride += width * 4 * 7; // Pass 1.
      }

      var interlaceskip = 8; // Tracking the row interval in the current pass.

      for (var i = 0, il = index_stream.length; i < il; ++i) {
        var index = index_stream[i];

        if (xleft === 0) {
          // Beginning of new scan line
          op += scanstride;
          xleft = framewidth;
          if (op >= opend) {
            // Catch the wrap to switch passes when interlacing.
            scanstride = framestride * 4 + width * 4 * (interlaceskip - 1);
            // interlaceskip / 2 * 4 is interlaceskip << 1.
            op = opbeg + (framewidth + framestride) * (interlaceskip << 1);
            interlaceskip >>= 1;
          }
        }

        if (index === trans) {
          op += 4;
        } else {
          var r = buf[palette_offset + index * 3];
          var g = buf[palette_offset + index * 3 + 1];
          var b = buf[palette_offset + index * 3 + 2];
          pixels[op++] = r;
          pixels[op++] = g;
          pixels[op++] = b;
          pixels[op++] = 255;
        }
        --xleft;
      }
    };
  }

  function GifReaderLZWOutputIndexStream(code_stream, p, output, output_length) {
    var min_code_size = code_stream[p++];

    var clear_code = 1 << min_code_size;
    var eoi_code = clear_code + 1;
    var next_code = eoi_code + 1;

    var cur_code_size = min_code_size + 1; // Number of bits per code.
    // NOTE: This shares the same name as the encoder, but has a different
    // meaning here.  Here this masks each code coming from the code stream.
    var code_mask = (1 << cur_code_size) - 1;
    var cur_shift = 0;
    var cur = 0;

    var op = 0; // Output pointer.

    var subblock_size = code_stream[p++];

    // TODO(deanm): Would using a TypedArray be any faster?  At least it would
    // solve the fast mode / backing store uncertainty.
    // var code_table = Array(4096);
    var code_table = new Int32Array(4096); // Can be signed, we only use 20 bits.

    var prev_code = null; // Track code-1.

    while (true) {
      // Read up to two bytes, making sure we always 12-bits for max sized code.
      while (cur_shift < 16) {
        if (subblock_size === 0) break; // No more data to be read.

        cur |= code_stream[p++] << cur_shift;
        cur_shift += 8;

        if (subblock_size === 1) {
          // Never let it get to 0 to hold logic above.
          subblock_size = code_stream[p++]; // Next subblock.
        } else {
          --subblock_size;
        }
      }

      // TODO(deanm): We should never really get here, we should have received
      // and EOI.
      if (cur_shift < cur_code_size) break;

      var code = cur & code_mask;
      cur >>= cur_code_size;
      cur_shift -= cur_code_size;

      // TODO(deanm): Maybe should check that the first code was a clear code,
      // at least this is what you're supposed to do.  But actually our encoder
      // now doesn't emit a clear code first anyway.
      if (code === clear_code) {
        // We don't actually have to clear the table.  This could be a good idea
        // for greater error checking, but we don't really do any anyway.  We
        // will just track it with next_code and overwrite old entries.

        next_code = eoi_code + 1;
        cur_code_size = min_code_size + 1;
        code_mask = (1 << cur_code_size) - 1;

        // Don't update prev_code ?
        prev_code = null;
        continue;
      } else if (code === eoi_code) {
        break;
      }

      // We have a similar situation as the decoder, where we want to store
      // variable length entries (code table entries), but we want to do in a
      // faster manner than an array of arrays.  The code below stores sort of a
      // linked list within the code table, and then "chases" through it to
      // construct the dictionary entries.  When a new entry is created, just the
      // last byte is stored, and the rest (prefix) of the entry is only
      // referenced by its table entry.  Then the code chases through the
      // prefixes until it reaches a single byte code.  We have to chase twice,
      // first to compute the length, and then to actually copy the data to the
      // output (backwards, since we know the length).  The alternative would be
      // storing something in an intermediate stack, but that doesn't make any
      // more sense.  I implemented an approach where it also stored the length
      // in the code table, although it's a bit tricky because you run out of
      // bits (12 + 12 + 8), but I didn't measure much improvements (the table
      // entries are generally not the long).  Even when I created benchmarks for
      // very long table entries the complexity did not seem worth it.
      // The code table stores the prefix entry in 12 bits and then the suffix
      // byte in 8 bits, so each entry is 20 bits.

      var chase_code = code < next_code ? code : prev_code;

      // Chase what we will output, either {CODE} or {CODE-1}.
      var chase_length = 0;
      var chase = chase_code;
      while (chase > clear_code) {
        chase = code_table[chase] >> 8;
        ++chase_length;
      }

      var k = chase;

      var op_end = op + chase_length + (chase_code !== code ? 1 : 0);
      if (op_end > output_length) {
        console.log("Warning, gif stream longer than expected.");
        return;
      }

      // Already have the first byte from the chase, might as well write it fast.
      output[op++] = k;

      op += chase_length;
      var b = op; // Track pointer, writing backwards.

      if (chase_code !== code)
        // The case of emitting {CODE-1} + k.
        output[op++] = k;

      chase = chase_code;
      while (chase_length--) {
        chase = code_table[chase];
        output[--b] = chase & 0xff; // Write backwards.
        chase >>= 8; // Pull down to the prefix code.
      }

      if (prev_code !== null && next_code < 4096) {
        code_table[next_code++] = (prev_code << 8) | k;
        // TODO(deanm): Figure out this clearing vs code growth logic better.  I
        // have an feeling that it should just happen somewhere else, for now it
        // is awkward between when we grow past the max and then hit a clear code.
        // For now just check if we hit the max 12-bits (then a clear code should
        // follow, also of course encoded in 12-bits).
        if (next_code >= code_mask + 1 && cur_code_size < 12) {
          ++cur_code_size;
          code_mask = (code_mask << 1) | 1;
        }
      }

      prev_code = code;
    }

    if (op !== output_length) {
      console.log("Warning, gif stream shorter than expected.");
    }

    return output;
  }

  /**
   * @license
    Copyright (c) 2008, Adobe Systems Incorporated
    All rights reserved.

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions are
    met:

    * Redistributions of source code must retain the above copyright notice,
      this list of conditions and the following disclaimer.

    * 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.

    * Neither the name of Adobe Systems Incorporated nor the names of its
      contributors may be used to endorse or promote products derived from
      this software without specific prior written permission.

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
    IS" AND ANY EXPRESS 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 THE COPYRIGHT OWNER OR
    CONTRIBUTORS 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.
  */
  /*
  JPEG encoder ported to JavaScript and optimized by Andreas Ritter, www.bytestrom.eu, 11/2009

  Basic GUI blocking jpeg encoder
  */

  function JPEGEncoder(quality) {
    var ffloor = Math.floor;
    var YTable = new Array(64);
    var UVTable = new Array(64);
    var fdtbl_Y = new Array(64);
    var fdtbl_UV = new Array(64);
    var YDC_HT;
    var UVDC_HT;
    var YAC_HT;
    var UVAC_HT;

    var bitcode = new Array(65535);
    var category = new Array(65535);
    var outputfDCTQuant = new Array(64);
    var DU = new Array(64);
    var byteout = [];
    var bytenew = 0;
    var bytepos = 7;

    var YDU = new Array(64);
    var UDU = new Array(64);
    var VDU = new Array(64);
    var clt = new Array(256);
    var RGB_YUV_TABLE = new Array(2048);
    var currentQuality;

    var ZigZag = [
      0,
      1,
      5,
      6,
      14,
      15,
      27,
      28,
      2,
      4,
      7,
      13,
      16,
      26,
      29,
      42,
      3,
      8,
      12,
      17,
      25,
      30,
      41,
      43,
      9,
      11,
      18,
      24,
      31,
      40,
      44,
      53,
      10,
      19,
      23,
      32,
      39,
      45,
      52,
      54,
      20,
      22,
      33,
      38,
      46,
      51,
      55,
      60,
      21,
      34,
      37,
      47,
      50,
      56,
      59,
      61,
      35,
      36,
      48,
      49,
      57,
      58,
      62,
      63
    ];

    var std_dc_luminance_nrcodes = [
      0,
      0,
      1,
      5,
      1,
      1,
      1,
      1,
      1,
      1,
      0,
      0,
      0,
      0,
      0,
      0,
      0
    ];
    var std_dc_luminance_values = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
    var std_ac_luminance_nrcodes = [
      0,
      0,
      2,
      1,
      3,
      3,
      2,
      4,
      3,
      5,
      5,
      4,
      4,
      0,
      0,
      1,
      0x7d
    ];
    var std_ac_luminance_values = [
      0x01,
      0x02,
      0x03,
      0x00,
      0x04,
      0x11,
      0x05,
      0x12,
      0x21,
      0x31,
      0x41,
      0x06,
      0x13,
      0x51,
      0x61,
      0x07,
      0x22,
      0x71,
      0x14,
      0x32,
      0x81,
      0x91,
      0xa1,
      0x08,
      0x23,
      0x42,
      0xb1,
      0xc1,
      0x15,
      0x52,
      0xd1,
      0xf0,
      0x24,
      0x33,
      0x62,
      0x72,
      0x82,
      0x09,
      0x0a,
      0x16,
      0x17,
      0x18,
      0x19,
      0x1a,
      0x25,
      0x26,
      0x27,
      0x28,
      0x29,
      0x2a,
      0x34,
      0x35,
      0x36,
      0x37,
      0x38,
      0x39,
      0x3a,
      0x43,
      0x44,
      0x45,
      0x46,
      0x47,
      0x48,
      0x49,
      0x4a,
      0x53,
      0x54,
      0x55,
      0x56,
      0x57,
      0x58,
      0x59,
      0x5a,
      0x63,
      0x64,
      0x65,
      0x66,
      0x67,
      0x68,
      0x69,
      0x6a,
      0x73,
      0x74,
      0x75,
      0x76,
      0x77,
      0x78,
      0x79,
      0x7a,
      0x83,
      0x84,
      0x85,
      0x86,
      0x87,
      0x88,
      0x89,
      0x8a,
      0x92,
      0x93,
      0x94,
      0x95,
      0x96,
      0x97,
      0x98,
      0x99,
      0x9a,
      0xa2,
      0xa3,
      0xa4,
      0xa5,
      0xa6,
      0xa7,
      0xa8,
      0xa9,
      0xaa,
      0xb2,
      0xb3,
      0xb4,
      0xb5,
      0xb6,
      0xb7,
      0xb8,
      0xb9,
      0xba,
      0xc2,
      0xc3,
      0xc4,
      0xc5,
      0xc6,
      0xc7,
      0xc8,
      0xc9,
      0xca,
      0xd2,
      0xd3,
      0xd4,
      0xd5,
      0xd6,
      0xd7,
      0xd8,
      0xd9,
      0xda,
      0xe1,
      0xe2,
      0xe3,
      0xe4,
      0xe5,
      0xe6,
      0xe7,
      0xe8,
      0xe9,
      0xea,
      0xf1,
      0xf2,
      0xf3,
      0xf4,
      0xf5,
      0xf6,
      0xf7,
      0xf8,
      0xf9,
      0xfa
    ];

    var std_dc_chrominance_nrcodes = [
      0,
      0,
      3,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      0,
      0,
      0,
      0,
      0
    ];
    var std_dc_chrominance_values = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
    var std_ac_chrominance_nrcodes = [
      0,
      0,
      2,
      1,
      2,
      4,
      4,
      3,
      4,
      7,
      5,
      4,
      4,
      0,
      1,
      2,
      0x77
    ];
    var std_ac_chrominance_values = [
      0x00,
      0x01,
      0x02,
      0x03,
      0x11,
      0x04,
      0x05,
      0x21,
      0x31,
      0x06,
      0x12,
      0x41,
      0x51,
      0x07,
      0x61,
      0x71,
      0x13,
      0x22,
      0x32,
      0x81,
      0x08,
      0x14,
      0x42,
      0x91,
      0xa1,
      0xb1,
      0xc1,
      0x09,
      0x23,
      0x33,
      0x52,
      0xf0,
      0x15,
      0x62,
      0x72,
      0xd1,
      0x0a,
      0x16,
      0x24,
      0x34,
      0xe1,
      0x25,
      0xf1,
      0x17,
      0x18,
      0x19,
      0x1a,
      0x26,
      0x27,
      0x28,
      0x29,
      0x2a,
      0x35,
      0x36,
      0x37,
      0x38,
      0x39,
      0x3a,
      0x43,
      0x44,
      0x45,
      0x46,
      0x47,
      0x48,
      0x49,
      0x4a,
      0x53,
      0x54,
      0x55,
      0x56,
      0x57,
      0x58,
      0x59,
      0x5a,
      0x63,
      0x64,
      0x65,
      0x66,
      0x67,
      0x68,
      0x69,
      0x6a,
      0x73,
      0x74,
      0x75,
      0x76,
      0x77,
      0x78,
      0x79,
      0x7a,
      0x82,
      0x83,
      0x84,
      0x85,
      0x86,
      0x87,
      0x88,
      0x89,
      0x8a,
      0x92,
      0x93,
      0x94,
      0x95,
      0x96,
      0x97,
      0x98,
      0x99,
      0x9a,
      0xa2,
      0xa3,
      0xa4,
      0xa5,
      0xa6,
      0xa7,
      0xa8,
      0xa9,
      0xaa,
      0xb2,
      0xb3,
      0xb4,
      0xb5,
      0xb6,
      0xb7,
      0xb8,
      0xb9,
      0xba,
      0xc2,
      0xc3,
      0xc4,
      0xc5,
      0xc6,
      0xc7,
      0xc8,
      0xc9,
      0xca,
      0xd2,
      0xd3,
      0xd4,
      0xd5,
      0xd6,
      0xd7,
      0xd8,
      0xd9,
      0xda,
      0xe2,
      0xe3,
      0xe4,
      0xe5,
      0xe6,
      0xe7,
      0xe8,
      0xe9,
      0xea,
      0xf2,
      0xf3,
      0xf4,
      0xf5,
      0xf6,
      0xf7,
      0xf8,
      0xf9,
      0xfa
    ];

    function initQuantTables(sf) {
      var YQT = [
        16,
        11,
        10,
        16,
        24,
        40,
        51,
        61,
        12,
        12,
        14,
        19,
        26,
        58,
        60,
        55,
        14,
        13,
        16,
        24,
        40,
        57,
        69,
        56,
        14,
        17,
        22,
        29,
        51,
        87,
        80,
        62,
        18,
        22,
        37,
        56,
        68,
        109,
        103,
        77,
        24,
        35,
        55,
        64,
        81,
        104,
        113,
        92,
        49,
        64,
        78,
        87,
        103,
        121,
        120,
        101,
        72,
        92,
        95,
        98,
        112,
        100,
        103,
        99
      ];

      for (var i = 0; i < 64; i++) {
        var t = ffloor((YQT[i] * sf + 50) / 100);
        t = Math.min(Math.max(t, 1), 255);
        YTable[ZigZag[i]] = t;
      }
      var UVQT = [
        17,
        18,
        24,
        47,
        99,
        99,
        99,
        99,
        18,
        21,
        26,
        66,
        99,
        99,
        99,
        99,
        24,
        26,
        56,
        99,
        99,
        99,
        99,
        99,
        47,
        66,
        99,
        99,
        99,
        99,
        99,
        99,
        99,
        99,
        99,
        99,
        99,
        99,
        99,
        99,
        99,
        99,
        99,
        99,
        99,
        99,
        99,
        99,
        99,
        99,
        99,
        99,
        99,
        99,
        99,
        99,
        99,
        99,
        99,
        99,
        99,
        99,
        99,
        99
      ];
      for (var j = 0; j < 64; j++) {
        var u = ffloor((UVQT[j] * sf + 50) / 100);
        u = Math.min(Math.max(u, 1), 255);
        UVTable[ZigZag[j]] = u;
      }
      var aasf = [
        1.0,
        1.387039845,
        1.306562965,
        1.175875602,
        1.0,
        0.785694958,
        0.5411961,
        0.275899379
      ];
      var k = 0;
      for (var row = 0; row < 8; row++) {
        for (var col = 0; col < 8; col++) {
          fdtbl_Y[k] = 1.0 / (YTable[ZigZag[k]] * aasf[row] * aasf[col] * 8.0);
          fdtbl_UV[k] = 1.0 / (UVTable[ZigZag[k]] * aasf[row] * aasf[col] * 8.0);
          k++;
        }
      }
    }

    function computeHuffmanTbl(nrcodes, std_table) {
      var codevalue = 0;
      var pos_in_table = 0;
      var HT = new Array();
      for (var k = 1; k <= 16; k++) {
        for (var j = 1; j <= nrcodes[k]; j++) {
          HT[std_table[pos_in_table]] = [];
          HT[std_table[pos_in_table]][0] = codevalue;
          HT[std_table[pos_in_table]][1] = k;
          pos_in_table++;
          codevalue++;
        }
        codevalue *= 2;
      }
      return HT;
    }

    function initHuffmanTbl() {
      YDC_HT = computeHuffmanTbl(
        std_dc_luminance_nrcodes,
        std_dc_luminance_values
      );
      UVDC_HT = computeHuffmanTbl(
        std_dc_chrominance_nrcodes,
        std_dc_chrominance_values
      );
      YAC_HT = computeHuffmanTbl(
        std_ac_luminance_nrcodes,
        std_ac_luminance_values
      );
      UVAC_HT = computeHuffmanTbl(
        std_ac_chrominance_nrcodes,
        std_ac_chrominance_values
      );
    }

    function initCategoryNumber() {
      var nrlower = 1;
      var nrupper = 2;
      for (var cat = 1; cat <= 15; cat++) {
        //Positive numbers
        for (var nr = nrlower; nr < nrupper; nr++) {
          category[32767 + nr] = cat;
          bitcode[32767 + nr] = [];
          bitcode[32767 + nr][1] = cat;
          bitcode[32767 + nr][0] = nr;
        }
        //Negative numbers
        for (var nrneg = -(nrupper - 1); nrneg <= -nrlower; nrneg++) {
          category[32767 + nrneg] = cat;
          bitcode[32767 + nrneg] = [];
          bitcode[32767 + nrneg][1] = cat;
          bitcode[32767 + nrneg][0] = nrupper - 1 + nrneg;
        }
        nrlower <<= 1;
        nrupper <<= 1;
      }
    }

    function initRGBYUVTable() {
      for (var i = 0; i < 256; i++) {
        RGB_YUV_TABLE[i] = 19595 * i;
        RGB_YUV_TABLE[(i + 256) >> 0] = 38470 * i;
        RGB_YUV_TABLE[(i + 512) >> 0] = 7471 * i + 0x8000;
        RGB_YUV_TABLE[(i + 768) >> 0] = -11059 * i;
        RGB_YUV_TABLE[(i + 1024) >> 0] = -21709 * i;
        RGB_YUV_TABLE[(i + 1280) >> 0] = 32768 * i + 0x807fff;
        RGB_YUV_TABLE[(i + 1536) >> 0] = -27439 * i;
        RGB_YUV_TABLE[(i + 1792) >> 0] = -5329 * i;
      }
    }

    // IO functions
    function writeBits(bs) {
      var value = bs[0];
      var posval = bs[1] - 1;
      while (posval >= 0) {
        if (value & (1 << posval)) {
          bytenew |= 1 << bytepos;
        }
        posval--;
        bytepos--;
        if (bytepos < 0) {
          if (bytenew == 0xff) {
            writeByte(0xff);
            writeByte(0);
          } else {
            writeByte(bytenew);
          }
          bytepos = 7;
          bytenew = 0;
        }
      }
    }

    function writeByte(value) {
      //byteout.push(clt[value]); // write char directly instead of converting later
      byteout.push(value);
    }

    function writeWord(value) {
      writeByte((value >> 8) & 0xff);
      writeByte(value & 0xff);
    }

    // DCT & quantization core
    function fDCTQuant(data, fdtbl) {
      var d0, d1, d2, d3, d4, d5, d6, d7;
      /* Pass 1: process rows. */
      var dataOff = 0;
      var i;
      var I8 = 8;
      var I64 = 64;
      for (i = 0; i < I8; ++i) {
        d0 = data[dataOff];
        d1 = data[dataOff + 1];
        d2 = data[dataOff + 2];
        d3 = data[dataOff + 3];
        d4 = data[dataOff + 4];
        d5 = data[dataOff + 5];
        d6 = data[dataOff + 6];
        d7 = data[dataOff + 7];

        var tmp0 = d0 + d7;
        var tmp7 = d0 - d7;
        var tmp1 = d1 + d6;
        var tmp6 = d1 - d6;
        var tmp2 = d2 + d5;
        var tmp5 = d2 - d5;
        var tmp3 = d3 + d4;
        var tmp4 = d3 - d4;

        /* Even part */
        var tmp10 = tmp0 + tmp3; /* phase 2 */
        var tmp13 = tmp0 - tmp3;
        var tmp11 = tmp1 + tmp2;
        var tmp12 = tmp1 - tmp2;

        data[dataOff] = tmp10 + tmp11; /* phase 3 */
        data[dataOff + 4] = tmp10 - tmp11;

        var z1 = (tmp12 + tmp13) * 0.707106781; /* c4 */
        data[dataOff + 2] = tmp13 + z1; /* phase 5 */
        data[dataOff + 6] = tmp13 - z1;

        /* Odd part */
        tmp10 = tmp4 + tmp5; /* phase 2 */
        tmp11 = tmp5 + tmp6;
        tmp12 = tmp6 + tmp7;

        /* The rotator is modified from fig 4-8 to avoid extra negations. */
        var z5 = (tmp10 - tmp12) * 0.382683433; /* c6 */
        var z2 = 0.5411961 * tmp10 + z5; /* c2-c6 */
        var z4 = 1.306562965 * tmp12 + z5; /* c2+c6 */
        var z3 = tmp11 * 0.707106781; /* c4 */

        var z11 = tmp7 + z3; /* phase 5 */
        var z13 = tmp7 - z3;

        data[dataOff + 5] = z13 + z2; /* phase 6 */
        data[dataOff + 3] = z13 - z2;
        data[dataOff + 1] = z11 + z4;
        data[dataOff + 7] = z11 - z4;

        dataOff += 8; /* advance pointer to next row */
      }

      /* Pass 2: process columns. */
      dataOff = 0;
      for (i = 0; i < I8; ++i) {
        d0 = data[dataOff];
        d1 = data[dataOff + 8];
        d2 = data[dataOff + 16];
        d3 = data[dataOff + 24];
        d4 = data[dataOff + 32];
        d5 = data[dataOff + 40];
        d6 = data[dataOff + 48];
        d7 = data[dataOff + 56];

        var tmp0p2 = d0 + d7;
        var tmp7p2 = d0 - d7;
        var tmp1p2 = d1 + d6;
        var tmp6p2 = d1 - d6;
        var tmp2p2 = d2 + d5;
        var tmp5p2 = d2 - d5;
        var tmp3p2 = d3 + d4;
        var tmp4p2 = d3 - d4;

        /* Even part */
        var tmp10p2 = tmp0p2 + tmp3p2; /* phase 2 */
        var tmp13p2 = tmp0p2 - tmp3p2;
        var tmp11p2 = tmp1p2 + tmp2p2;
        var tmp12p2 = tmp1p2 - tmp2p2;

        data[dataOff] = tmp10p2 + tmp11p2; /* phase 3 */
        data[dataOff + 32] = tmp10p2 - tmp11p2;

        var z1p2 = (tmp12p2 + tmp13p2) * 0.707106781; /* c4 */
        data[dataOff + 16] = tmp13p2 + z1p2; /* phase 5 */
        data[dataOff + 48] = tmp13p2 - z1p2;

        /* Odd part */
        tmp10p2 = tmp4p2 + tmp5p2; /* phase 2 */
        tmp11p2 = tmp5p2 + tmp6p2;
        tmp12p2 = tmp6p2 + tmp7p2;

        /* The rotator is modified from fig 4-8 to avoid extra negations. */
        var z5p2 = (tmp10p2 - tmp12p2) * 0.382683433; /* c6 */
        var z2p2 = 0.5411961 * tmp10p2 + z5p2; /* c2-c6 */
        var z4p2 = 1.306562965 * tmp12p2 + z5p2; /* c2+c6 */
        var z3p2 = tmp11p2 * 0.707106781; /* c4 */

        var z11p2 = tmp7p2 + z3p2; /* phase 5 */
        var z13p2 = tmp7p2 - z3p2;

        data[dataOff + 40] = z13p2 + z2p2; /* phase 6 */
        data[dataOff + 24] = z13p2 - z2p2;
        data[dataOff + 8] = z11p2 + z4p2;
        data[dataOff + 56] = z11p2 - z4p2;

        dataOff++; /* advance pointer to next column */
      }

      // Quantize/descale the coefficients
      var fDCTQuant;
      for (i = 0; i < I64; ++i) {
        // Apply the quantization and scaling factor & Round to nearest integer
        fDCTQuant = data[i] * fdtbl[i];
        outputfDCTQuant[i] =
          fDCTQuant > 0.0 ? (fDCTQuant + 0.5) | 0 : (fDCTQuant - 0.5) | 0;
        //outputfDCTQuant[i] = fround(fDCTQuant);
      }
      return outputfDCTQuant;
    }

    function writeAPP0() {
      writeWord(0xffe0); // marker
      writeWord(16); // length
      writeByte(0x4a); // J
      writeByte(0x46); // F
      writeByte(0x49); // I
      writeByte(0x46); // F
      writeByte(0); // = "JFIF",'\0'
      writeByte(1); // versionhi
      writeByte(1); // versionlo
      writeByte(0); // xyunits
      writeWord(1); // xdensity
      writeWord(1); // ydensity
      writeByte(0); // thumbnwidth
      writeByte(0); // thumbnheight
    }

    function writeSOF0(width, height) {
      writeWord(0xffc0); // marker
      writeWord(17); // length, truecolor YUV JPG
      writeByte(8); // precision
      writeWord(height);
      writeWord(width);
      writeByte(3); // nrofcomponents
      writeByte(1); // IdY
      writeByte(0x11); // HVY
      writeByte(0); // QTY
      writeByte(2); // IdU
      writeByte(0x11); // HVU
      writeByte(1); // QTU
      writeByte(3); // IdV
      writeByte(0x11); // HVV
      writeByte(1); // QTV
    }

    function writeDQT() {
      writeWord(0xffdb); // marker
      writeWord(132); // length
      writeByte(0);
      for (var i = 0; i < 64; i++) {
        writeByte(YTable[i]);
      }
      writeByte(1);
      for (var j = 0; j < 64; j++) {
        writeByte(UVTable[j]);
      }
    }

    function writeDHT() {
      writeWord(0xffc4); // marker
      writeWord(0x01a2); // length

      writeByte(0); // HTYDCinfo
      for (var i = 0; i < 16; i++) {
        writeByte(std_dc_luminance_nrcodes[i + 1]);
      }
      for (var j = 0; j <= 11; j++) {
        writeByte(std_dc_luminance_values[j]);
      }

      writeByte(0x10); // HTYACinfo
      for (var k = 0; k < 16; k++) {
        writeByte(std_ac_luminance_nrcodes[k + 1]);
      }
      for (var l = 0; l <= 161; l++) {
        writeByte(std_ac_luminance_values[l]);
      }

      writeByte(1); // HTUDCinfo
      for (var m = 0; m < 16; m++) {
        writeByte(std_dc_chrominance_nrcodes[m + 1]);
      }
      for (var n = 0; n <= 11; n++) {
        writeByte(std_dc_chrominance_values[n]);
      }

      writeByte(0x11); // HTUACinfo
      for (var o = 0; o < 16; o++) {
        writeByte(std_ac_chrominance_nrcodes[o + 1]);
      }
      for (var p = 0; p <= 161; p++) {
        writeByte(std_ac_chrominance_values[p]);
      }
    }

    function writeSOS() {
      writeWord(0xffda); // marker
      writeWord(12); // length
      writeByte(3); // nrofcomponents
      writeByte(1); // IdY
      writeByte(0); // HTY
      writeByte(2); // IdU
      writeByte(0x11); // HTU
      writeByte(3); // IdV
      writeByte(0x11); // HTV
      writeByte(0); // Ss
      writeByte(0x3f); // Se
      writeByte(0); // Bf
    }

    function processDU(CDU, fdtbl, DC, HTDC, HTAC) {
      var EOB = HTAC[0x00];
      var M16zeroes = HTAC[0xf0];
      var pos;
      var I16 = 16;
      var I63 = 63;
      var I64 = 64;
      var DU_DCT = fDCTQuant(CDU, fdtbl);
      //ZigZag reorder
      for (var j = 0; j < I64; ++j) {
        DU[ZigZag[j]] = DU_DCT[j];
      }
      var Diff = DU[0] - DC;
      DC = DU[0];
      //Encode DC
      if (Diff == 0) {
        writeBits(HTDC[0]); // Diff might be 0
      } else {
        pos = 32767 + Diff;
        writeBits(HTDC[category[pos]]);
        writeBits(bitcode[pos]);
      }
      //Encode ACs
      var end0pos = 63; // was const... which is crazy
      while (end0pos > 0 && DU[end0pos] == 0) {
        end0pos--;
      }
      //end0pos = first element in reverse order !=0
      if (end0pos == 0) {
        writeBits(EOB);
        return DC;
      }
      var i = 1;
      var lng;
      while (i <= end0pos) {
        var startpos = i;
        while (DU[i] == 0 && i <= end0pos) {
          ++i;
        }
        var nrzeroes = i - startpos;
        if (nrzeroes >= I16) {
          lng = nrzeroes >> 4;
          for (var nrmarker = 1; nrmarker <= lng; ++nrmarker)
            writeBits(M16zeroes);
          nrzeroes = nrzeroes & 0xf;
        }
        pos = 32767 + DU[i];
        writeBits(HTAC[(nrzeroes << 4) + category[pos]]);
        writeBits(bitcode[pos]);
        i++;
      }
      if (end0pos != I63) {
        writeBits(EOB);
      }
      return DC;
    }

    function initCharLookupTable() {
      var sfcc = String.fromCharCode;
      for (var i = 0; i < 256; i++) {
        ///// ACHTUNG // 255
        clt[i] = sfcc(i);
      }
    }

    this.encode = function(
      image,
      quality // image data object
    ) {
      if (quality) setQuality(quality);

      // Initialize bit writer
      byteout = new Array();
      bytenew = 0;
      bytepos = 7;

      // Add JPEG headers
      writeWord(0xffd8); // SOI
      writeAPP0();
      writeDQT();
      writeSOF0(image.width, image.height);
      writeDHT();
      writeSOS();

      // Encode 8x8 macroblocks
      var DCY = 0;
      var DCU = 0;
      var DCV = 0;

      bytenew = 0;
      bytepos = 7;

      this.encode.displayName = "_encode_";

      var imageData = image.data;
      var width = image.width;
      var height = image.height;

      var quadWidth = width * 4;

      var x,
        y = 0;
      var r, g, b;
      var start, p, col, row, pos;
      while (y < height) {
        x = 0;
        while (x < quadWidth) {
          start = quadWidth * y + x;
          col = -1;
          row = 0;

          for (pos = 0; pos < 64; pos++) {
            row = pos >> 3; // /8
            col = (pos & 7) * 4; // %8
            p = start + row * quadWidth + col;

            if (y + row >= height) {
              // padding bottom
              p -= quadWidth * (y + 1 + row - height);
            }

            if (x + col >= quadWidth) {
              // padding right
              p -= x + col - quadWidth + 4;
            }

            r = imageData[p++];
            g = imageData[p++];
            b = imageData[p++];

            /* // calculate YUV values dynamically
  					YDU[pos]=((( 0.29900)*r+( 0.58700)*g+( 0.11400)*b))-128; //-0x80
  					UDU[pos]=(((-0.16874)*r+(-0.33126)*g+( 0.50000)*b));
  					VDU[pos]=((( 0.50000)*r+(-0.41869)*g+(-0.08131)*b));
  					*/

            // use lookup table (slightly faster)
            YDU[pos] =
              ((RGB_YUV_TABLE[r] +
                RGB_YUV_TABLE[(g + 256) >> 0] +
                RGB_YUV_TABLE[(b + 512) >> 0]) >>
                16) -
              128;
            UDU[pos] =
              ((RGB_YUV_TABLE[(r + 768) >> 0] +
                RGB_YUV_TABLE[(g + 1024) >> 0] +
                RGB_YUV_TABLE[(b + 1280) >> 0]) >>
                16) -
              128;
            VDU[pos] =
              ((RGB_YUV_TABLE[(r + 1280) >> 0] +
                RGB_YUV_TABLE[(g + 1536) >> 0] +
                RGB_YUV_TABLE[(b + 1792) >> 0]) >>
                16) -
              128;
          }

          DCY = processDU(YDU, fdtbl_Y, DCY, YDC_HT, YAC_HT);
          DCU = processDU(UDU, fdtbl_UV, DCU, UVDC_HT, UVAC_HT);
          DCV = processDU(VDU, fdtbl_UV, DCV, UVDC_HT, UVAC_HT);
          x += 32;
        }
        y += 8;
      }

      ////////////////////////////////////////////////////////////////

      // Do the bit alignment of the EOI marker
      if (bytepos >= 0) {
        var fillbits = [];
        fillbits[1] = bytepos + 1;
        fillbits[0] = (1 << (bytepos + 1)) - 1;
        writeBits(fillbits);
      }

      writeWord(0xffd9); //EOI

      return new Uint8Array(byteout);
    };

    function setQuality(quality) {
      quality = Math.min(Math.max(quality, 1), 100);

      if (currentQuality == quality) return; // don't recalc if unchanged

      var sf =
        quality < 50 ? Math.floor(5000 / quality) : Math.floor(200 - quality * 2);

      initQuantTables(sf);
      currentQuality = quality;
      //console.log('Quality set to: '+quality +'%');
    }

    function init() {
      quality = quality || 50;
      // Create tables
      initCharLookupTable();
      initHuffmanTbl();
      initCategoryNumber();
      initRGBYUVTable();

      setQuality(quality);
    }
    init();
  }

  /**
   * @license
   * Copyright (c) 2017 Aras Abbasi
   *
   * Licensed under the MIT License.
   * http://opensource.org/licenses/mit-license
   */

  /**
   * jsPDF Gif Support PlugIn
   *
   * @name gif_support
   * @module
   */
  (function(jsPDFAPI) {

    jsPDFAPI.processGIF89A = function(imageData, index, alias, compression) {
      var reader = new GifReader(imageData);
      var width = reader.width,
        height = reader.height;
      var qu = 100;
      var pixels = [];

      reader.decodeAndBlitFrameRGBA(0, pixels);
      var rawImageData = {
        data: pixels,
        width: width,
        height: height
      };

      var encoder = new JPEGEncoder(qu);
      var data = encoder.encode(rawImageData, qu);
      return jsPDFAPI.processJPEG.call(this, data, index, alias, compression);
    };

    jsPDFAPI.processGIF87A = jsPDFAPI.processGIF89A;
  })(jsPDF.API);

  /**
   * @author shaozilee
   *
   * Bmp format decoder,support 1bit 4bit 8bit 24bit bmp
   *
   */

  function BmpDecoder(buffer, is_with_alpha) {
    this.pos = 0;
    this.buffer = buffer;
    this.datav = new DataView(buffer.buffer);
    this.is_with_alpha = !!is_with_alpha;
    this.bottom_up = true;
    this.flag =
      String.fromCharCode(this.buffer[0]) + String.fromCharCode(this.buffer[1]);
    this.pos += 2;
    if (["BM", "BA", "CI", "CP", "IC", "PT"].indexOf(this.flag) === -1)
      throw new Error("Invalid BMP File");
    this.parseHeader();
    this.parseBGR();
  }

  BmpDecoder.prototype.parseHeader = function() {
    this.fileSize = this.datav.getUint32(this.pos, true);
    this.pos += 4;
    this.reserved = this.datav.getUint32(this.pos, true);
    this.pos += 4;
    this.offset = this.datav.getUint32(this.pos, true);
    this.pos += 4;
    this.headerSize = this.datav.getUint32(this.pos, true);
    this.pos += 4;
    this.width = this.datav.getUint32(this.pos, true);
    this.pos += 4;
    this.height = this.datav.getInt32(this.pos, true);
    this.pos += 4;
    this.planes = this.datav.getUint16(this.pos, true);
    this.pos += 2;
    this.bitPP = this.datav.getUint16(this.pos, true);
    this.pos += 2;
    this.compress = this.datav.getUint32(this.pos, true);
    this.pos += 4;
    this.rawSize = this.datav.getUint32(this.pos, true);
    this.pos += 4;
    this.hr = this.datav.getUint32(this.pos, true);
    this.pos += 4;
    this.vr = this.datav.getUint32(this.pos, true);
    this.pos += 4;
    this.colors = this.datav.getUint32(this.pos, true);
    this.pos += 4;
    this.importantColors = this.datav.getUint32(this.pos, true);
    this.pos += 4;

    if (this.bitPP === 16 && this.is_with_alpha) {
      this.bitPP = 15;
    }
    if (this.bitPP < 15) {
      var len = this.colors === 0 ? 1 << this.bitPP : this.colors;
      this.palette = new Array(len);
      for (var i = 0; i < len; i++) {
        var blue = this.datav.getUint8(this.pos++, true);
        var green = this.datav.getUint8(this.pos++, true);
        var red = this.datav.getUint8(this.pos++, true);
        var quad = this.datav.getUint8(this.pos++, true);
        this.palette[i] = {
          red: red,
          green: green,
          blue: blue,
          quad: quad
        };
      }
    }
    if (this.height < 0) {
      this.height *= -1;
      this.bottom_up = false;
    }
  };

  BmpDecoder.prototype.parseBGR = function() {
    this.pos = this.offset;
    try {
      var bitn = "bit" + this.bitPP;
      var len = this.width * this.height * 4;
      this.data = new Uint8Array(len);

      this[bitn]();
    } catch (e) {
      console.log("bit decode error:" + e);
    }
  };

  BmpDecoder.prototype.bit1 = function() {
    var xlen = Math.ceil(this.width / 8);
    var mode = xlen % 4;
    var y;
    for (y = this.height - 1; y >= 0; y--) {
      var line = this.bottom_up ? y : this.height - 1 - y;
      for (var x = 0; x < xlen; x++) {
        var b = this.datav.getUint8(this.pos++, true);
        var location = line * this.width * 4 + x * 8 * 4;
        for (var i = 0; i < 8; i++) {
          if (x * 8 + i < this.width) {
            var rgb = this.palette[(b >> (7 - i)) & 0x1];
            this.data[location + i * 4] = rgb.blue;
            this.data[location + i * 4 + 1] = rgb.green;
            this.data[location + i * 4 + 2] = rgb.red;
            this.data[location + i * 4 + 3] = 0xff;
          } else {
            break;
          }
        }
      }

      if (mode !== 0) {
        this.pos += 4 - mode;
      }
    }
  };

  BmpDecoder.prototype.bit4 = function() {
    var xlen = Math.ceil(this.width / 2);
    var mode = xlen % 4;
    for (var y = this.height - 1; y >= 0; y--) {
      var line = this.bottom_up ? y : this.height - 1 - y;
      for (var x = 0; x < xlen; x++) {
        var b = this.datav.getUint8(this.pos++, true);
        var location = line * this.width * 4 + x * 2 * 4;

        var before = b >> 4;
        var after = b & 0x0f;

        var rgb = this.palette[before];
        this.data[location] = rgb.blue;
        this.data[location + 1] = rgb.green;
        this.data[location + 2] = rgb.red;
        this.data[location + 3] = 0xff;

        if (x * 2 + 1 >= this.width) break;

        rgb = this.palette[after];
        this.data[location + 4] = rgb.blue;
        this.data[location + 4 + 1] = rgb.green;
        this.data[location + 4 + 2] = rgb.red;
        this.data[location + 4 + 3] = 0xff;
      }

      if (mode !== 0) {
        this.pos += 4 - mode;
      }
    }
  };

  BmpDecoder.prototype.bit8 = function() {
    var mode = this.width % 4;
    for (var y = this.height - 1; y >= 0; y--) {
      var line = this.bottom_up ? y : this.height - 1 - y;
      for (var x = 0; x < this.width; x++) {
        var b = this.datav.getUint8(this.pos++, true);
        var location = line * this.width * 4 + x * 4;
        if (b < this.palette.length) {
          var rgb = this.palette[b];
          this.data[location] = rgb.red;
          this.data[location + 1] = rgb.green;
          this.data[location + 2] = rgb.blue;
          this.data[location + 3] = 0xff;
        } else {
          this.data[location] = 0xff;
          this.data[location + 1] = 0xff;
          this.data[location + 2] = 0xff;
          this.data[location + 3] = 0xff;
        }
      }
      if (mode !== 0) {
        this.pos += 4 - mode;
      }
    }
  };

  BmpDecoder.prototype.bit15 = function() {
    var dif_w = this.width % 3;
    var _11111 = parseInt("11111", 2),
      _1_5 = _11111;
    for (var y = this.height - 1; y >= 0; y--) {
      var line = this.bottom_up ? y : this.height - 1 - y;
      for (var x = 0; x < this.width; x++) {
        var B = this.datav.getUint16(this.pos, true);
        this.pos += 2;
        var blue = (((B & _1_5) / _1_5) * 255) | 0;
        var green = ((((B >> 5) & _1_5) / _1_5) * 255) | 0;
        var red = ((((B >> 10) & _1_5) / _1_5) * 255) | 0;
        var alpha = B >> 15 ? 0xff : 0x00;

        var location = line * this.width * 4 + x * 4;
        this.data[location] = red;
        this.data[location + 1] = green;
        this.data[location + 2] = blue;
        this.data[location + 3] = alpha;
      }
      //skip extra bytes
      this.pos += dif_w;
    }
  };

  BmpDecoder.prototype.bit16 = function() {
    var dif_w = this.width % 3;
    var _11111 = parseInt("11111", 2),
      _1_5 = _11111;
    var _111111 = parseInt("111111", 2),
      _1_6 = _111111;
    for (var y = this.height - 1; y >= 0; y--) {
      var line = this.bottom_up ? y : this.height - 1 - y;
      for (var x = 0; x < this.width; x++) {
        var B = this.datav.getUint16(this.pos, true);
        this.pos += 2;
        var alpha = 0xff;
        var blue = (((B & _1_5) / _1_5) * 255) | 0;
        var green = ((((B >> 5) & _1_6) / _1_6) * 255) | 0;
        var red = (((B >> 11) / _1_5) * 255) | 0;

        var location = line * this.width * 4 + x * 4;
        this.data[location] = red;
        this.data[location + 1] = green;
        this.data[location + 2] = blue;
        this.data[location + 3] = alpha;
      }
      //skip extra bytes
      this.pos += dif_w;
    }
  };

  BmpDecoder.prototype.bit24 = function() {
    //when height > 0
    for (var y = this.height - 1; y >= 0; y--) {
      var line = this.bottom_up ? y : this.height - 1 - y;
      for (var x = 0; x < this.width; x++) {
        var blue = this.datav.getUint8(this.pos++, true);
        var green = this.datav.getUint8(this.pos++, true);
        var red = this.datav.getUint8(this.pos++, true);
        var location = line * this.width * 4 + x * 4;
        this.data[location] = red;
        this.data[location + 1] = green;
        this.data[location + 2] = blue;
        this.data[location + 3] = 0xff;
      }
      //skip extra bytes
      this.pos += this.width % 4;
    }
  };

  /**
   * add 32bit decode func
   * @author soubok
   */
  BmpDecoder.prototype.bit32 = function() {
    //when height > 0
    for (var y = this.height - 1; y >= 0; y--) {
      var line = this.bottom_up ? y : this.height - 1 - y;
      for (var x = 0; x < this.width; x++) {
        var blue = this.datav.getUint8(this.pos++, true);
        var green = this.datav.getUint8(this.pos++, true);
        var red = this.datav.getUint8(this.pos++, true);
        var alpha = this.datav.getUint8(this.pos++, true);
        var location = line * this.width * 4 + x * 4;
        this.data[location] = red;
        this.data[location + 1] = green;
        this.data[location + 2] = blue;
        this.data[location + 3] = alpha;
      }
      //skip extra bytes
      //this.pos += (this.width % 4);
    }
  };

  BmpDecoder.prototype.getData = function() {
    return this.data;
  };

  /**
   * @license
   * Copyright (c) 2018 Aras Abbasi
   *
   * Licensed under the MIT License.
   * http://opensource.org/licenses/mit-license
   */

  /**
   * jsPDF bmp Support PlugIn
   * @name bmp_support
   * @module
   */
  (function(jsPDFAPI) {

    jsPDFAPI.processBMP = function(imageData, index, alias, compression) {
      var reader = new BmpDecoder(imageData, false);
      var width = reader.width,
        height = reader.height;
      var qu = 100;
      var pixels = reader.getData();

      var rawImageData = {
        data: pixels,
        width: width,
        height: height
      };

      var encoder = new JPEGEncoder(qu);
      var data = encoder.encode(rawImageData, qu);
      return jsPDFAPI.processJPEG.call(this, data, index, alias, compression);
    };
  })(jsPDF.API);

  function WebPDecoder(imageData) {

    function x(F) {
      if (!F) throw Error("assert :P");
    }
    function fa(F, L, J) {
      for (var H = 0; 4 > H; H++) if (F[L + H] != J.charCodeAt(H)) return !0;
      return !1;
    }
    function I(F, L, J, H, Z) {
      for (var O = 0; O < Z; O++) F[L + O] = J[H + O];
    }
    function M(F, L, J, H) {
      for (var Z = 0; Z < H; Z++) F[L + Z] = J;
    }
    function V(F) {
      return new Int32Array(F);
    }
    function wa(F, L) {
      for (var J = [], H = 0; H < F; H++) J.push(new L());
      return J;
    }
    function wb() {
      function F(J, H, Z) {
        for (var O = Z[H], L = 0; L < O; L++) {
          J.push(Z.length > H + 1 ? [] : 0);
          if (Z.length < H + 1) break;
          F(J[L], H + 1, Z);
        }
      }
      var L = [];
      F(L, 0, [3, 11]);
      return L;
    }
    function Ed(F, L) {
      function J(H, O, F) {
        for (var Z = F[O], ma = 0; ma < Z; ma++) {
          H.push(F.length > O + 1 ? [] : new L());
          if (F.length < O + 1) break;
          J(H[ma], O + 1, F);
        }
      }
      var H = [];
      J(H, 0, F);
      return H;
    }
    WebPDecoder = function() {
      var self = this;
      function L(a, b) {
        for (var c = (1 << (b - 1)) >>> 0; a & c; ) c >>>= 1;
        return c ? (a & (c - 1)) + c : a;
      }
      function J(a, b, c, d, e) {
        x(!(d % c));
        do (d -= c), (a[b + d] = e);
        while (0 < d);
      }
      function H(a, b, c, d, e, f) {
        var g = b,
          h = 1 << c,
          k,
          l,
          m = V(16),
          n = V(16);
        x(0 != e);
        x(null != d);
        x(null != a);
        x(0 < c);
        for (l = 0; l < e; ++l) {
          if (15 < d[l]) return 0;
          ++m[d[l]];
        }
        if (m[0] == e) return 0;
        n[1] = 0;
        for (k = 1; 15 > k; ++k) {
          if (m[k] > 1 << k) return 0;
          n[k + 1] = n[k] + m[k];
        }
        for (l = 0; l < e; ++l) (k = d[l]), 0 < d[l] && (f[n[k]++] = l);
        if (1 == n[15])
          return (d = new O()), (d.g = 0), (d.value = f[0]), J(a, g, 1, h, d), h;
        var r = -1,
          q = h - 1,
          t = 0,
          v = 1,
          p = 1,
          u,
          w = 1 << c;
        l = 0;
        k = 1;
        for (e = 2; k <= c; ++k, e <<= 1) {
          p <<= 1;
          v += p;
          p -= m[k];
          if (0 > p) return 0;
          for (; 0 < m[k]; --m[k])
            (d = new O()),
              (d.g = k),
              (d.value = f[l++]),
              J(a, g + t, e, w, d),
              (t = L(t, k));
        }
        k = c + 1;
        for (e = 2; 15 >= k; ++k, e <<= 1) {
          p <<= 1;
          v += p;
          p -= m[k];
          if (0 > p) return 0;
          for (; 0 < m[k]; --m[k]) {
            d = new O();
            if ((t & q) != r) {
              g += w;
              r = k;
              for (u = 1 << (r - c); 15 > r; ) {
                u -= m[r];
                if (0 >= u) break;
                ++r;
                u <<= 1;
              }
              u = r - c;
              w = 1 << u;
              h += w;
              r = t & q;
              a[b + r].g = u + c;
              a[b + r].value = g - b - r;
            }
            d.g = k - c;
            d.value = f[l++];
            J(a, g + (t >> c), e, w, d);
            t = L(t, k);
          }
        }
        return v != 2 * n[15] - 1 ? 0 : h;
      }
      function Z(a, b, c, d, e) {
        x(2328 >= e);
        if (512 >= e) var f = V(512);
        else if (((f = V(e)), null == f)) return 0;
        return H(a, b, c, d, e, f);
      }
      function O() {
        this.value = this.g = 0;
      }
      function Fd() {
        this.value = this.g = 0;
      }
      function Ub() {
        this.G = wa(5, O);
        this.H = V(5);
        this.jc = this.Qb = this.qb = this.nd = 0;
        this.pd = wa(xb, Fd);
      }
      function ma(a, b, c, d) {
        x(null != a);
        x(null != b);
        x(2147483648 > d);
        a.Ca = 254;
        a.I = 0;
        a.b = -8;
        a.Ka = 0;
        a.oa = b;
        a.pa = c;
        a.Jd = b;
        a.Yc = c + d;
        a.Zc = 4 <= d ? c + d - 4 + 1 : c;
        Qa(a);
      }
      function na(a, b) {
        for (var c = 0; 0 < b--; ) c |= K(a, 128) << b;
        return c;
      }
      function ca(a, b) {
        var c = na(a, b);
        return G(a) ? -c : c;
      }
      function cb(a, b, c, d) {
        var e,
          f = 0;
        x(null != a);
        x(null != b);
        x(4294967288 > d);
        a.Sb = d;
        a.Ra = 0;
        a.u = 0;
        a.h = 0;
        4 < d && (d = 4);
        for (e = 0; e < d; ++e) f += b[c + e] << (8 * e);
        a.Ra = f;
        a.bb = d;
        a.oa = b;
        a.pa = c;
      }
      function Vb(a) {
        for (; 8 <= a.u && a.bb < a.Sb; )
          (a.Ra >>>= 8),
            (a.Ra += (a.oa[a.pa + a.bb] << (ob - 8)) >>> 0),
            ++a.bb,
            (a.u -= 8);
        db(a) && ((a.h = 1), (a.u = 0));
      }
      function D(a, b) {
        x(0 <= b);
        if (!a.h && b <= Gd) {
          var c = pb(a) & Hd[b];
          a.u += b;
          Vb(a);
          return c;
        }
        a.h = 1;
        return (a.u = 0);
      }
      function Wb() {
        this.b = this.Ca = this.I = 0;
        this.oa = [];
        this.pa = 0;
        this.Jd = [];
        this.Yc = 0;
        this.Zc = [];
        this.Ka = 0;
      }
      function Ra() {
        this.Ra = 0;
        this.oa = [];
        this.h = this.u = this.bb = this.Sb = this.pa = 0;
      }
      function pb(a) {
        return (a.Ra >>> (a.u & (ob - 1))) >>> 0;
      }
      function db(a) {
        x(a.bb <= a.Sb);
        return a.h || (a.bb == a.Sb && a.u > ob);
      }
      function qb(a, b) {
        a.u = b;
        a.h = db(a);
      }
      function Sa(a) {
        a.u >= Xb && (x(a.u >= Xb), Vb(a));
      }
      function Qa(a) {
        x(null != a && null != a.oa);
        a.pa < a.Zc
          ? ((a.I = (a.oa[a.pa++] | (a.I << 8)) >>> 0), (a.b += 8))
          : (x(null != a && null != a.oa),
            a.pa < a.Yc
              ? ((a.b += 8), (a.I = a.oa[a.pa++] | (a.I << 8)))
              : a.Ka
              ? (a.b = 0)
              : ((a.I <<= 8), (a.b += 8), (a.Ka = 1)));
      }
      function G(a) {
        return na(a, 1);
      }
      function K(a, b) {
        var c = a.Ca;
        0 > a.b && Qa(a);
        var d = a.b,
          e = (c * b) >>> 8,
          f = (a.I >>> d > e) + 0;
        f ? ((c -= e), (a.I -= ((e + 1) << d) >>> 0)) : (c = e + 1);
        d = c;
        for (e = 0; 256 <= d; ) (e += 8), (d >>= 8);
        d = 7 ^ (e + Id[d]);
        a.b -= d;
        a.Ca = (c << d) - 1;
        return f;
      }
      function ra(a, b, c) {
        a[b + 0] = (c >> 24) & 255;
        a[b + 1] = (c >> 16) & 255;
        a[b + 2] = (c >> 8) & 255;
        a[b + 3] = (c >> 0) & 255;
      }
      function Ta(a, b) {
        return (a[b + 0] << 0) | (a[b + 1] << 8);
      }
      function Yb(a, b) {
        return Ta(a, b) | (a[b + 2] << 16);
      }
      function Ha(a, b) {
        return Ta(a, b) | (Ta(a, b + 2) << 16);
      }
      function Zb(a, b) {
        var c = 1 << b;
        x(null != a);
        x(0 < b);
        a.X = V(c);
        if (null == a.X) return 0;
        a.Mb = 32 - b;
        a.Xa = b;
        return 1;
      }
      function $b(a, b) {
        x(null != a);
        x(null != b);
        x(a.Xa == b.Xa);
        I(b.X, 0, a.X, 0, 1 << b.Xa);
      }
      function ac() {
        this.X = [];
        this.Xa = this.Mb = 0;
      }
      function bc(a, b, c, d) {
        x(null != c);
        x(null != d);
        var e = c[0],
          f = d[0];
        0 == e && (e = (a * f + b / 2) / b);
        0 == f && (f = (b * e + a / 2) / a);
        if (0 >= e || 0 >= f) return 0;
        c[0] = e;
        d[0] = f;
        return 1;
      }
      function xa(a, b) {
        return (a + (1 << b) - 1) >>> b;
      }
      function yb(a, b) {
        return (
          (((((a & 4278255360) + (b & 4278255360)) >>> 0) & 4278255360) +
            ((((a & 16711935) + (b & 16711935)) >>> 0) & 16711935)) >>>
          0
        );
      }
      function X(a, b) {
        self[b] = function(b, d, e, f, g, h, k) {
          var c;
          for (c = 0; c < g; ++c) {
            var m = self[a](h[k + c - 1], e, f + c);
            h[k + c] = yb(b[d + c], m);
          }
        };
      }
      function Jd() {
        this.ud = this.hd = this.jd = 0;
      }
      function aa(a, b) {
        return ((((a ^ b) & 4278124286) >>> 1) + (a & b)) >>> 0;
      }
      function sa(a) {
        if (0 <= a && 256 > a) return a;
        if (0 > a) return 0;
        if (255 < a) return 255;
      }
      function eb(a, b) {
        return sa(a + ((a - b + 0.5) >> 1));
      }
      function Ia(a, b, c) {
        return Math.abs(b - c) - Math.abs(a - c);
      }
      function cc(a, b, c, d, e, f, g) {
        d = f[g - 1];
        for (c = 0; c < e; ++c) f[g + c] = d = yb(a[b + c], d);
      }
      function Kd(a, b, c, d, e) {
        var f;
        for (f = 0; f < c; ++f) {
          var g = a[b + f],
            h = (g >> 8) & 255,
            k = g & 16711935,
            k = k + ((h << 16) + h),
            k = k & 16711935;
          d[e + f] = ((g & 4278255360) + k) >>> 0;
        }
      }
      function dc(a, b) {
        b.jd = (a >> 0) & 255;
        b.hd = (a >> 8) & 255;
        b.ud = (a >> 16) & 255;
      }
      function Ld(a, b, c, d, e, f) {
        var g;
        for (g = 0; g < d; ++g) {
          var h = b[c + g],
            k = h >>> 8,
            l = h >>> 16,
            m = h,
            l = l + ((((a.jd << 24) >> 24) * ((k << 24) >> 24)) >>> 5),
            l = l & 255,
            m = m + ((((a.hd << 24) >> 24) * ((k << 24) >> 24)) >>> 5),
            m = m + ((((a.ud << 24) >> 24) * ((l << 24) >> 24)) >>> 5),
            m = m & 255;
          e[f + g] = (h & 4278255360) + (l << 16) + m;
        }
      }
      function ec(a, b, c, d, e) {
        self[b] = function(a, b, c, k, l, m, n, r, q) {
          for (k = n; k < r; ++k)
            for (n = 0; n < q; ++n) l[m++] = e(c[d(a[b++])]);
        };
        self[a] = function(a, b, h, k, l, m, n) {
          var f = 8 >> a.b,
            g = a.Ea,
            t = a.K[0],
            v = a.w;
          if (8 > f)
            for (a = (1 << a.b) - 1, v = (1 << f) - 1; b < h; ++b) {
              var p = 0,
                u;
              for (u = 0; u < g; ++u)
                u & a || (p = d(k[l++])), (m[n++] = e(t[p & v])), (p >>= f);
            }
          else self["VP8LMapColor" + c](k, l, t, v, m, n, b, h, g);
        };
      }
      function Md(a, b, c, d, e) {
        for (c = b + c; b < c; ) {
          var f = a[b++];
          d[e++] = (f >> 16) & 255;
          d[e++] = (f >> 8) & 255;
          d[e++] = (f >> 0) & 255;
        }
      }
      function Nd(a, b, c, d, e) {
        for (c = b + c; b < c; ) {
          var f = a[b++];
          d[e++] = (f >> 16) & 255;
          d[e++] = (f >> 8) & 255;
          d[e++] = (f >> 0) & 255;
          d[e++] = (f >> 24) & 255;
        }
      }
      function Od(a, b, c, d, e) {
        for (c = b + c; b < c; ) {
          var f = a[b++],
            g = ((f >> 16) & 240) | ((f >> 12) & 15),
            f = ((f >> 0) & 240) | ((f >> 28) & 15);
          d[e++] = g;
          d[e++] = f;
        }
      }
      function Pd(a, b, c, d, e) {
        for (c = b + c; b < c; ) {
          var f = a[b++],
            g = ((f >> 16) & 248) | ((f >> 13) & 7),
            f = ((f >> 5) & 224) | ((f >> 3) & 31);
          d[e++] = g;
          d[e++] = f;
        }
      }
      function Qd(a, b, c, d, e) {
        for (c = b + c; b < c; ) {
          var f = a[b++];
          d[e++] = (f >> 0) & 255;
          d[e++] = (f >> 8) & 255;
          d[e++] = (f >> 16) & 255;
        }
      }
      function fb(a, b, c, d, e, f) {
        if (0 == f)
          for (c = b + c; b < c; )
            (f = a[b++]),
              ra(
                d,
                ((f[0] >> 24) |
                  ((f[1] >> 8) & 65280) |
                  ((f[2] << 8) & 16711680) |
                  (f[3] << 24)) >>>
                  0
              ),
              (e += 32);
        else I(d, e, a, b, c);
      }
      function gb(a, b) {
        self[b][0] = self[a + "0"];
        self[b][1] = self[a + "1"];
        self[b][2] = self[a + "2"];
        self[b][3] = self[a + "3"];
        self[b][4] = self[a + "4"];
        self[b][5] = self[a + "5"];
        self[b][6] = self[a + "6"];
        self[b][7] = self[a + "7"];
        self[b][8] = self[a + "8"];
        self[b][9] = self[a + "9"];
        self[b][10] = self[a + "10"];
        self[b][11] = self[a + "11"];
        self[b][12] = self[a + "12"];
        self[b][13] = self[a + "13"];
        self[b][14] = self[a + "0"];
        self[b][15] = self[a + "0"];
      }
      function hb(a) {
        return a == zb || a == Ab || a == Ja || a == Bb;
      }
      function Rd() {
        this.eb = [];
        this.size = this.A = this.fb = 0;
      }
      function Sd() {
        this.y = [];
        this.f = [];
        this.ea = [];
        this.F = [];
        this.Tc = this.Ed = this.Cd = this.Fd = this.lb = this.Db = this.Ab = this.fa = this.J = this.W = this.N = this.O = 0;
      }
      function Cb() {
        this.Rd = this.height = this.width = this.S = 0;
        this.f = {};
        this.f.RGBA = new Rd();
        this.f.kb = new Sd();
        this.sd = null;
      }
      function Td() {
        this.width = [0];
        this.height = [0];
        this.Pd = [0];
        this.Qd = [0];
        this.format = [0];
      }
      function Ud() {
        this.Id = this.fd = this.Md = this.hb = this.ib = this.da = this.bd = this.cd = this.j = this.v = this.Da = this.Sd = this.ob = 0;
      }
      function Vd(a) {
        alert("todo:WebPSamplerProcessPlane");
        return a.T;
      }
      function Wd(a, b) {
        var c = a.T,
          d = b.ba.f.RGBA,
          e = d.eb,
          f = d.fb + a.ka * d.A,
          g = P[b.ba.S],
          h = a.y,
          k = a.O,
          l = a.f,
          m = a.N,
          n = a.ea,
          r = a.W,
          q = b.cc,
          t = b.dc,
          v = b.Mc,
          p = b.Nc,
          u = a.ka,
          w = a.ka + a.T,
          y = a.U,
          A = (y + 1) >> 1;
        0 == u
          ? g(h, k, null, null, l, m, n, r, l, m, n, r, e, f, null, null, y)
          : (g(b.ec, b.fc, h, k, q, t, v, p, l, m, n, r, e, f - d.A, e, f, y),
            ++c);
        for (; u + 2 < w; u += 2)
          (q = l),
            (t = m),
            (v = n),
            (p = r),
            (m += a.Rc),
            (r += a.Rc),
            (f += 2 * d.A),
            (k += 2 * a.fa),
            g(h, k - a.fa, h, k, q, t, v, p, l, m, n, r, e, f - d.A, e, f, y);
        k += a.fa;
        a.j + w < a.o
          ? (I(b.ec, b.fc, h, k, y),
            I(b.cc, b.dc, l, m, A),
            I(b.Mc, b.Nc, n, r, A),
            c--)
          : w & 1 ||
            g(
              h,
              k,
              null,
              null,
              l,
              m,
              n,
              r,
              l,
              m,
              n,
              r,
              e,
              f + d.A,
              null,
              null,
              y
            );
        return c;
      }
      function Xd(a, b, c) {
        var d = a.F,
          e = [a.J];
        if (null != d) {
          var f = a.U,
            g = b.ba.S,
            h = g == ya || g == Ja;
          b = b.ba.f.RGBA;
          var k = [0],
            l = a.ka;
          k[0] = a.T;
          a.Kb &&
            (0 == l ? --k[0] : (--l, (e[0] -= a.width)),
            a.j + a.ka + a.T == a.o && (k[0] = a.o - a.j - l));
          var m = b.eb,
            l = b.fb + l * b.A;
          a = fc(d, e[0], a.width, f, k, m, l + (h ? 0 : 3), b.A);
          x(c == k);
          a && hb(g) && za(m, l, h, f, k, b.A);
        }
        return 0;
      }
      function gc(a) {
        var b = a.ma,
          c = b.ba.S,
          d = 11 > c,
          e = c == Ua || c == Va || c == ya || c == Db || 12 == c || hb(c);
        b.memory = null;
        b.Ib = null;
        b.Jb = null;
        b.Nd = null;
        if (!hc(b.Oa, a, e ? 11 : 12)) return 0;
        e && hb(c) && ic();
        if (a.da) alert("todo:use_scaling");
        else {
          if (d) {
            if (((b.Ib = Vd), a.Kb)) {
              c = (a.U + 1) >> 1;
              b.memory = V(a.U + 2 * c);
              if (null == b.memory) return 0;
              b.ec = b.memory;
              b.fc = 0;
              b.cc = b.ec;
              b.dc = b.fc + a.U;
              b.Mc = b.cc;
              b.Nc = b.dc + c;
              b.Ib = Wd;
              ic();
            }
          } else alert("todo:EmitYUV");
          e && ((b.Jb = Xd), d && Aa());
        }
        if (d && !jc) {
          for (a = 0; 256 > a; ++a)
            (Yd[a] = (89858 * (a - 128) + Ba) >> Wa),
              (Zd[a] = -22014 * (a - 128) + Ba),
              ($d[a] = -45773 * (a - 128)),
              (ae[a] = (113618 * (a - 128) + Ba) >> Wa);
          for (a = ta; a < Eb; ++a)
            (b = (76283 * (a - 16) + Ba) >> Wa),
              (be[a - ta] = ga(b, 255)),
              (ce[a - ta] = ga((b + 8) >> 4, 15));
          jc = 1;
        }
        return 1;
      }
      function kc(a) {
        var b = a.ma,
          c = a.U,
          d = a.T;
        x(!(a.ka & 1));
        if (0 >= c || 0 >= d) return 0;
        c = b.Ib(a, b);
        null != b.Jb && b.Jb(a, b, c);
        b.Dc += c;
        return 1;
      }
      function lc(a) {
        a.ma.memory = null;
      }
      function mc(a, b, c, d) {
        if (47 != D(a, 8)) return 0;
        b[0] = D(a, 14) + 1;
        c[0] = D(a, 14) + 1;
        d[0] = D(a, 1);
        return 0 != D(a, 3) ? 0 : !a.h;
      }
      function ib(a, b) {
        if (4 > a) return a + 1;
        var c = (a - 2) >> 1;
        return ((2 + (a & 1)) << c) + D(b, c) + 1;
      }
      function nc(a, b) {
        if (120 < b) return b - 120;
        var c = de[b - 1],
          c = (c >> 4) * a + (8 - (c & 15));
        return 1 <= c ? c : 1;
      }
      function ua(a, b, c) {
        var d = pb(c);
        b += d & 255;
        var e = a[b].g - 8;
        0 < e &&
          (qb(c, c.u + 8),
          (d = pb(c)),
          (b += a[b].value),
          (b += d & ((1 << e) - 1)));
        qb(c, c.u + a[b].g);
        return a[b].value;
      }
      function ub(a, b, c) {
        c.g += a.g;
        c.value += (a.value << b) >>> 0;
        x(8 >= c.g);
        return a.g;
      }
      function ha(a, b, c) {
        var d = a.xc;
        b = 0 == d ? 0 : a.vc[a.md * (c >> d) + (b >> d)];
        x(b < a.Wb);
        return a.Ya[b];
      }
      function oc(a, b, c, d) {
        var e = a.ab,
          f = a.c * b,
          g = a.C;
        b = g + b;
        var h = c,
          k = d;
        d = a.Ta;
        for (c = a.Ua; 0 < e--; ) {
          var l = a.gc[e],
            m = g,
            n = b,
            r = h,
            q = k,
            k = d,
            h = c,
            t = l.Ea;
          x(m < n);
          x(n <= l.nc);
          switch (l.hc) {
            case 2:
              pc(r, q, (n - m) * t, k, h);
              break;
            case 0:
              var v = l,
                p = m,
                u = n,
                w = k,
                y = h,
                A = v.Ea;
              0 == p &&
                (ee(r, q, null, null, 1, w, y),
                cc(r, q + 1, 0, 0, A - 1, w, y + 1),
                (q += A),
                (y += A),
                ++p);
              for (
                var E = 1 << v.b,
                  B = E - 1,
                  C = xa(A, v.b),
                  N = v.K,
                  v = v.w + (p >> v.b) * C;
                p < u;

              ) {
                var z = N,
                  Q = v,
                  S = 1;
                for (fe(r, q, w, y - A, 1, w, y); S < A; ) {
                  var K = qc[(z[Q++] >> 8) & 15],
                    D = (S & ~B) + E;
                  D > A && (D = A);
                  K(r, q + +S, w, y + S - A, D - S, w, y + S);
                  S = D;
                }
                q += A;
                y += A;
                ++p;
                p & B || (v += C);
              }
              n != l.nc && I(k, h - t, k, h + (n - m - 1) * t, t);
              break;
            case 1:
              t = r;
              u = q;
              r = l.Ea;
              q = 1 << l.b;
              w = q - 1;
              y = r & ~w;
              A = r - y;
              p = xa(r, l.b);
              E = l.K;
              for (l = l.w + (m >> l.b) * p; m < n; ) {
                B = E;
                C = l;
                N = new Jd();
                v = u + y;
                for (z = u + r; u < v; )
                  dc(B[C++], N), Fb(N, t, u, q, k, h), (u += q), (h += q);
                u < z &&
                  (dc(B[C++], N), Fb(N, t, u, A, k, h), (u += A), (h += A));
                ++m;
                m & w || (l += p);
              }
              break;
            case 3:
              if (r == k && q == h && 0 < l.b) {
                y = (n - m) * xa(l.Ea, l.b);
                t = h + (n - m) * t - y;
                u = k;
                r = t;
                q = k;
                w = h;
                A = y;
                p = [];
                for (y = A - 1; 0 <= y; --y) p[y] = q[w + y];
                for (y = A - 1; 0 <= y; --y) u[r + y] = p[y];
                rc(l, m, n, k, t, k, h);
              } else rc(l, m, n, r, q, k, h);
          }
          h = d;
          k = c;
        }
        k != c && I(d, c, h, k, f);
      }
      function ge(a, b) {
        var c = a.V,
          d = a.Ba + a.c * a.C,
          e = b - a.C;
        x(b <= a.l.o);
        x(16 >= e);
        if (0 < e) {
          var f = a.l,
            g = a.Ta,
            h = a.Ua,
            k = f.width;
          oc(a, e, c, d);
          h = [h];
          c = a.C;
          d = b;
          e = h;
          x(c < d);
          x(f.v < f.va);
          d > f.o && (d = f.o);
          if (c < f.j) {
            var l = f.j - c,
              c = f.j;
            e[0] += l * k;
          }
          c >= d
            ? (c = 0)
            : ((e[0] += 4 * f.v),
              (f.ka = c - f.j),
              (f.U = f.va - f.v),
              (f.T = d - c),
              (c = 1));
          if (c) {
            h = h[0];
            c = a.ca;
            if (11 > c.S) {
              for (
                var m = c.f.RGBA,
                  d = c.S,
                  e = f.U,
                  f = f.T,
                  l = m.eb,
                  n = m.A,
                  r = f,
                  m = m.fb + a.Ma * m.A;
                0 < r--;

              ) {
                var q = g,
                  t = h,
                  v = e,
                  p = l,
                  u = m;
                switch (d) {
                  case Ca:
                    sc(q, t, v, p, u);
                    break;
                  case Ua:
                    Gb(q, t, v, p, u);
                    break;
                  case zb:
                    Gb(q, t, v, p, u);
                    za(p, u, 0, v, 1, 0);
                    break;
                  case tc:
                    uc(q, t, v, p, u);
                    break;
                  case Va:
                    fb(q, t, v, p, u, 1);
                    break;
                  case Ab:
                    fb(q, t, v, p, u, 1);
                    za(p, u, 0, v, 1, 0);
                    break;
                  case ya:
                    fb(q, t, v, p, u, 0);
                    break;
                  case Ja:
                    fb(q, t, v, p, u, 0);
                    za(p, u, 1, v, 1, 0);
                    break;
                  case Db:
                    Hb(q, t, v, p, u);
                    break;
                  case Bb:
                    Hb(q, t, v, p, u);
                    vc(p, u, v, 1, 0);
                    break;
                  case wc:
                    xc(q, t, v, p, u);
                    break;
                  default:
                    x(0);
                }
                h += k;
                m += n;
              }
              a.Ma += f;
            } else alert("todo:EmitRescaledRowsYUVA");
            x(a.Ma <= c.height);
          }
        }
        a.C = b;
        x(a.C <= a.i);
      }
      function yc(a) {
        var b;
        if (0 < a.ua) return 0;
        for (b = 0; b < a.Wb; ++b) {
          var c = a.Ya[b].G,
            d = a.Ya[b].H;
          if (
            0 < c[1][d[1] + 0].g ||
            0 < c[2][d[2] + 0].g ||
            0 < c[3][d[3] + 0].g
          )
            return 0;
        }
        return 1;
      }
      function zc(a, b, c, d, e, f) {
        if (0 != a.Z) {
          var g = a.qd,
            h = a.rd;
          for (x(null != ia[a.Z]); b < c; ++b)
            ia[a.Z](g, h, d, e, d, e, f), (g = d), (h = e), (e += f);
          a.qd = g;
          a.rd = h;
        }
      }
      function Ib(a, b) {
        var c = a.l.ma,
          d = 0 == c.Z || 1 == c.Z ? a.l.j : a.C,
          d = a.C < d ? d : a.C;
        x(b <= a.l.o);
        if (b > d) {
          var e = a.l.width,
            f = c.ca,
            g = c.tb + e * d,
            h = a.V,
            k = a.Ba + a.c * d,
            l = a.gc;
          x(1 == a.ab);
          x(3 == l[0].hc);
          he(l[0], d, b, h, k, f, g);
          zc(c, d, b, f, g, e);
        }
        a.C = a.Ma = b;
      }
      function Jb(a, b, c, d, e, f, g) {
        var h = a.$ / d,
          k = a.$ % d,
          l = a.m,
          m = a.s,
          n = c + a.$,
          r = n;
        e = c + d * e;
        var q = c + d * f,
          t = 280 + m.ua,
          v = a.Pb ? h : 16777216,
          p = 0 < m.ua ? m.Wa : null,
          u = m.wc,
          w = n < q ? ha(m, k, h) : null;
        x(a.C < f);
        x(q <= e);
        var y = !1;
        a: for (;;) {
          for (; y || n < q; ) {
            var A = 0;
            if (h >= v) {
              var v = a,
                E = n - c;
              x(v.Pb);
              v.wd = v.m;
              v.xd = E;
              0 < v.s.ua && $b(v.s.Wa, v.s.vb);
              v = h + ie;
            }
            k & u || (w = ha(m, k, h));
            x(null != w);
            w.Qb && ((b[n] = w.qb), (y = !0));
            if (!y)
              if ((Sa(l), w.jc)) {
                var A = l,
                  E = b,
                  B = n,
                  C = w.pd[pb(A) & (xb - 1)];
                x(w.jc);
                256 > C.g
                  ? (qb(A, A.u + C.g), (E[B] = C.value), (A = 0))
                  : (qb(A, A.u + C.g - 256), x(256 <= C.value), (A = C.value));
                0 == A && (y = !0);
              } else A = ua(w.G[0], w.H[0], l);
            if (l.h) break;
            if (y || 256 > A) {
              if (!y)
                if (w.nd) b[n] = (w.qb | (A << 8)) >>> 0;
                else {
                  Sa(l);
                  y = ua(w.G[1], w.H[1], l);
                  Sa(l);
                  E = ua(w.G[2], w.H[2], l);
                  B = ua(w.G[3], w.H[3], l);
                  if (l.h) break;
                  b[n] = ((B << 24) | (y << 16) | (A << 8) | E) >>> 0;
                }
              y = !1;
              ++n;
              ++k;
              if (
                k >= d &&
                ((k = 0),
                ++h,
                null != g && h <= f && !(h % 16) && g(a, h),
                null != p)
              )
                for (; r < n; )
                  (A = b[r++]),
                    (p.X[((506832829 * A) & 4294967295) >>> p.Mb] = A);
            } else if (280 > A) {
              A = ib(A - 256, l);
              E = ua(w.G[4], w.H[4], l);
              Sa(l);
              E = ib(E, l);
              E = nc(d, E);
              if (l.h) break;
              if (n - c < E || e - n < A) break a;
              else for (B = 0; B < A; ++B) b[n + B] = b[n + B - E];
              n += A;
              for (k += A; k >= d; )
                (k -= d), ++h, null != g && h <= f && !(h % 16) && g(a, h);
              x(n <= e);
              k & u && (w = ha(m, k, h));
              if (null != p)
                for (; r < n; )
                  (A = b[r++]),
                    (p.X[((506832829 * A) & 4294967295) >>> p.Mb] = A);
            } else if (A < t) {
              y = A - 280;
              for (x(null != p); r < n; )
                (A = b[r++]), (p.X[((506832829 * A) & 4294967295) >>> p.Mb] = A);
              A = n;
              E = p;
              x(!(y >>> E.Xa));
              b[A] = E.X[y];
              y = !0;
            } else break a;
            y || x(l.h == db(l));
          }
          if (a.Pb && l.h && n < e)
            x(a.m.h),
              (a.a = 5),
              (a.m = a.wd),
              (a.$ = a.xd),
              0 < a.s.ua && $b(a.s.vb, a.s.Wa);
          else if (l.h) break a;
          else null != g && g(a, h > f ? f : h), (a.a = 0), (a.$ = n - c);
          return 1;
        }
        a.a = 3;
        return 0;
      }
      function Ac(a) {
        x(null != a);
        a.vc = null;
        a.yc = null;
        a.Ya = null;
        var b = a.Wa;
        null != b && (b.X = null);
        a.vb = null;
        x(null != a);
      }
      function Bc() {
        var a = new je();
        if (null == a) return null;
        a.a = 0;
        a.xb = Cc;
        gb("Predictor", "VP8LPredictors");
        gb("Predictor", "VP8LPredictors_C");
        gb("PredictorAdd", "VP8LPredictorsAdd");
        gb("PredictorAdd", "VP8LPredictorsAdd_C");
        pc = Kd;
        Fb = Ld;
        sc = Md;
        Gb = Nd;
        Hb = Od;
        xc = Pd;
        uc = Qd;
        self.VP8LMapColor32b = ke;
        self.VP8LMapColor8b = le;
        return a;
      }
      function rb(a, b, c, d, e) {
        var f = 1,
          g = [a],
          h = [b],
          k = d.m,
          l = d.s,
          m = null,
          n = 0;
        a: for (;;) {
          if (c)
            for (; f && D(k, 1); ) {
              var r = g,
                q = h,
                t = d,
                v = 1,
                p = t.m,
                u = t.gc[t.ab],
                w = D(p, 2);
              if (t.Oc & (1 << w)) f = 0;
              else {
                t.Oc |= 1 << w;
                u.hc = w;
                u.Ea = r[0];
                u.nc = q[0];
                u.K = [null];
                ++t.ab;
                x(4 >= t.ab);
                switch (w) {
                  case 0:
                  case 1:
                    u.b = D(p, 3) + 2;
                    v = rb(xa(u.Ea, u.b), xa(u.nc, u.b), 0, t, u.K);
                    u.K = u.K[0];
                    break;
                  case 3:
                    var y = D(p, 8) + 1,
                      A = 16 < y ? 0 : 4 < y ? 1 : 2 < y ? 2 : 3;
                    r[0] = xa(u.Ea, A);
                    u.b = A;
                    var v = rb(y, 1, 0, t, u.K),
                      E;
                    if ((E = v)) {
                      var B,
                        C = y,
                        N = u,
                        z = 1 << (8 >> N.b),
                        Q = V(z);
                      if (null == Q) E = 0;
                      else {
                        var S = N.K[0],
                          K = N.w;
                        Q[0] = N.K[0][0];
                        for (B = 1; B < 1 * C; ++B) Q[B] = yb(S[K + B], Q[B - 1]);
                        for (; B < 4 * z; ++B) Q[B] = 0;
                        N.K[0] = null;
                        N.K[0] = Q;
                        E = 1;
                      }
                    }
                    v = E;
                    break;
                  case 2:
                    break;
                  default:
                    x(0);
                }
                f = v;
              }
            }
          g = g[0];
          h = h[0];
          if (f && D(k, 1) && ((n = D(k, 4)), (f = 1 <= n && 11 >= n), !f)) {
            d.a = 3;
            break a;
          }
          var H;
          if ((H = f))
            b: {
              var F = d,
                G = g,
                L = h,
                J = n,
                T = c,
                Da,
                ba,
                X = F.m,
                R = F.s,
                P = [null],
                U,
                W = 1,
                aa = 0,
                na = me[J];
              c: for (;;) {
                if (T && D(X, 1)) {
                  var ca = D(X, 3) + 2,
                    ga = xa(G, ca),
                    ka = xa(L, ca),
                    qa = ga * ka;
                  if (!rb(ga, ka, 0, F, P)) break c;
                  P = P[0];
                  R.xc = ca;
                  for (Da = 0; Da < qa; ++Da) {
                    var ia = (P[Da] >> 8) & 65535;
                    P[Da] = ia;
                    ia >= W && (W = ia + 1);
                  }
                }
                if (X.h) break c;
                for (ba = 0; 5 > ba; ++ba) {
                  var Y = Dc[ba];
                  !ba && 0 < J && (Y += 1 << J);
                  aa < Y && (aa = Y);
                }
                var ma = wa(W * na, O);
                var ua = W,
                  va = wa(ua, Ub);
                if (null == va) var la = null;
                else x(65536 >= ua), (la = va);
                var ha = V(aa);
                if (null == la || null == ha || null == ma) {
                  F.a = 1;
                  break c;
                }
                var pa = ma;
                for (Da = U = 0; Da < W; ++Da) {
                  var ja = la[Da],
                    da = ja.G,
                    ea = ja.H,
                    Fa = 0,
                    ra = 1,
                    Ha = 0;
                  for (ba = 0; 5 > ba; ++ba) {
                    Y = Dc[ba];
                    da[ba] = pa;
                    ea[ba] = U;
                    !ba && 0 < J && (Y += 1 << J);
                    d: {
                      var sa,
                        za = Y,
                        ta = F,
                        oa = ha,
                        db = pa,
                        eb = U,
                        Ia = 0,
                        Ka = ta.m,
                        fb = D(Ka, 1);
                      M(oa, 0, 0, za);
                      if (fb) {
                        var gb = D(Ka, 1) + 1,
                          hb = D(Ka, 1),
                          Ja = D(Ka, 0 == hb ? 1 : 8);
                        oa[Ja] = 1;
                        2 == gb && ((Ja = D(Ka, 8)), (oa[Ja] = 1));
                        var ya = 1;
                      } else {
                        var Ua = V(19),
                          Va = D(Ka, 4) + 4;
                        if (19 < Va) {
                          ta.a = 3;
                          var Aa = 0;
                          break d;
                        }
                        for (sa = 0; sa < Va; ++sa) Ua[ne[sa]] = D(Ka, 3);
                        var Ba = void 0,
                          sb = void 0,
                          Wa = ta,
                          ib = Ua,
                          Ca = za,
                          Xa = oa,
                          Oa = 0,
                          La = Wa.m,
                          Ya = 8,
                          Za = wa(128, O);
                        e: for (;;) {
                          if (!Z(Za, 0, 7, ib, 19)) break e;
                          if (D(La, 1)) {
                            var kb = 2 + 2 * D(La, 3),
                              Ba = 2 + D(La, kb);
                            if (Ba > Ca) break e;
                          } else Ba = Ca;
                          for (sb = 0; sb < Ca && Ba--; ) {
                            Sa(La);
                            var $a = Za[0 + (pb(La) & 127)];
                            qb(La, La.u + $a.g);
                            var jb = $a.value;
                            if (16 > jb) (Xa[sb++] = jb), 0 != jb && (Ya = jb);
                            else {
                              var lb = 16 == jb,
                                ab = jb - 16,
                                mb = oe[ab],
                                bb = D(La, pe[ab]) + mb;
                              if (sb + bb > Ca) break e;
                              else
                                for (var nb = lb ? Ya : 0; 0 < bb--; )
                                  Xa[sb++] = nb;
                            }
                          }
                          Oa = 1;
                          break e;
                        }
                        Oa || (Wa.a = 3);
                        ya = Oa;
                      }
                      (ya = ya && !Ka.h) && (Ia = Z(db, eb, 8, oa, za));
                      ya && 0 != Ia ? (Aa = Ia) : ((ta.a = 3), (Aa = 0));
                    }
                    if (0 == Aa) break c;
                    ra && 1 == qe[ba] && (ra = 0 == pa[U].g);
                    Fa += pa[U].g;
                    U += Aa;
                    if (3 >= ba) {
                      var Pa = ha[0],
                        tb;
                      for (tb = 1; tb < Y; ++tb) ha[tb] > Pa && (Pa = ha[tb]);
                      Ha += Pa;
                    }
                  }
                  ja.nd = ra;
                  ja.Qb = 0;
                  ra &&
                    ((ja.qb =
                      ((da[3][ea[3] + 0].value << 24) |
                        (da[1][ea[1] + 0].value << 16) |
                        da[2][ea[2] + 0].value) >>>
                      0),
                    0 == Fa &&
                      256 > da[0][ea[0] + 0].value &&
                      ((ja.Qb = 1), (ja.qb += da[0][ea[0] + 0].value << 8)));
                  ja.jc = !ja.Qb && 6 > Ha;
                  if (ja.jc) {
                    var Ga,
                      Ea = ja;
                    for (Ga = 0; Ga < xb; ++Ga) {
                      var Ma = Ga,
                        Na = Ea.pd[Ma],
                        vb = Ea.G[0][Ea.H[0] + Ma];
                      256 <= vb.value
                        ? ((Na.g = vb.g + 256), (Na.value = vb.value))
                        : ((Na.g = 0),
                          (Na.value = 0),
                          (Ma >>= ub(vb, 8, Na)),
                          (Ma >>= ub(Ea.G[1][Ea.H[1] + Ma], 16, Na)),
                          (Ma >>= ub(Ea.G[2][Ea.H[2] + Ma], 0, Na)),
                          ub(Ea.G[3][Ea.H[3] + Ma], 24, Na));
                    }
                  }
                }
                R.vc = P;
                R.Wb = W;
                R.Ya = la;
                R.yc = ma;
                H = 1;
                break b;
              }
              H = 0;
            }
          f = H;
          if (!f) {
            d.a = 3;
            break a;
          }
          if (0 < n) {
            if (((l.ua = 1 << n), !Zb(l.Wa, n))) {
              d.a = 1;
              f = 0;
              break a;
            }
          } else l.ua = 0;
          var Qa = d,
            cb = g,
            ob = h,
            Ra = Qa.s,
            Ta = Ra.xc;
          Qa.c = cb;
          Qa.i = ob;
          Ra.md = xa(cb, Ta);
          Ra.wc = 0 == Ta ? -1 : (1 << Ta) - 1;
          if (c) {
            d.xb = re;
            break a;
          }
          m = V(g * h);
          if (null == m) {
            d.a = 1;
            f = 0;
            break a;
          }
          f = (f = Jb(d, m, 0, g, h, h, null)) && !k.h;
          break a;
        }
        f
          ? (null != e ? (e[0] = m) : (x(null == m), x(c)), (d.$ = 0), c || Ac(l))
          : Ac(l);
        return f;
      }
      function Ec(a, b) {
        var c = a.c * a.i,
          d = c + b + 16 * b;
        x(a.c <= b);
        a.V = V(d);
        if (null == a.V) return (a.Ta = null), (a.Ua = 0), (a.a = 1), 0;
        a.Ta = a.V;
        a.Ua = a.Ba + c + b;
        return 1;
      }
      function se(a, b) {
        var c = a.C,
          d = b - c,
          e = a.V,
          f = a.Ba + a.c * c;
        for (x(b <= a.l.o); 0 < d; ) {
          var g = 16 < d ? 16 : d,
            h = a.l.ma,
            k = a.l.width,
            l = k * g,
            m = h.ca,
            n = h.tb + k * c,
            r = a.Ta,
            q = a.Ua;
          oc(a, g, e, f);
          Fc(r, q, m, n, l);
          zc(h, c, c + g, m, n, k);
          d -= g;
          e += g * a.c;
          c += g;
        }
        x(c == b);
        a.C = a.Ma = b;
      }
      function te(a, b) {
        var c = [0],
          d = [0],
          e = [0];
        a: for (;;) {
          if (null == a) return 0;
          if (null == b) return (a.a = 2), 0;
          a.l = b;
          a.a = 0;
          cb(a.m, b.data, b.w, b.ha);
          if (!mc(a.m, c, d, e)) {
            a.a = 3;
            break a;
          }
          a.xb = Cc;
          b.width = c[0];
          b.height = d[0];
          if (!rb(c[0], d[0], 1, a, null)) break a;
          return 1;
        }
        x(0 != a.a);
        return 0;
      }
      function ue() {
        this.ub = this.yd = this.td = this.Rb = 0;
      }
      function ve() {
        this.Kd = this.Ld = this.Ud = this.Td = this.i = this.c = 0;
      }
      function we() {
        this.Fb = this.Bb = this.Cb = 0;
        this.Zb = V(4);
        this.Lb = V(4);
      }
      function Gc() {
        this.Yb = wb();
      }
      function xe() {
        this.jb = V(3);
        this.Wc = Ed([4, 8], Gc);
        this.Xc = Ed([4, 17], Gc);
      }
      function ye() {
        this.Pc = this.wb = this.Tb = this.zd = 0;
        this.vd = new V(4);
        this.od = new V(4);
      }
      function Xa() {
        this.ld = this.La = this.dd = this.tc = 0;
      }
      function Hc() {
        this.Na = this.la = 0;
      }
      function ze() {
        this.Sc = [0, 0];
        this.Eb = [0, 0];
        this.Qc = [0, 0];
        this.ia = this.lc = 0;
      }
      function Kb() {
        this.ad = V(384);
        this.Za = 0;
        this.Ob = V(16);
        this.$b = this.Ad = this.ia = this.Gc = this.Hc = this.Dd = 0;
      }
      function Ae() {
        this.uc = this.M = this.Nb = 0;
        this.wa = Array(new Xa());
        this.Y = 0;
        this.ya = Array(new Kb());
        this.aa = 0;
        this.l = new Oa();
      }
      function Ic() {
        this.y = V(16);
        this.f = V(8);
        this.ea = V(8);
      }
      function Be() {
        this.cb = this.a = 0;
        this.sc = "";
        this.m = new Wb();
        this.Od = new ue();
        this.Kc = new ve();
        this.ed = new ye();
        this.Qa = new we();
        this.Ic = this.$c = this.Aa = 0;
        this.D = new Ae();
        this.Xb = this.Va = this.Hb = this.zb = this.yb = this.Ub = this.za = 0;
        this.Jc = wa(8, Wb);
        this.ia = 0;
        this.pb = wa(4, ze);
        this.Pa = new xe();
        this.Bd = this.kc = 0;
        this.Ac = [];
        this.Bc = 0;
        this.zc = [0, 0, 0, 0];
        this.Gd = Array(new Ic());
        this.Hd = 0;
        this.rb = Array(new Hc());
        this.sb = 0;
        this.wa = Array(new Xa());
        this.Y = 0;
        this.oc = [];
        this.pc = 0;
        this.sa = [];
        this.ta = 0;
        this.qa = [];
        this.ra = 0;
        this.Ha = [];
        this.B = this.R = this.Ia = 0;
        this.Ec = [];
        this.M = this.ja = this.Vb = this.Fc = 0;
        this.ya = Array(new Kb());
        this.L = this.aa = 0;
        this.gd = Ed([4, 2], Xa);
        this.ga = null;
        this.Fa = [];
        this.Cc = this.qc = this.P = 0;
        this.Gb = [];
        this.Uc = 0;
        this.mb = [];
        this.nb = 0;
        this.rc = [];
        this.Ga = this.Vc = 0;
      }
      function ga(a, b) {
        return 0 > a ? 0 : a > b ? b : a;
      }
      function Oa() {
        this.T = this.U = this.ka = this.height = this.width = 0;
        this.y = [];
        this.f = [];
        this.ea = [];
        this.Rc = this.fa = this.W = this.N = this.O = 0;
        this.ma = "void";
        this.put = "VP8IoPutHook";
        this.ac = "VP8IoSetupHook";
        this.bc = "VP8IoTeardownHook";
        this.ha = this.Kb = 0;
        this.data = [];
        this.hb = this.ib = this.da = this.o = this.j = this.va = this.v = this.Da = this.ob = this.w = 0;
        this.F = [];
        this.J = 0;
      }
      function Ce() {
        var a = new Be();
        null != a &&
          ((a.a = 0), (a.sc = "OK"), (a.cb = 0), (a.Xb = 0), oa || (oa = De));
        return a;
      }
      function T(a, b, c) {
        0 == a.a && ((a.a = b), (a.sc = c), (a.cb = 0));
        return 0;
      }
      function Jc(a, b, c) {
        return 3 <= c && 157 == a[b + 0] && 1 == a[b + 1] && 42 == a[b + 2];
      }
      function Kc(a, b) {
        if (null == a) return 0;
        a.a = 0;
        a.sc = "OK";
        if (null == b) return T(a, 2, "null VP8Io passed to VP8GetHeaders()");
        var c = b.data;
        var d = b.w;
        var e = b.ha;
        if (4 > e) return T(a, 7, "Truncated header.");
        var f = c[d + 0] | (c[d + 1] << 8) | (c[d + 2] << 16);
        var g = a.Od;
        g.Rb = !(f & 1);
        g.td = (f >> 1) & 7;
        g.yd = (f >> 4) & 1;
        g.ub = f >> 5;
        if (3 < g.td) return T(a, 3, "Incorrect keyframe parameters.");
        if (!g.yd) return T(a, 4, "Frame not displayable.");
        d += 3;
        e -= 3;
        var h = a.Kc;
        if (g.Rb) {
          if (7 > e) return T(a, 7, "cannot parse picture header");
          if (!Jc(c, d, e)) return T(a, 3, "Bad code word");
          h.c = ((c[d + 4] << 8) | c[d + 3]) & 16383;
          h.Td = c[d + 4] >> 6;
          h.i = ((c[d + 6] << 8) | c[d + 5]) & 16383;
          h.Ud = c[d + 6] >> 6;
          d += 7;
          e -= 7;
          a.za = (h.c + 15) >> 4;
          a.Ub = (h.i + 15) >> 4;
          b.width = h.c;
          b.height = h.i;
          b.Da = 0;
          b.j = 0;
          b.v = 0;
          b.va = b.width;
          b.o = b.height;
          b.da = 0;
          b.ib = b.width;
          b.hb = b.height;
          b.U = b.width;
          b.T = b.height;
          f = a.Pa;
          M(f.jb, 0, 255, f.jb.length);
          f = a.Qa;
          x(null != f);
          f.Cb = 0;
          f.Bb = 0;
          f.Fb = 1;
          M(f.Zb, 0, 0, f.Zb.length);
          M(f.Lb, 0, 0, f.Lb);
        }
        if (g.ub > e) return T(a, 7, "bad partition length");
        f = a.m;
        ma(f, c, d, g.ub);
        d += g.ub;
        e -= g.ub;
        g.Rb && ((h.Ld = G(f)), (h.Kd = G(f)));
        h = a.Qa;
        var k = a.Pa,
          l;
        x(null != f);
        x(null != h);
        h.Cb = G(f);
        if (h.Cb) {
          h.Bb = G(f);
          if (G(f)) {
            h.Fb = G(f);
            for (l = 0; 4 > l; ++l) h.Zb[l] = G(f) ? ca(f, 7) : 0;
            for (l = 0; 4 > l; ++l) h.Lb[l] = G(f) ? ca(f, 6) : 0;
          }
          if (h.Bb) for (l = 0; 3 > l; ++l) k.jb[l] = G(f) ? na(f, 8) : 255;
        } else h.Bb = 0;
        if (f.Ka) return T(a, 3, "cannot parse segment header");
        h = a.ed;
        h.zd = G(f);
        h.Tb = na(f, 6);
        h.wb = na(f, 3);
        h.Pc = G(f);
        if (h.Pc && G(f)) {
          for (k = 0; 4 > k; ++k) G(f) && (h.vd[k] = ca(f, 6));
          for (k = 0; 4 > k; ++k) G(f) && (h.od[k] = ca(f, 6));
        }
        a.L = 0 == h.Tb ? 0 : h.zd ? 1 : 2;
        if (f.Ka) return T(a, 3, "cannot parse filter header");
        l = d;
        var m = e;
        e = l;
        d = l + m;
        h = m;
        a.Xb = (1 << na(a.m, 2)) - 1;
        k = a.Xb;
        if (m < 3 * k) c = 7;
        else {
          l += 3 * k;
          h -= 3 * k;
          for (m = 0; m < k; ++m) {
            var n = c[e + 0] | (c[e + 1] << 8) | (c[e + 2] << 16);
            n > h && (n = h);
            ma(a.Jc[+m], c, l, n);
            l += n;
            h -= n;
            e += 3;
          }
          ma(a.Jc[+k], c, l, h);
          c = l < d ? 0 : 5;
        }
        if (0 != c) return T(a, c, "cannot parse partitions");
        l = a.m;
        c = na(l, 7);
        e = G(l) ? ca(l, 4) : 0;
        d = G(l) ? ca(l, 4) : 0;
        h = G(l) ? ca(l, 4) : 0;
        k = G(l) ? ca(l, 4) : 0;
        l = G(l) ? ca(l, 4) : 0;
        m = a.Qa;
        for (n = 0; 4 > n; ++n) {
          if (m.Cb) {
            var r = m.Zb[n];
            m.Fb || (r += c);
          } else if (0 < n) {
            a.pb[n] = a.pb[0];
            continue;
          } else r = c;
          var q = a.pb[n];
          q.Sc[0] = Lb[ga(r + e, 127)];
          q.Sc[1] = Mb[ga(r + 0, 127)];
          q.Eb[0] = 2 * Lb[ga(r + d, 127)];
          q.Eb[1] = (101581 * Mb[ga(r + h, 127)]) >> 16;
          8 > q.Eb[1] && (q.Eb[1] = 8);
          q.Qc[0] = Lb[ga(r + k, 117)];
          q.Qc[1] = Mb[ga(r + l, 127)];
          q.lc = r + l;
        }
        if (!g.Rb) return T(a, 4, "Not a key frame.");
        G(f);
        g = a.Pa;
        for (c = 0; 4 > c; ++c) {
          for (e = 0; 8 > e; ++e)
            for (d = 0; 3 > d; ++d)
              for (h = 0; 11 > h; ++h)
                (k = K(f, Ee[c][e][d][h]) ? na(f, 8) : Fe[c][e][d][h]),
                  (g.Wc[c][e].Yb[d][h] = k);
          for (e = 0; 17 > e; ++e) g.Xc[c][e] = g.Wc[c][Ge[e]];
        }
        a.kc = G(f);
        a.kc && (a.Bd = na(f, 8));
        return (a.cb = 1);
      }
      function De(a, b, c, d, e, f, g) {
        var h = b[e].Yb[c];
        for (c = 0; 16 > e; ++e) {
          if (!K(a, h[c + 0])) return e;
          for (; !K(a, h[c + 1]); )
            if (((h = b[++e].Yb[0]), (c = 0), 16 == e)) return 16;
          var k = b[e + 1].Yb;
          if (K(a, h[c + 2])) {
            var l = a,
              m = h,
              n = c;
            var r = 0;
            if (K(l, m[n + 3]))
              if (K(l, m[n + 6])) {
                h = 0;
                r = K(l, m[n + 8]);
                m = K(l, m[n + 9 + r]);
                n = 2 * r + m;
                r = 0;
                for (m = He[n]; m[h]; ++h) r += r + K(l, m[h]);
                r += 3 + (8 << n);
              } else
                K(l, m[n + 7])
                  ? ((r = 7 + 2 * K(l, 165)), (r += K(l, 145)))
                  : (r = 5 + K(l, 159));
            else K(l, m[n + 4]) ? (r = 3 + K(l, m[n + 5])) : (r = 2);
            h = k[2];
          } else (r = 1), (h = k[1]);
          k = g + Ie[e];
          l = a;
          0 > l.b && Qa(l);
          var m = l.b,
            n = l.Ca >> 1,
            q = (n - (l.I >> m)) >> 31;
          --l.b;
          l.Ca += q;
          l.Ca |= 1;
          l.I -= ((n + 1) & q) << m;
          f[k] = ((r ^ q) - q) * d[(0 < e) + 0];
        }
        return 16;
      }
      function Lc(a) {
        var b = a.rb[a.sb - 1];
        b.la = 0;
        b.Na = 0;
        M(a.zc, 0, 0, a.zc.length);
        a.ja = 0;
      }
      function Je(a, b) {
        for (a.M = 0; a.M < a.Va; ++a.M) {
          var c = a.Jc[a.M & a.Xb],
            d = a.m,
            e = a,
            f;
          for (f = 0; f < e.za; ++f) {
            var g = d;
            var h = e;
            var k = h.Ac,
              l = h.Bc + 4 * f,
              m = h.zc,
              n = h.ya[h.aa + f];
            h.Qa.Bb
              ? (n.$b = K(g, h.Pa.jb[0])
                  ? 2 + K(g, h.Pa.jb[2])
                  : K(g, h.Pa.jb[1]))
              : (n.$b = 0);
            h.kc && (n.Ad = K(g, h.Bd));
            n.Za = !K(g, 145) + 0;
            if (n.Za) {
              var r = n.Ob,
                q = 0;
              for (h = 0; 4 > h; ++h) {
                var t = m[0 + h];
                var v;
                for (v = 0; 4 > v; ++v) {
                  t = Ke[k[l + v]][t];
                  for (var p = Mc[K(g, t[0])]; 0 < p; )
                    p = Mc[2 * p + K(g, t[p])];
                  t = -p;
                  k[l + v] = t;
                }
                I(r, q, k, l, 4);
                q += 4;
                m[0 + h] = t;
              }
            } else
              (t = K(g, 156) ? (K(g, 128) ? 1 : 3) : K(g, 163) ? 2 : 0),
                (n.Ob[0] = t),
                M(k, l, t, 4),
                M(m, 0, t, 4);
            n.Dd = K(g, 142) ? (K(g, 114) ? (K(g, 183) ? 1 : 3) : 2) : 0;
          }
          if (e.m.Ka) return T(a, 7, "Premature end-of-partition0 encountered.");
          for (; a.ja < a.za; ++a.ja) {
            d = a;
            e = c;
            g = d.rb[d.sb - 1];
            k = d.rb[d.sb + d.ja];
            f = d.ya[d.aa + d.ja];
            if ((l = d.kc ? f.Ad : 0))
              (g.la = k.la = 0),
                f.Za || (g.Na = k.Na = 0),
                (f.Hc = 0),
                (f.Gc = 0),
                (f.ia = 0);
            else {
              var u,
                w,
                g = k,
                k = e,
                l = d.Pa.Xc,
                m = d.ya[d.aa + d.ja],
                n = d.pb[m.$b];
              h = m.ad;
              r = 0;
              q = d.rb[d.sb - 1];
              t = v = 0;
              M(h, r, 0, 384);
              if (m.Za) {
                var y = 0;
                var A = l[3];
              } else {
                p = V(16);
                var E = g.Na + q.Na;
                E = oa(k, l[1], E, n.Eb, 0, p, 0);
                g.Na = q.Na = (0 < E) + 0;
                if (1 < E) Nc(p, 0, h, r);
                else {
                  var B = (p[0] + 3) >> 3;
                  for (p = 0; 256 > p; p += 16) h[r + p] = B;
                }
                y = 1;
                A = l[0];
              }
              var C = g.la & 15;
              var N = q.la & 15;
              for (p = 0; 4 > p; ++p) {
                var z = N & 1;
                for (B = w = 0; 4 > B; ++B)
                  (E = z + (C & 1)),
                    (E = oa(k, A, E, n.Sc, y, h, r)),
                    (z = E > y),
                    (C = (C >> 1) | (z << 7)),
                    (w = (w << 2) | (3 < E ? 3 : 1 < E ? 2 : 0 != h[r + 0])),
                    (r += 16);
                C >>= 4;
                N = (N >> 1) | (z << 7);
                v = ((v << 8) | w) >>> 0;
              }
              A = C;
              y = N >> 4;
              for (u = 0; 4 > u; u += 2) {
                w = 0;
                C = g.la >> (4 + u);
                N = q.la >> (4 + u);
                for (p = 0; 2 > p; ++p) {
                  z = N & 1;
                  for (B = 0; 2 > B; ++B)
                    (E = z + (C & 1)),
                      (E = oa(k, l[2], E, n.Qc, 0, h, r)),
                      (z = 0 < E),
                      (C = (C >> 1) | (z << 3)),
                      (w = (w << 2) | (3 < E ? 3 : 1 < E ? 2 : 0 != h[r + 0])),
                      (r += 16);
                  C >>= 2;
                  N = (N >> 1) | (z << 5);
                }
                t |= w << (4 * u);
                A |= (C << 4) << u;
                y |= (N & 240) << u;
              }
              g.la = A;
              q.la = y;
              m.Hc = v;
              m.Gc = t;
              m.ia = t & 43690 ? 0 : n.ia;
              l = !(v | t);
            }
            0 < d.L &&
              ((d.wa[d.Y + d.ja] = d.gd[f.$b][f.Za]),
              (d.wa[d.Y + d.ja].La |= !l));
            if (e.Ka) return T(a, 7, "Premature end-of-file encountered.");
          }
          Lc(a);
          c = a;
          d = b;
          e = 1;
          f = c.D;
          g = 0 < c.L && c.M >= c.zb && c.M <= c.Va;
          if (0 == c.Aa)
            a: {
              (f.M = c.M), (f.uc = g), Oc(c, f), (e = 1);
              w = c.D;
              f = w.Nb;
              t = Ya[c.L];
              g = t * c.R;
              k = (t / 2) * c.B;
              p = 16 * f * c.R;
              B = 8 * f * c.B;
              l = c.sa;
              m = c.ta - g + p;
              n = c.qa;
              h = c.ra - k + B;
              r = c.Ha;
              q = c.Ia - k + B;
              C = w.M;
              N = 0 == C;
              v = C >= c.Va - 1;
              2 == c.Aa && Oc(c, w);
              if (w.uc)
                for (E = c, z = E.D.M, x(E.D.uc), w = E.yb; w < E.Hb; ++w) {
                  var Q = E;
                  y = w;
                  A = z;
                  var S = Q.D,
                    D = S.Nb;
                  u = Q.R;
                  var S = S.wa[S.Y + y],
                    F = Q.sa,
                    H = Q.ta + 16 * D * u + 16 * y,
                    J = S.dd,
                    G = S.tc;
                  if (0 != G)
                    if ((x(3 <= G), 1 == Q.L))
                      0 < y && Pc(F, H, u, G + 4),
                        S.La && Qc(F, H, u, G),
                        0 < A && Rc(F, H, u, G + 4),
                        S.La && Sc(F, H, u, G);
                    else {
                      var L = Q.B,
                        O = Q.qa,
                        P = Q.ra + 8 * D * L + 8 * y,
                        R = Q.Ha,
                        Q = Q.Ia + 8 * D * L + 8 * y,
                        D = S.ld;
                      0 < y &&
                        (Tc(F, H, u, G + 4, J, D),
                        Uc(O, P, R, Q, L, G + 4, J, D));
                      S.La && (Vc(F, H, u, G, J, D), Wc(O, P, R, Q, L, G, J, D));
                      0 < A &&
                        (Xc(F, H, u, G + 4, J, D),
                        Yc(O, P, R, Q, L, G + 4, J, D));
                      S.La && (Zc(F, H, u, G, J, D), $c(O, P, R, Q, L, G, J, D));
                    }
                }
              c.ia && alert("todo:DitherRow");
              if (null != d.put) {
                w = 16 * C;
                C = 16 * (C + 1);
                N
                  ? ((d.y = c.sa),
                    (d.O = c.ta + p),
                    (d.f = c.qa),
                    (d.N = c.ra + B),
                    (d.ea = c.Ha),
                    (d.W = c.Ia + B))
                  : ((w -= t),
                    (d.y = l),
                    (d.O = m),
                    (d.f = n),
                    (d.N = h),
                    (d.ea = r),
                    (d.W = q));
                v || (C -= t);
                C > d.o && (C = d.o);
                d.F = null;
                d.J = null;
                if (
                  null != c.Fa &&
                  0 < c.Fa.length &&
                  w < C &&
                  ((d.J = Le(c, d, w, C - w)),
                  (d.F = c.mb),
                  null == d.F && 0 == d.F.length)
                ) {
                  e = T(c, 3, "Could not decode alpha data.");
                  break a;
                }
                w < d.j &&
                  ((t = d.j - w),
                  (w = d.j),
                  x(!(t & 1)),
                  (d.O += c.R * t),
                  (d.N += c.B * (t >> 1)),
                  (d.W += c.B * (t >> 1)),
                  null != d.F && (d.J += d.width * t));
                w < C &&
                  ((d.O += d.v),
                  (d.N += d.v >> 1),
                  (d.W += d.v >> 1),
                  null != d.F && (d.J += d.v),
                  (d.ka = w - d.j),
                  (d.U = d.va - d.v),
                  (d.T = C - w),
                  (e = d.put(d)));
              }
              f + 1 != c.Ic ||
                v ||
                (I(c.sa, c.ta - g, l, m + 16 * c.R, g),
                I(c.qa, c.ra - k, n, h + 8 * c.B, k),
                I(c.Ha, c.Ia - k, r, q + 8 * c.B, k));
            }
          if (!e) return T(a, 6, "Output aborted.");
        }
        return 1;
      }
      function Me(a, b) {
        if (null == a) return 0;
        if (null == b) return T(a, 2, "NULL VP8Io parameter in VP8Decode().");
        if (!a.cb && !Kc(a, b)) return 0;
        x(a.cb);
        if (null == b.ac || b.ac(b)) {
          b.ob && (a.L = 0);
          var c = Ya[a.L];
          2 == a.L
            ? ((a.yb = 0), (a.zb = 0))
            : ((a.yb = (b.v - c) >> 4),
              (a.zb = (b.j - c) >> 4),
              0 > a.yb && (a.yb = 0),
              0 > a.zb && (a.zb = 0));
          a.Va = (b.o + 15 + c) >> 4;
          a.Hb = (b.va + 15 + c) >> 4;
          a.Hb > a.za && (a.Hb = a.za);
          a.Va > a.Ub && (a.Va = a.Ub);
          if (0 < a.L) {
            var d = a.ed;
            for (c = 0; 4 > c; ++c) {
              var e;
              if (a.Qa.Cb) {
                var f = a.Qa.Lb[c];
                a.Qa.Fb || (f += d.Tb);
              } else f = d.Tb;
              for (e = 0; 1 >= e; ++e) {
                var g = a.gd[c][e],
                  h = f;
                d.Pc && ((h += d.vd[0]), e && (h += d.od[0]));
                h = 0 > h ? 0 : 63 < h ? 63 : h;
                if (0 < h) {
                  var k = h;
                  0 < d.wb &&
                    ((k = 4 < d.wb ? k >> 2 : k >> 1),
                    k > 9 - d.wb && (k = 9 - d.wb));
                  1 > k && (k = 1);
                  g.dd = k;
                  g.tc = 2 * h + k;
                  g.ld = 40 <= h ? 2 : 15 <= h ? 1 : 0;
                } else g.tc = 0;
                g.La = e;
              }
            }
          }
          c = 0;
        } else T(a, 6, "Frame setup failed"), (c = a.a);
        if ((c = 0 == c)) {
          if (c) {
            a.$c = 0;
            0 < a.Aa || (a.Ic = Ne);
            b: {
              c = a.Ic;
              var k = a.za,
                d = 4 * k,
                l = 32 * k,
                m = k + 1,
                n = 0 < a.L ? k * (0 < a.Aa ? 2 : 1) : 0,
                r = (2 == a.Aa ? 2 : 1) * k;
              e = ((3 * (16 * c + Ya[a.L])) / 2) * l;
              f = null != a.Fa && 0 < a.Fa.length ? a.Kc.c * a.Kc.i : 0;
              g = d + 832 + e + f;
              if (g != g) c = 0;
              else {
                if (g > a.Vb) {
                  a.Vb = 0;
                  a.Ec = V(g);
                  a.Fc = 0;
                  if (null == a.Ec) {
                    c = T(a, 1, "no memory during frame initialization.");
                    break b;
                  }
                  a.Vb = g;
                }
                g = a.Ec;
                h = a.Fc;
                a.Ac = g;
                a.Bc = h;
                h += d;
                a.Gd = wa(l, Ic);
                a.Hd = 0;
                a.rb = wa(m + 1, Hc);
                a.sb = 1;
                a.wa = n ? wa(n, Xa) : null;
                a.Y = 0;
                a.D.Nb = 0;
                a.D.wa = a.wa;
                a.D.Y = a.Y;
                0 < a.Aa && (a.D.Y += k);
                x(!0);
                a.oc = g;
                a.pc = h;
                h += 832;
                a.ya = wa(r, Kb);
                a.aa = 0;
                a.D.ya = a.ya;
                a.D.aa = a.aa;
                2 == a.Aa && (a.D.aa += k);
                a.R = 16 * k;
                a.B = 8 * k;
                l = Ya[a.L];
                k = l * a.R;
                l = (l / 2) * a.B;
                a.sa = g;
                a.ta = h + k;
                a.qa = a.sa;
                a.ra = a.ta + 16 * c * a.R + l;
                a.Ha = a.qa;
                a.Ia = a.ra + 8 * c * a.B + l;
                a.$c = 0;
                h += e;
                a.mb = f ? g : null;
                a.nb = f ? h : null;
                x(h + f <= a.Fc + a.Vb);
                Lc(a);
                M(a.Ac, a.Bc, 0, d);
                c = 1;
              }
            }
            if (c) {
              b.ka = 0;
              b.y = a.sa;
              b.O = a.ta;
              b.f = a.qa;
              b.N = a.ra;
              b.ea = a.Ha;
              b.Vd = a.Ia;
              b.fa = a.R;
              b.Rc = a.B;
              b.F = null;
              b.J = 0;
              if (!ad) {
                for (c = -255; 255 >= c; ++c) bd[255 + c] = 0 > c ? -c : c;
                for (c = -1020; 1020 >= c; ++c)
                  cd[1020 + c] = -128 > c ? -128 : 127 < c ? 127 : c;
                for (c = -112; 112 >= c; ++c)
                  dd[112 + c] = -16 > c ? -16 : 15 < c ? 15 : c;
                for (c = -255; 510 >= c; ++c)
                  ed[255 + c] = 0 > c ? 0 : 255 < c ? 255 : c;
                ad = 1;
              }
              Nc = Oe;
              Za = Pe;
              Nb = Qe;
              pa = Re;
              Ob = Se;
              fd = Te;
              Xc = Ue;
              Tc = Ve;
              Yc = We;
              Uc = Xe;
              Zc = Ye;
              Vc = Ze;
              $c = $e;
              Wc = af;
              Rc = gd;
              Pc = hd;
              Sc = bf;
              Qc = cf;
              W[0] = df;
              W[1] = ef;
              W[2] = ff;
              W[3] = gf;
              W[4] = hf;
              W[5] = jf;
              W[6] = kf;
              W[7] = lf;
              W[8] = mf;
              W[9] = nf;
              Y[0] = of;
              Y[1] = pf;
              Y[2] = qf;
              Y[3] = rf;
              Y[4] = sf;
              Y[5] = tf;
              Y[6] = uf;
              ka[0] = vf;
              ka[1] = wf;
              ka[2] = xf;
              ka[3] = yf;
              ka[4] = zf;
              ka[5] = Af;
              ka[6] = Bf;
              c = 1;
            } else c = 0;
          }
          c && (c = Je(a, b));
          null != b.bc && b.bc(b);
          c &= 1;
        }
        if (!c) return 0;
        a.cb = 0;
        return c;
      }
      function qa(a, b, c, d, e) {
        e = a[b + c + 32 * d] + (e >> 3);
        a[b + c + 32 * d] = e & -256 ? (0 > e ? 0 : 255) : e;
      }
      function kb(a, b, c, d, e, f) {
        qa(a, b, 0, c, d + e);
        qa(a, b, 1, c, d + f);
        qa(a, b, 2, c, d - f);
        qa(a, b, 3, c, d - e);
      }
      function da(a) {
        return ((20091 * a) >> 16) + a;
      }
      function id(a, b, c, d) {
        var e = 0,
          f;
        var g = V(16);
        for (f = 0; 4 > f; ++f) {
          var h = a[b + 0] + a[b + 8];
          var k = a[b + 0] - a[b + 8];
          var l = ((35468 * a[b + 4]) >> 16) - da(a[b + 12]);
          var m = da(a[b + 4]) + ((35468 * a[b + 12]) >> 16);
          g[e + 0] = h + m;
          g[e + 1] = k + l;
          g[e + 2] = k - l;
          g[e + 3] = h - m;
          e += 4;
          b++;
        }
        for (f = e = 0; 4 > f; ++f)
          (a = g[e + 0] + 4),
            (h = a + g[e + 8]),
            (k = a - g[e + 8]),
            (l = ((35468 * g[e + 4]) >> 16) - da(g[e + 12])),
            (m = da(g[e + 4]) + ((35468 * g[e + 12]) >> 16)),
            qa(c, d, 0, 0, h + m),
            qa(c, d, 1, 0, k + l),
            qa(c, d, 2, 0, k - l),
            qa(c, d, 3, 0, h - m),
            e++,
            (d += 32);
      }
      function Te(a, b, c, d) {
        var e = a[b + 0] + 4,
          f = (35468 * a[b + 4]) >> 16,
          g = da(a[b + 4]),
          h = (35468 * a[b + 1]) >> 16;
        a = da(a[b + 1]);
        kb(c, d, 0, e + g, a, h);
        kb(c, d, 1, e + f, a, h);
        kb(c, d, 2, e - f, a, h);
        kb(c, d, 3, e - g, a, h);
      }
      function Pe(a, b, c, d, e) {
        id(a, b, c, d);
        e && id(a, b + 16, c, d + 4);
      }
      function Qe(a, b, c, d) {
        Za(a, b + 0, c, d, 1);
        Za(a, b + 32, c, d + 128, 1);
      }
      function Re(a, b, c, d) {
        a = a[b + 0] + 4;
        var e;
        for (e = 0; 4 > e; ++e) for (b = 0; 4 > b; ++b) qa(c, d, b, e, a);
      }
      function Se(a, b, c, d) {
        a[b + 0] && pa(a, b + 0, c, d);
        a[b + 16] && pa(a, b + 16, c, d + 4);
        a[b + 32] && pa(a, b + 32, c, d + 128);
        a[b + 48] && pa(a, b + 48, c, d + 128 + 4);
      }
      function Oe(a, b, c, d) {
        var e = V(16),
          f;
        for (f = 0; 4 > f; ++f) {
          var g = a[b + 0 + f] + a[b + 12 + f];
          var h = a[b + 4 + f] + a[b + 8 + f];
          var k = a[b + 4 + f] - a[b + 8 + f];
          var l = a[b + 0 + f] - a[b + 12 + f];
          e[0 + f] = g + h;
          e[8 + f] = g - h;
          e[4 + f] = l + k;
          e[12 + f] = l - k;
        }
        for (f = 0; 4 > f; ++f)
          (a = e[0 + 4 * f] + 3),
            (g = a + e[3 + 4 * f]),
            (h = e[1 + 4 * f] + e[2 + 4 * f]),
            (k = e[1 + 4 * f] - e[2 + 4 * f]),
            (l = a - e[3 + 4 * f]),
            (c[d + 0] = (g + h) >> 3),
            (c[d + 16] = (l + k) >> 3),
            (c[d + 32] = (g - h) >> 3),
            (c[d + 48] = (l - k) >> 3),
            (d += 64);
      }
      function Pb(a, b, c) {
        var d = b - 32,
          e = R,
          f = 255 - a[d - 1],
          g;
        for (g = 0; g < c; ++g) {
          var h = e,
            k = f + a[b - 1],
            l;
          for (l = 0; l < c; ++l) a[b + l] = h[k + a[d + l]];
          b += 32;
        }
      }
      function ef(a, b) {
        Pb(a, b, 4);
      }
      function wf(a, b) {
        Pb(a, b, 8);
      }
      function pf(a, b) {
        Pb(a, b, 16);
      }
      function qf(a, b) {
        var c;
        for (c = 0; 16 > c; ++c) I(a, b + 32 * c, a, b - 32, 16);
      }
      function rf(a, b) {
        var c;
        for (c = 16; 0 < c; --c) M(a, b, a[b - 1], 16), (b += 32);
      }
      function $a(a, b, c) {
        var d;
        for (d = 0; 16 > d; ++d) M(b, c + 32 * d, a, 16);
      }
      function of(a, b) {
        var c = 16,
          d;
        for (d = 0; 16 > d; ++d) c += a[b - 1 + 32 * d] + a[b + d - 32];
        $a(c >> 5, a, b);
      }
      function sf(a, b) {
        var c = 8,
          d;
        for (d = 0; 16 > d; ++d) c += a[b - 1 + 32 * d];
        $a(c >> 4, a, b);
      }
      function tf(a, b) {
        var c = 8,
          d;
        for (d = 0; 16 > d; ++d) c += a[b + d - 32];
        $a(c >> 4, a, b);
      }
      function uf(a, b) {
        $a(128, a, b);
      }
      function z(a, b, c) {
        return (a + 2 * b + c + 2) >> 2;
      }
      function ff(a, b) {
        var c = b - 32,
          c = new Uint8Array([
            z(a[c - 1], a[c + 0], a[c + 1]),
            z(a[c + 0], a[c + 1], a[c + 2]),
            z(a[c + 1], a[c + 2], a[c + 3]),
            z(a[c + 2], a[c + 3], a[c + 4])
          ]),
          d;
        for (d = 0; 4 > d; ++d) I(a, b + 32 * d, c, 0, c.length);
      }
      function gf(a, b) {
        var c = a[b - 1],
          d = a[b - 1 + 32],
          e = a[b - 1 + 64],
          f = a[b - 1 + 96];
        ra(a, b + 0, 16843009 * z(a[b - 1 - 32], c, d));
        ra(a, b + 32, 16843009 * z(c, d, e));
        ra(a, b + 64, 16843009 * z(d, e, f));
        ra(a, b + 96, 16843009 * z(e, f, f));
      }
      function df(a, b) {
        var c = 4,
          d;
        for (d = 0; 4 > d; ++d) c += a[b + d - 32] + a[b - 1 + 32 * d];
        c >>= 3;
        for (d = 0; 4 > d; ++d) M(a, b + 32 * d, c, 4);
      }
      function hf(a, b) {
        var c = a[b - 1 + 0],
          d = a[b - 1 + 32],
          e = a[b - 1 + 64],
          f = a[b - 1 - 32],
          g = a[b + 0 - 32],
          h = a[b + 1 - 32],
          k = a[b + 2 - 32],
          l = a[b + 3 - 32];
        a[b + 0 + 96] = z(d, e, a[b - 1 + 96]);
        a[b + 1 + 96] = a[b + 0 + 64] = z(c, d, e);
        a[b + 2 + 96] = a[b + 1 + 64] = a[b + 0 + 32] = z(f, c, d);
        a[b + 3 + 96] = a[b + 2 + 64] = a[b + 1 + 32] = a[b + 0 + 0] = z(g, f, c);
        a[b + 3 + 64] = a[b + 2 + 32] = a[b + 1 + 0] = z(h, g, f);
        a[b + 3 + 32] = a[b + 2 + 0] = z(k, h, g);
        a[b + 3 + 0] = z(l, k, h);
      }
      function kf(a, b) {
        var c = a[b + 1 - 32],
          d = a[b + 2 - 32],
          e = a[b + 3 - 32],
          f = a[b + 4 - 32],
          g = a[b + 5 - 32],
          h = a[b + 6 - 32],
          k = a[b + 7 - 32];
        a[b + 0 + 0] = z(a[b + 0 - 32], c, d);
        a[b + 1 + 0] = a[b + 0 + 32] = z(c, d, e);
        a[b + 2 + 0] = a[b + 1 + 32] = a[b + 0 + 64] = z(d, e, f);
        a[b + 3 + 0] = a[b + 2 + 32] = a[b + 1 + 64] = a[b + 0 + 96] = z(e, f, g);
        a[b + 3 + 32] = a[b + 2 + 64] = a[b + 1 + 96] = z(f, g, h);
        a[b + 3 + 64] = a[b + 2 + 96] = z(g, h, k);
        a[b + 3 + 96] = z(h, k, k);
      }
      function jf(a, b) {
        var c = a[b - 1 + 0],
          d = a[b - 1 + 32],
          e = a[b - 1 + 64],
          f = a[b - 1 - 32],
          g = a[b + 0 - 32],
          h = a[b + 1 - 32],
          k = a[b + 2 - 32],
          l = a[b + 3 - 32];
        a[b + 0 + 0] = a[b + 1 + 64] = (f + g + 1) >> 1;
        a[b + 1 + 0] = a[b + 2 + 64] = (g + h + 1) >> 1;
        a[b + 2 + 0] = a[b + 3 + 64] = (h + k + 1) >> 1;
        a[b + 3 + 0] = (k + l + 1) >> 1;
        a[b + 0 + 96] = z(e, d, c);
        a[b + 0 + 64] = z(d, c, f);
        a[b + 0 + 32] = a[b + 1 + 96] = z(c, f, g);
        a[b + 1 + 32] = a[b + 2 + 96] = z(f, g, h);
        a[b + 2 + 32] = a[b + 3 + 96] = z(g, h, k);
        a[b + 3 + 32] = z(h, k, l);
      }
      function lf(a, b) {
        var c = a[b + 0 - 32],
          d = a[b + 1 - 32],
          e = a[b + 2 - 32],
          f = a[b + 3 - 32],
          g = a[b + 4 - 32],
          h = a[b + 5 - 32],
          k = a[b + 6 - 32],
          l = a[b + 7 - 32];
        a[b + 0 + 0] = (c + d + 1) >> 1;
        a[b + 1 + 0] = a[b + 0 + 64] = (d + e + 1) >> 1;
        a[b + 2 + 0] = a[b + 1 + 64] = (e + f + 1) >> 1;
        a[b + 3 + 0] = a[b + 2 + 64] = (f + g + 1) >> 1;
        a[b + 0 + 32] = z(c, d, e);
        a[b + 1 + 32] = a[b + 0 + 96] = z(d, e, f);
        a[b + 2 + 32] = a[b + 1 + 96] = z(e, f, g);
        a[b + 3 + 32] = a[b + 2 + 96] = z(f, g, h);
        a[b + 3 + 64] = z(g, h, k);
        a[b + 3 + 96] = z(h, k, l);
      }
      function nf(a, b) {
        var c = a[b - 1 + 0],
          d = a[b - 1 + 32],
          e = a[b - 1 + 64],
          f = a[b - 1 + 96];
        a[b + 0 + 0] = (c + d + 1) >> 1;
        a[b + 2 + 0] = a[b + 0 + 32] = (d + e + 1) >> 1;
        a[b + 2 + 32] = a[b + 0 + 64] = (e + f + 1) >> 1;
        a[b + 1 + 0] = z(c, d, e);
        a[b + 3 + 0] = a[b + 1 + 32] = z(d, e, f);
        a[b + 3 + 32] = a[b + 1 + 64] = z(e, f, f);
        a[b + 3 + 64] = a[b + 2 + 64] = a[b + 0 + 96] = a[b + 1 + 96] = a[
          b + 2 + 96
        ] = a[b + 3 + 96] = f;
      }
      function mf(a, b) {
        var c = a[b - 1 + 0],
          d = a[b - 1 + 32],
          e = a[b - 1 + 64],
          f = a[b - 1 + 96],
          g = a[b - 1 - 32],
          h = a[b + 0 - 32],
          k = a[b + 1 - 32],
          l = a[b + 2 - 32];
        a[b + 0 + 0] = a[b + 2 + 32] = (c + g + 1) >> 1;
        a[b + 0 + 32] = a[b + 2 + 64] = (d + c + 1) >> 1;
        a[b + 0 + 64] = a[b + 2 + 96] = (e + d + 1) >> 1;
        a[b + 0 + 96] = (f + e + 1) >> 1;
        a[b + 3 + 0] = z(h, k, l);
        a[b + 2 + 0] = z(g, h, k);
        a[b + 1 + 0] = a[b + 3 + 32] = z(c, g, h);
        a[b + 1 + 32] = a[b + 3 + 64] = z(d, c, g);
        a[b + 1 + 64] = a[b + 3 + 96] = z(e, d, c);
        a[b + 1 + 96] = z(f, e, d);
      }
      function xf(a, b) {
        var c;
        for (c = 0; 8 > c; ++c) I(a, b + 32 * c, a, b - 32, 8);
      }
      function yf(a, b) {
        var c;
        for (c = 0; 8 > c; ++c) M(a, b, a[b - 1], 8), (b += 32);
      }
      function lb(a, b, c) {
        var d;
        for (d = 0; 8 > d; ++d) M(b, c + 32 * d, a, 8);
      }
      function vf(a, b) {
        var c = 8,
          d;
        for (d = 0; 8 > d; ++d) c += a[b + d - 32] + a[b - 1 + 32 * d];
        lb(c >> 4, a, b);
      }
      function Af(a, b) {
        var c = 4,
          d;
        for (d = 0; 8 > d; ++d) c += a[b + d - 32];
        lb(c >> 3, a, b);
      }
      function zf(a, b) {
        var c = 4,
          d;
        for (d = 0; 8 > d; ++d) c += a[b - 1 + 32 * d];
        lb(c >> 3, a, b);
      }
      function Bf(a, b) {
        lb(128, a, b);
      }
      function ab(a, b, c) {
        var d = a[b - c],
          e = a[b + 0],
          f = 3 * (e - d) + Qb[1020 + a[b - 2 * c] - a[b + c]],
          g = mb[112 + ((f + 4) >> 3)];
        a[b - c] = R[255 + d + mb[112 + ((f + 3) >> 3)]];
        a[b + 0] = R[255 + e - g];
      }
      function jd(a, b, c, d) {
        var e = a[b + 0],
          f = a[b + c];
        return U[255 + a[b - 2 * c] - a[b - c]] > d || U[255 + f - e] > d;
      }
      function kd(a, b, c, d) {
        return (
          4 * U[255 + a[b - c] - a[b + 0]] + U[255 + a[b - 2 * c] - a[b + c]] <= d
        );
      }
      function ld(a, b, c, d, e) {
        var f = a[b - 3 * c],
          g = a[b - 2 * c],
          h = a[b - c],
          k = a[b + 0],
          l = a[b + c],
          m = a[b + 2 * c],
          n = a[b + 3 * c];
        return 4 * U[255 + h - k] + U[255 + g - l] > d
          ? 0
          : U[255 + a[b - 4 * c] - f] <= e &&
              U[255 + f - g] <= e &&
              U[255 + g - h] <= e &&
              U[255 + n - m] <= e &&
              U[255 + m - l] <= e &&
              U[255 + l - k] <= e;
      }
      function gd(a, b, c, d) {
        var e = 2 * d + 1;
        for (d = 0; 16 > d; ++d) kd(a, b + d, c, e) && ab(a, b + d, c);
      }
      function hd(a, b, c, d) {
        var e = 2 * d + 1;
        for (d = 0; 16 > d; ++d) kd(a, b + d * c, 1, e) && ab(a, b + d * c, 1);
      }
      function bf(a, b, c, d) {
        var e;
        for (e = 3; 0 < e; --e) (b += 4 * c), gd(a, b, c, d);
      }
      function cf(a, b, c, d) {
        var e;
        for (e = 3; 0 < e; --e) (b += 4), hd(a, b, c, d);
      }
      function ea(a, b, c, d, e, f, g, h) {
        for (f = 2 * f + 1; 0 < e--; ) {
          if (ld(a, b, c, f, g))
            if (jd(a, b, c, h)) ab(a, b, c);
            else {
              var k = a,
                l = b,
                m = c,
                n = k[l - 2 * m],
                r = k[l - m],
                q = k[l + 0],
                t = k[l + m],
                v = k[l + 2 * m],
                p = Qb[1020 + 3 * (q - r) + Qb[1020 + n - t]],
                u = (27 * p + 63) >> 7,
                w = (18 * p + 63) >> 7,
                p = (9 * p + 63) >> 7;
              k[l - 3 * m] = R[255 + k[l - 3 * m] + p];
              k[l - 2 * m] = R[255 + n + w];
              k[l - m] = R[255 + r + u];
              k[l + 0] = R[255 + q - u];
              k[l + m] = R[255 + t - w];
              k[l + 2 * m] = R[255 + v - p];
            }
          b += d;
        }
      }
      function Fa(a, b, c, d, e, f, g, h) {
        for (f = 2 * f + 1; 0 < e--; ) {
          if (ld(a, b, c, f, g))
            if (jd(a, b, c, h)) ab(a, b, c);
            else {
              var k = a,
                l = b,
                m = c,
                n = k[l - m],
                r = k[l + 0],
                q = k[l + m],
                t = 3 * (r - n),
                v = mb[112 + ((t + 4) >> 3)],
                t = mb[112 + ((t + 3) >> 3)],
                p = (v + 1) >> 1;
              k[l - 2 * m] = R[255 + k[l - 2 * m] + p];
              k[l - m] = R[255 + n + t];
              k[l + 0] = R[255 + r - v];
              k[l + m] = R[255 + q - p];
            }
          b += d;
        }
      }
      function Ue(a, b, c, d, e, f) {
        ea(a, b, c, 1, 16, d, e, f);
      }
      function Ve(a, b, c, d, e, f) {
        ea(a, b, 1, c, 16, d, e, f);
      }
      function Ye(a, b, c, d, e, f) {
        var g;
        for (g = 3; 0 < g; --g) (b += 4 * c), Fa(a, b, c, 1, 16, d, e, f);
      }
      function Ze(a, b, c, d, e, f) {
        var g;
        for (g = 3; 0 < g; --g) (b += 4), Fa(a, b, 1, c, 16, d, e, f);
      }
      function We(a, b, c, d, e, f, g, h) {
        ea(a, b, e, 1, 8, f, g, h);
        ea(c, d, e, 1, 8, f, g, h);
      }
      function Xe(a, b, c, d, e, f, g, h) {
        ea(a, b, 1, e, 8, f, g, h);
        ea(c, d, 1, e, 8, f, g, h);
      }
      function $e(a, b, c, d, e, f, g, h) {
        Fa(a, b + 4 * e, e, 1, 8, f, g, h);
        Fa(c, d + 4 * e, e, 1, 8, f, g, h);
      }
      function af(a, b, c, d, e, f, g, h) {
        Fa(a, b + 4, 1, e, 8, f, g, h);
        Fa(c, d + 4, 1, e, 8, f, g, h);
      }
      function Cf() {
        this.ba = new Cb();
        this.ec = [];
        this.cc = [];
        this.Mc = [];
        this.Dc = this.Nc = this.dc = this.fc = 0;
        this.Oa = new Ud();
        this.memory = 0;
        this.Ib = "OutputFunc";
        this.Jb = "OutputAlphaFunc";
        this.Nd = "OutputRowFunc";
      }
      function md() {
        this.data = [];
        this.offset = this.kd = this.ha = this.w = 0;
        this.na = [];
        this.xa = this.gb = this.Ja = this.Sa = this.P = 0;
      }
      function Df() {
        this.nc = this.Ea = this.b = this.hc = 0;
        this.K = [];
        this.w = 0;
      }
      function Ef() {
        this.ua = 0;
        this.Wa = new ac();
        this.vb = new ac();
        this.md = this.xc = this.wc = 0;
        this.vc = [];
        this.Wb = 0;
        this.Ya = new Ub();
        this.yc = new O();
      }
      function je() {
        this.xb = this.a = 0;
        this.l = new Oa();
        this.ca = new Cb();
        this.V = [];
        this.Ba = 0;
        this.Ta = [];
        this.Ua = 0;
        this.m = new Ra();
        this.Pb = 0;
        this.wd = new Ra();
        this.Ma = this.$ = this.C = this.i = this.c = this.xd = 0;
        this.s = new Ef();
        this.ab = 0;
        this.gc = wa(4, Df);
        this.Oc = 0;
      }
      function Ff() {
        this.Lc = this.Z = this.$a = this.i = this.c = 0;
        this.l = new Oa();
        this.ic = 0;
        this.ca = [];
        this.tb = 0;
        this.qd = null;
        this.rd = 0;
      }
      function Rb(a, b, c, d, e, f, g) {
        a = null == a ? 0 : a[b + 0];
        for (b = 0; b < g; ++b) (e[f + b] = (a + c[d + b]) & 255), (a = e[f + b]);
      }
      function Gf(a, b, c, d, e, f, g) {
        if (null == a) Rb(null, null, c, d, e, f, g);
        else {
          var h;
          for (h = 0; h < g; ++h) e[f + h] = (a[b + h] + c[d + h]) & 255;
        }
      }
      function Hf(a, b, c, d, e, f, g) {
        if (null == a) Rb(null, null, c, d, e, f, g);
        else {
          var h = a[b + 0],
            k = h,
            l = h,
            m;
          for (m = 0; m < g; ++m)
            (h = a[b + m]),
              (k = l + h - k),
              (l = (c[d + m] + (k & -256 ? (0 > k ? 0 : 255) : k)) & 255),
              (k = h),
              (e[f + m] = l);
        }
      }
      function Le(a, b, c, d) {
        var e = b.width,
          f = b.o;
        x(null != a && null != b);
        if (0 > c || 0 >= d || c + d > f) return null;
        if (!a.Cc) {
          if (null == a.ga) {
            a.ga = new Ff();
            var g;
            (g = null == a.ga) ||
              ((g = b.width * b.o),
              x(0 == a.Gb.length),
              (a.Gb = V(g)),
              (a.Uc = 0),
              null == a.Gb
                ? (g = 0)
                : ((a.mb = a.Gb), (a.nb = a.Uc), (a.rc = null), (g = 1)),
              (g = !g));
            if (!g) {
              g = a.ga;
              var h = a.Fa,
                k = a.P,
                l = a.qc,
                m = a.mb,
                n = a.nb,
                r = k + 1,
                q = l - 1,
                t = g.l;
              x(null != h && null != m && null != b);
              ia[0] = null;
              ia[1] = Rb;
              ia[2] = Gf;
              ia[3] = Hf;
              g.ca = m;
              g.tb = n;
              g.c = b.width;
              g.i = b.height;
              x(0 < g.c && 0 < g.i);
              if (1 >= l) b = 0;
              else if (
                ((g.$a = (h[k + 0] >> 0) & 3),
                (g.Z = (h[k + 0] >> 2) & 3),
                (g.Lc = (h[k + 0] >> 4) & 3),
                (k = (h[k + 0] >> 6) & 3),
                0 > g.$a || 1 < g.$a || 4 <= g.Z || 1 < g.Lc || k)
              )
                b = 0;
              else if (
                ((t.put = kc),
                (t.ac = gc),
                (t.bc = lc),
                (t.ma = g),
                (t.width = b.width),
                (t.height = b.height),
                (t.Da = b.Da),
                (t.v = b.v),
                (t.va = b.va),
                (t.j = b.j),
                (t.o = b.o),
                g.$a)
              )
                b: {
                  x(1 == g.$a), (b = Bc());
                  c: for (;;) {
                    if (null == b) {
                      b = 0;
                      break b;
                    }
                    x(null != g);
                    g.mc = b;
                    b.c = g.c;
                    b.i = g.i;
                    b.l = g.l;
                    b.l.ma = g;
                    b.l.width = g.c;
                    b.l.height = g.i;
                    b.a = 0;
                    cb(b.m, h, r, q);
                    if (!rb(g.c, g.i, 1, b, null)) break c;
                    1 == b.ab && 3 == b.gc[0].hc && yc(b.s)
                      ? ((g.ic = 1),
                        (h = b.c * b.i),
                        (b.Ta = null),
                        (b.Ua = 0),
                        (b.V = V(h)),
                        (b.Ba = 0),
                        null == b.V ? ((b.a = 1), (b = 0)) : (b = 1))
                      : ((g.ic = 0), (b = Ec(b, g.c)));
                    if (!b) break c;
                    b = 1;
                    break b;
                  }
                  g.mc = null;
                  b = 0;
                }
              else b = q >= g.c * g.i;
              g = !b;
            }
            if (g) return null;
            1 != a.ga.Lc ? (a.Ga = 0) : (d = f - c);
          }
          x(null != a.ga);
          x(c + d <= f);
          a: {
            h = a.ga;
            b = h.c;
            f = h.l.o;
            if (0 == h.$a) {
              r = a.rc;
              q = a.Vc;
              t = a.Fa;
              k = a.P + 1 + c * b;
              l = a.mb;
              m = a.nb + c * b;
              x(k <= a.P + a.qc);
              if (0 != h.Z)
                for (x(null != ia[h.Z]), g = 0; g < d; ++g)
                  ia[h.Z](r, q, t, k, l, m, b),
                    (r = l),
                    (q = m),
                    (m += b),
                    (k += b);
              else
                for (g = 0; g < d; ++g)
                  I(l, m, t, k, b), (r = l), (q = m), (m += b), (k += b);
              a.rc = r;
              a.Vc = q;
            } else {
              x(null != h.mc);
              b = c + d;
              g = h.mc;
              x(null != g);
              x(b <= g.i);
              if (g.C >= b) b = 1;
              else if ((h.ic || Aa(), h.ic)) {
                var h = g.V,
                  r = g.Ba,
                  q = g.c,
                  v = g.i,
                  t = 1,
                  k = g.$ / q,
                  l = g.$ % q,
                  m = g.m,
                  n = g.s,
                  p = g.$,
                  u = q * v,
                  w = q * b,
                  y = n.wc,
                  A = p < w ? ha(n, l, k) : null;
                x(p <= u);
                x(b <= v);
                x(yc(n));
                c: for (;;) {
                  for (; !m.h && p < w; ) {
                    l & y || (A = ha(n, l, k));
                    x(null != A);
                    Sa(m);
                    v = ua(A.G[0], A.H[0], m);
                    if (256 > v)
                      (h[r + p] = v),
                        ++p,
                        ++l,
                        l >= q && ((l = 0), ++k, k <= b && !(k % 16) && Ib(g, k));
                    else if (280 > v) {
                      var v = ib(v - 256, m);
                      var E = ua(A.G[4], A.H[4], m);
                      Sa(m);
                      E = ib(E, m);
                      E = nc(q, E);
                      if (p >= E && u - p >= v) {
                        var B;
                        for (B = 0; B < v; ++B) h[r + p + B] = h[r + p + B - E];
                      } else {
                        t = 0;
                        break c;
                      }
                      p += v;
                      for (l += v; l >= q; )
                        (l -= q), ++k, k <= b && !(k % 16) && Ib(g, k);
                      p < w && l & y && (A = ha(n, l, k));
                    } else {
                      t = 0;
                      break c;
                    }
                    x(m.h == db(m));
                  }
                  Ib(g, k > b ? b : k);
                  break c;
                }
                !t || (m.h && p < u) ? ((t = 0), (g.a = m.h ? 5 : 3)) : (g.$ = p);
                b = t;
              } else b = Jb(g, g.V, g.Ba, g.c, g.i, b, se);
              if (!b) {
                d = 0;
                break a;
              }
            }
            c + d >= f && (a.Cc = 1);
            d = 1;
          }
          if (!d) return null;
          if (
            a.Cc &&
            ((d = a.ga), null != d && (d.mc = null), (a.ga = null), 0 < a.Ga)
          )
            return alert("todo:WebPDequantizeLevels"), null;
        }
        return a.nb + c * e;
      }
      function If(a, b, c, d, e, f) {
        for (; 0 < e--; ) {
          var g = a,
            h = b + (c ? 1 : 0),
            k = a,
            l = b + (c ? 0 : 3),
            m;
          for (m = 0; m < d; ++m) {
            var n = k[l + 4 * m];
            255 != n &&
              ((n *= 32897),
              (g[h + 4 * m + 0] = (g[h + 4 * m + 0] * n) >> 23),
              (g[h + 4 * m + 1] = (g[h + 4 * m + 1] * n) >> 23),
              (g[h + 4 * m + 2] = (g[h + 4 * m + 2] * n) >> 23));
          }
          b += f;
        }
      }
      function Jf(a, b, c, d, e) {
        for (; 0 < d--; ) {
          var f;
          for (f = 0; f < c; ++f) {
            var g = a[b + 2 * f + 0],
              h = a[b + 2 * f + 1],
              k = h & 15,
              l = 4369 * k,
              h = (((h & 240) | (h >> 4)) * l) >> 16;
            a[b + 2 * f + 0] =
              (((((g & 240) | (g >> 4)) * l) >> 16) & 240) |
              ((((((g & 15) | (g << 4)) * l) >> 16) >> 4) & 15);
            a[b + 2 * f + 1] = (h & 240) | k;
          }
          b += e;
        }
      }
      function Kf(a, b, c, d, e, f, g, h) {
        var k = 255,
          l,
          m;
        for (m = 0; m < e; ++m) {
          for (l = 0; l < d; ++l) {
            var n = a[b + l];
            f[g + 4 * l] = n;
            k &= n;
          }
          b += c;
          g += h;
        }
        return 255 != k;
      }
      function Lf(a, b, c, d, e) {
        var f;
        for (f = 0; f < e; ++f) c[d + f] = a[b + f] >> 8;
      }
      function Aa() {
        za = If;
        vc = Jf;
        fc = Kf;
        Fc = Lf;
      }
      function va(a, b, c) {
        self[a] = function(a, e, f, g, h, k, l, m, n, r, q, t, v, p, u, w, y) {
          var d,
            E = (y - 1) >> 1;
          var B = h[k + 0] | (l[m + 0] << 16);
          var C = n[r + 0] | (q[t + 0] << 16);
          x(null != a);
          var z = (3 * B + C + 131074) >> 2;
          b(a[e + 0], z & 255, z >> 16, v, p);
          null != f &&
            ((z = (3 * C + B + 131074) >> 2),
            b(f[g + 0], z & 255, z >> 16, u, w));
          for (d = 1; d <= E; ++d) {
            var D = h[k + d] | (l[m + d] << 16);
            var G = n[r + d] | (q[t + d] << 16);
            var F = B + D + C + G + 524296;
            var H = (F + 2 * (D + C)) >> 3;
            F = (F + 2 * (B + G)) >> 3;
            z = (H + B) >> 1;
            B = (F + D) >> 1;
            b(a[e + 2 * d - 1], z & 255, z >> 16, v, p + (2 * d - 1) * c);
            b(a[e + 2 * d - 0], B & 255, B >> 16, v, p + (2 * d - 0) * c);
            null != f &&
              ((z = (F + C) >> 1),
              (B = (H + G) >> 1),
              b(f[g + 2 * d - 1], z & 255, z >> 16, u, w + (2 * d - 1) * c),
              b(f[g + 2 * d + 0], B & 255, B >> 16, u, w + (2 * d + 0) * c));
            B = D;
            C = G;
          }
          y & 1 ||
            ((z = (3 * B + C + 131074) >> 2),
            b(a[e + y - 1], z & 255, z >> 16, v, p + (y - 1) * c),
            null != f &&
              ((z = (3 * C + B + 131074) >> 2),
              b(f[g + y - 1], z & 255, z >> 16, u, w + (y - 1) * c)));
        };
      }
      function ic() {
        P[Ca] = Mf;
        P[Ua] = nd;
        P[tc] = Nf;
        P[Va] = od;
        P[ya] = pd;
        P[Db] = qd;
        P[wc] = Of;
        P[zb] = nd;
        P[Ab] = od;
        P[Ja] = pd;
        P[Bb] = qd;
      }
      function Sb(a) {
        return a & ~Pf ? (0 > a ? 0 : 255) : a >> rd;
      }
      function bb(a, b) {
        return Sb(((19077 * a) >> 8) + ((26149 * b) >> 8) - 14234);
      }
      function nb(a, b, c) {
        return Sb(
          ((19077 * a) >> 8) - ((6419 * b) >> 8) - ((13320 * c) >> 8) + 8708
        );
      }
      function Pa(a, b) {
        return Sb(((19077 * a) >> 8) + ((33050 * b) >> 8) - 17685);
      }
      function Ga(a, b, c, d, e) {
        d[e + 0] = bb(a, c);
        d[e + 1] = nb(a, b, c);
        d[e + 2] = Pa(a, b);
      }
      function Tb(a, b, c, d, e) {
        d[e + 0] = Pa(a, b);
        d[e + 1] = nb(a, b, c);
        d[e + 2] = bb(a, c);
      }
      function sd(a, b, c, d, e) {
        var f = nb(a, b, c);
        b = ((f << 3) & 224) | (Pa(a, b) >> 3);
        d[e + 0] = (bb(a, c) & 248) | (f >> 5);
        d[e + 1] = b;
      }
      function td(a, b, c, d, e) {
        var f = (Pa(a, b) & 240) | 15;
        d[e + 0] = (bb(a, c) & 240) | (nb(a, b, c) >> 4);
        d[e + 1] = f;
      }
      function ud(a, b, c, d, e) {
        d[e + 0] = 255;
        Ga(a, b, c, d, e + 1);
      }
      function vd(a, b, c, d, e) {
        Tb(a, b, c, d, e);
        d[e + 3] = 255;
      }
      function wd(a, b, c, d, e) {
        Ga(a, b, c, d, e);
        d[e + 3] = 255;
      }
      function ga(a, b) {
        return 0 > a ? 0 : a > b ? b : a;
      }
      function la(a, b, c) {
        self[a] = function(a, e, f, g, h, k, l, m, n) {
          for (var d = m + (n & -2) * c; m != d; )
            b(a[e + 0], f[g + 0], h[k + 0], l, m),
              b(a[e + 1], f[g + 0], h[k + 0], l, m + c),
              (e += 2),
              ++g,
              ++k,
              (m += 2 * c);
          n & 1 && b(a[e + 0], f[g + 0], h[k + 0], l, m);
        };
      }
      function xd(a, b, c) {
        return 0 == c ? (0 == a ? (0 == b ? 6 : 5) : 0 == b ? 4 : 0) : c;
      }
      function yd(a, b, c, d, e) {
        switch (a >>> 30) {
          case 3:
            Za(b, c, d, e, 0);
            break;
          case 2:
            fd(b, c, d, e);
            break;
          case 1:
            pa(b, c, d, e);
        }
      }
      function Oc(a, b) {
        var c,
          d,
          e = b.M,
          f = b.Nb,
          g = a.oc,
          h = a.pc + 40,
          k = a.oc,
          l = a.pc + 584,
          m = a.oc,
          n = a.pc + 600;
        for (c = 0; 16 > c; ++c) g[h + 32 * c - 1] = 129;
        for (c = 0; 8 > c; ++c)
          (k[l + 32 * c - 1] = 129), (m[n + 32 * c - 1] = 129);
        0 < e
          ? (g[h - 1 - 32] = k[l - 1 - 32] = m[n - 1 - 32] = 129)
          : (M(g, h - 32 - 1, 127, 21),
            M(k, l - 32 - 1, 127, 9),
            M(m, n - 32 - 1, 127, 9));
        for (d = 0; d < a.za; ++d) {
          var r = b.ya[b.aa + d];
          if (0 < d) {
            for (c = -1; 16 > c; ++c) I(g, h + 32 * c - 4, g, h + 32 * c + 12, 4);
            for (c = -1; 8 > c; ++c)
              I(k, l + 32 * c - 4, k, l + 32 * c + 4, 4),
                I(m, n + 32 * c - 4, m, n + 32 * c + 4, 4);
          }
          var q = a.Gd,
            t = a.Hd + d,
            v = r.ad,
            p = r.Hc;
          0 < e &&
            (I(g, h - 32, q[t].y, 0, 16),
            I(k, l - 32, q[t].f, 0, 8),
            I(m, n - 32, q[t].ea, 0, 8));
          if (r.Za) {
            var u = g;
            var w = h - 32 + 16;
            0 < e &&
              (d >= a.za - 1
                ? M(u, w, q[t].y[15], 4)
                : I(u, w, q[t + 1].y, 0, 4));
            for (c = 0; 4 > c; c++)
              u[w + 128 + c] = u[w + 256 + c] = u[w + 384 + c] = u[w + 0 + c];
            for (c = 0; 16 > c; ++c, p <<= 2)
              (u = g), (w = h + zd[c]), W[r.Ob[c]](u, w), yd(p, v, 16 * +c, u, w);
          } else if (((u = xd(d, e, r.Ob[0])), Y[u](g, h), 0 != p))
            for (c = 0; 16 > c; ++c, p <<= 2) yd(p, v, 16 * +c, g, h + zd[c]);
          c = r.Gc;
          u = xd(d, e, r.Dd);
          ka[u](k, l);
          ka[u](m, n);
          r = c >> 0;
          p = v;
          u = k;
          w = l;
          r & 255 && (r & 170 ? Nb(p, 256, u, w) : Ob(p, 256, u, w));
          c >>= 8;
          r = m;
          p = n;
          c & 255 && (c & 170 ? Nb(v, 320, r, p) : Ob(v, 320, r, p));
          e < a.Ub - 1 &&
            (I(q[t].y, 0, g, h + 480, 16),
            I(q[t].f, 0, k, l + 224, 8),
            I(q[t].ea, 0, m, n + 224, 8));
          c = 8 * f * a.B;
          q = a.sa;
          t = a.ta + 16 * d + 16 * f * a.R;
          v = a.qa;
          r = a.ra + 8 * d + c;
          p = a.Ha;
          u = a.Ia + 8 * d + c;
          for (c = 0; 16 > c; ++c) I(q, t + c * a.R, g, h + 32 * c, 16);
          for (c = 0; 8 > c; ++c)
            I(v, r + c * a.B, k, l + 32 * c, 8),
              I(p, u + c * a.B, m, n + 32 * c, 8);
        }
      }
      function Ad(a, b, c, d, e, f, g, h, k) {
        var l = [0],
          m = [0],
          n = 0,
          r = null != k ? k.kd : 0,
          q = null != k ? k : new md();
        if (null == a || 12 > c) return 7;
        q.data = a;
        q.w = b;
        q.ha = c;
        b = [b];
        c = [c];
        q.gb = [q.gb];
        a: {
          var t = b;
          var v = c;
          var p = q.gb;
          x(null != a);
          x(null != v);
          x(null != p);
          p[0] = 0;
          if (12 <= v[0] && !fa(a, t[0], "RIFF")) {
            if (fa(a, t[0] + 8, "WEBP")) {
              p = 3;
              break a;
            }
            var u = Ha(a, t[0] + 4);
            if (12 > u || 4294967286 < u) {
              p = 3;
              break a;
            }
            if (r && u > v[0] - 8) {
              p = 7;
              break a;
            }
            p[0] = u;
            t[0] += 12;
            v[0] -= 12;
          }
          p = 0;
        }
        if (0 != p) return p;
        u = 0 < q.gb[0];
        for (c = c[0]; ; ) {
          t = [0];
          n = [n];
          a: {
            var w = a;
            v = b;
            p = c;
            var y = n,
              A = l,
              z = m,
              B = t;
            y[0] = 0;
            if (8 > p[0]) p = 7;
            else {
              if (!fa(w, v[0], "VP8X")) {
                if (10 != Ha(w, v[0] + 4)) {
                  p = 3;
                  break a;
                }
                if (18 > p[0]) {
                  p = 7;
                  break a;
                }
                var C = Ha(w, v[0] + 8);
                var D = 1 + Yb(w, v[0] + 12);
                w = 1 + Yb(w, v[0] + 15);
                if (2147483648 <= D * w) {
                  p = 3;
                  break a;
                }
                null != B && (B[0] = C);
                null != A && (A[0] = D);
                null != z && (z[0] = w);
                v[0] += 18;
                p[0] -= 18;
                y[0] = 1;
              }
              p = 0;
            }
          }
          n = n[0];
          t = t[0];
          if (0 != p) return p;
          v = !!(t & 2);
          if (!u && n) return 3;
          null != f && (f[0] = !!(t & 16));
          null != g && (g[0] = v);
          null != h && (h[0] = 0);
          g = l[0];
          t = m[0];
          if (n && v && null == k) {
            p = 0;
            break;
          }
          if (4 > c) {
            p = 7;
            break;
          }
          if ((u && n) || (!u && !n && !fa(a, b[0], "ALPH"))) {
            c = [c];
            q.na = [q.na];
            q.P = [q.P];
            q.Sa = [q.Sa];
            a: {
              C = a;
              p = b;
              u = c;
              var y = q.gb,
                A = q.na,
                z = q.P,
                B = q.Sa;
              D = 22;
              x(null != C);
              x(null != u);
              w = p[0];
              var F = u[0];
              x(null != A);
              x(null != B);
              A[0] = null;
              z[0] = null;
              for (B[0] = 0; ; ) {
                p[0] = w;
                u[0] = F;
                if (8 > F) {
                  p = 7;
                  break a;
                }
                var G = Ha(C, w + 4);
                if (4294967286 < G) {
                  p = 3;
                  break a;
                }
                var H = (8 + G + 1) & -2;
                D += H;
                if (0 < y && D > y) {
                  p = 3;
                  break a;
                }
                if (!fa(C, w, "VP8 ") || !fa(C, w, "VP8L")) {
                  p = 0;
                  break a;
                }
                if (F[0] < H) {
                  p = 7;
                  break a;
                }
                fa(C, w, "ALPH") || ((A[0] = C), (z[0] = w + 8), (B[0] = G));
                w += H;
                F -= H;
              }
            }
            c = c[0];
            q.na = q.na[0];
            q.P = q.P[0];
            q.Sa = q.Sa[0];
            if (0 != p) break;
          }
          c = [c];
          q.Ja = [q.Ja];
          q.xa = [q.xa];
          a: if (
            ((y = a),
            (p = b),
            (u = c),
            (A = q.gb[0]),
            (z = q.Ja),
            (B = q.xa),
            (C = p[0]),
            (w = !fa(y, C, "VP8 ")),
            (D = !fa(y, C, "VP8L")),
            x(null != y),
            x(null != u),
            x(null != z),
            x(null != B),
            8 > u[0])
          )
            p = 7;
          else {
            if (w || D) {
              y = Ha(y, C + 4);
              if (12 <= A && y > A - 12) {
                p = 3;
                break a;
              }
              if (r && y > u[0] - 8) {
                p = 7;
                break a;
              }
              z[0] = y;
              p[0] += 8;
              u[0] -= 8;
              B[0] = D;
            } else
              (B[0] = 5 <= u[0] && 47 == y[C + 0] && !(y[C + 4] >> 5)),
                (z[0] = u[0]);
            p = 0;
          }
          c = c[0];
          q.Ja = q.Ja[0];
          q.xa = q.xa[0];
          b = b[0];
          if (0 != p) break;
          if (4294967286 < q.Ja) return 3;
          null == h || v || (h[0] = q.xa ? 2 : 1);
          g = [g];
          t = [t];
          if (q.xa) {
            if (5 > c) {
              p = 7;
              break;
            }
            h = g;
            r = t;
            v = f;
            null == a || 5 > c
              ? (a = 0)
              : 5 <= c && 47 == a[b + 0] && !(a[b + 4] >> 5)
              ? ((u = [0]),
                (y = [0]),
                (A = [0]),
                (z = new Ra()),
                cb(z, a, b, c),
                mc(z, u, y, A)
                  ? (null != h && (h[0] = u[0]),
                    null != r && (r[0] = y[0]),
                    null != v && (v[0] = A[0]),
                    (a = 1))
                  : (a = 0))
              : (a = 0);
          } else {
            if (10 > c) {
              p = 7;
              break;
            }
            h = t;
            null == a || 10 > c || !Jc(a, b + 3, c - 3)
              ? (a = 0)
              : ((r = a[b + 0] | (a[b + 1] << 8) | (a[b + 2] << 16)),
                (v = ((a[b + 7] << 8) | a[b + 6]) & 16383),
                (a = ((a[b + 9] << 8) | a[b + 8]) & 16383),
                r & 1 ||
                3 < ((r >> 1) & 7) ||
                !((r >> 4) & 1) ||
                r >> 5 >= q.Ja ||
                !v ||
                !a
                  ? (a = 0)
                  : (g && (g[0] = v), h && (h[0] = a), (a = 1)));
          }
          if (!a) return 3;
          g = g[0];
          t = t[0];
          if (n && (l[0] != g || m[0] != t)) return 3;
          null != k &&
            ((k[0] = q),
            (k.offset = b - k.w),
            x(4294967286 > b - k.w),
            x(k.offset == k.ha - c));
          break;
        }
        return 0 == p || (7 == p && n && null == k)
          ? (null != f && (f[0] |= null != q.na && 0 < q.na.length),
            null != d && (d[0] = g),
            null != e && (e[0] = t),
            0)
          : p;
      }
      function hc(a, b, c) {
        var d = b.width,
          e = b.height,
          f = 0,
          g = 0,
          h = d,
          k = e;
        b.Da = null != a && 0 < a.Da;
        if (
          b.Da &&
          ((h = a.cd),
          (k = a.bd),
          (f = a.v),
          (g = a.j),
          11 > c || ((f &= -2), (g &= -2)),
          0 > f || 0 > g || 0 >= h || 0 >= k || f + h > d || g + k > e)
        )
          return 0;
        b.v = f;
        b.j = g;
        b.va = f + h;
        b.o = g + k;
        b.U = h;
        b.T = k;
        b.da = null != a && 0 < a.da;
        if (b.da) {
          c = [a.ib];
          f = [a.hb];
          if (!bc(h, k, c, f)) return 0;
          b.ib = c[0];
          b.hb = f[0];
        }
        b.ob = null != a && a.ob;
        b.Kb = null == a || !a.Sd;
        b.da && ((b.ob = b.ib < (3 * d) / 4 && b.hb < (3 * e) / 4), (b.Kb = 0));
        return 1;
      }
      function Bd(a) {
        if (null == a) return 2;
        if (11 > a.S) {
          var b = a.f.RGBA;
          b.fb += (a.height - 1) * b.A;
          b.A = -b.A;
        } else
          (b = a.f.kb),
            (a = a.height),
            (b.O += (a - 1) * b.fa),
            (b.fa = -b.fa),
            (b.N += ((a - 1) >> 1) * b.Ab),
            (b.Ab = -b.Ab),
            (b.W += ((a - 1) >> 1) * b.Db),
            (b.Db = -b.Db),
            null != b.F && ((b.J += (a - 1) * b.lb), (b.lb = -b.lb));
        return 0;
      }
      function Cd(a, b, c, d) {
        if (null == d || 0 >= a || 0 >= b) return 2;
        if (null != c) {
          if (c.Da) {
            var e = c.cd,
              f = c.bd,
              g = c.v & -2,
              h = c.j & -2;
            if (0 > g || 0 > h || 0 >= e || 0 >= f || g + e > a || h + f > b)
              return 2;
            a = e;
            b = f;
          }
          if (c.da) {
            e = [c.ib];
            f = [c.hb];
            if (!bc(a, b, e, f)) return 2;
            a = e[0];
            b = f[0];
          }
        }
        d.width = a;
        d.height = b;
        a: {
          var k = d.width;
          var l = d.height;
          a = d.S;
          if (0 >= k || 0 >= l || !(a >= Ca && 13 > a)) a = 2;
          else {
            if (0 >= d.Rd && null == d.sd) {
              var g = (f = e = b = 0),
                h = k * Dd[a],
                m = h * l;
              11 > a ||
                ((b = (k + 1) / 2),
                (f = ((l + 1) / 2) * b),
                12 == a && ((e = k), (g = e * l)));
              l = V(m + 2 * f + g);
              if (null == l) {
                a = 1;
                break a;
              }
              d.sd = l;
              11 > a
                ? ((k = d.f.RGBA),
                  (k.eb = l),
                  (k.fb = 0),
                  (k.A = h),
                  (k.size = m))
                : ((k = d.f.kb),
                  (k.y = l),
                  (k.O = 0),
                  (k.fa = h),
                  (k.Fd = m),
                  (k.f = l),
                  (k.N = 0 + m),
                  (k.Ab = b),
                  (k.Cd = f),
                  (k.ea = l),
                  (k.W = 0 + m + f),
                  (k.Db = b),
                  (k.Ed = f),
                  12 == a && ((k.F = l), (k.J = 0 + m + 2 * f)),
                  (k.Tc = g),
                  (k.lb = e));
            }
            b = 1;
            e = d.S;
            f = d.width;
            g = d.height;
            if (e >= Ca && 13 > e)
              if (11 > e)
                (a = d.f.RGBA),
                  (h = Math.abs(a.A)),
                  (b &= h * (g - 1) + f <= a.size),
                  (b &= h >= f * Dd[e]),
                  (b &= null != a.eb);
              else {
                a = d.f.kb;
                h = (f + 1) / 2;
                m = (g + 1) / 2;
                k = Math.abs(a.fa);
                var l = Math.abs(a.Ab),
                  n = Math.abs(a.Db),
                  r = Math.abs(a.lb),
                  q = r * (g - 1) + f;
                b &= k * (g - 1) + f <= a.Fd;
                b &= l * (m - 1) + h <= a.Cd;
                b &= n * (m - 1) + h <= a.Ed;
                b = b & (k >= f) & (l >= h) & (n >= h);
                b &= null != a.y;
                b &= null != a.f;
                b &= null != a.ea;
                12 == e && ((b &= r >= f), (b &= q <= a.Tc), (b &= null != a.F));
              }
            else b = 0;
            a = b ? 0 : 2;
          }
        }
        if (0 != a) return a;
        null != c && c.fd && (a = Bd(d));
        return a;
      }
      var xb = 64,
        Hd = [
          0,
          1,
          3,
          7,
          15,
          31,
          63,
          127,
          255,
          511,
          1023,
          2047,
          4095,
          8191,
          16383,
          32767,
          65535,
          131071,
          262143,
          524287,
          1048575,
          2097151,
          4194303,
          8388607,
          16777215
        ],
        Gd = 24,
        ob = 32,
        Xb = 8,
        Id = [
          0,
          0,
          1,
          1,
          2,
          2,
          2,
          2,
          3,
          3,
          3,
          3,
          3,
          3,
          3,
          3,
          4,
          4,
          4,
          4,
          4,
          4,
          4,
          4,
          4,
          4,
          4,
          4,
          4,
          4,
          4,
          4,
          5,
          5,
          5,
          5,
          5,
          5,
          5,
          5,
          5,
          5,
          5,
          5,
          5,
          5,
          5,
          5,
          5,
          5,
          5,
          5,
          5,
          5,
          5,
          5,
          5,
          5,
          5,
          5,
          5,
          5,
          5,
          5,
          6,
          6,
          6,
          6,
          6,
          6,
          6,
          6,
          6,
          6,
          6,
          6,
          6,
          6,
          6,
          6,
          6,
          6,
          6,
          6,
          6,
          6,
          6,
          6,
          6,
          6,
          6,
          6,
          6,
          6,
          6,
          6,
          6,
          6,
          6,
          6,
          6,
          6,
          6,
          6,
          6,
          6,
          6,
          6,
          6,
          6,
          6,
          6,
          6,
          6,
          6,
          6,
          6,
          6,
          6,
          6,
          6,
          6,
          6,
          6,
          6,
          6,
          6,
          6,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7,
          7
        ];
      X("Predictor0", "PredictorAdd0");
      self.Predictor0 = function() {
        return 4278190080;
      };
      self.Predictor1 = function(a) {
        return a;
      };
      self.Predictor2 = function(a, b, c) {
        return b[c + 0];
      };
      self.Predictor3 = function(a, b, c) {
        return b[c + 1];
      };
      self.Predictor4 = function(a, b, c) {
        return b[c - 1];
      };
      self.Predictor5 = function(a, b, c) {
        return aa(aa(a, b[c + 1]), b[c + 0]);
      };
      self.Predictor6 = function(a, b, c) {
        return aa(a, b[c - 1]);
      };
      self.Predictor7 = function(a, b, c) {
        return aa(a, b[c + 0]);
      };
      self.Predictor8 = function(a, b, c) {
        return aa(b[c - 1], b[c + 0]);
      };
      self.Predictor9 = function(a, b, c) {
        return aa(b[c + 0], b[c + 1]);
      };
      self.Predictor10 = function(a, b, c) {
        return aa(aa(a, b[c - 1]), aa(b[c + 0], b[c + 1]));
      };
      self.Predictor11 = function(a, b, c) {
        var d = b[c + 0];
        b = b[c - 1];
        return 0 >=
          Ia((d >> 24) & 255, (a >> 24) & 255, (b >> 24) & 255) +
            Ia((d >> 16) & 255, (a >> 16) & 255, (b >> 16) & 255) +
            Ia((d >> 8) & 255, (a >> 8) & 255, (b >> 8) & 255) +
            Ia(d & 255, a & 255, b & 255)
          ? d
          : a;
      };
      self.Predictor12 = function(a, b, c) {
        var d = b[c + 0];
        b = b[c - 1];
        return (
          ((sa(((a >> 24) & 255) + ((d >> 24) & 255) - ((b >> 24) & 255)) << 24) |
            (sa(((a >> 16) & 255) + ((d >> 16) & 255) - ((b >> 16) & 255)) <<
              16) |
            (sa(((a >> 8) & 255) + ((d >> 8) & 255) - ((b >> 8) & 255)) << 8) |
            sa((a & 255) + (d & 255) - (b & 255))) >>>
          0
        );
      };
      self.Predictor13 = function(a, b, c) {
        var d = b[c - 1];
        a = aa(a, b[c + 0]);
        return (
          ((eb((a >> 24) & 255, (d >> 24) & 255) << 24) |
            (eb((a >> 16) & 255, (d >> 16) & 255) << 16) |
            (eb((a >> 8) & 255, (d >> 8) & 255) << 8) |
            eb((a >> 0) & 255, (d >> 0) & 255)) >>>
          0
        );
      };
      var ee = self.PredictorAdd0;
      self.PredictorAdd1 = cc;
      X("Predictor2", "PredictorAdd2");
      X("Predictor3", "PredictorAdd3");
      X("Predictor4", "PredictorAdd4");
      X("Predictor5", "PredictorAdd5");
      X("Predictor6", "PredictorAdd6");
      X("Predictor7", "PredictorAdd7");
      X("Predictor8", "PredictorAdd8");
      X("Predictor9", "PredictorAdd9");
      X("Predictor10", "PredictorAdd10");
      X("Predictor11", "PredictorAdd11");
      X("Predictor12", "PredictorAdd12");
      X("Predictor13", "PredictorAdd13");
      var fe = self.PredictorAdd2;
      ec(
        "ColorIndexInverseTransform",
        "MapARGB",
        "32b",
        function(a) {
          return (a >> 8) & 255;
        },
        function(a) {
          return a;
        }
      );
      ec(
        "VP8LColorIndexInverseTransformAlpha",
        "MapAlpha",
        "8b",
        function(a) {
          return a;
        },
        function(a) {
          return (a >> 8) & 255;
        }
      );
      var rc = self.ColorIndexInverseTransform,
        ke = self.MapARGB,
        he = self.VP8LColorIndexInverseTransformAlpha,
        le = self.MapAlpha,
        pc,
        qc = (self.VP8LPredictorsAdd = []);
      qc.length = 16;
      (self.VP8LPredictors = []).length = 16;
      (self.VP8LPredictorsAdd_C = []).length = 16;
      (self.VP8LPredictors_C = []).length = 16;
      var Fb,
        sc,
        Gb,
        Hb,
        xc,
        uc,
        bd = V(511),
        cd = V(2041),
        dd = V(225),
        ed = V(767),
        ad = 0,
        Qb = cd,
        mb = dd,
        R = ed,
        U = bd,
        Ca = 0,
        Ua = 1,
        tc = 2,
        Va = 3,
        ya = 4,
        Db = 5,
        wc = 6,
        zb = 7,
        Ab = 8,
        Ja = 9,
        Bb = 10,
        pe = [2, 3, 7],
        oe = [3, 3, 11],
        Dc = [280, 256, 256, 256, 40],
        qe = [0, 1, 1, 1, 0],
        ne = [17, 18, 0, 1, 2, 3, 4, 5, 16, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
        de = [
          24,
          7,
          23,
          25,
          40,
          6,
          39,
          41,
          22,
          26,
          38,
          42,
          56,
          5,
          55,
          57,
          21,
          27,
          54,
          58,
          37,
          43,
          72,
          4,
          71,
          73,
          20,
          28,
          53,
          59,
          70,
          74,
          36,
          44,
          88,
          69,
          75,
          52,
          60,
          3,
          87,
          89,
          19,
          29,
          86,
          90,
          35,
          45,
          68,
          76,
          85,
          91,
          51,
          61,
          104,
          2,
          103,
          105,
          18,
          30,
          102,
          106,
          34,
          46,
          84,
          92,
          67,
          77,
          101,
          107,
          50,
          62,
          120,
          1,
          119,
          121,
          83,
          93,
          17,
          31,
          100,
          108,
          66,
          78,
          118,
          122,
          33,
          47,
          117,
          123,
          49,
          63,
          99,
          109,
          82,
          94,
          0,
          116,
          124,
          65,
          79,
          16,
          32,
          98,
          110,
          48,
          115,
          125,
          81,
          95,
          64,
          114,
          126,
          97,
          111,
          80,
          113,
          127,
          96,
          112
        ],
        me = [
          2954,
          2956,
          2958,
          2962,
          2970,
          2986,
          3018,
          3082,
          3212,
          3468,
          3980,
          5004
        ],
        ie = 8,
        Lb = [
          4,
          5,
          6,
          7,
          8,
          9,
          10,
          10,
          11,
          12,
          13,
          14,
          15,
          16,
          17,
          17,
          18,
          19,
          20,
          20,
          21,
          21,
          22,
          22,
          23,
          23,
          24,
          25,
          25,
          26,
          27,
          28,
          29,
          30,
          31,
          32,
          33,
          34,
          35,
          36,
          37,
          37,
          38,
          39,
          40,
          41,
          42,
          43,
          44,
          45,
          46,
          46,
          47,
          48,
          49,
          50,
          51,
          52,
          53,
          54,
          55,
          56,
          57,
          58,
          59,
          60,
          61,
          62,
          63,
          64,
          65,
          66,
          67,
          68,
          69,
          70,
          71,
          72,
          73,
          74,
          75,
          76,
          76,
          77,
          78,
          79,
          80,
          81,
          82,
          83,
          84,
          85,
          86,
          87,
          88,
          89,
          91,
          93,
          95,
          96,
          98,
          100,
          101,
          102,
          104,
          106,
          108,
          110,
          112,
          114,
          116,
          118,
          122,
          124,
          126,
          128,
          130,
          132,
          134,
          136,
          138,
          140,
          143,
          145,
          148,
          151,
          154,
          157
        ],
        Mb = [
          4,
          5,
          6,
          7,
          8,
          9,
          10,
          11,
          12,
          13,
          14,
          15,
          16,
          17,
          18,
          19,
          20,
          21,
          22,
          23,
          24,
          25,
          26,
          27,
          28,
          29,
          30,
          31,
          32,
          33,
          34,
          35,
          36,
          37,
          38,
          39,
          40,
          41,
          42,
          43,
          44,
          45,
          46,
          47,
          48,
          49,
          50,
          51,
          52,
          53,
          54,
          55,
          56,
          57,
          58,
          60,
          62,
          64,
          66,
          68,
          70,
          72,
          74,
          76,
          78,
          80,
          82,
          84,
          86,
          88,
          90,
          92,
          94,
          96,
          98,
          100,
          102,
          104,
          106,
          108,
          110,
          112,
          114,
          116,
          119,
          122,
          125,
          128,
          131,
          134,
          137,
          140,
          143,
          146,
          149,
          152,
          155,
          158,
          161,
          164,
          167,
          170,
          173,
          177,
          181,
          185,
          189,
          193,
          197,
          201,
          205,
          209,
          213,
          217,
          221,
          225,
          229,
          234,
          239,
          245,
          249,
          254,
          259,
          264,
          269,
          274,
          279,
          284
        ],
        oa = null,
        He = [
          [173, 148, 140, 0],
          [176, 155, 140, 135, 0],
          [180, 157, 141, 134, 130, 0],
          [254, 254, 243, 230, 196, 177, 153, 140, 133, 130, 129, 0]
        ],
        Ie = [0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15],
        Mc = [-0, 1, -1, 2, -2, 3, 4, 6, -3, 5, -4, -5, -6, 7, -7, 8, -8, -9],
        Fe = [
          [
            [
              [128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128],
              [128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128],
              [128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128]
            ],
            [
              [253, 136, 254, 255, 228, 219, 128, 128, 128, 128, 128],
              [189, 129, 242, 255, 227, 213, 255, 219, 128, 128, 128],
              [106, 126, 227, 252, 214, 209, 255, 255, 128, 128, 128]
            ],
            [
              [1, 98, 248, 255, 236, 226, 255, 255, 128, 128, 128],
              [181, 133, 238, 254, 221, 234, 255, 154, 128, 128, 128],
              [78, 134, 202, 247, 198, 180, 255, 219, 128, 128, 128]
            ],
            [
              [1, 185, 249, 255, 243, 255, 128, 128, 128, 128, 128],
              [184, 150, 247, 255, 236, 224, 128, 128, 128, 128, 128],
              [77, 110, 216, 255, 236, 230, 128, 128, 128, 128, 128]
            ],
            [
              [1, 101, 251, 255, 241, 255, 128, 128, 128, 128, 128],
              [170, 139, 241, 252, 236, 209, 255, 255, 128, 128, 128],
              [37, 116, 196, 243, 228, 255, 255, 255, 128, 128, 128]
            ],
            [
              [1, 204, 254, 255, 245, 255, 128, 128, 128, 128, 128],
              [207, 160, 250, 255, 238, 128, 128, 128, 128, 128, 128],
              [102, 103, 231, 255, 211, 171, 128, 128, 128, 128, 128]
            ],
            [
              [1, 152, 252, 255, 240, 255, 128, 128, 128, 128, 128],
              [177, 135, 243, 255, 234, 225, 128, 128, 128, 128, 128],
              [80, 129, 211, 255, 194, 224, 128, 128, 128, 128, 128]
            ],
            [
              [1, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128],
              [246, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128],
              [255, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128]
            ]
          ],
          [
            [
              [198, 35, 237, 223, 193, 187, 162, 160, 145, 155, 62],
              [131, 45, 198, 221, 172, 176, 220, 157, 252, 221, 1],
              [68, 47, 146, 208, 149, 167, 221, 162, 255, 223, 128]
            ],
            [
              [1, 149, 241, 255, 221, 224, 255, 255, 128, 128, 128],
              [184, 141, 234, 253, 222, 220, 255, 199, 128, 128, 128],
              [81, 99, 181, 242, 176, 190, 249, 202, 255, 255, 128]
            ],
            [
              [1, 129, 232, 253, 214, 197, 242, 196, 255, 255, 128],
              [99, 121, 210, 250, 201, 198, 255, 202, 128, 128, 128],
              [23, 91, 163, 242, 170, 187, 247, 210, 255, 255, 128]
            ],
            [
              [1, 200, 246, 255, 234, 255, 128, 128, 128, 128, 128],
              [109, 178, 241, 255, 231, 245, 255, 255, 128, 128, 128],
              [44, 130, 201, 253, 205, 192, 255, 255, 128, 128, 128]
            ],
            [
              [1, 132, 239, 251, 219, 209, 255, 165, 128, 128, 128],
              [94, 136, 225, 251, 218, 190, 255, 255, 128, 128, 128],
              [22, 100, 174, 245, 186, 161, 255, 199, 128, 128, 128]
            ],
            [
              [1, 182, 249, 255, 232, 235, 128, 128, 128, 128, 128],
              [124, 143, 241, 255, 227, 234, 128, 128, 128, 128, 128],
              [35, 77, 181, 251, 193, 211, 255, 205, 128, 128, 128]
            ],
            [
              [1, 157, 247, 255, 236, 231, 255, 255, 128, 128, 128],
              [121, 141, 235, 255, 225, 227, 255, 255, 128, 128, 128],
              [45, 99, 188, 251, 195, 217, 255, 224, 128, 128, 128]
            ],
            [
              [1, 1, 251, 255, 213, 255, 128, 128, 128, 128, 128],
              [203, 1, 248, 255, 255, 128, 128, 128, 128, 128, 128],
              [137, 1, 177, 255, 224, 255, 128, 128, 128, 128, 128]
            ]
          ],
          [
            [
              [253, 9, 248, 251, 207, 208, 255, 192, 128, 128, 128],
              [175, 13, 224, 243, 193, 185, 249, 198, 255, 255, 128],
              [73, 17, 171, 221, 161, 179, 236, 167, 255, 234, 128]
            ],
            [
              [1, 95, 247, 253, 212, 183, 255, 255, 128, 128, 128],
              [239, 90, 244, 250, 211, 209, 255, 255, 128, 128, 128],
              [155, 77, 195, 248, 188, 195, 255, 255, 128, 128, 128]
            ],
            [
              [1, 24, 239, 251, 218, 219, 255, 205, 128, 128, 128],
              [201, 51, 219, 255, 196, 186, 128, 128, 128, 128, 128],
              [69, 46, 190, 239, 201, 218, 255, 228, 128, 128, 128]
            ],
            [
              [1, 191, 251, 255, 255, 128, 128, 128, 128, 128, 128],
              [223, 165, 249, 255, 213, 255, 128, 128, 128, 128, 128],
              [141, 124, 248, 255, 255, 128, 128, 128, 128, 128, 128]
            ],
            [
              [1, 16, 248, 255, 255, 128, 128, 128, 128, 128, 128],
              [190, 36, 230, 255, 236, 255, 128, 128, 128, 128, 128],
              [149, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128]
            ],
            [
              [1, 226, 255, 128, 128, 128, 128, 128, 128, 128, 128],
              [247, 192, 255, 128, 128, 128, 128, 128, 128, 128, 128],
              [240, 128, 255, 128, 128, 128, 128, 128, 128, 128, 128]
            ],
            [
              [1, 134, 252, 255, 255, 128, 128, 128, 128, 128, 128],
              [213, 62, 250, 255, 255, 128, 128, 128, 128, 128, 128],
              [55, 93, 255, 128, 128, 128, 128, 128, 128, 128, 128]
            ],
            [
              [128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128],
              [128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128],
              [128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128]
            ]
          ],
          [
            [
              [202, 24, 213, 235, 186, 191, 220, 160, 240, 175, 255],
              [126, 38, 182, 232, 169, 184, 228, 174, 255, 187, 128],
              [61, 46, 138, 219, 151, 178, 240, 170, 255, 216, 128]
            ],
            [
              [1, 112, 230, 250, 199, 191, 247, 159, 255, 255, 128],
              [166, 109, 228, 252, 211, 215, 255, 174, 128, 128, 128],
              [39, 77, 162, 232, 172, 180, 245, 178, 255, 255, 128]
            ],
            [
              [1, 52, 220, 246, 198, 199, 249, 220, 255, 255, 128],
              [124, 74, 191, 243, 183, 193, 250, 221, 255, 255, 128],
              [24, 71, 130, 219, 154, 170, 243, 182, 255, 255, 128]
            ],
            [
              [1, 182, 225, 249, 219, 240, 255, 224, 128, 128, 128],
              [149, 150, 226, 252, 216, 205, 255, 171, 128, 128, 128],
              [28, 108, 170, 242, 183, 194, 254, 223, 255, 255, 128]
            ],
            [
              [1, 81, 230, 252, 204, 203, 255, 192, 128, 128, 128],
              [123, 102, 209, 247, 188, 196, 255, 233, 128, 128, 128],
              [20, 95, 153, 243, 164, 173, 255, 203, 128, 128, 128]
            ],
            [
              [1, 222, 248, 255, 216, 213, 128, 128, 128, 128, 128],
              [168, 175, 246, 252, 235, 205, 255, 255, 128, 128, 128],
              [47, 116, 215, 255, 211, 212, 255, 255, 128, 128, 128]
            ],
            [
              [1, 121, 236, 253, 212, 214, 255, 255, 128, 128, 128],
              [141, 84, 213, 252, 201, 202, 255, 219, 128, 128, 128],
              [42, 80, 160, 240, 162, 185, 255, 205, 128, 128, 128]
            ],
            [
              [1, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128],
              [244, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128],
              [238, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128]
            ]
          ]
        ],
        Ke = [
          [
            [231, 120, 48, 89, 115, 113, 120, 152, 112],
            [152, 179, 64, 126, 170, 118, 46, 70, 95],
            [175, 69, 143, 80, 85, 82, 72, 155, 103],
            [56, 58, 10, 171, 218, 189, 17, 13, 152],
            [114, 26, 17, 163, 44, 195, 21, 10, 173],
            [121, 24, 80, 195, 26, 62, 44, 64, 85],
            [144, 71, 10, 38, 171, 213, 144, 34, 26],
            [170, 46, 55, 19, 136, 160, 33, 206, 71],
            [63, 20, 8, 114, 114, 208, 12, 9, 226],
            [81, 40, 11, 96, 182, 84, 29, 16, 36]
          ],
          [
            [134, 183, 89, 137, 98, 101, 106, 165, 148],
            [72, 187, 100, 130, 157, 111, 32, 75, 80],
            [66, 102, 167, 99, 74, 62, 40, 234, 128],
            [41, 53, 9, 178, 241, 141, 26, 8, 107],
            [74, 43, 26, 146, 73, 166, 49, 23, 157],
            [65, 38, 105, 160, 51, 52, 31, 115, 128],
            [104, 79, 12, 27, 217, 255, 87, 17, 7],
            [87, 68, 71, 44, 114, 51, 15, 186, 23],
            [47, 41, 14, 110, 182, 183, 21, 17, 194],
            [66, 45, 25, 102, 197, 189, 23, 18, 22]
          ],
          [
            [88, 88, 147, 150, 42, 46, 45, 196, 205],
            [43, 97, 183, 117, 85, 38, 35, 179, 61],
            [39, 53, 200, 87, 26, 21, 43, 232, 171],
            [56, 34, 51, 104, 114, 102, 29, 93, 77],
            [39, 28, 85, 171, 58, 165, 90, 98, 64],
            [34, 22, 116, 206, 23, 34, 43, 166, 73],
            [107, 54, 32, 26, 51, 1, 81, 43, 31],
            [68, 25, 106, 22, 64, 171, 36, 225, 114],
            [34, 19, 21, 102, 132, 188, 16, 76, 124],
            [62, 18, 78, 95, 85, 57, 50, 48, 51]
          ],
          [
            [193, 101, 35, 159, 215, 111, 89, 46, 111],
            [60, 148, 31, 172, 219, 228, 21, 18, 111],
            [112, 113, 77, 85, 179, 255, 38, 120, 114],
            [40, 42, 1, 196, 245, 209, 10, 25, 109],
            [88, 43, 29, 140, 166, 213, 37, 43, 154],
            [61, 63, 30, 155, 67, 45, 68, 1, 209],
            [100, 80, 8, 43, 154, 1, 51, 26, 71],
            [142, 78, 78, 16, 255, 128, 34, 197, 171],
            [41, 40, 5, 102, 211, 183, 4, 1, 221],
            [51, 50, 17, 168, 209, 192, 23, 25, 82]
          ],
          [
            [138, 31, 36, 171, 27, 166, 38, 44, 229],
            [67, 87, 58, 169, 82, 115, 26, 59, 179],
            [63, 59, 90, 180, 59, 166, 93, 73, 154],
            [40, 40, 21, 116, 143, 209, 34, 39, 175],
            [47, 15, 16, 183, 34, 223, 49, 45, 183],
            [46, 17, 33, 183, 6, 98, 15, 32, 183],
            [57, 46, 22, 24, 128, 1, 54, 17, 37],
            [65, 32, 73, 115, 28, 128, 23, 128, 205],
            [40, 3, 9, 115, 51, 192, 18, 6, 223],
            [87, 37, 9, 115, 59, 77, 64, 21, 47]
          ],
          [
            [104, 55, 44, 218, 9, 54, 53, 130, 226],
            [64, 90, 70, 205, 40, 41, 23, 26, 57],
            [54, 57, 112, 184, 5, 41, 38, 166, 213],
            [30, 34, 26, 133, 152, 116, 10, 32, 134],
            [39, 19, 53, 221, 26, 114, 32, 73, 255],
            [31, 9, 65, 234, 2, 15, 1, 118, 73],
            [75, 32, 12, 51, 192, 255, 160, 43, 51],
            [88, 31, 35, 67, 102, 85, 55, 186, 85],
            [56, 21, 23, 111, 59, 205, 45, 37, 192],
            [55, 38, 70, 124, 73, 102, 1, 34, 98]
          ],
          [
            [125, 98, 42, 88, 104, 85, 117, 175, 82],
            [95, 84, 53, 89, 128, 100, 113, 101, 45],
            [75, 79, 123, 47, 51, 128, 81, 171, 1],
            [57, 17, 5, 71, 102, 57, 53, 41, 49],
            [38, 33, 13, 121, 57, 73, 26, 1, 85],
            [41, 10, 67, 138, 77, 110, 90, 47, 114],
            [115, 21, 2, 10, 102, 255, 166, 23, 6],
            [101, 29, 16, 10, 85, 128, 101, 196, 26],
            [57, 18, 10, 102, 102, 213, 34, 20, 43],
            [117, 20, 15, 36, 163, 128, 68, 1, 26]
          ],
          [
            [102, 61, 71, 37, 34, 53, 31, 243, 192],
            [69, 60, 71, 38, 73, 119, 28, 222, 37],
            [68, 45, 128, 34, 1, 47, 11, 245, 171],
            [62, 17, 19, 70, 146, 85, 55, 62, 70],
            [37, 43, 37, 154, 100, 163, 85, 160, 1],
            [63, 9, 92, 136, 28, 64, 32, 201, 85],
            [75, 15, 9, 9, 64, 255, 184, 119, 16],
            [86, 6, 28, 5, 64, 255, 25, 248, 1],
            [56, 8, 17, 132, 137, 255, 55, 116, 128],
            [58, 15, 20, 82, 135, 57, 26, 121, 40]
          ],
          [
            [164, 50, 31, 137, 154, 133, 25, 35, 218],
            [51, 103, 44, 131, 131, 123, 31, 6, 158],
            [86, 40, 64, 135, 148, 224, 45, 183, 128],
            [22, 26, 17, 131, 240, 154, 14, 1, 209],
            [45, 16, 21, 91, 64, 222, 7, 1, 197],
            [56, 21, 39, 155, 60, 138, 23, 102, 213],
            [83, 12, 13, 54, 192, 255, 68, 47, 28],
            [85, 26, 85, 85, 128, 128, 32, 146, 171],
            [18, 11, 7, 63, 144, 171, 4, 4, 246],
            [35, 27, 10, 146, 174, 171, 12, 26, 128]
          ],
          [
            [190, 80, 35, 99, 180, 80, 126, 54, 45],
            [85, 126, 47, 87, 176, 51, 41, 20, 32],
            [101, 75, 128, 139, 118, 146, 116, 128, 85],
            [56, 41, 15, 176, 236, 85, 37, 9, 62],
            [71, 30, 17, 119, 118, 255, 17, 18, 138],
            [101, 38, 60, 138, 55, 70, 43, 26, 142],
            [146, 36, 19, 30, 171, 255, 97, 27, 20],
            [138, 45, 61, 62, 219, 1, 81, 188, 64],
            [32, 41, 20, 117, 151, 142, 20, 21, 163],
            [112, 19, 12, 61, 195, 128, 48, 4, 24]
          ]
        ],
        Ee = [
          [
            [
              [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
              [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
              [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255]
            ],
            [
              [176, 246, 255, 255, 255, 255, 255, 255, 255, 255, 255],
              [223, 241, 252, 255, 255, 255, 255, 255, 255, 255, 255],
              [249, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255]
            ],
            [
              [255, 244, 252, 255, 255, 255, 255, 255, 255, 255, 255],
              [234, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255],
              [253, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255]
            ],
            [
              [255, 246, 254, 255, 255, 255, 255, 255, 255, 255, 255],
              [239, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255],
              [254, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255]
            ],
            [
              [255, 248, 254, 255, 255, 255, 255, 255, 255, 255, 255],
              [251, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255],
              [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255]
            ],
            [
              [255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255],
              [251, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255],
              [254, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255]
            ],
            [
              [255, 254, 253, 255, 254, 255, 255, 255, 255, 255, 255],
              [250, 255, 254, 255, 254, 255, 255, 255, 255, 255, 255],
              [254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255]
            ],
            [
              [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
              [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
              [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255]
            ]
          ],
          [
            [
              [217, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
              [225, 252, 241, 253, 255, 255, 254, 255, 255, 255, 255],
              [234, 250, 241, 250, 253, 255, 253, 254, 255, 255, 255]
            ],
            [
              [255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255],
              [223, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255],
              [238, 253, 254, 254, 255, 255, 255, 255, 255, 255, 255]
            ],
            [
              [255, 248, 254, 255, 255, 255, 255, 255, 255, 255, 255],
              [249, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255],
              [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255]
            ],
            [
              [255, 253, 255, 255, 255, 255, 255, 255, 255, 255, 255],
              [247, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255],
              [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255]
            ],
            [
              [255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255],
              [252, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
              [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255]
            ],
            [
              [255, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255],
              [253, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
              [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255]
            ],
            [
              [255, 254, 253, 255, 255, 255, 255, 255, 255, 255, 255],
              [250, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
              [254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255]
            ],
            [
              [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
              [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
              [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255]
            ]
          ],
          [
            [
              [186, 251, 250, 255, 255, 255, 255, 255, 255, 255, 255],
              [234, 251, 244, 254, 255, 255, 255, 255, 255, 255, 255],
              [251, 251, 243, 253, 254, 255, 254, 255, 255, 255, 255]
            ],
            [
              [255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255],
              [236, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255],
              [251, 253, 253, 254, 254, 255, 255, 255, 255, 255, 255]
            ],
            [
              [255, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255],
              [254, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255],
              [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255]
            ],
            [
              [255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255],
              [254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255],
              [254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255]
            ],
            [
              [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
              [254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
              [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255]
            ],
            [
              [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
              [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
              [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255]
            ],
            [
              [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
              [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
              [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255]
            ],
            [
              [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
              [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
              [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255]
            ]
          ],
          [
            [
              [248, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
              [250, 254, 252, 254, 255, 255, 255, 255, 255, 255, 255],
              [248, 254, 249, 253, 255, 255, 255, 255, 255, 255, 255]
            ],
            [
              [255, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255],
              [246, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255],
              [252, 254, 251, 254, 254, 255, 255, 255, 255, 255, 255]
            ],
            [
              [255, 254, 252, 255, 255, 255, 255, 255, 255, 255, 255],
              [248, 254, 253, 255, 255, 255, 255, 255, 255, 255, 255],
              [253, 255, 254, 254, 255, 255, 255, 255, 255, 255, 255]
            ],
            [
              [255, 251, 254, 255, 255, 255, 255, 255, 255, 255, 255],
              [245, 251, 254, 255, 255, 255, 255, 255, 255, 255, 255],
              [253, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255]
            ],
            [
              [255, 251, 253, 255, 255, 255, 255, 255, 255, 255, 255],
              [252, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255],
              [255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255]
            ],
            [
              [255, 252, 255, 255, 255, 255, 255, 255, 255, 255, 255],
              [249, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255],
              [255, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255]
            ],
            [
              [255, 255, 253, 255, 255, 255, 255, 255, 255, 255, 255],
              [250, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
              [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255]
            ],
            [
              [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
              [254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
              [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255]
            ]
          ]
        ],
        Ge = [0, 1, 2, 3, 6, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6, 7, 0],
        Nc,
        Y = [],
        W = [],
        ka = [],
        Za,
        fd,
        Nb,
        pa,
        Ob,
        Xc,
        Tc,
        Yc,
        Uc,
        Zc,
        Vc,
        $c,
        Wc,
        Rc,
        Pc,
        Sc,
        Qc,
        re = 1,
        Cc = 2,
        ia = [],
        za,
        vc,
        fc,
        Fc,
        P = [];
      va("UpsampleRgbLinePair", Ga, 3);
      va("UpsampleBgrLinePair", Tb, 3);
      va("UpsampleRgbaLinePair", wd, 4);
      va("UpsampleBgraLinePair", vd, 4);
      va("UpsampleArgbLinePair", ud, 4);
      va("UpsampleRgba4444LinePair", td, 2);
      va("UpsampleRgb565LinePair", sd, 2);
      var Mf = self.UpsampleRgbLinePair,
        Nf = self.UpsampleBgrLinePair,
        nd = self.UpsampleRgbaLinePair,
        od = self.UpsampleBgraLinePair,
        pd = self.UpsampleArgbLinePair,
        qd = self.UpsampleRgba4444LinePair,
        Of = self.UpsampleRgb565LinePair,
        Wa = 16,
        Ba = 1 << (Wa - 1),
        ta = -227,
        Eb = 482,
        rd = 6,
        Pf = (256 << rd) - 1,
        jc = 0,
        Yd = V(256),
        ae = V(256),
        $d = V(256),
        Zd = V(256),
        be = V(Eb - ta),
        ce = V(Eb - ta);
      la("YuvToRgbRow", Ga, 3);
      la("YuvToBgrRow", Tb, 3);
      la("YuvToRgbaRow", wd, 4);
      la("YuvToBgraRow", vd, 4);
      la("YuvToArgbRow", ud, 4);
      la("YuvToRgba4444Row", td, 2);
      la("YuvToRgb565Row", sd, 2);
      var zd = [
          0,
          4,
          8,
          12,
          128,
          132,
          136,
          140,
          256,
          260,
          264,
          268,
          384,
          388,
          392,
          396
        ],
        Ya = [0, 2, 8],
        Qf = [8, 7, 6, 4, 4, 2, 2, 2, 1, 1, 1, 1],
        Ne = 1;
      this.WebPDecodeRGBA = function(a, b, c, d, e) {
        var f = Ua;
        var g = new Cf(),
          h = new Cb();
        g.ba = h;
        h.S = f;
        h.width = [h.width];
        h.height = [h.height];
        var k = h.width;
        var l = h.height,
          m = new Td();
        if (null == m || null == a) var n = 2;
        else
          x(null != m),
            (n = Ad(a, b, c, m.width, m.height, m.Pd, m.Qd, m.format, null));
        0 != n
          ? (k = 0)
          : (null != k && (k[0] = m.width[0]),
            null != l && (l[0] = m.height[0]),
            (k = 1));
        if (k) {
          h.width = h.width[0];
          h.height = h.height[0];
          null != d && (d[0] = h.width);
          null != e && (e[0] = h.height);
          b: {
            d = new Oa();
            e = new md();
            e.data = a;
            e.w = b;
            e.ha = c;
            e.kd = 1;
            b = [0];
            x(null != e);
            a = Ad(e.data, e.w, e.ha, null, null, null, b, null, e);
            (0 == a || 7 == a) && b[0] && (a = 4);
            b = a;
            if (0 == b) {
              x(null != g);
              d.data = e.data;
              d.w = e.w + e.offset;
              d.ha = e.ha - e.offset;
              d.put = kc;
              d.ac = gc;
              d.bc = lc;
              d.ma = g;
              if (e.xa) {
                a = Bc();
                if (null == a) {
                  g = 1;
                  break b;
                }
                if (te(a, d)) {
                  b = Cd(d.width, d.height, g.Oa, g.ba);
                  if ((d = 0 == b)) {
                    c: {
                      d = a;
                      d: for (;;) {
                        if (null == d) {
                          d = 0;
                          break c;
                        }
                        x(null != d.s.yc);
                        x(null != d.s.Ya);
                        x(0 < d.s.Wb);
                        c = d.l;
                        x(null != c);
                        e = c.ma;
                        x(null != e);
                        if (0 != d.xb) {
                          d.ca = e.ba;
                          d.tb = e.tb;
                          x(null != d.ca);
                          if (!hc(e.Oa, c, Va)) {
                            d.a = 2;
                            break d;
                          }
                          if (!Ec(d, c.width)) break d;
                          if (c.da) break d;
                          (c.da || hb(d.ca.S)) && Aa();
                          11 > d.ca.S ||
                            (alert("todo:WebPInitConvertARGBToYUV"),
                            null != d.ca.f.kb.F && Aa());
                          if (
                            d.Pb &&
                            0 < d.s.ua &&
                            null == d.s.vb.X &&
                            !Zb(d.s.vb, d.s.Wa.Xa)
                          ) {
                            d.a = 1;
                            break d;
                          }
                          d.xb = 0;
                        }
                        if (!Jb(d, d.V, d.Ba, d.c, d.i, c.o, ge)) break d;
                        e.Dc = d.Ma;
                        d = 1;
                        break c;
                      }
                      x(0 != d.a);
                      d = 0;
                    }
                    d = !d;
                  }
                  d && (b = a.a);
                } else b = a.a;
              } else {
                a = new Ce();
                if (null == a) {
                  g = 1;
                  break b;
                }
                a.Fa = e.na;
                a.P = e.P;
                a.qc = e.Sa;
                if (Kc(a, d)) {
                  if (((b = Cd(d.width, d.height, g.Oa, g.ba)), 0 == b)) {
                    a.Aa = 0;
                    c = g.Oa;
                    e = a;
                    x(null != e);
                    if (null != c) {
                      k = c.Md;
                      k = 0 > k ? 0 : 100 < k ? 255 : (255 * k) / 100;
                      if (0 < k) {
                        for (l = m = 0; 4 > l; ++l)
                          (n = e.pb[l]),
                            12 > n.lc &&
                              (n.ia = (k * Qf[0 > n.lc ? 0 : n.lc]) >> 3),
                            (m |= n.ia);
                        m && (alert("todo:VP8InitRandom"), (e.ia = 1));
                      }
                      e.Ga = c.Id;
                      100 < e.Ga ? (e.Ga = 100) : 0 > e.Ga && (e.Ga = 0);
                    }
                    Me(a, d) || (b = a.a);
                  }
                } else b = a.a;
              }
              0 == b && null != g.Oa && g.Oa.fd && (b = Bd(g.ba));
            }
            g = b;
          }
          f = 0 != g ? null : 11 > f ? h.f.RGBA.eb : h.f.kb.y;
        } else f = null;
        return f;
      };
      var Dd = [3, 4, 3, 4, 4, 2, 2, 4, 4, 4, 2, 1, 1];
    };
    new WebPDecoder();

    /** @license
     * Copyright (c) 2017 Dominik Homberger

  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.

  https://webpjs.appspot.com
  WebPRiffParser dominikhlbg@gmail.com
  */

    function memcmp(data, data_off, str, size) {
      for (var i = 0; i < size; i++)
        if (data[data_off + i] != str.charCodeAt(i)) return true;
      return false;
    }

    function GetTag(data, data_off) {
      var str = "";
      for (var i = 0; i < 4; i++) str += String.fromCharCode(data[data_off++]);
      return str;
    }

    function GetLE16(data, data_off) {
      return (data[data_off + 0] << 0) | (data[data_off + 1] << 8);
    }

    function GetLE24(data, data_off) {
      return (
        ((data[data_off + 0] << 0) |
          (data[data_off + 1] << 8) |
          (data[data_off + 2] << 16)) >>>
        0
      );
    }

    function GetLE32(data, data_off) {
      return (
        ((data[data_off + 0] << 0) |
          (data[data_off + 1] << 8) |
          (data[data_off + 2] << 16) |
          (data[data_off + 3] << 24)) >>>
        0
      );
    }

    function WebPRiffParser(src, src_off) {
      var imagearray = {};
      var i = 0;
      var alpha_chunk = false;
      var alpha_size = 0;
      var alpha_offset = 0;
      imagearray["frames"] = [];
      if (memcmp(src, src_off, "RIFF", 4)) return;
      src_off += 4;
      var riff_size = GetLE32(src, src_off) + 8;
      src_off += 8;

      while (src_off < src.length) {
        var fourcc = GetTag(src, src_off);
        src_off += 4;

        var payload_size = GetLE32(src, src_off);
        src_off += 4;
        var payload_size_padded = payload_size + (payload_size & 1);

        switch (fourcc) {
          case "VP8 ":
          case "VP8L":
            if (typeof imagearray["frames"][i] === "undefined")
              imagearray["frames"][i] = {};
            var obj = imagearray["frames"][i];
            var height = [0];
            var width = [0];
            obj["src_off"] = alpha_chunk ? alpha_offset : src_off - 8;
            obj["src_size"] = alpha_size + payload_size + 8;
            //var rgba = webpdecoder.WebPDecodeRGBA(src,(alpha_chunk?alpha_offset:src_off-8),alpha_size+payload_size+8,width,height);
            //imagearray[i]={'rgba':rgba,'width':width[0],'height':height[0]};
            i++;
            if (alpha_chunk) {
              alpha_chunk = false;
              alpha_size = 0;
              alpha_offset = 0;
            }
            break;
          case "VP8X":
            var obj = (imagearray["header"] = {});
            var feature_flags = (obj["feature_flags"] = src[src_off]);
            var src_off_ = src_off + 4;
            var canvas_width = (obj["canvas_width"] = 1 + GetLE24(src, src_off_));
            src_off_ += 3;
            var canvas_height = (obj["canvas_height"] =
              1 + GetLE24(src, src_off_));
            src_off_ += 3;
            break;
          case "ALPH":
            alpha_chunk = true;
            alpha_size = payload_size_padded + 8;
            alpha_offset = src_off - 8;
            break;

          case "ANIM":
            var obj = imagearray["header"];
            var bgcolor = (obj["bgcolor"] = GetLE32(src, src_off));
            src_off_ = src_off + 4;

            var loop_count = (obj["loop_count"] = GetLE16(src, src_off_));
            src_off_ += 2;
            break;
          case "ANMF":
            var offset_x = 0,
              offset_y = 0,
              width = 0,
              height = 0,
              duration = 0,
              blend = 0,
              dispose = 0,
              temp = 0;
            var obj = (imagearray["frames"][i] = {});
            obj["offset_x"] = offset_x = 2 * GetLE24(src, src_off);
            src_off += 3;
            obj["offset_y"] = offset_y = 2 * GetLE24(src, src_off);
            src_off += 3;
            obj["width"] = width = 1 + GetLE24(src, src_off);
            src_off += 3;
            obj["height"] = height = 1 + GetLE24(src, src_off);
            src_off += 3;
            obj["duration"] = duration = GetLE24(src, src_off);
            src_off += 3;
            temp = src[src_off++];
            obj["dispose"] = dispose = temp & 1;
            obj["blend"] = blend = (temp >> 1) & 1;
            break;
        }
        if (fourcc != "ANMF") src_off += payload_size_padded;
      }
      return imagearray;
    }

    var height = [0];
    var width = [0];
    var pixels = [];
    var webpdecoder = new WebPDecoder();

    var response = imageData;
    var imagearray = WebPRiffParser(response, 0);
    imagearray["response"] = response;
    imagearray["rgbaoutput"] = true;
    imagearray["dataurl"] = false;

    var header = imagearray["header"] ? imagearray["header"] : null;
    var frames = imagearray["frames"] ? imagearray["frames"] : null;

    if (header) {
      header["loop_counter"] = header["loop_count"];
      height = [header["canvas_height"]];
      width = [header["canvas_width"]];
      for (var f = 0; f < frames.length; f++)
        if (frames[f]["blend"] == 0) {
          break;
        }
    }

    var frame = frames[0];
    var rgba = webpdecoder.WebPDecodeRGBA(
      response,
      frame["src_off"],
      frame["src_size"],
      width,
      height
    );
    frame["rgba"] = rgba;
    frame["imgwidth"] = width[0];
    frame["imgheight"] = height[0];

    for (var i = 0; i < width[0] * height[0] * 4; i++) {
      pixels[i] = rgba[i];
    }

    this.width = width;
    this.height = height;
    this.data = pixels;
    return this;
  }

  WebPDecoder.prototype.getData = function() {
    return this.data;
  };

  /**
   * @license
   * Copyright (c) 2019 Aras Abbasi
   *
   * Licensed under the MIT License.
   * http://opensource.org/licenses/mit-license
   */

  /**
   * jsPDF webp Support PlugIn
   *
   * @name webp_support
   * @module
   */
  (function(jsPDFAPI) {

    jsPDFAPI.processWEBP = function(imageData, index, alias, compression) {
      var reader = new WebPDecoder(imageData, false);
      var width = reader.width,
        height = reader.height;
      var qu = 100;
      var pixels = reader.getData();

      var rawImageData = {
        data: pixels,
        width: width,
        height: height
      };

      var encoder = new JPEGEncoder(qu);
      var data = encoder.encode(rawImageData, qu);
      return jsPDFAPI.processJPEG.call(this, data, index, alias, compression);
    };
  })(jsPDF.API);

  /**
   * @license
   * Licensed under the MIT License.
   * http://opensource.org/licenses/mit-license
   */

  /**
   * jsPDF setLanguage Plugin
   *
   * @name setLanguage
   * @module
   */
  (function(jsPDFAPI) {

    /**
     * Add Language Tag to the generated PDF
     *
     * @name setLanguage
     * @function
     * @param {string} langCode The Language code as ISO-639-1 (e.g. 'en') or as country language code (e.g. 'en-GB').
     * @returns {jsPDF}
     * @example
     * var doc = new jsPDF()
     * doc.text(10, 10, 'This is a test')
     * doc.setLanguage("en-US")
     * doc.save('english.pdf')
     */
    jsPDFAPI.setLanguage = function(langCode) {

      var langCodes = {
        af: "Afrikaans",
        sq: "Albanian",
        ar: "Arabic (Standard)",
        "ar-DZ": "Arabic (Algeria)",
        "ar-BH": "Arabic (Bahrain)",
        "ar-EG": "Arabic (Egypt)",
        "ar-IQ": "Arabic (Iraq)",
        "ar-JO": "Arabic (Jordan)",
        "ar-KW": "Arabic (Kuwait)",
        "ar-LB": "Arabic (Lebanon)",
        "ar-LY": "Arabic (Libya)",
        "ar-MA": "Arabic (Morocco)",
        "ar-OM": "Arabic (Oman)",
        "ar-QA": "Arabic (Qatar)",
        "ar-SA": "Arabic (Saudi Arabia)",
        "ar-SY": "Arabic (Syria)",
        "ar-TN": "Arabic (Tunisia)",
        "ar-AE": "Arabic (U.A.E.)",
        "ar-YE": "Arabic (Yemen)",
        an: "Aragonese",
        hy: "Armenian",
        as: "Assamese",
        ast: "Asturian",
        az: "Azerbaijani",
        eu: "Basque",
        be: "Belarusian",
        bn: "Bengali",
        bs: "Bosnian",
        br: "Breton",
        bg: "Bulgarian",
        my: "Burmese",
        ca: "Catalan",
        ch: "Chamorro",
        ce: "Chechen",
        zh: "Chinese",
        "zh-HK": "Chinese (Hong Kong)",
        "zh-CN": "Chinese (PRC)",
        "zh-SG": "Chinese (Singapore)",
        "zh-TW": "Chinese (Taiwan)",
        cv: "Chuvash",
        co: "Corsican",
        cr: "Cree",
        hr: "Croatian",
        cs: "Czech",
        da: "Danish",
        nl: "Dutch (Standard)",
        "nl-BE": "Dutch (Belgian)",
        en: "English",
        "en-AU": "English (Australia)",
        "en-BZ": "English (Belize)",
        "en-CA": "English (Canada)",
        "en-IE": "English (Ireland)",
        "en-JM": "English (Jamaica)",
        "en-NZ": "English (New Zealand)",
        "en-PH": "English (Philippines)",
        "en-ZA": "English (South Africa)",
        "en-TT": "English (Trinidad & Tobago)",
        "en-GB": "English (United Kingdom)",
        "en-US": "English (United States)",
        "en-ZW": "English (Zimbabwe)",
        eo: "Esperanto",
        et: "Estonian",
        fo: "Faeroese",
        fj: "Fijian",
        fi: "Finnish",
        fr: "French (Standard)",
        "fr-BE": "French (Belgium)",
        "fr-CA": "French (Canada)",
        "fr-FR": "French (France)",
        "fr-LU": "French (Luxembourg)",
        "fr-MC": "French (Monaco)",
        "fr-CH": "French (Switzerland)",
        fy: "Frisian",
        fur: "Friulian",
        gd: "Gaelic (Scots)",
        "gd-IE": "Gaelic (Irish)",
        gl: "Galacian",
        ka: "Georgian",
        de: "German (Standard)",
        "de-AT": "German (Austria)",
        "de-DE": "German (Germany)",
        "de-LI": "German (Liechtenstein)",
        "de-LU": "German (Luxembourg)",
        "de-CH": "German (Switzerland)",
        el: "Greek",
        gu: "Gujurati",
        ht: "Haitian",
        he: "Hebrew",
        hi: "Hindi",
        hu: "Hungarian",
        is: "Icelandic",
        id: "Indonesian",
        iu: "Inuktitut",
        ga: "Irish",
        it: "Italian (Standard)",
        "it-CH": "Italian (Switzerland)",
        ja: "Japanese",
        kn: "Kannada",
        ks: "Kashmiri",
        kk: "Kazakh",
        km: "Khmer",
        ky: "Kirghiz",
        tlh: "Klingon",
        ko: "Korean",
        "ko-KP": "Korean (North Korea)",
        "ko-KR": "Korean (South Korea)",
        la: "Latin",
        lv: "Latvian",
        lt: "Lithuanian",
        lb: "Luxembourgish",
        mk: "FYRO Macedonian",
        ms: "Malay",
        ml: "Malayalam",
        mt: "Maltese",
        mi: "Maori",
        mr: "Marathi",
        mo: "Moldavian",
        nv: "Navajo",
        ng: "Ndonga",
        ne: "Nepali",
        no: "Norwegian",
        nb: "Norwegian (Bokmal)",
        nn: "Norwegian (Nynorsk)",
        oc: "Occitan",
        or: "Oriya",
        om: "Oromo",
        fa: "Persian",
        "fa-IR": "Persian/Iran",
        pl: "Polish",
        pt: "Portuguese",
        "pt-BR": "Portuguese (Brazil)",
        pa: "Punjabi",
        "pa-IN": "Punjabi (India)",
        "pa-PK": "Punjabi (Pakistan)",
        qu: "Quechua",
        rm: "Rhaeto-Romanic",
        ro: "Romanian",
        "ro-MO": "Romanian (Moldavia)",
        ru: "Russian",
        "ru-MO": "Russian (Moldavia)",
        sz: "Sami (Lappish)",
        sg: "Sango",
        sa: "Sanskrit",
        sc: "Sardinian",
        sd: "Sindhi",
        si: "Singhalese",
        sr: "Serbian",
        sk: "Slovak",
        sl: "Slovenian",
        so: "Somani",
        sb: "Sorbian",
        es: "Spanish",
        "es-AR": "Spanish (Argentina)",
        "es-BO": "Spanish (Bolivia)",
        "es-CL": "Spanish (Chile)",
        "es-CO": "Spanish (Colombia)",
        "es-CR": "Spanish (Costa Rica)",
        "es-DO": "Spanish (Dominican Republic)",
        "es-EC": "Spanish (Ecuador)",
        "es-SV": "Spanish (El Salvador)",
        "es-GT": "Spanish (Guatemala)",
        "es-HN": "Spanish (Honduras)",
        "es-MX": "Spanish (Mexico)",
        "es-NI": "Spanish (Nicaragua)",
        "es-PA": "Spanish (Panama)",
        "es-PY": "Spanish (Paraguay)",
        "es-PE": "Spanish (Peru)",
        "es-PR": "Spanish (Puerto Rico)",
        "es-ES": "Spanish (Spain)",
        "es-UY": "Spanish (Uruguay)",
        "es-VE": "Spanish (Venezuela)",
        sx: "Sutu",
        sw: "Swahili",
        sv: "Swedish",
        "sv-FI": "Swedish (Finland)",
        "sv-SV": "Swedish (Sweden)",
        ta: "Tamil",
        tt: "Tatar",
        te: "Teluga",
        th: "Thai",
        tig: "Tigre",
        ts: "Tsonga",
        tn: "Tswana",
        tr: "Turkish",
        tk: "Turkmen",
        uk: "Ukrainian",
        hsb: "Upper Sorbian",
        ur: "Urdu",
        ve: "Venda",
        vi: "Vietnamese",
        vo: "Volapuk",
        wa: "Walloon",
        cy: "Welsh",
        xh: "Xhosa",
        ji: "Yiddish",
        zu: "Zulu"
      };

      if (this.internal.languageSettings === undefined) {
        this.internal.languageSettings = {};
        this.internal.languageSettings.isSubscribed = false;
      }

      if (langCodes[langCode] !== undefined) {
        this.internal.languageSettings.languageCode = langCode;
        if (this.internal.languageSettings.isSubscribed === false) {
          this.internal.events.subscribe("putCatalog", function() {
            this.internal.write(
              "/Lang (" + this.internal.languageSettings.languageCode + ")"
            );
          });
          this.internal.languageSettings.isSubscribed = true;
        }
      }
      return this;
    };
  })(jsPDF.API);

  /** @license
   * MIT license.
   * Copyright (c) 2012 Willow Systems Corporation, willow-systems.com
   *               2014 Diego Casorran, https://github.com/diegocr
   *
   * 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.
   * ====================================================================
   */

  /**
   * jsPDF split_text_to_size plugin
   *
   * @name split_text_to_size
   * @module
   */
  (function(API) {
    /**
     * Returns an array of length matching length of the 'word' string, with each
     * cell occupied by the width of the char in that position.
     *
     * @name getCharWidthsArray
     * @function
     * @param {string} text
     * @param {Object} options
     * @returns {Array}
     */
    var getCharWidthsArray = (API.getCharWidthsArray = function(text, options) {
      options = options || {};

      var activeFont = options.font || this.internal.getFont();
      var fontSize = options.fontSize || this.internal.getFontSize();
      var charSpace = options.charSpace || this.internal.getCharSpace();

      var widths = options.widths
        ? options.widths
        : activeFont.metadata.Unicode.widths;
      var widthsFractionOf = widths.fof ? widths.fof : 1;
      var kerning = options.kerning
        ? options.kerning
        : activeFont.metadata.Unicode.kerning;
      var kerningFractionOf = kerning.fof ? kerning.fof : 1;
      var doKerning = options.doKerning === false ? false : true;
      var kerningValue = 0;

      var i;
      var length = text.length;
      var char_code;
      var prior_char_code = 0; //for kerning
      var default_char_width = widths[0] || widthsFractionOf;
      var output = [];

      for (i = 0; i < length; i++) {
        char_code = text.charCodeAt(i);

        if (typeof activeFont.metadata.widthOfString === "function") {
          output.push(
            (activeFont.metadata.widthOfGlyph(
              activeFont.metadata.characterToGlyph(char_code)
            ) +
              charSpace * (1000 / fontSize) || 0) / 1000
          );
        } else {
          if (
            doKerning &&
            typeof kerning[char_code] === "object" &&
            !isNaN(parseInt(kerning[char_code][prior_char_code], 10))
          ) {
            kerningValue =
              kerning[char_code][prior_char_code] / kerningFractionOf;
          } else {
            kerningValue = 0;
          }
          output.push(
            (widths[char_code] || default_char_width) / widthsFractionOf +
              kerningValue
          );
        }
        prior_char_code = char_code;
      }

      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.
     *
     * @name getStringUnitWidth
     * @public
     * @function
     * @param {string} text
     * @param {string} options
     * @returns {number} result
     */
    var getStringUnitWidth = (API.getStringUnitWidth = function(text, options) {
      options = options || {};

      var fontSize = options.fontSize || this.internal.getFontSize();
      var font = options.font || this.internal.getFont();
      var charSpace = options.charSpace || this.internal.getCharSpace();
      var result = 0;

      if (API.processArabic) {
        text = API.processArabic(text);
      }

      if (typeof font.metadata.widthOfString === "function") {
        result =
          font.metadata.widthOfString(text, fontSize, charSpace) / fontSize;
      } else {
        result = getCharWidthsArray
          .apply(this, arguments)
          .reduce(function(pv, cv) {
            return pv + cv;
          }, 0);
      }
      return result;
    });

    /**
    returns array of lines
    */
    var splitLongWord = function(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(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.apply(this, [" ", 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.apply(this, [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.apply(this, [word, options]);
        current_word_length = widths_array.reduce(function(pv, cv) {
          return pv + cv;
        }, 0);

        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.apply(this, [
              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 = widths_array
              .slice(word.length - (line[0] ? line[0].length : 0))
              .reduce(function(pv, cv) {
                return pv + cv;
              }, 0);
          } 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;
        }
      }

      var postProcess;
      if (lineIndent) {
        postProcess = function(ln, idx) {
          return (idx ? pad : "") + ln.join(" ");
        };
      } else {
        postProcess = function(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.
     *
     * @name splitTextToSize
     * @public
     * @function
     * @param {string} text Unencoded, regular JavaScript (Unicode, UTF-16 / UCS-2) string.
     * @param {number} size Nominal number, measured in units default to this instance of jsPDF.
     * @param {Object} options Optional flags needed for chopper to do the right thing.
     * @returns {Array} array Array with strings chopped to size.
     */
    API.splitTextToSize = function(text, maxlen, options) {

      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 {
                font: f.metadata,
                fontSize: this.internal.getFontSize(),
                charSpace: this.internal.getCharSpace()
              };
            }
          } else {
            return {
              widths: options.widths,
              kerning: options.kerning
            };
          }
        }.call(this, options);

      // first we split on end-of-line chars
      var paragraphs;
      if (Array.isArray(text)) {
        paragraphs = text;
      } else {
        paragraphs = String(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.apply(this, [
            paragraphs[i],
            fontUnit_maxLen,
            newOptions
          ])
        );
      }

      return output;
    };
  })(jsPDF.API);

  /** @license
   jsPDF standard_fonts_metrics plugin
   * Copyright (c) 2012 Willow Systems Corporation, willow-systems.com
   * MIT license.
   * 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.
   * ====================================================================
   */

  /**
   * This file adds the standard font metrics to jsPDF.
   *
   * 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.
   *
   * @name standard_fonts_metrics
   * @module
   */

  (function(API) {
    API.__fontmetrics__ = API.__fontmetrics__ || {};

    var decoded = "0123456789abcdef",
      encoded = "klmnopqrstuvwxyz",
      mappingUncompress = {},
      mappingCompress = {};

    for (var i = 0; i < encoded.length; i++) {
      mappingUncompress[encoded[i]] = decoded[i];
      mappingCompress[decoded[i]] = encoded[i];
    }

    var hex = function(value) {
      return "0x" + parseInt(value, 10).toString(16);
    };

    var compress = (API.__fontmetrics__.compress = function(data) {
      var vals = ["{"];
      var value, keystring, valuestring, numberprefix;

      for (var key in data) {
        value = data[key];

        if (!isNaN(parseInt(key, 10))) {
          key = parseInt(key, 10);
          keystring = hex(key).slice(2);
          keystring =
            keystring.slice(0, -1) + mappingCompress[keystring.slice(-1)];
        } else {
          keystring = "'" + key + "'";
        }

        if (typeof value == "number") {
          if (value < 0) {
            valuestring = hex(value).slice(3);
            numberprefix = "-";
          } else {
            valuestring = hex(value).slice(2);
            numberprefix = "";
          }
          valuestring =
            numberprefix +
            valuestring.slice(0, -1) +
            mappingCompress[valuestring.slice(-1)];
        } else {
          if (typeof value === "object") {
            valuestring = compress(value);
          } else {
            throw new Error(
              "Don't know what to do with value type " + typeof value + "."
            );
          }
        }
        vals.push(keystring + valuestring);
      }
      vals.push("}");
      return vals.join("");
    });

    /**
     * Uncompresses data compressed into custom, base16-like format.
     *
     * @public
     * @function
     * @param
     * @returns {Type}
     */
    var uncompress = (API.__fontmetrics__.uncompress = function(data) {
      if (typeof data !== "string") {
        throw new Error("Invalid argument passed to uncompress.");
      }

      var 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;

      for (var i = 1; i < datalen; i += 1) {
        // - { } ' are special.

        ch = data[i];

        if (ch == "'") {
          if (stringparts) {
            // end of string mode
            key = stringparts.join("");
            stringparts = undefined;
          } else {
            // start of string mode
            stringparts = [];
          }
        } else if (stringparts) {
          stringparts.push(ch);
        } else if (ch == "{") {
          // start of object
          parentchain.push([activeobject, key]);
          activeobject = {};
          key = undefined;
        } else if (ch == "}") {
          // end of object
          parent_key_pair = parentchain.pop();
          parent_key_pair[0][parent_key_pair[1]] = activeobject;
          key = undefined;
          activeobject = parent_key_pair[0];
        } else if (ch == "-") {
          sign = -1;
        } else {
          // must be number
          if (key === undefined) {
            if (mappingUncompress.hasOwnProperty(ch)) {
              keyparts += mappingUncompress[ch];
              key = parseInt(keyparts, 16) * sign;
              sign = +1;
              keyparts = "";
            } else {
              keyparts += ch;
            }
          } else {
            if (mappingUncompress.hasOwnProperty(ch)) {
              valueparts += mappingUncompress[ch];
              activeobject[key] = parseInt(valueparts, 16) * sign;
              sign = +1;
              key = undefined;
              valueparts = "";
            } else {
              valueparts += ch;
            }
          }
        }
      }
      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}"
      )
    };
    var 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'
      }
    };

    var 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(data) {
        var font = data.font;

        var metrics = fontMetrics["Unicode"][font.postScriptName];
        if (metrics) {
          font.metadata["Unicode"] = {};
          font.metadata["Unicode"].widths = metrics.widths;
          font.metadata["Unicode"].kerning = metrics.kerning;
        }

        var encodingBlock = encodings["Unicode"][font.postScriptName];
        if (encodingBlock) {
          font.metadata["Unicode"].encoding = encodingBlock;
          font.encoding = encodingBlock.codePages[0];
        }
      }
    ]); // end of adding event handler
  })(jsPDF.API);

  /**
   * @license
   * Licensed under the MIT License.
   * http://opensource.org/licenses/mit-license
   */

  /**
   * @name ttfsupport
   * @module
   */
  (function(jsPDF) {

    var binaryStringToUint8Array = function(binary_string) {
      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;
    };

    var addFont = function(font, file) {
      // eslint-disable-next-line no-control-regex
      if (/^\x00\x01\x00\x00/.test(file)) {
        file = binaryStringToUint8Array(file);
      } else {
        file = binaryStringToUint8Array(atob(file));
      }
      font.metadata = jsPDF.API.TTFFont.open(file);
      font.metadata.Unicode = font.metadata.Unicode || {
        encoding: {},
        kerning: {},
        widths: []
      };
      font.metadata.glyIdsUsed = [0];
    };

    jsPDF.API.events.push([
      "addFont",
      function(data) {
        var file = undefined;
        var font = data.font;
        var instance = data.instance;
        if (font.isStandardFont) {
          return;
        }
        if (typeof instance !== "undefined") {
          if (instance.existsFileInVFS(font.postScriptName) === false) {
            file = instance.loadFile(font.postScriptName);
          } else {
            file = instance.getFileFromVFS(font.postScriptName);
          }
          if (typeof file !== "string") {
            throw new Error(
              "Font is not stored as string-data in vFS, import fonts or remove declaration doc.addFont('" +
                font.postScriptName +
                "')."
            );
          }
          addFont(font, file);
        } else {
          throw new Error(
            "Font does not exist in vFS, import fonts or remove declaration doc.addFont('" +
              font.postScriptName +
              "')."
          );
        }
      }
    ]); // end of adding event handler
  })(jsPDF);

  /** @license
   * Copyright (c) 2012 Willow Systems Corporation, willow-systems.com
   *
   * 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.
   * ====================================================================
   */

  /**
   * jsPDF SVG plugin
   *
   * @name svg
   * @module
   */
  (function(jsPDFAPI) {

    function loadCanvg() {
      return (function() {
        if (globalObject["canvg"]) {
          return Promise.resolve(globalObject["canvg"]);
        }


        if (typeof exports === "object" && typeof module !== "undefined") {
          return new Promise(function(resolve, reject) {
            try {
              resolve(require("canvg"));
            } catch (e) {
              reject(e);
            }
          });
        }
        if (typeof define === "function" && define.amd) {
          return new Promise(function(resolve, reject) {
            try {
              require(["canvg"], resolve);
            } catch (e) {
              reject(e);
            }
          });
        }
        return Promise.reject(new Error("Could not load canvg"));
      })()
        .catch(function(e) {
          return Promise.reject(new Error("Could not load canvg: " + e));
        })
        .then(function(canvg) {
          return canvg.default ? canvg.default : canvg;
        });
    }

    /**
     * Parses SVG XML and saves it as image into the PDF.
     *
     * Depends on canvas-element and canvg
     *
     * @name addSvgAsImage
     * @public
     * @function
     * @param {string} SVG-Data as Text
     * @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} width of SVG-Image (in units declared at inception of PDF document)
     * @param {number} height of SVG-Image (in units declared at inception of PDF document)
     * @param {string} alias of SVG-Image (if used multiple times)
     * @param {string} compression of the generated JPEG, can have the values 'NONE', 'FAST', 'MEDIUM' and 'SLOW'
     * @param {number} rotation of the image in degrees (0-359)
     *
     * @returns jsPDF jsPDF-instance
     */
    jsPDFAPI.addSvgAsImage = function(
      svg,
      x,
      y,
      w,
      h,
      alias,
      compression,
      rotation
    ) {
      if (isNaN(x) || isNaN(y)) {
        console.error("jsPDF.addSvgAsImage: Invalid coordinates", arguments);
        throw new Error("Invalid coordinates passed to jsPDF.addSvgAsImage");
      }

      if (isNaN(w) || isNaN(h)) {
        console.error("jsPDF.addSvgAsImage: Invalid measurements", arguments);
        throw new Error(
          "Invalid measurements (width and/or height) passed to jsPDF.addSvgAsImage"
        );
      }

      var canvas = document.createElement("canvas");
      canvas.width = w;
      canvas.height = h;
      var ctx = canvas.getContext("2d");
      ctx.fillStyle = "#fff"; /// set white fill style
      ctx.fillRect(0, 0, canvas.width, canvas.height);

      var options = {
        ignoreMouse: true,
        ignoreAnimation: true,
        ignoreDimensions: true
      };
      var doc = this;
      return loadCanvg()
        .then(
          function(canvg) {
            return canvg.fromString(ctx, svg, options);
          },
          function() {
            return Promise.reject(new Error("Could not load canvg."));
          }
        )
        .then(function(instance) {
          return instance.render(options);
        })
        .then(function() {
          doc.addImage(
            canvas.toDataURL("image/jpeg", 1.0),
            x,
            y,
            w,
            h,
            compression,
            rotation
          );
        });
    };
  })(jsPDF.API);

  /**
   * @license
   * ====================================================================
   * Copyright (c) 2013 Eduardo Menezes de Morais, eduardo.morais@usp.br
   *
   * 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.
   * ====================================================================
   */

  /**
   * jsPDF total_pages plugin
   * @name total_pages
   * @module
   */
  (function(jsPDFAPI) {
    /**
     * @name putTotalPages
     * @function
     * @param {string} pageExpression Regular Expression
     * @returns {jsPDF} jsPDF-instance
     */

    jsPDFAPI.putTotalPages = function(pageExpression) {

      var replaceExpression;
      var totalNumberOfPages = 0;
      if (parseInt(this.internal.getFont().id.substr(1), 10) < 15) {
        replaceExpression = new RegExp(pageExpression, "g");
        totalNumberOfPages = this.internal.getNumberOfPages();
      } else {
        replaceExpression = new RegExp(
          this.pdfEscape16(pageExpression, this.internal.getFont()),
          "g"
        );
        totalNumberOfPages = this.pdfEscape16(
          this.internal.getNumberOfPages() + "",
          this.internal.getFont()
        );
      }

      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,
            totalNumberOfPages
          );
        }
      }

      return this;
    };
  })(jsPDF.API);

  /**
   * @license
   * jsPDF viewerPreferences Plugin
   * @author Aras Abbasi (github.com/arasabbasi)
   * Licensed under the MIT License.
   * http://opensource.org/licenses/mit-license
   */

  /**
   * Adds the ability to set ViewerPreferences and by thus
   * controlling the way the document is to be presented on the
   * screen or in print.
   * @name viewerpreferences
   * @module
   */
  (function(jsPDFAPI) {
    /**
     * Set the ViewerPreferences of the generated PDF
     *
     * @name viewerPreferences
     * @function
     * @public
     * @param {Object} options Array with the ViewerPreferences<br />
     * Example: doc.viewerPreferences({"FitWindow":true});<br />
     * <br />
     * You can set following preferences:<br />
     * <br/>
     * <b>HideToolbar</b> <i>(boolean)</i><br />
     * Default value: false<br />
     * <br />
     * <b>HideMenubar</b> <i>(boolean)</i><br />
     * Default value: false.<br />
     * <br />
     * <b>HideWindowUI</b> <i>(boolean)</i><br />
     * Default value: false.<br />
     * <br />
     * <b>FitWindow</b> <i>(boolean)</i><br />
     * Default value: false.<br />
     * <br />
     * <b>CenterWindow</b> <i>(boolean)</i><br />
     * Default value: false<br />
     * <br />
     * <b>DisplayDocTitle</b> <i>(boolean)</i><br />
     * Default value: false.<br />
     * <br />
     * <b>NonFullScreenPageMode</b> <i>(string)</i><br />
     * Possible values: UseNone, UseOutlines, UseThumbs, UseOC<br />
     * Default value: UseNone<br/>
     * <br />
     * <b>Direction</b> <i>(string)</i><br />
     * Possible values: L2R, R2L<br />
     * Default value: L2R.<br />
     * <br />
     * <b>ViewArea</b> <i>(string)</i><br />
     * Possible values: MediaBox, CropBox, TrimBox, BleedBox, ArtBox<br />
     * Default value: CropBox.<br />
     * <br />
     * <b>ViewClip</b> <i>(string)</i><br />
     * Possible values: MediaBox, CropBox, TrimBox, BleedBox, ArtBox<br />
     * Default value: CropBox<br />
     * <br />
     * <b>PrintArea</b> <i>(string)</i><br />
     * Possible values: MediaBox, CropBox, TrimBox, BleedBox, ArtBox<br />
     * Default value: CropBox<br />
     * <br />
     * <b>PrintClip</b> <i>(string)</i><br />
     * Possible values: MediaBox, CropBox, TrimBox, BleedBox, ArtBox<br />
     * Default value: CropBox.<br />
     * <br />
     * <b>PrintScaling</b> <i>(string)</i><br />
     * Possible values: AppDefault, None<br />
     * Default value: AppDefault.<br />
     * <br />
     * <b>Duplex</b> <i>(string)</i><br />
     * Possible values: Simplex, DuplexFlipLongEdge, DuplexFlipShortEdge
     * Default value: none<br />
     * <br />
     * <b>PickTrayByPDFSize</b> <i>(boolean)</i><br />
     * Default value: false<br />
     * <br />
     * <b>PrintPageRange</b> <i>(Array)</i><br />
     * Example: [[1,5], [7,9]]<br />
     * Default value: as defined by PDF viewer application<br />
     * <br />
     * <b>NumCopies</b> <i>(Number)</i><br />
     * Possible values: 1, 2, 3, 4, 5<br />
     * Default value: 1<br />
     * <br />
     * For more information see the PDF Reference, sixth edition on Page 577
     * @param {boolean} doReset True to reset the settings
     * @function
     * @returns jsPDF jsPDF-instance
     * @example
     * var doc = new jsPDF()
     * doc.text('This is a test', 10, 10)
     * doc.viewerPreferences({'FitWindow': true}, true)
     * doc.save("viewerPreferences.pdf")
     *
     * // Example printing 10 copies, using cropbox, and hiding UI.
     * doc.viewerPreferences({
     *   'HideWindowUI': true,
     *   'PrintArea': 'CropBox',
     *   'NumCopies': 10
     * })
     */
    jsPDFAPI.viewerPreferences = function(options, doReset) {
      options = options || {};
      doReset = doReset || false;

      var configuration;
      var configurationTemplate = {
        HideToolbar: {
          defaultValue: false,
          value: false,
          type: "boolean",
          explicitSet: false,
          valueSet: [true, false],
          pdfVersion: 1.3
        },
        HideMenubar: {
          defaultValue: false,
          value: false,
          type: "boolean",
          explicitSet: false,
          valueSet: [true, false],
          pdfVersion: 1.3
        },
        HideWindowUI: {
          defaultValue: false,
          value: false,
          type: "boolean",
          explicitSet: false,
          valueSet: [true, false],
          pdfVersion: 1.3
        },
        FitWindow: {
          defaultValue: false,
          value: false,
          type: "boolean",
          explicitSet: false,
          valueSet: [true, false],
          pdfVersion: 1.3
        },
        CenterWindow: {
          defaultValue: false,
          value: false,
          type: "boolean",
          explicitSet: false,
          valueSet: [true, false],
          pdfVersion: 1.3
        },
        DisplayDocTitle: {
          defaultValue: false,
          value: false,
          type: "boolean",
          explicitSet: false,
          valueSet: [true, false],
          pdfVersion: 1.4
        },
        NonFullScreenPageMode: {
          defaultValue: "UseNone",
          value: "UseNone",
          type: "name",
          explicitSet: false,
          valueSet: ["UseNone", "UseOutlines", "UseThumbs", "UseOC"],
          pdfVersion: 1.3
        },
        Direction: {
          defaultValue: "L2R",
          value: "L2R",
          type: "name",
          explicitSet: false,
          valueSet: ["L2R", "R2L"],
          pdfVersion: 1.3
        },
        ViewArea: {
          defaultValue: "CropBox",
          value: "CropBox",
          type: "name",
          explicitSet: false,
          valueSet: ["MediaBox", "CropBox", "TrimBox", "BleedBox", "ArtBox"],
          pdfVersion: 1.4
        },
        ViewClip: {
          defaultValue: "CropBox",
          value: "CropBox",
          type: "name",
          explicitSet: false,
          valueSet: ["MediaBox", "CropBox", "TrimBox", "BleedBox", "ArtBox"],
          pdfVersion: 1.4
        },
        PrintArea: {
          defaultValue: "CropBox",
          value: "CropBox",
          type: "name",
          explicitSet: false,
          valueSet: ["MediaBox", "CropBox", "TrimBox", "BleedBox", "ArtBox"],
          pdfVersion: 1.4
        },
        PrintClip: {
          defaultValue: "CropBox",
          value: "CropBox",
          type: "name",
          explicitSet: false,
          valueSet: ["MediaBox", "CropBox", "TrimBox", "BleedBox", "ArtBox"],
          pdfVersion: 1.4
        },
        PrintScaling: {
          defaultValue: "AppDefault",
          value: "AppDefault",
          type: "name",
          explicitSet: false,
          valueSet: ["AppDefault", "None"],
          pdfVersion: 1.6
        },
        Duplex: {
          defaultValue: "",
          value: "none",
          type: "name",
          explicitSet: false,
          valueSet: [
            "Simplex",
            "DuplexFlipShortEdge",
            "DuplexFlipLongEdge",
            "none"
          ],
          pdfVersion: 1.7
        },
        PickTrayByPDFSize: {
          defaultValue: false,
          value: false,
          type: "boolean",
          explicitSet: false,
          valueSet: [true, false],
          pdfVersion: 1.7
        },
        PrintPageRange: {
          defaultValue: "",
          value: "",
          type: "array",
          explicitSet: false,
          valueSet: null,
          pdfVersion: 1.7
        },
        NumCopies: {
          defaultValue: 1,
          value: 1,
          type: "integer",
          explicitSet: false,
          valueSet: null,
          pdfVersion: 1.7
        }
      };

      var configurationKeys = Object.keys(configurationTemplate);

      var rangeArray = [];
      var i = 0;
      var j = 0;
      var k = 0;
      var isValid;

      var method;
      var value;

      function arrayContainsElement(array, element) {
        var iterator;
        var result = false;

        for (iterator = 0; iterator < array.length; iterator += 1) {
          if (array[iterator] === element) {
            result = true;
          }
        }
        return result;
      }

      if (this.internal.viewerpreferences === undefined) {
        this.internal.viewerpreferences = {};
        this.internal.viewerpreferences.configuration = JSON.parse(
          JSON.stringify(configurationTemplate)
        );
        this.internal.viewerpreferences.isSubscribed = false;
      }
      configuration = this.internal.viewerpreferences.configuration;

      if (options === "reset" || doReset === true) {
        var len = configurationKeys.length;

        for (k = 0; k < len; k += 1) {
          configuration[configurationKeys[k]].value =
            configuration[configurationKeys[k]].defaultValue;
          configuration[configurationKeys[k]].explicitSet = false;
        }
      }

      if (typeof options === "object") {
        for (method in options) {
          value = options[method];
          if (
            arrayContainsElement(configurationKeys, method) &&
            value !== undefined
          ) {
            if (
              configuration[method].type === "boolean" &&
              typeof value === "boolean"
            ) {
              configuration[method].value = value;
            } else if (
              configuration[method].type === "name" &&
              arrayContainsElement(configuration[method].valueSet, value)
            ) {
              configuration[method].value = value;
            } else if (
              configuration[method].type === "integer" &&
              Number.isInteger(value)
            ) {
              configuration[method].value = value;
            } else if (configuration[method].type === "array") {
              for (i = 0; i < value.length; i += 1) {
                isValid = true;
                if (value[i].length === 1 && typeof value[i][0] === "number") {
                  rangeArray.push(String(value[i] - 1));
                } else if (value[i].length > 1) {
                  for (j = 0; j < value[i].length; j += 1) {
                    if (typeof value[i][j] !== "number") {
                      isValid = false;
                    }
                  }
                  if (isValid === true) {
                    rangeArray.push([value[i][0] - 1, value[i][1] - 1].join(" "));
                  }
                }
              }
              configuration[method].value = "[" + rangeArray.join(" ") + "]";
            } else {
              configuration[method].value = configuration[method].defaultValue;
            }

            configuration[method].explicitSet = true;
          }
        }
      }

      if (this.internal.viewerpreferences.isSubscribed === false) {
        this.internal.events.subscribe("putCatalog", function() {
          var pdfDict = [];
          var vPref;
          for (vPref in configuration) {
            if (configuration[vPref].explicitSet === true) {
              if (configuration[vPref].type === "name") {
                pdfDict.push("/" + vPref + " /" + configuration[vPref].value);
              } else {
                pdfDict.push("/" + vPref + " " + configuration[vPref].value);
              }
            }
          }
          if (pdfDict.length !== 0) {
            this.internal.write(
              "/ViewerPreferences\n<<\n" + pdfDict.join("\n") + "\n>>"
            );
          }
        });
        this.internal.viewerpreferences.isSubscribed = true;
      }

      this.internal.viewerpreferences.configuration = configuration;
      return this;
    };
  })(jsPDF.API);

  /** ====================================================================
   * @license
   * jsPDF XMP metadata plugin
   * Copyright (c) 2016 Jussi Utunen, u-jussi@suomi24.fi
   *
   * 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.
   * ====================================================================
   */

  /**
   * @name xmp_metadata
   * @module
   */
  (function(jsPDFAPI) {

    var postPutResources = function() {
      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="' +
        this.internal.__metadata__.namespaceuri +
        '"><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(this.internal.__metadata__.metadata)
      );
      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;

      this.internal.__metadata__.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");
    };

    var putCatalog = function() {
      if (this.internal.__metadata__.metadata_object_number) {
        this.internal.write(
          "/Metadata " +
            this.internal.__metadata__.metadata_object_number +
            " 0 R"
        );
      }
    };

    /**
     * Adds XMP formatted metadata to PDF
     *
     * @name addMetadata
     * @function
     * @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.
     * @returns {jsPDF} jsPDF-instance
     */
    jsPDFAPI.addMetadata = function(metadata, namespaceuri) {
      if (typeof this.internal.__metadata__ === "undefined") {
        this.internal.__metadata__ = {
          metadata: metadata,
          namespaceuri: namespaceuri || "http://jspdf.default.namespaceuri/"
        };
        this.internal.events.subscribe("putCatalog", putCatalog);

        this.internal.events.subscribe("postPutResources", postPutResources);
      }
      return this;
    };
  })(jsPDF.API);

  /**
   * @name utf8
   * @module
   */
  (function(jsPDF) {
    var jsPDFAPI = jsPDF.API;

    /***************************************************************************************************/
    /* function : pdfEscape16                                                                          */
    /* comment : The character id of a 2-byte string is converted to a hexadecimal number by obtaining */
    /*   the corresponding glyph id and width, and then adding padding to the string.                  */
    /***************************************************************************************************/
    var pdfEscape16 = (jsPDFAPI.pdfEscape16 = function(text, font) {
      var widths = font.metadata.Unicode.widths;
      var padz = ["", "0", "00", "000", "0000"];
      var ar = [""];
      for (var i = 0, l = text.length, t; i < l; ++i) {
        t = font.metadata.characterToGlyph(text.charCodeAt(i));
        font.metadata.glyIdsUsed.push(t);
        font.metadata.toUnicode[t] = text.charCodeAt(i);
        if (widths.indexOf(t) == -1) {
          widths.push(t);
          widths.push([parseInt(font.metadata.widthOfGlyph(t), 10)]);
        }
        if (t == "0") {
          //Spaces are not allowed in cmap.
          return ar.join("");
        } else {
          t = t.toString(16);
          ar.push(padz[4 - t.length], t);
        }
      }
      return ar.join("");
    });

    var toUnicodeCmap = function(map) {
      var code, codes, range, unicode, unicodeMap, _i, _len;
      unicodeMap =
        "/CIDInit /ProcSet findresource begin\n12 dict begin\nbegincmap\n/CIDSystemInfo <<\n  /Registry (Adobe)\n  /Ordering (UCS)\n  /Supplement 0\n>> def\n/CMapName /Adobe-Identity-UCS def\n/CMapType 2 def\n1 begincodespacerange\n<0000><ffff>\nendcodespacerange";
      codes = Object.keys(map).sort(function(a, b) {
        return a - b;
      });

      range = [];
      for (_i = 0, _len = codes.length; _i < _len; _i++) {
        code = codes[_i];
        if (range.length >= 100) {
          unicodeMap +=
            "\n" +
            range.length +
            " beginbfchar\n" +
            range.join("\n") +
            "\nendbfchar";
          range = [];
        }

        if (
          map[code] !== undefined &&
          map[code] !== null &&
          typeof map[code].toString === "function"
        ) {
          unicode = ("0000" + map[code].toString(16)).slice(-4);
          code = ("0000" + (+code).toString(16)).slice(-4);
          range.push("<" + code + "><" + unicode + ">");
        }
      }

      if (range.length) {
        unicodeMap +=
          "\n" +
          range.length +
          " beginbfchar\n" +
          range.join("\n") +
          "\nendbfchar\n";
      }
      unicodeMap +=
        "endcmap\nCMapName currentdict /CMap defineresource pop\nend\nend";
      return unicodeMap;
    };

    var identityHFunction = function(options) {
      var font = options.font;
      var out = options.out;
      var newObject = options.newObject;
      var putStream = options.putStream;
      var pdfEscapeWithNeededParanthesis = options.pdfEscapeWithNeededParanthesis;

      if (
        font.metadata instanceof jsPDF.API.TTFFont &&
        font.encoding === "Identity-H"
      ) {
        //Tag with Identity-H
        var widths = font.metadata.Unicode.widths;
        var data = font.metadata.subset.encode(font.metadata.glyIdsUsed, 1);
        var pdfOutput = data;
        var pdfOutput2 = "";
        for (var i = 0; i < pdfOutput.length; i++) {
          pdfOutput2 += String.fromCharCode(pdfOutput[i]);
        }
        var fontTable = newObject();
        putStream({ data: pdfOutput2, addLength1: true, objectId: fontTable });
        out("endobj");

        var cmap = newObject();
        var cmapData = toUnicodeCmap(font.metadata.toUnicode);
        putStream({ data: cmapData, addLength1: true, objectId: cmap });
        out("endobj");

        var fontDescriptor = newObject();
        out("<<");
        out("/Type /FontDescriptor");
        out("/FontName /" + pdfEscapeWithNeededParanthesis(font.fontName));
        out("/FontFile2 " + fontTable + " 0 R");
        out("/FontBBox " + jsPDF.API.PDFObject.convert(font.metadata.bbox));
        out("/Flags " + font.metadata.flags);
        out("/StemV " + font.metadata.stemV);
        out("/ItalicAngle " + font.metadata.italicAngle);
        out("/Ascent " + font.metadata.ascender);
        out("/Descent " + font.metadata.decender);
        out("/CapHeight " + font.metadata.capHeight);
        out(">>");
        out("endobj");

        var DescendantFont = newObject();
        out("<<");
        out("/Type /Font");
        out("/BaseFont /" + pdfEscapeWithNeededParanthesis(font.fontName));
        out("/FontDescriptor " + fontDescriptor + " 0 R");
        out("/W " + jsPDF.API.PDFObject.convert(widths));
        out("/CIDToGIDMap /Identity");
        out("/DW 1000");
        out("/Subtype /CIDFontType2");
        out("/CIDSystemInfo");
        out("<<");
        out("/Supplement 0");
        out("/Registry (Adobe)");
        out("/Ordering (" + font.encoding + ")");
        out(">>");
        out(">>");
        out("endobj");

        font.objectNumber = newObject();
        out("<<");
        out("/Type /Font");
        out("/Subtype /Type0");
        out("/ToUnicode " + cmap + " 0 R");
        out("/BaseFont /" + pdfEscapeWithNeededParanthesis(font.fontName));
        out("/Encoding /" + font.encoding);
        out("/DescendantFonts [" + DescendantFont + " 0 R]");
        out(">>");
        out("endobj");

        font.isAlreadyPutted = true;
      }
    };

    jsPDFAPI.events.push([
      "putFont",
      function(args) {
        identityHFunction(args);
      }
    ]);

    var winAnsiEncodingFunction = function(options) {
      var font = options.font;
      var out = options.out;
      var newObject = options.newObject;
      var putStream = options.putStream;
      var pdfEscapeWithNeededParanthesis = options.pdfEscapeWithNeededParanthesis;

      if (
        font.metadata instanceof jsPDF.API.TTFFont &&
        font.encoding === "WinAnsiEncoding"
      ) {
        //Tag with WinAnsi encoding
        var data = font.metadata.rawData;
        var pdfOutput = data;
        var pdfOutput2 = "";
        for (var i = 0; i < pdfOutput.length; i++) {
          pdfOutput2 += String.fromCharCode(pdfOutput[i]);
        }
        var fontTable = newObject();
        putStream({ data: pdfOutput2, addLength1: true, objectId: fontTable });
        out("endobj");

        var cmap = newObject();
        var cmapData = toUnicodeCmap(font.metadata.toUnicode);
        putStream({ data: cmapData, addLength1: true, objectId: cmap });
        out("endobj");

        var fontDescriptor = newObject();
        out("<<");
        out("/Descent " + font.metadata.decender);
        out("/CapHeight " + font.metadata.capHeight);
        out("/StemV " + font.metadata.stemV);
        out("/Type /FontDescriptor");
        out("/FontFile2 " + fontTable + " 0 R");
        out("/Flags 96");
        out("/FontBBox " + jsPDF.API.PDFObject.convert(font.metadata.bbox));
        out("/FontName /" + pdfEscapeWithNeededParanthesis(font.fontName));
        out("/ItalicAngle " + font.metadata.italicAngle);
        out("/Ascent " + font.metadata.ascender);
        out(">>");
        out("endobj");
        font.objectNumber = newObject();
        for (var j = 0; j < font.metadata.hmtx.widths.length; j++) {
          font.metadata.hmtx.widths[j] = parseInt(
            font.metadata.hmtx.widths[j] * (1000 / font.metadata.head.unitsPerEm)
          ); //Change the width of Em units to Point units.
        }
        out(
          "<</Subtype/TrueType/Type/Font/ToUnicode " +
            cmap +
            " 0 R/BaseFont/" +
            pdfEscapeWithNeededParanthesis(font.fontName) +
            "/FontDescriptor " +
            fontDescriptor +
            " 0 R" +
            "/Encoding/" +
            font.encoding +
            " /FirstChar 29 /LastChar 255 /Widths " +
            jsPDF.API.PDFObject.convert(font.metadata.hmtx.widths) +
            ">>"
        );
        out("endobj");
        font.isAlreadyPutted = true;
      }
    };

    jsPDFAPI.events.push([
      "putFont",
      function(args) {
        winAnsiEncodingFunction(args);
      }
    ]);

    var utf8TextFunction = function(args) {
      var text = args.text || "";
      var x = args.x;
      var y = args.y;
      var options = args.options || {};
      var mutex = args.mutex || {};

      var pdfEscape = mutex.pdfEscape;
      var activeFontKey = mutex.activeFontKey;
      var fonts = mutex.fonts;
      var key = activeFontKey;

      var str = "",
        s = 0,
        cmapConfirm;
      var strText = "";
      var encoding = fonts[key].encoding;

      if (fonts[key].encoding !== "Identity-H") {
        return {
          text: text,
          x: x,
          y: y,
          options: options,
          mutex: mutex
        };
      }
      strText = text;

      key = activeFontKey;
      if (Array.isArray(text)) {
        strText = text[0];
      }
      for (s = 0; s < strText.length; s += 1) {
        if (fonts[key].metadata.hasOwnProperty("cmap")) {
          cmapConfirm =
            fonts[key].metadata.cmap.unicode.codeMap[strText[s].charCodeAt(0)];
          /*
               if (Object.prototype.toString.call(text) === '[object Array]') {
                  var i = 0;
                 // for (i = 0; i < text.length; i += 1) {
                      if (Object.prototype.toString.call(text[s]) === '[object Array]') {
                          cmapConfirm = fonts[key].metadata.cmap.unicode.codeMap[strText[s][0].charCodeAt(0)]; //Make sure the cmap has the corresponding glyph id
                      } else {

                      }
                  //}

              } else {
                  cmapConfirm = fonts[key].metadata.cmap.unicode.codeMap[strText[s].charCodeAt(0)]; //Make sure the cmap has the corresponding glyph id
              }*/
        }
        if (!cmapConfirm) {
          if (
            strText[s].charCodeAt(0) < 256 &&
            fonts[key].metadata.hasOwnProperty("Unicode")
          ) {
            str += strText[s];
          } else {
            str += "";
          }
        } else {
          str += strText[s];
        }
      }
      var result = "";
      if (parseInt(key.slice(1)) < 14 || encoding === "WinAnsiEncoding") {
        //For the default 13 font
        result = pdfEscape(str, key)
          .split("")
          .map(function(cv) {
            return cv.charCodeAt(0).toString(16);
          })
          .join("");
      } else if (encoding === "Identity-H") {
        result = pdfEscape16(str, fonts[key]);
      }
      mutex.isHex = true;

      return {
        text: result,
        x: x,
        y: y,
        options: options,
        mutex: mutex
      };
    };

    var utf8EscapeFunction = function(parms) {
      var text = parms.text || "",
        x = parms.x,
        y = parms.y,
        options = parms.options,
        mutex = parms.mutex;
      var tmpText = [];
      var args = {
        text: text,
        x: x,
        y: y,
        options: options,
        mutex: mutex
      };

      if (Array.isArray(text)) {
        var i = 0;
        for (i = 0; i < text.length; i += 1) {
          if (Array.isArray(text[i])) {
            if (text[i].length === 3) {
              tmpText.push([
                utf8TextFunction(Object.assign({}, args, { text: text[i][0] }))
                  .text,
                text[i][1],
                text[i][2]
              ]);
            } else {
              tmpText.push(
                utf8TextFunction(Object.assign({}, args, { text: text[i] })).text
              );
            }
          } else {
            tmpText.push(
              utf8TextFunction(Object.assign({}, args, { text: text[i] })).text
            );
          }
        }
        parms.text = tmpText;
      } else {
        parms.text = utf8TextFunction(
          Object.assign({}, args, { text: text })
        ).text;
      }
    };

    jsPDFAPI.events.push(["postProcessText", utf8EscapeFunction]);
  })(jsPDF);

  /**
   * @license
   * jsPDF virtual FileSystem functionality
   *
   * Licensed under the MIT License.
   * http://opensource.org/licenses/mit-license
   */

  /**
   * Use the vFS to handle files
   *
   * @name vFS
   * @module
   */
  (function(jsPDFAPI) {

    var _initializeVFS = function() {
      if (typeof this.internal.vFS === "undefined") {
        this.internal.vFS = {};
      }
      return true;
    };

    /**
     * Check if the file exists in the vFS
     *
     * @name existsFileInVFS
     * @function
     * @param {string} Possible filename in the vFS.
     * @returns {boolean}
     * @example
     * doc.existsFileInVFS("someFile.txt");
     */
    jsPDFAPI.existsFileInVFS = function(filename) {
      _initializeVFS.call(this);
      return typeof this.internal.vFS[filename] !== "undefined";
    };

    /**
     * Add a file to the vFS
     *
     * @name addFileToVFS
     * @function
     * @param {string} filename The name of the file which should be added.
     * @param {string} filecontent The content of the file.
     * @returns {jsPDF}
     * @example
     * doc.addFileToVFS("someFile.txt", "BADFACE1");
     */
    jsPDFAPI.addFileToVFS = function(filename, filecontent) {
      _initializeVFS.call(this);
      this.internal.vFS[filename] = filecontent;
      return this;
    };

    /**
     * Get the file from the vFS
     *
     * @name getFileFromVFS
     * @function
     * @param {string} The name of the file which gets requested.
     * @returns {string}
     * @example
     * doc.getFileFromVFS("someFile.txt");
     */
    jsPDFAPI.getFileFromVFS = function(filename) {
      _initializeVFS.call(this);

      if (typeof this.internal.vFS[filename] !== "undefined") {
        return this.internal.vFS[filename];
      }
      return null;
    };
  })(jsPDF.API);

  /**
   * @license
   * Unicode Bidi Engine based on the work of Alex Shensis (@asthensis)
   * MIT License
   */

  (function(jsPDF) {
    /**
     * Table of Unicode types.
     *
     * Generated by:
     *
     * var bidi = require("./bidi/index");
     * var bidi_accumulate = bidi.slice(0, 256).concat(bidi.slice(0x0500, 0x0500 + 256 * 3)).
     * concat(bidi.slice(0x2000, 0x2000 + 256)).concat(bidi.slice(0xFB00, 0xFB00 + 256)).
     * concat(bidi.slice(0xFE00, 0xFE00 + 2 * 256));
     *
     * for( var i = 0; i < bidi_accumulate.length; i++) {
     * 	if(bidi_accumulate[i] === undefined || bidi_accumulate[i] === 'ON')
     * 		bidi_accumulate[i] = 'N'; //mark as neutral to conserve space and substitute undefined
     * }
     * var bidiAccumulateStr = 'return [ "' + bidi_accumulate.toString().replace(/,/g, '", "') + '" ];';
     * require("fs").writeFile('unicode-types.js', bidiAccumulateStr);
     *
     * Based on:
     * https://github.com/mathiasbynens/unicode-8.0.0
     */
    var bidiUnicodeTypes = [
      "BN",
      "BN",
      "BN",
      "BN",
      "BN",
      "BN",
      "BN",
      "BN",
      "BN",
      "S",
      "B",
      "S",
      "WS",
      "B",
      "BN",
      "BN",
      "BN",
      "BN",
      "BN",
      "BN",
      "BN",
      "BN",
      "BN",
      "BN",
      "BN",
      "BN",
      "BN",
      "BN",
      "B",
      "B",
      "B",
      "S",
      "WS",
      "N",
      "N",
      "ET",
      "ET",
      "ET",
      "N",
      "N",
      "N",
      "N",
      "N",
      "ES",
      "CS",
      "ES",
      "CS",
      "CS",
      "EN",
      "EN",
      "EN",
      "EN",
      "EN",
      "EN",
      "EN",
      "EN",
      "EN",
      "EN",
      "CS",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "N",
      "N",
      "N",
      "N",
      "BN",
      "BN",
      "BN",
      "BN",
      "BN",
      "BN",
      "B",
      "BN",
      "BN",
      "BN",
      "BN",
      "BN",
      "BN",
      "BN",
      "BN",
      "BN",
      "BN",
      "BN",
      "BN",
      "BN",
      "BN",
      "BN",
      "BN",
      "BN",
      "BN",
      "BN",
      "BN",
      "BN",
      "BN",
      "BN",
      "BN",
      "BN",
      "BN",
      "CS",
      "N",
      "ET",
      "ET",
      "ET",
      "ET",
      "N",
      "N",
      "N",
      "N",
      "L",
      "N",
      "N",
      "BN",
      "N",
      "N",
      "ET",
      "ET",
      "EN",
      "EN",
      "N",
      "L",
      "N",
      "N",
      "N",
      "EN",
      "L",
      "N",
      "N",
      "N",
      "N",
      "N",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "N",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "N",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "N",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "N",
      "N",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "N",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "N",
      "L",
      "N",
      "N",
      "N",
      "N",
      "N",
      "ET",
      "N",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "R",
      "NSM",
      "R",
      "NSM",
      "NSM",
      "R",
      "NSM",
      "NSM",
      "R",
      "NSM",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "R",
      "R",
      "R",
      "R",
      "R",
      "R",
      "R",
      "R",
      "R",
      "R",
      "R",
      "R",
      "R",
      "R",
      "R",
      "R",
      "R",
      "R",
      "R",
      "R",
      "R",
      "R",
      "R",
      "R",
      "R",
      "R",
      "R",
      "N",
      "N",
      "N",
      "N",
      "N",
      "R",
      "R",
      "R",
      "R",
      "R",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "AN",
      "AN",
      "AN",
      "AN",
      "AN",
      "AN",
      "N",
      "N",
      "AL",
      "ET",
      "ET",
      "AL",
      "CS",
      "AL",
      "N",
      "N",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "AL",
      "AL",
      "N",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "AN",
      "AN",
      "AN",
      "AN",
      "AN",
      "AN",
      "AN",
      "AN",
      "AN",
      "AN",
      "ET",
      "AN",
      "AN",
      "AL",
      "AL",
      "AL",
      "NSM",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "AN",
      "N",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "AL",
      "AL",
      "NSM",
      "NSM",
      "N",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "AL",
      "AL",
      "EN",
      "EN",
      "EN",
      "EN",
      "EN",
      "EN",
      "EN",
      "EN",
      "EN",
      "EN",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "N",
      "AL",
      "AL",
      "NSM",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "N",
      "N",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "AL",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "R",
      "R",
      "R",
      "R",
      "R",
      "R",
      "R",
      "R",
      "R",
      "R",
      "R",
      "R",
      "R",
      "R",
      "R",
      "R",
      "R",
      "R",
      "R",
      "R",
      "R",
      "R",
      "R",
      "R",
      "R",
      "R",
      "R",
      "R",
      "R",
      "R",
      "R",
      "R",
      "R",
      "R",
      "R",
      "R",
      "R",
      "R",
      "R",
      "R",
      "R",
      "R",
      "R",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "R",
      "R",
      "N",
      "N",
      "N",
      "N",
      "R",
      "N",
      "N",
      "N",
      "N",
      "N",
      "WS",
      "WS",
      "WS",
      "WS",
      "WS",
      "WS",
      "WS",
      "WS",
      "WS",
      "WS",
      "WS",
      "BN",
      "BN",
      "BN",
      "L",
      "R",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "WS",
      "B",
      "LRE",
      "RLE",
      "PDF",
      "LRO",
      "RLO",
      "CS",
      "ET",
      "ET",
      "ET",
      "ET",
      "ET",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "CS",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "WS",
      "BN",
      "BN",
      "BN",
      "BN",
      "BN",
      "N",
      "LRI",
      "RLI",
      "FSI",
      "PDI",
      "BN",
      "BN",
      "BN",
      "BN",
      "BN",
      "BN",
      "EN",
      "L",
      "N",
      "N",
      "EN",
      "EN",
      "EN",
      "EN",
      "EN",
      "EN",
      "ES",
      "ES",
      "N",
      "N",
      "N",
      "L",
      "EN",
      "EN",
      "EN",
      "EN",
      "EN",
      "EN",
      "EN",
      "EN",
      "EN",
      "EN",
      "ES",
      "ES",
      "N",
      "N",
      "N",
      "N",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "N",
      "N",
      "N",
      "ET",
      "ET",
      "ET",
      "ET",
      "ET",
      "ET",
      "ET",
      "ET",
      "ET",
      "ET",
      "ET",
      "ET",
      "ET",
      "ET",
      "ET",
      "ET",
      "ET",
      "ET",
      "ET",
      "ET",
      "ET",
      "ET",
      "ET",
      "ET",
      "ET",
      "ET",
      "ET",
      "ET",
      "ET",
      "ET",
      "ET",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "L",
      "L",
      "L",
      "L",
      "L",
      "N",
      "N",
      "N",
      "N",
      "N",
      "R",
      "NSM",
      "R",
      "R",
      "R",
      "R",
      "R",
      "R",
      "R",
      "R",
      "R",
      "R",
      "ES",
      "R",
      "R",
      "R",
      "R",
      "R",
      "R",
      "R",
      "R",
      "R",
      "R",
      "R",
      "R",
      "R",
      "N",
      "R",
      "R",
      "R",
      "R",
      "R",
      "N",
      "R",
      "N",
      "R",
      "R",
      "N",
      "R",
      "R",
      "N",
      "R",
      "R",
      "R",
      "R",
      "R",
      "R",
      "R",
      "R",
      "R",
      "R",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "NSM",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "CS",
      "N",
      "CS",
      "N",
      "N",
      "CS",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "ET",
      "N",
      "N",
      "ES",
      "ES",
      "N",
      "N",
      "N",
      "N",
      "N",
      "ET",
      "ET",
      "N",
      "N",
      "N",
      "N",
      "N",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "N",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "AL",
      "N",
      "N",
      "BN",
      "N",
      "N",
      "N",
      "ET",
      "ET",
      "ET",
      "N",
      "N",
      "N",
      "N",
      "N",
      "ES",
      "CS",
      "ES",
      "CS",
      "CS",
      "EN",
      "EN",
      "EN",
      "EN",
      "EN",
      "EN",
      "EN",
      "EN",
      "EN",
      "EN",
      "CS",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "N",
      "N",
      "N",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "N",
      "N",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "N",
      "N",
      "L",
      "L",
      "L",
      "L",
      "L",
      "L",
      "N",
      "N",
      "L",
      "L",
      "L",
      "N",
      "N",
      "N",
      "ET",
      "ET",
      "N",
      "N",
      "N",
      "ET",
      "ET",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N",
      "N"
    ];

    /**
     * Unicode Bidi algorithm compliant Bidi engine.
     * For reference see http://unicode.org/reports/tr9/
     */

    /**
     * constructor ( options )
     *
     * Initializes Bidi engine
     *
     * @param {Object} See 'setOptions' below for detailed description.
     * options are cashed between invocation of 'doBidiReorder' method
     *
     * sample usage pattern of BidiEngine:
     * var opt = {
     * 	isInputVisual: true,
     * 	isInputRtl: false,
     * 	isOutputVisual: false,
     * 	isOutputRtl: false,
     * 	isSymmetricSwapping: true
     * }
     * var sourceToTarget = [], levels = [];
     * var bidiEng = Globalize.bidiEngine(opt);
     * var src = "text string to be reordered";
     * var ret = bidiEng.doBidiReorder(src, sourceToTarget, levels);
     */

    jsPDF.__bidiEngine__ = jsPDF.prototype.__bidiEngine__ = function(options) {
      var _UNICODE_TYPES = _bidiUnicodeTypes;

      var _STATE_TABLE_LTR = [
        [0, 3, 0, 1, 0, 0, 0],
        [0, 3, 0, 1, 2, 2, 0],
        [0, 3, 0, 0x11, 2, 0, 1],
        [0, 3, 5, 5, 4, 1, 0],
        [0, 3, 0x15, 0x15, 4, 0, 1],
        [0, 3, 5, 5, 4, 2, 0]
      ];

      var _STATE_TABLE_RTL = [
        [2, 0, 1, 1, 0, 1, 0],
        [2, 0, 1, 1, 0, 2, 0],
        [2, 0, 2, 1, 3, 2, 0],
        [2, 0, 2, 0x21, 3, 1, 1]
      ];

      var _TYPE_NAMES_MAP = { L: 0, R: 1, EN: 2, AN: 3, N: 4, B: 5, S: 6 };

      var _UNICODE_RANGES_MAP = {
        0: 0,
        5: 1,
        6: 2,
        7: 3,
        0x20: 4,
        0xfb: 5,
        0xfe: 6,
        0xff: 7
      };

      var _SWAP_TABLE = [
        "\u0028",
        "\u0029",
        "\u0028",
        "\u003C",
        "\u003E",
        "\u003C",
        "\u005B",
        "\u005D",
        "\u005B",
        "\u007B",
        "\u007D",
        "\u007B",
        "\u00AB",
        "\u00BB",
        "\u00AB",
        "\u2039",
        "\u203A",
        "\u2039",
        "\u2045",
        "\u2046",
        "\u2045",
        "\u207D",
        "\u207E",
        "\u207D",
        "\u208D",
        "\u208E",
        "\u208D",
        "\u2264",
        "\u2265",
        "\u2264",
        "\u2329",
        "\u232A",
        "\u2329",
        "\uFE59",
        "\uFE5A",
        "\uFE59",
        "\uFE5B",
        "\uFE5C",
        "\uFE5B",
        "\uFE5D",
        "\uFE5E",
        "\uFE5D",
        "\uFE64",
        "\uFE65",
        "\uFE64"
      ];

      var _LTR_RANGES_REG_EXPR = new RegExp(
        /^([1-4|9]|1[0-9]|2[0-9]|3[0168]|4[04589]|5[012]|7[78]|159|16[0-9]|17[0-2]|21[569]|22[03489]|250)$/
      );

      var _lastArabic = false,
        _hasUbatB,
        _hasUbatS,
        DIR_LTR = 0,
        DIR_RTL = 1,
        _isInVisual,
        _isInRtl,
        _isOutVisual,
        _isOutRtl,
        _isSymmetricSwapping,
        _dir = DIR_LTR;

      this.__bidiEngine__ = {};

      var _init = function(text, sourceToTargetMap) {
        if (sourceToTargetMap) {
          for (var i = 0; i < text.length; i++) {
            sourceToTargetMap[i] = i;
          }
        }
        if (_isInRtl === undefined) {
          _isInRtl = _isContextualDirRtl(text);
        }
        if (_isOutRtl === undefined) {
          _isOutRtl = _isContextualDirRtl(text);
        }
      };

      // for reference see 3.2 in http://unicode.org/reports/tr9/
      //
      var _getCharType = function(ch) {
        var charCode = ch.charCodeAt(),
          range = charCode >> 8,
          rangeIdx = _UNICODE_RANGES_MAP[range];

        if (rangeIdx !== undefined) {
          return _UNICODE_TYPES[rangeIdx * 256 + (charCode & 0xff)];
        } else if (range === 0xfc || range === 0xfd) {
          return "AL";
        } else if (_LTR_RANGES_REG_EXPR.test(range)) {
          //unlikely case
          return "L";
        } else if (range === 8) {
          // even less likely
          return "R";
        }
        return "N"; //undefined type, mark as neutral
      };

      var _isContextualDirRtl = function(text) {
        for (var i = 0, charType; i < text.length; i++) {
          charType = _getCharType(text.charAt(i));
          if (charType === "L") {
            return false;
          } else if (charType === "R") {
            return true;
          }
        }
        return false;
      };

      // for reference see 3.3.4 & 3.3.5 in http://unicode.org/reports/tr9/
      //
      var _resolveCharType = function(chars, types, resolvedTypes, index) {
        var cType = types[index],
          wType,
          nType,
          i,
          len;
        switch (cType) {
          case "L":
          case "R":
            _lastArabic = false;
            break;
          case "N":
          case "AN":
            break;

          case "EN":
            if (_lastArabic) {
              cType = "AN";
            }
            break;

          case "AL":
            _lastArabic = true;
            cType = "R";
            break;

          case "WS":
            cType = "N";
            break;

          case "CS":
            if (
              index < 1 ||
              index + 1 >= types.length ||
              ((wType = resolvedTypes[index - 1]) !== "EN" && wType !== "AN") ||
              ((nType = types[index + 1]) !== "EN" && nType !== "AN")
            ) {
              cType = "N";
            } else if (_lastArabic) {
              nType = "AN";
            }
            cType = nType === wType ? nType : "N";
            break;

          case "ES":
            wType = index > 0 ? resolvedTypes[index - 1] : "B";
            cType =
              wType === "EN" &&
              index + 1 < types.length &&
              types[index + 1] === "EN"
                ? "EN"
                : "N";
            break;

          case "ET":
            if (index > 0 && resolvedTypes[index - 1] === "EN") {
              cType = "EN";
              break;
            } else if (_lastArabic) {
              cType = "N";
              break;
            }
            i = index + 1;
            len = types.length;
            while (i < len && types[i] === "ET") {
              i++;
            }
            if (i < len && types[i] === "EN") {
              cType = "EN";
            } else {
              cType = "N";
            }
            break;

          case "NSM":
            if (_isInVisual && !_isInRtl) {
              //V->L
              len = types.length;
              i = index + 1;
              while (i < len && types[i] === "NSM") {
                i++;
              }
              if (i < len) {
                var c = chars[index];
                var rtlCandidate = (c >= 0x0591 && c <= 0x08ff) || c === 0xfb1e;
                wType = types[i];
                if (rtlCandidate && (wType === "R" || wType === "AL")) {
                  cType = "R";
                  break;
                }
              }
            }
            if (index < 1 || (wType = types[index - 1]) === "B") {
              cType = "N";
            } else {
              cType = resolvedTypes[index - 1];
            }
            break;

          case "B":
            _lastArabic = false;
            _hasUbatB = true;
            cType = _dir;
            break;

          case "S":
            _hasUbatS = true;
            cType = "N";
            break;

          case "LRE":
          case "RLE":
          case "LRO":
          case "RLO":
          case "PDF":
            _lastArabic = false;
            break;
          case "BN":
            cType = "N";
            break;
        }
        return cType;
      };

      var _handleUbatS = function(types, levels, length) {
        for (var i = 0; i < length; i++) {
          if (types[i] === "S") {
            levels[i] = _dir;
            for (var j = i - 1; j >= 0; j--) {
              if (types[j] === "WS") {
                levels[j] = _dir;
              } else {
                break;
              }
            }
          }
        }
      };

      var _invertString = function(text, sourceToTargetMap, levels) {
        var charArray = text.split("");
        if (levels) {
          _computeLevels(charArray, levels, { hiLevel: _dir });
        }
        charArray.reverse();
        sourceToTargetMap && sourceToTargetMap.reverse();
        return charArray.join("");
      };

      // For reference see 3.3 in http://unicode.org/reports/tr9/
      //
      var _computeLevels = function(chars, levels, params) {
        var action,
          condition,
          i,
          index,
          newLevel,
          prevState,
          condPos = -1,
          len = chars.length,
          newState = 0,
          resolvedTypes = [],
          stateTable = _dir ? _STATE_TABLE_RTL : _STATE_TABLE_LTR,
          types = [];

        _lastArabic = false;
        _hasUbatB = false;
        _hasUbatS = false;
        for (i = 0; i < len; i++) {
          types[i] = _getCharType(chars[i]);
        }
        for (index = 0; index < len; index++) {
          prevState = newState;
          resolvedTypes[index] = _resolveCharType(
            chars,
            types,
            resolvedTypes,
            index
          );
          newState = stateTable[prevState][_TYPE_NAMES_MAP[resolvedTypes[index]]];
          action = newState & 0xf0;
          newState &= 0x0f;
          levels[index] = newLevel = stateTable[newState][5];
          if (action > 0) {
            if (action === 0x10) {
              for (i = condPos; i < index; i++) {
                levels[i] = 1;
              }
              condPos = -1;
            } else {
              condPos = -1;
            }
          }
          condition = stateTable[newState][6];
          if (condition) {
            if (condPos === -1) {
              condPos = index;
            }
          } else {
            if (condPos > -1) {
              for (i = condPos; i < index; i++) {
                levels[i] = newLevel;
              }
              condPos = -1;
            }
          }
          if (types[index] === "B") {
            levels[index] = 0;
          }
          params.hiLevel |= newLevel;
        }
        if (_hasUbatS) {
          _handleUbatS(types, levels, len);
        }
      };

      // for reference see 3.4 in http://unicode.org/reports/tr9/
      //
      var _invertByLevel = function(
        level,
        charArray,
        sourceToTargetMap,
        levels,
        params
      ) {
        if (params.hiLevel < level) {
          return;
        }
        if (level === 1 && _dir === DIR_RTL && !_hasUbatB) {
          charArray.reverse();
          sourceToTargetMap && sourceToTargetMap.reverse();
          return;
        }
        var ch,
          high,
          end,
          low,
          len = charArray.length,
          start = 0;

        while (start < len) {
          if (levels[start] >= level) {
            end = start + 1;
            while (end < len && levels[end] >= level) {
              end++;
            }
            for (low = start, high = end - 1; low < high; low++, high--) {
              ch = charArray[low];
              charArray[low] = charArray[high];
              charArray[high] = ch;
              if (sourceToTargetMap) {
                ch = sourceToTargetMap[low];
                sourceToTargetMap[low] = sourceToTargetMap[high];
                sourceToTargetMap[high] = ch;
              }
            }
            start = end;
          }
          start++;
        }
      };

      // for reference see 7 & BD16 in http://unicode.org/reports/tr9/
      //
      var _symmetricSwap = function(charArray, levels, params) {
        if (params.hiLevel !== 0 && _isSymmetricSwapping) {
          for (var i = 0, index; i < charArray.length; i++) {
            if (levels[i] === 1) {
              index = _SWAP_TABLE.indexOf(charArray[i]);
              if (index >= 0) {
                charArray[i] = _SWAP_TABLE[index + 1];
              }
            }
          }
        }
      };

      var _reorder = function(text, sourceToTargetMap, levels) {
        var charArray = text.split(""),
          params = { hiLevel: _dir };

        if (!levels) {
          levels = [];
        }
        _computeLevels(charArray, levels, params);
        _symmetricSwap(charArray, levels, params);
        _invertByLevel(DIR_RTL + 1, charArray, sourceToTargetMap, levels, params);
        _invertByLevel(DIR_RTL, charArray, sourceToTargetMap, levels, params);
        return charArray.join("");
      };

      // doBidiReorder( text, sourceToTargetMap, levels )
      // Performs Bidi reordering by implementing Unicode Bidi algorithm.
      // Returns reordered string
      // @text [String]:
      // - input string to be reordered, this is input parameter
      // $sourceToTargetMap [Array] (optional)
      // - resultant mapping between input and output strings, this is output parameter
      // $levels [Array] (optional)
      // - array of calculated Bidi levels, , this is output parameter
      this.__bidiEngine__.doBidiReorder = function(
        text,
        sourceToTargetMap,
        levels
      ) {
        _init(text, sourceToTargetMap);
        if (!_isInVisual && _isOutVisual && !_isOutRtl) {
          // LLTR->VLTR, LRTL->VLTR
          _dir = _isInRtl ? DIR_RTL : DIR_LTR;
          text = _reorder(text, sourceToTargetMap, levels);
        } else if (_isInVisual && _isOutVisual && _isInRtl ^ _isOutRtl) {
          // VRTL->VLTR, VLTR->VRTL
          _dir = _isInRtl ? DIR_RTL : DIR_LTR;
          text = _invertString(text, sourceToTargetMap, levels);
        } else if (!_isInVisual && _isOutVisual && _isOutRtl) {
          // LLTR->VRTL, LRTL->VRTL
          _dir = _isInRtl ? DIR_RTL : DIR_LTR;
          text = _reorder(text, sourceToTargetMap, levels);
          text = _invertString(text, sourceToTargetMap);
        } else if (_isInVisual && !_isInRtl && !_isOutVisual && !_isOutRtl) {
          // VLTR->LLTR
          _dir = DIR_LTR;
          text = _reorder(text, sourceToTargetMap, levels);
        } else if (_isInVisual && !_isOutVisual && _isInRtl ^ _isOutRtl) {
          // VLTR->LRTL, VRTL->LLTR
          text = _invertString(text, sourceToTargetMap);
          if (_isInRtl) {
            //LLTR -> VLTR
            _dir = DIR_LTR;
            text = _reorder(text, sourceToTargetMap, levels);
          } else {
            //LRTL -> VRTL
            _dir = DIR_RTL;
            text = _reorder(text, sourceToTargetMap, levels);
            text = _invertString(text, sourceToTargetMap);
          }
        } else if (_isInVisual && _isInRtl && !_isOutVisual && _isOutRtl) {
          //  VRTL->LRTL
          _dir = DIR_RTL;
          text = _reorder(text, sourceToTargetMap, levels);
          text = _invertString(text, sourceToTargetMap);
        } else if (!_isInVisual && !_isOutVisual && _isInRtl ^ _isOutRtl) {
          // LRTL->LLTR, LLTR->LRTL
          var isSymmetricSwappingOrig = _isSymmetricSwapping;
          if (_isInRtl) {
            //LRTL->LLTR
            _dir = DIR_RTL;
            text = _reorder(text, sourceToTargetMap, levels);
            _dir = DIR_LTR;
            _isSymmetricSwapping = false;
            text = _reorder(text, sourceToTargetMap, levels);
            _isSymmetricSwapping = isSymmetricSwappingOrig;
          } else {
            //LLTR->LRTL
            _dir = DIR_LTR;
            text = _reorder(text, sourceToTargetMap, levels);
            text = _invertString(text, sourceToTargetMap);
            _dir = DIR_RTL;
            _isSymmetricSwapping = false;
            text = _reorder(text, sourceToTargetMap, levels);
            _isSymmetricSwapping = isSymmetricSwappingOrig;
            text = _invertString(text, sourceToTargetMap);
          }
        }
        return text;
      };

      /**
       * @name setOptions( options )
       * @function
       * Sets options for Bidi conversion
       * @param {Object}:
       * - isInputVisual {boolean} (defaults to false): allowed values: true(Visual mode), false(Logical mode)
       * - isInputRtl {boolean}: allowed values true(Right-to-left direction), false (Left-to-right directiion), undefined(Contectual direction, i.e.direction defined by first strong character of input string)
       * - isOutputVisual {boolean} (defaults to false): allowed values: true(Visual mode), false(Logical mode)
       * - isOutputRtl {boolean}: allowed values true(Right-to-left direction), false (Left-to-right directiion), undefined(Contectual direction, i.e.direction defined by first strong characterof input string)
       * - isSymmetricSwapping {boolean} (defaults to false): allowed values true(needs symmetric swapping), false (no need in symmetric swapping),
       */
      this.__bidiEngine__.setOptions = function(options) {
        if (options) {
          _isInVisual = options.isInputVisual;
          _isOutVisual = options.isOutputVisual;
          _isInRtl = options.isInputRtl;
          _isOutRtl = options.isOutputRtl;
          _isSymmetricSwapping = options.isSymmetricSwapping;
        }
      };

      this.__bidiEngine__.setOptions(options);
      return this.__bidiEngine__;
    };

    var _bidiUnicodeTypes = bidiUnicodeTypes;

    var bidiEngine = new jsPDF.__bidiEngine__({ isInputVisual: true });

    var bidiEngineFunction = function(args) {
      var text = args.text;
      var x = args.x;
      var y = args.y;
      var options = args.options || {};
      var mutex = args.mutex || {};
      var lang = options.lang;
      var tmpText = [];

      options.isInputVisual =
        typeof options.isInputVisual === "boolean" ? options.isInputVisual : true;
      bidiEngine.setOptions(options);

      if (Object.prototype.toString.call(text) === "[object Array]") {
        var i = 0;
        tmpText = [];
        for (i = 0; i < text.length; i += 1) {
          if (Object.prototype.toString.call(text[i]) === "[object Array]") {
            tmpText.push([
              bidiEngine.doBidiReorder(text[i][0]),
              text[i][1],
              text[i][2]
            ]);
          } else {
            tmpText.push([bidiEngine.doBidiReorder(text[i])]);
          }
        }
        args.text = tmpText;
      } else {
        args.text = bidiEngine.doBidiReorder(text);
      }
      bidiEngine.setOptions({ isInputVisual: true });
    };

    jsPDF.API.events.push(["postProcessText", bidiEngineFunction]);
  })(jsPDF);

  /* eslint-disable no-control-regex */

  jsPDF.API.TTFFont = (function() {
    /************************************************************************/
    /* function : open                                                       */
    /* comment : Decode the encoded ttf content and create a TTFFont object. */
    /************************************************************************/
    TTFFont.open = function(file) {
      return new TTFFont(file);
    };
    /***************************************************************/
    /* function : TTFFont gernerator                               */
    /* comment : Decode TTF contents are parsed, Data,             */
    /* Subset object is created, and registerTTF function is called.*/
    /***************************************************************/
    function TTFFont(rawData) {
      var data;
      this.rawData = rawData;
      data = this.contents = new Data(rawData);
      this.contents.pos = 4;
      if (data.readString(4) === "ttcf") {
        throw new Error("TTCF not supported.");
      } else {
        data.pos = 0;
        this.parse();
        this.subset = new Subset(this);
        this.registerTTF();
      }
    }
    /********************************************************/
    /* function : parse                                     */
    /* comment : TTF Parses the file contents by each table.*/
    /********************************************************/
    TTFFont.prototype.parse = function() {
      this.directory = new Directory(this.contents);
      this.head = new HeadTable(this);
      this.name = new NameTable(this);
      this.cmap = new CmapTable(this);
      this.toUnicode = {};
      this.hhea = new HheaTable(this);
      this.maxp = new MaxpTable(this);
      this.hmtx = new HmtxTable(this);
      this.post = new PostTable(this);
      this.os2 = new OS2Table(this);
      this.loca = new LocaTable(this);
      this.glyf = new GlyfTable(this);
      this.ascender =
        (this.os2.exists && this.os2.ascender) || this.hhea.ascender;
      this.decender =
        (this.os2.exists && this.os2.decender) || this.hhea.decender;
      this.lineGap = (this.os2.exists && this.os2.lineGap) || this.hhea.lineGap;
      return (this.bbox = [
        this.head.xMin,
        this.head.yMin,
        this.head.xMax,
        this.head.yMax
      ]);
    };
    /***************************************************************/
    /* function : registerTTF                                      */
    /* comment : Get the value to assign pdf font descriptors.     */
    /***************************************************************/
    TTFFont.prototype.registerTTF = function() {
      var e, hi, low, raw, _ref;
      this.scaleFactor = 1000.0 / this.head.unitsPerEm;
      this.bbox = function() {
        var _i, _len, _ref, _results;
        _ref = this.bbox;
        _results = [];
        for (_i = 0, _len = _ref.length; _i < _len; _i++) {
          e = _ref[_i];
          _results.push(Math.round(e * this.scaleFactor));
        }
        return _results;
      }.call(this);
      this.stemV = 0;
      if (this.post.exists) {
        raw = this.post.italic_angle;
        hi = raw >> 16;
        low = raw & 0xff;
        if ((hi & 0x8000) !== 0) {
          hi = -((hi ^ 0xffff) + 1);
        }
        this.italicAngle = +("" + hi + "." + low);
      } else {
        this.italicAngle = 0;
      }
      this.ascender = Math.round(this.ascender * this.scaleFactor);
      this.decender = Math.round(this.decender * this.scaleFactor);
      this.lineGap = Math.round(this.lineGap * this.scaleFactor);
      this.capHeight = (this.os2.exists && this.os2.capHeight) || this.ascender;
      this.xHeight = (this.os2.exists && this.os2.xHeight) || 0;
      this.familyClass = ((this.os2.exists && this.os2.familyClass) || 0) >> 8;
      this.isSerif =
        (_ref = this.familyClass) === 1 ||
        _ref === 2 ||
        _ref === 3 ||
        _ref === 4 ||
        _ref === 5 ||
        _ref === 7;
      this.isScript = this.familyClass === 10;
      this.flags = 0;
      if (this.post.isFixedPitch) {
        this.flags |= 1 << 0;
      }
      if (this.isSerif) {
        this.flags |= 1 << 1;
      }
      if (this.isScript) {
        this.flags |= 1 << 3;
      }
      if (this.italicAngle !== 0) {
        this.flags |= 1 << 6;
      }
      this.flags |= 1 << 5;
      if (!this.cmap.unicode) {
        throw new Error("No unicode cmap for font");
      }
    };
    TTFFont.prototype.characterToGlyph = function(character) {
      var _ref;
      return (
        ((_ref = this.cmap.unicode) != null ? _ref.codeMap[character] : void 0) ||
        0
      );
    };
    TTFFont.prototype.widthOfGlyph = function(glyph) {
      var scale;
      scale = 1000.0 / this.head.unitsPerEm;
      return this.hmtx.forGlyph(glyph).advance * scale;
    };
    TTFFont.prototype.widthOfString = function(string, size, charSpace) {
      var charCode, i, scale, width, _ref;
      string = "" + string;
      width = 0;
      for (
        i = 0, _ref = string.length;
        0 <= _ref ? i < _ref : i > _ref;
        i = 0 <= _ref ? ++i : --i
      ) {
        charCode = string.charCodeAt(i);
        width +=
          this.widthOfGlyph(this.characterToGlyph(charCode)) +
            charSpace * (1000 / size) || 0;
      }
      scale = size / 1000;
      return width * scale;
    };
    TTFFont.prototype.lineHeight = function(size, includeGap) {
      var gap;
      if (includeGap == null) {
        includeGap = false;
      }
      gap = includeGap ? this.lineGap : 0;
      return ((this.ascender + gap - this.decender) / 1000) * size;
    };
    return TTFFont;
  })();

  /************************************************************************************************/
  /* function : Data                                                                              */
  /* comment : The ttf data decoded and stored in an array is read and written to the Data object.*/
  /************************************************************************************************/
  var Data = (function() {
    function Data(data) {
      this.data = data != null ? data : [];
      this.pos = 0;
      this.length = this.data.length;
    }
    Data.prototype.readByte = function() {
      return this.data[this.pos++];
    };
    Data.prototype.writeByte = function(byte) {
      return (this.data[this.pos++] = byte);
    };
    Data.prototype.readUInt32 = function() {
      var b1, b2, b3, b4;
      b1 = this.readByte() * 0x1000000;
      b2 = this.readByte() << 16;
      b3 = this.readByte() << 8;
      b4 = this.readByte();
      return b1 + b2 + b3 + b4;
    };
    Data.prototype.writeUInt32 = function(val) {
      this.writeByte((val >>> 24) & 0xff);
      this.writeByte((val >> 16) & 0xff);
      this.writeByte((val >> 8) & 0xff);
      return this.writeByte(val & 0xff);
    };
    Data.prototype.readInt32 = function() {
      var int;
      int = this.readUInt32();
      if (int >= 0x80000000) {
        return int - 0x100000000;
      } else {
        return int;
      }
    };
    Data.prototype.writeInt32 = function(val) {
      if (val < 0) {
        val += 0x100000000;
      }
      return this.writeUInt32(val);
    };
    Data.prototype.readUInt16 = function() {
      var b1, b2;
      b1 = this.readByte() << 8;
      b2 = this.readByte();
      return b1 | b2;
    };
    Data.prototype.writeUInt16 = function(val) {
      this.writeByte((val >> 8) & 0xff);
      return this.writeByte(val & 0xff);
    };
    Data.prototype.readInt16 = function() {
      var int;
      int = this.readUInt16();
      if (int >= 0x8000) {
        return int - 0x10000;
      } else {
        return int;
      }
    };
    Data.prototype.writeInt16 = function(val) {
      if (val < 0) {
        val += 0x10000;
      }
      return this.writeUInt16(val);
    };
    Data.prototype.readString = function(length) {
      var i, ret;
      ret = [];
      for (
        i = 0;
        0 <= length ? i < length : i > length;
        i = 0 <= length ? ++i : --i
      ) {
        ret[i] = String.fromCharCode(this.readByte());
      }
      return ret.join("");
    };
    Data.prototype.writeString = function(val) {
      var i, _ref, _results;
      _results = [];
      for (
        i = 0, _ref = val.length;
        0 <= _ref ? i < _ref : i > _ref;
        i = 0 <= _ref ? ++i : --i
      ) {
        _results.push(this.writeByte(val.charCodeAt(i)));
      }
      return _results;
    };
    /*Data.prototype.stringAt = function (pos, length) {
              this.pos = pos;
              return this.readString(length);
          };*/
    Data.prototype.readShort = function() {
      return this.readInt16();
    };
    Data.prototype.writeShort = function(val) {
      return this.writeInt16(val);
    };
    Data.prototype.readLongLong = function() {
      var b1, b2, b3, b4, b5, b6, b7, b8;
      b1 = this.readByte();
      b2 = this.readByte();
      b3 = this.readByte();
      b4 = this.readByte();
      b5 = this.readByte();
      b6 = this.readByte();
      b7 = this.readByte();
      b8 = this.readByte();
      if (b1 & 0x80) {
        return (
          ((b1 ^ 0xff) * 0x100000000000000 +
            (b2 ^ 0xff) * 0x1000000000000 +
            (b3 ^ 0xff) * 0x10000000000 +
            (b4 ^ 0xff) * 0x100000000 +
            (b5 ^ 0xff) * 0x1000000 +
            (b6 ^ 0xff) * 0x10000 +
            (b7 ^ 0xff) * 0x100 +
            (b8 ^ 0xff) +
            1) *
          -1
        );
      }
      return (
        b1 * 0x100000000000000 +
        b2 * 0x1000000000000 +
        b3 * 0x10000000000 +
        b4 * 0x100000000 +
        b5 * 0x1000000 +
        b6 * 0x10000 +
        b7 * 0x100 +
        b8
      );
    };
    Data.prototype.writeLongLong = function(val) {
      var high, low;
      high = Math.floor(val / 0x100000000);
      low = val & 0xffffffff;
      this.writeByte((high >> 24) & 0xff);
      this.writeByte((high >> 16) & 0xff);
      this.writeByte((high >> 8) & 0xff);
      this.writeByte(high & 0xff);
      this.writeByte((low >> 24) & 0xff);
      this.writeByte((low >> 16) & 0xff);
      this.writeByte((low >> 8) & 0xff);
      return this.writeByte(low & 0xff);
    };
    Data.prototype.readInt = function() {
      return this.readInt32();
    };
    Data.prototype.writeInt = function(val) {
      return this.writeInt32(val);
    };
    /*Data.prototype.slice = function (start, end) {
              return this.data.slice(start, end);
          };*/
    Data.prototype.read = function(bytes) {
      var buf, i;
      buf = [];
      for (
        i = 0;
        0 <= bytes ? i < bytes : i > bytes;
        i = 0 <= bytes ? ++i : --i
      ) {
        buf.push(this.readByte());
      }
      return buf;
    };
    Data.prototype.write = function(bytes) {
      var byte, i, _len, _results;
      _results = [];
      for (i = 0, _len = bytes.length; i < _len; i++) {
        byte = bytes[i];
        _results.push(this.writeByte(byte));
      }
      return _results;
    };
    return Data;
  })();

  var Directory = (function() {
    var checksum;

    /*****************************************************************************************************/
    /* function : Directory generator                                                                    */
    /* comment : Initialize the offset, tag, length, and checksum for each table for the font to be used.*/
    /*****************************************************************************************************/
    function Directory(data) {
      var entry, i, _ref;
      this.scalarType = data.readInt();
      this.tableCount = data.readShort();
      this.searchRange = data.readShort();
      this.entrySelector = data.readShort();
      this.rangeShift = data.readShort();
      this.tables = {};
      for (
        i = 0, _ref = this.tableCount;
        0 <= _ref ? i < _ref : i > _ref;
        i = 0 <= _ref ? ++i : --i
      ) {
        entry = {
          tag: data.readString(4),
          checksum: data.readInt(),
          offset: data.readInt(),
          length: data.readInt()
        };
        this.tables[entry.tag] = entry;
      }
    }
    /********************************************************************************************************/
    /* function : encode                                                                                    */
    /* comment : It encodes and stores the font table object and information used for the directory object. */
    /********************************************************************************************************/
    Directory.prototype.encode = function(tables) {
      var adjustment,
        directory,
        directoryLength,
        entrySelector,
        headOffset,
        log2,
        offset,
        rangeShift,
        searchRange,
        sum,
        table,
        tableCount,
        tableData,
        tag;
      tableCount = Object.keys(tables).length;
      log2 = Math.log(2);
      searchRange = Math.floor(Math.log(tableCount) / log2) * 16;
      entrySelector = Math.floor(searchRange / log2);
      rangeShift = tableCount * 16 - searchRange;
      directory = new Data();
      directory.writeInt(this.scalarType);
      directory.writeShort(tableCount);
      directory.writeShort(searchRange);
      directory.writeShort(entrySelector);
      directory.writeShort(rangeShift);
      directoryLength = tableCount * 16;
      offset = directory.pos + directoryLength;
      headOffset = null;
      tableData = [];
      for (tag in tables) {
        table = tables[tag];
        directory.writeString(tag);
        directory.writeInt(checksum(table));
        directory.writeInt(offset);
        directory.writeInt(table.length);
        tableData = tableData.concat(table);
        if (tag === "head") {
          headOffset = offset;
        }
        offset += table.length;
        while (offset % 4) {
          tableData.push(0);
          offset++;
        }
      }
      directory.write(tableData);
      sum = checksum(directory.data);
      adjustment = 0xb1b0afba - sum;
      directory.pos = headOffset + 8;
      directory.writeUInt32(adjustment);
      return directory.data;
    };
    /***************************************************************/
    /* function : checksum                                         */
    /* comment : Duplicate the table for the tag.                  */
    /***************************************************************/
    checksum = function(data) {
      var i, sum, tmp, _ref;
      data = __slice.call(data);
      while (data.length % 4) {
        data.push(0);
      }
      tmp = new Data(data);
      sum = 0;
      for (i = 0, _ref = data.length; i < _ref; i = i += 4) {
        sum += tmp.readUInt32();
      }
      return sum & 0xffffffff;
    };
    return Directory;
  })();

  var Table,
    __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) {
      for (var key in parent) {
        if (__hasProp.call(parent, key)) child[key] = parent[key];
      }

      function ctor() {
        this.constructor = child;
      }
      ctor.prototype = parent.prototype;
      child.prototype = new ctor();
      child.__super__ = parent.prototype;
      return child;
    };

  /***************************************************************/
  /* function : Table                                            */
  /* comment : Save info for each table, and parse the table.    */
  /***************************************************************/
  Table = (function() {
    function Table(file) {
      var info;
      this.file = file;
      info = this.file.directory.tables[this.tag];
      this.exists = !!info;
      if (info) {
        (this.offset = info.offset), (this.length = info.length);
        this.parse(this.file.contents);
      }
    }
    Table.prototype.parse = function() {};
    Table.prototype.encode = function() {};
    Table.prototype.raw = function() {
      if (!this.exists) {
        return null;
      }
      this.file.contents.pos = this.offset;
      return this.file.contents.read(this.length);
    };
    return Table;
  })();

  var HeadTable = (function(_super) {
    __extends(HeadTable, _super);

    function HeadTable() {
      return HeadTable.__super__.constructor.apply(this, arguments);
    }
    HeadTable.prototype.tag = "head";
    HeadTable.prototype.parse = function(data) {
      data.pos = this.offset;
      this.version = data.readInt();
      this.revision = data.readInt();
      this.checkSumAdjustment = data.readInt();
      this.magicNumber = data.readInt();
      this.flags = data.readShort();
      this.unitsPerEm = data.readShort();
      this.created = data.readLongLong();
      this.modified = data.readLongLong();
      this.xMin = data.readShort();
      this.yMin = data.readShort();
      this.xMax = data.readShort();
      this.yMax = data.readShort();
      this.macStyle = data.readShort();
      this.lowestRecPPEM = data.readShort();
      this.fontDirectionHint = data.readShort();
      this.indexToLocFormat = data.readShort();
      return (this.glyphDataFormat = data.readShort());
    };
    HeadTable.prototype.encode = function(indexToLocFormat) {
      var table;
      table = new Data();
      table.writeInt(this.version);
      table.writeInt(this.revision);
      table.writeInt(this.checkSumAdjustment);
      table.writeInt(this.magicNumber);
      table.writeShort(this.flags);
      table.writeShort(this.unitsPerEm);
      table.writeLongLong(this.created);
      table.writeLongLong(this.modified);
      table.writeShort(this.xMin);
      table.writeShort(this.yMin);
      table.writeShort(this.xMax);
      table.writeShort(this.yMax);
      table.writeShort(this.macStyle);
      table.writeShort(this.lowestRecPPEM);
      table.writeShort(this.fontDirectionHint);
      table.writeShort(indexToLocFormat);
      table.writeShort(this.glyphDataFormat);
      return table.data;
    };
    return HeadTable;
  })(Table);

  /************************************************************************************/
  /* function : CmapEntry                                                             */
  /* comment : Cmap Initializes and encodes object information (required by pdf spec).*/
  /************************************************************************************/
  var CmapEntry = (function() {
    function CmapEntry(data, offset) {
      var code,
        count,
        endCode,
        glyphId,
        glyphIds,
        i,
        idDelta,
        idRangeOffset,
        index,
        saveOffset,
        segCount,
        segCountX2,
        start,
        startCode,
        tail,
        _j,
        _k,
        _len;
      this.platformID = data.readUInt16();
      this.encodingID = data.readShort();
      this.offset = offset + data.readInt();
      saveOffset = data.pos;
      data.pos = this.offset;
      this.format = data.readUInt16();
      this.length = data.readUInt16();
      this.language = data.readUInt16();
      this.isUnicode =
        (this.platformID === 3 && this.encodingID === 1 && this.format === 4) ||
        (this.platformID === 0 && this.format === 4);
      this.codeMap = {};
      switch (this.format) {
        case 0:
          for (i = 0; i < 256; ++i) {
            this.codeMap[i] = data.readByte();
          }
          break;
        case 4:
          segCountX2 = data.readUInt16();
          segCount = segCountX2 / 2;
          data.pos += 6;
          endCode = (function() {
            var _j, _results;
            _results = [];
            for (
              i = _j = 0;
              0 <= segCount ? _j < segCount : _j > segCount;
              i = 0 <= segCount ? ++_j : --_j
            ) {
              _results.push(data.readUInt16());
            }
            return _results;
          })();
          data.pos += 2;
          startCode = (function() {
            var _j, _results;
            _results = [];
            for (
              i = _j = 0;
              0 <= segCount ? _j < segCount : _j > segCount;
              i = 0 <= segCount ? ++_j : --_j
            ) {
              _results.push(data.readUInt16());
            }
            return _results;
          })();
          idDelta = (function() {
            var _j, _results;
            _results = [];
            for (
              i = _j = 0;
              0 <= segCount ? _j < segCount : _j > segCount;
              i = 0 <= segCount ? ++_j : --_j
            ) {
              _results.push(data.readUInt16());
            }
            return _results;
          })();
          idRangeOffset = (function() {
            var _j, _results;
            _results = [];
            for (
              i = _j = 0;
              0 <= segCount ? _j < segCount : _j > segCount;
              i = 0 <= segCount ? ++_j : --_j
            ) {
              _results.push(data.readUInt16());
            }
            return _results;
          })();
          count = (this.length - data.pos + this.offset) / 2;
          glyphIds = (function() {
            var _j, _results;
            _results = [];
            for (
              i = _j = 0;
              0 <= count ? _j < count : _j > count;
              i = 0 <= count ? ++_j : --_j
            ) {
              _results.push(data.readUInt16());
            }
            return _results;
          })();
          for (i = _j = 0, _len = endCode.length; _j < _len; i = ++_j) {
            tail = endCode[i];
            start = startCode[i];
            for (
              code = _k = start;
              start <= tail ? _k <= tail : _k >= tail;
              code = start <= tail ? ++_k : --_k
            ) {
              if (idRangeOffset[i] === 0) {
                glyphId = code + idDelta[i];
              } else {
                index = idRangeOffset[i] / 2 + (code - start) - (segCount - i);
                glyphId = glyphIds[index] || 0;
                if (glyphId !== 0) {
                  glyphId += idDelta[i];
                }
              }
              this.codeMap[code] = glyphId & 0xffff;
            }
          }
      }
      data.pos = saveOffset;
    }
    CmapEntry.encode = function(charmap, encoding) {
      var charMap,
        code,
        codeMap,
        codes,
        delta,
        deltas,
        diff,
        endCode,
        endCodes,
        entrySelector,
        glyphIDs,
        i,
        id,
        indexes,
        last,
        map,
        nextID,
        offset,
        old,
        rangeOffsets,
        rangeShift,
        searchRange,
        segCount,
        segCountX2,
        startCode,
        startCodes,
        startGlyph,
        subtable,
        _i,
        _j,
        _k,
        _l,
        _len,
        _len1,
        _len2,
        _len3,
        _len4,
        _len5,
        _len6,
        _len7,
        _m,
        _n,
        _name,
        _o,
        _p,
        _q;
      subtable = new Data();
      codes = Object.keys(charmap).sort(function(a, b) {
        return a - b;
      });
      switch (encoding) {
        case "macroman":
          id = 0;
          indexes = (function() {
            var _results = [];
            for (i = 0; i < 256; ++i) {
              _results.push(0);
            }
            return _results;
          })();
          map = {
            0: 0
          };
          codeMap = {};
          for (_i = 0, _len = codes.length; _i < _len; _i++) {
            code = codes[_i];
            if (map[(_name = charmap[code])] == null) {
              map[_name] = ++id;
            }
            codeMap[code] = {
              old: charmap[code],
              new: map[charmap[code]]
            };
            indexes[code] = map[charmap[code]];
          }
          subtable.writeUInt16(1);
          subtable.writeUInt16(0);
          subtable.writeUInt32(12);
          subtable.writeUInt16(0);
          subtable.writeUInt16(262);
          subtable.writeUInt16(0);
          subtable.write(indexes);
          return {
            charMap: codeMap,
            subtable: subtable.data,
            maxGlyphID: id + 1
          };
        case "unicode":
          startCodes = [];
          endCodes = [];
          nextID = 0;
          map = {};
          charMap = {};
          last = diff = null;
          for (_j = 0, _len1 = codes.length; _j < _len1; _j++) {
            code = codes[_j];
            old = charmap[code];
            if (map[old] == null) {
              map[old] = ++nextID;
            }
            charMap[code] = {
              old: old,
              new: map[old]
            };
            delta = map[old] - code;
            if (last == null || delta !== diff) {
              if (last) {
                endCodes.push(last);
              }
              startCodes.push(code);
              diff = delta;
            }
            last = code;
          }
          if (last) {
            endCodes.push(last);
          }
          endCodes.push(0xffff);
          startCodes.push(0xffff);
          segCount = startCodes.length;
          segCountX2 = segCount * 2;
          searchRange = 2 * Math.pow(Math.log(segCount) / Math.LN2, 2);
          entrySelector = Math.log(searchRange / 2) / Math.LN2;
          rangeShift = 2 * segCount - searchRange;
          deltas = [];
          rangeOffsets = [];
          glyphIDs = [];
          for (i = _k = 0, _len2 = startCodes.length; _k < _len2; i = ++_k) {
            startCode = startCodes[i];
            endCode = endCodes[i];
            if (startCode === 0xffff) {
              deltas.push(0);
              rangeOffsets.push(0);
              break;
            }
            startGlyph = charMap[startCode]["new"];
            if (startCode - startGlyph >= 0x8000) {
              deltas.push(0);
              rangeOffsets.push(2 * (glyphIDs.length + segCount - i));
              for (
                code = _l = startCode;
                startCode <= endCode ? _l <= endCode : _l >= endCode;
                code = startCode <= endCode ? ++_l : --_l
              ) {
                glyphIDs.push(charMap[code]["new"]);
              }
            } else {
              deltas.push(startGlyph - startCode);
              rangeOffsets.push(0);
            }
          }
          subtable.writeUInt16(3);
          subtable.writeUInt16(1);
          subtable.writeUInt32(12);
          subtable.writeUInt16(4);
          subtable.writeUInt16(16 + segCount * 8 + glyphIDs.length * 2);
          subtable.writeUInt16(0);
          subtable.writeUInt16(segCountX2);
          subtable.writeUInt16(searchRange);
          subtable.writeUInt16(entrySelector);
          subtable.writeUInt16(rangeShift);
          for (_m = 0, _len3 = endCodes.length; _m < _len3; _m++) {
            code = endCodes[_m];
            subtable.writeUInt16(code);
          }
          subtable.writeUInt16(0);
          for (_n = 0, _len4 = startCodes.length; _n < _len4; _n++) {
            code = startCodes[_n];
            subtable.writeUInt16(code);
          }
          for (_o = 0, _len5 = deltas.length; _o < _len5; _o++) {
            delta = deltas[_o];
            subtable.writeUInt16(delta);
          }
          for (_p = 0, _len6 = rangeOffsets.length; _p < _len6; _p++) {
            offset = rangeOffsets[_p];
            subtable.writeUInt16(offset);
          }
          for (_q = 0, _len7 = glyphIDs.length; _q < _len7; _q++) {
            id = glyphIDs[_q];
            subtable.writeUInt16(id);
          }
          return {
            charMap: charMap,
            subtable: subtable.data,
            maxGlyphID: nextID + 1
          };
      }
    };
    return CmapEntry;
  })();

  var CmapTable = (function(_super) {
    __extends(CmapTable, _super);

    function CmapTable() {
      return CmapTable.__super__.constructor.apply(this, arguments);
    }
    CmapTable.prototype.tag = "cmap";
    CmapTable.prototype.parse = function(data) {
      var entry, i, tableCount;
      data.pos = this.offset;
      this.version = data.readUInt16();
      tableCount = data.readUInt16();
      this.tables = [];
      this.unicode = null;
      for (
        i = 0;
        0 <= tableCount ? i < tableCount : i > tableCount;
        i = 0 <= tableCount ? ++i : --i
      ) {
        entry = new CmapEntry(data, this.offset);
        this.tables.push(entry);
        if (entry.isUnicode) {
          if (this.unicode == null) {
            this.unicode = entry;
          }
        }
      }
      return true;
    };
    /*************************************************************************/
    /* function : encode                                                     */
    /* comment : Encode the cmap table corresponding to the input character. */
    /*************************************************************************/
    CmapTable.encode = function(charmap, encoding) {
      var result, table;
      if (encoding == null) {
        encoding = "macroman";
      }
      result = CmapEntry.encode(charmap, encoding);
      table = new Data();
      table.writeUInt16(0);
      table.writeUInt16(1);
      result.table = table.data.concat(result.subtable);
      return result;
    };
    return CmapTable;
  })(Table);

  var HheaTable = (function(_super) {
    __extends(HheaTable, _super);

    function HheaTable() {
      return HheaTable.__super__.constructor.apply(this, arguments);
    }
    HheaTable.prototype.tag = "hhea";
    HheaTable.prototype.parse = function(data) {
      data.pos = this.offset;
      this.version = data.readInt();
      this.ascender = data.readShort();
      this.decender = data.readShort();
      this.lineGap = data.readShort();
      this.advanceWidthMax = data.readShort();
      this.minLeftSideBearing = data.readShort();
      this.minRightSideBearing = data.readShort();
      this.xMaxExtent = data.readShort();
      this.caretSlopeRise = data.readShort();
      this.caretSlopeRun = data.readShort();
      this.caretOffset = data.readShort();
      data.pos += 4 * 2;
      this.metricDataFormat = data.readShort();
      return (this.numberOfMetrics = data.readUInt16());
    };
    /*HheaTable.prototype.encode = function (ids) {
              var i, table, _i, _ref;
              table = new Data;
              table.writeInt(this.version);
              table.writeShort(this.ascender);
              table.writeShort(this.decender);
              table.writeShort(this.lineGap);
              table.writeShort(this.advanceWidthMax);
              table.writeShort(this.minLeftSideBearing);
              table.writeShort(this.minRightSideBearing);
              table.writeShort(this.xMaxExtent);
              table.writeShort(this.caretSlopeRise);
              table.writeShort(this.caretSlopeRun);
              table.writeShort(this.caretOffset);
              for (i = _i = 0, _ref = 4 * 2; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
                  table.writeByte(0);
              }
              table.writeShort(this.metricDataFormat);
              table.writeUInt16(ids.length);
              return table.data;
          };*/
    return HheaTable;
  })(Table);

  var OS2Table = (function(_super) {
    __extends(OS2Table, _super);

    function OS2Table() {
      return OS2Table.__super__.constructor.apply(this, arguments);
    }
    OS2Table.prototype.tag = "OS/2";
    OS2Table.prototype.parse = function(data) {
      data.pos = this.offset;
      this.version = data.readUInt16();
      this.averageCharWidth = data.readShort();
      this.weightClass = data.readUInt16();
      this.widthClass = data.readUInt16();
      this.type = data.readShort();
      this.ySubscriptXSize = data.readShort();
      this.ySubscriptYSize = data.readShort();
      this.ySubscriptXOffset = data.readShort();
      this.ySubscriptYOffset = data.readShort();
      this.ySuperscriptXSize = data.readShort();
      this.ySuperscriptYSize = data.readShort();
      this.ySuperscriptXOffset = data.readShort();
      this.ySuperscriptYOffset = data.readShort();
      this.yStrikeoutSize = data.readShort();
      this.yStrikeoutPosition = data.readShort();
      this.familyClass = data.readShort();
      this.panose = (function() {
        var i, _results;
        _results = [];
        for (i = 0; i < 10; ++i) {
          _results.push(data.readByte());
        }
        return _results;
      })();
      this.charRange = (function() {
        var i, _results;
        _results = [];
        for (i = 0; i < 4; ++i) {
          _results.push(data.readInt());
        }
        return _results;
      })();
      this.vendorID = data.readString(4);
      this.selection = data.readShort();
      this.firstCharIndex = data.readShort();
      this.lastCharIndex = data.readShort();
      if (this.version > 0) {
        this.ascent = data.readShort();
        this.descent = data.readShort();
        this.lineGap = data.readShort();
        this.winAscent = data.readShort();
        this.winDescent = data.readShort();
        this.codePageRange = (function() {
          var i, _results;
          _results = [];
          for (i = 0; i < 2; i = ++i) {
            _results.push(data.readInt());
          }
          return _results;
        })();
        if (this.version > 1) {
          this.xHeight = data.readShort();
          this.capHeight = data.readShort();
          this.defaultChar = data.readShort();
          this.breakChar = data.readShort();
          return (this.maxContext = data.readShort());
        }
      }
    };
    /*OS2Table.prototype.encode = function () {
              return this.raw();
          };*/
    return OS2Table;
  })(Table);

  var PostTable = (function(_super) {
    __extends(PostTable, _super);

    function PostTable() {
      return PostTable.__super__.constructor.apply(this, arguments);
    }
    PostTable.prototype.tag = "post";
    PostTable.prototype.parse = function(data) {
      var length, numberOfGlyphs, _results;
      data.pos = this.offset;
      this.format = data.readInt();
      this.italicAngle = data.readInt();
      this.underlinePosition = data.readShort();
      this.underlineThickness = data.readShort();
      this.isFixedPitch = data.readInt();
      this.minMemType42 = data.readInt();
      this.maxMemType42 = data.readInt();
      this.minMemType1 = data.readInt();
      this.maxMemType1 = data.readInt();
      switch (this.format) {
        case 0x00010000:
          break;
        case 0x00020000:
          numberOfGlyphs = data.readUInt16();
          this.glyphNameIndex = [];
          var i;
          for (
            i = 0;
            0 <= numberOfGlyphs ? i < numberOfGlyphs : i > numberOfGlyphs;
            i = 0 <= numberOfGlyphs ? ++i : --i
          ) {
            this.glyphNameIndex.push(data.readUInt16());
          }
          this.names = [];
          _results = [];
          while (data.pos < this.offset + this.length) {
            length = data.readByte();
            _results.push(this.names.push(data.readString(length)));
          }
          return _results;
        case 0x00025000:
          numberOfGlyphs = data.readUInt16();
          return (this.offsets = data.read(numberOfGlyphs));
        case 0x00030000:
          break;
        case 0x00040000:
          return (this.map = function() {
            var _j, _ref, _results1;
            _results1 = [];
            for (
              i = _j = 0, _ref = this.file.maxp.numGlyphs;
              0 <= _ref ? _j < _ref : _j > _ref;
              i = 0 <= _ref ? ++_j : --_j
            ) {
              _results1.push(data.readUInt32());
            }
            return _results1;
          }.call(this));
      }
    };
    return PostTable;
  })(Table);

  /*********************************************************************************************************/
  /* function : NameEntry                                                                                  */
  /* comment : Store copyright information, platformID, encodingID, and languageID in the NameEntry object.*/
  /*********************************************************************************************************/
  var NameEntry = (function() {
    function NameEntry(raw, entry) {
      this.raw = raw;
      this.length = raw.length;
      this.platformID = entry.platformID;
      this.encodingID = entry.encodingID;
      this.languageID = entry.languageID;
    }
    return NameEntry;
  })();

  var NameTable = (function(_super) {
    __extends(NameTable, _super);

    function NameTable() {
      return NameTable.__super__.constructor.apply(this, arguments);
    }
    NameTable.prototype.tag = "name";
    NameTable.prototype.parse = function(data) {
      var count,
        entries,
        entry,
        i,
        name,
        stringOffset,
        strings,
        text,
        _j,
        _len,
        _name;
      data.pos = this.offset;
      data.readShort(); //format
      count = data.readShort();
      stringOffset = data.readShort();
      entries = [];
      for (
        i = 0;
        0 <= count ? i < count : i > count;
        i = 0 <= count ? ++i : --i
      ) {
        entries.push({
          platformID: data.readShort(),
          encodingID: data.readShort(),
          languageID: data.readShort(),
          nameID: data.readShort(),
          length: data.readShort(),
          offset: this.offset + stringOffset + data.readShort()
        });
      }
      strings = {};
      for (i = _j = 0, _len = entries.length; _j < _len; i = ++_j) {
        entry = entries[i];
        data.pos = entry.offset;
        text = data.readString(entry.length);
        name = new NameEntry(text, entry);
        if (strings[(_name = entry.nameID)] == null) {
          strings[_name] = [];
        }
        strings[entry.nameID].push(name);
      }
      this.strings = strings;
      this.copyright = strings[0];
      this.fontFamily = strings[1];
      this.fontSubfamily = strings[2];
      this.uniqueSubfamily = strings[3];
      this.fontName = strings[4];
      this.version = strings[5];
      try {
        this.postscriptName = strings[6][0].raw.replace(
          /[\x00-\x19\x80-\xff]/g,
          ""
        );
      } catch (e) {
        this.postscriptName = strings[4][0].raw.replace(
          /[\x00-\x19\x80-\xff]/g,
          ""
        );
      }
      this.trademark = strings[7];
      this.manufacturer = strings[8];
      this.designer = strings[9];
      this.description = strings[10];
      this.vendorUrl = strings[11];
      this.designerUrl = strings[12];
      this.license = strings[13];
      this.licenseUrl = strings[14];
      this.preferredFamily = strings[15];
      this.preferredSubfamily = strings[17];
      this.compatibleFull = strings[18];
      return (this.sampleText = strings[19]);
    };
    /*NameTable.prototype.encode = function () {
              var id, list, nameID, nameTable, postscriptName, strCount, strTable, string, strings, table, val, _i, _len, _ref;
              strings = {};
              _ref = this.strings;
              for (id in _ref) {
                  val = _ref[id];
                  strings[id] = val;
              }
              postscriptName = new NameEntry("" + subsetTag + "+" + this.postscriptName, {
                  platformID: 1
                  , encodingID: 0
                  , languageID: 0
              });
              strings[6] = [postscriptName];
              subsetTag = successorOf(subsetTag);
              strCount = 0;
              for (id in strings) {
                  list = strings[id];
                  if (list != null) {
                      strCount += list.length;
                  }
              }
              table = new Data;
              strTable = new Data;
              table.writeShort(0);
              table.writeShort(strCount);
              table.writeShort(6 + 12 * strCount);
              for (nameID in strings) {
                  list = strings[nameID];
                  if (list != null) {
                      for (_i = 0, _len = list.length; _i < _len; _i++) {
                          string = list[_i];
                          table.writeShort(string.platformID);
                          table.writeShort(string.encodingID);
                          table.writeShort(string.languageID);
                          table.writeShort(nameID);
                          table.writeShort(string.length);
                          table.writeShort(strTable.pos);
                          strTable.writeString(string.raw);
                      }
                  }
              }
              return nameTable = {
                  postscriptName: postscriptName.raw
                  , table: table.data.concat(strTable.data)
              };
          };*/
    return NameTable;
  })(Table);

  var MaxpTable = (function(_super) {
    __extends(MaxpTable, _super);

    function MaxpTable() {
      return MaxpTable.__super__.constructor.apply(this, arguments);
    }
    MaxpTable.prototype.tag = "maxp";
    MaxpTable.prototype.parse = function(data) {
      data.pos = this.offset;
      this.version = data.readInt();
      this.numGlyphs = data.readUInt16();
      this.maxPoints = data.readUInt16();
      this.maxContours = data.readUInt16();
      this.maxCompositePoints = data.readUInt16();
      this.maxComponentContours = data.readUInt16();
      this.maxZones = data.readUInt16();
      this.maxTwilightPoints = data.readUInt16();
      this.maxStorage = data.readUInt16();
      this.maxFunctionDefs = data.readUInt16();
      this.maxInstructionDefs = data.readUInt16();
      this.maxStackElements = data.readUInt16();
      this.maxSizeOfInstructions = data.readUInt16();
      this.maxComponentElements = data.readUInt16();
      return (this.maxComponentDepth = data.readUInt16());
    };
    /*MaxpTable.prototype.encode = function (ids) {
              var table;
              table = new Data;
              table.writeInt(this.version);
              table.writeUInt16(ids.length);
              table.writeUInt16(this.maxPoints);
              table.writeUInt16(this.maxContours);
              table.writeUInt16(this.maxCompositePoints);
              table.writeUInt16(this.maxComponentContours);
              table.writeUInt16(this.maxZones);
              table.writeUInt16(this.maxTwilightPoints);
              table.writeUInt16(this.maxStorage);
              table.writeUInt16(this.maxFunctionDefs);
              table.writeUInt16(this.maxInstructionDefs);
              table.writeUInt16(this.maxStackElements);
              table.writeUInt16(this.maxSizeOfInstructions);
              table.writeUInt16(this.maxComponentElements);
              table.writeUInt16(this.maxComponentDepth);
              return table.data;
          };*/
    return MaxpTable;
  })(Table);

  var HmtxTable = (function(_super) {
    __extends(HmtxTable, _super);

    function HmtxTable() {
      return HmtxTable.__super__.constructor.apply(this, arguments);
    }
    HmtxTable.prototype.tag = "hmtx";
    HmtxTable.prototype.parse = function(data) {
      var i, last, lsbCount, m, _j, _ref, _results;
      data.pos = this.offset;
      this.metrics = [];
      for (
        i = 0, _ref = this.file.hhea.numberOfMetrics;
        0 <= _ref ? i < _ref : i > _ref;
        i = 0 <= _ref ? ++i : --i
      ) {
        this.metrics.push({
          advance: data.readUInt16(),
          lsb: data.readInt16()
        });
      }
      lsbCount = this.file.maxp.numGlyphs - this.file.hhea.numberOfMetrics;
      this.leftSideBearings = (function() {
        var _j, _results;
        _results = [];
        for (
          i = _j = 0;
          0 <= lsbCount ? _j < lsbCount : _j > lsbCount;
          i = 0 <= lsbCount ? ++_j : --_j
        ) {
          _results.push(data.readInt16());
        }
        return _results;
      })();
      this.widths = function() {
        var _j, _len, _ref1, _results;
        _ref1 = this.metrics;
        _results = [];
        for (_j = 0, _len = _ref1.length; _j < _len; _j++) {
          m = _ref1[_j];
          _results.push(m.advance);
        }
        return _results;
      }.call(this);
      last = this.widths[this.widths.length - 1];
      _results = [];
      for (
        i = _j = 0;
        0 <= lsbCount ? _j < lsbCount : _j > lsbCount;
        i = 0 <= lsbCount ? ++_j : --_j
      ) {
        _results.push(this.widths.push(last));
      }
      return _results;
    };
    /***************************************************************/
    /* function : forGlyph                                         */
    /* comment : Returns the advance width and lsb for this glyph. */
    /***************************************************************/
    HmtxTable.prototype.forGlyph = function(id) {
      if (id in this.metrics) {
        return this.metrics[id];
      }
      return {
        advance: this.metrics[this.metrics.length - 1].advance,
        lsb: this.leftSideBearings[id - this.metrics.length]
      };
    };
    /*HmtxTable.prototype.encode = function (mapping) {
              var id, metric, table, _i, _len;
              table = new Data;
              for (_i = 0, _len = mapping.length; _i < _len; _i++) {
                  id = mapping[_i];
                  metric = this.forGlyph(id);
                  table.writeUInt16(metric.advance);
                  table.writeUInt16(metric.lsb);
              }
              return table.data;
          };*/
    return HmtxTable;
  })(Table);

  var __slice = [].slice;

  var GlyfTable = (function(_super) {
    __extends(GlyfTable, _super);

    function GlyfTable() {
      return GlyfTable.__super__.constructor.apply(this, arguments);
    }
    GlyfTable.prototype.tag = "glyf";
    GlyfTable.prototype.parse = function() {
      return (this.cache = {});
    };
    GlyfTable.prototype.glyphFor = function(id) {
      var data,
        index,
        length,
        loca,
        numberOfContours,
        raw,
        xMax,
        xMin,
        yMax,
        yMin;
      if (id in this.cache) {
        return this.cache[id];
      }
      loca = this.file.loca;
      data = this.file.contents;
      index = loca.indexOf(id);
      length = loca.lengthOf(id);
      if (length === 0) {
        return (this.cache[id] = null);
      }
      data.pos = this.offset + index;
      raw = new Data(data.read(length));
      numberOfContours = raw.readShort();
      xMin = raw.readShort();
      yMin = raw.readShort();
      xMax = raw.readShort();
      yMax = raw.readShort();
      if (numberOfContours === -1) {
        this.cache[id] = new CompoundGlyph(raw, xMin, yMin, xMax, yMax);
      } else {
        this.cache[id] = new SimpleGlyph(
          raw,
          numberOfContours,
          xMin,
          yMin,
          xMax,
          yMax
        );
      }
      return this.cache[id];
    };
    GlyfTable.prototype.encode = function(glyphs, mapping, old2new) {
      var glyph, id, offsets, table, _i, _len;
      table = [];
      offsets = [];
      for (_i = 0, _len = mapping.length; _i < _len; _i++) {
        id = mapping[_i];
        glyph = glyphs[id];
        offsets.push(table.length);
        if (glyph) {
          table = table.concat(glyph.encode(old2new));
        }
      }
      offsets.push(table.length);
      return {
        table: table,
        offsets: offsets
      };
    };
    return GlyfTable;
  })(Table);

  var SimpleGlyph = (function() {
    /**************************************************************************/
    /* function : SimpleGlyph                                                 */
    /* comment : Stores raw, xMin, yMin, xMax, and yMax values for this glyph.*/
    /**************************************************************************/
    function SimpleGlyph(raw, numberOfContours, xMin, yMin, xMax, yMax) {
      this.raw = raw;
      this.numberOfContours = numberOfContours;
      this.xMin = xMin;
      this.yMin = yMin;
      this.xMax = xMax;
      this.yMax = yMax;
      this.compound = false;
    }
    SimpleGlyph.prototype.encode = function() {
      return this.raw.data;
    };
    return SimpleGlyph;
  })();

  var CompoundGlyph = (function() {
    var ARG_1_AND_2_ARE_WORDS,
      MORE_COMPONENTS,
      WE_HAVE_AN_X_AND_Y_SCALE,
      WE_HAVE_A_SCALE,
      WE_HAVE_A_TWO_BY_TWO;
    ARG_1_AND_2_ARE_WORDS = 0x0001;
    WE_HAVE_A_SCALE = 0x0008;
    MORE_COMPONENTS = 0x0020;
    WE_HAVE_AN_X_AND_Y_SCALE = 0x0040;
    WE_HAVE_A_TWO_BY_TWO = 0x0080;

    /********************************************************************************************************************/
    /* function : CompoundGlypg generator                                                                               */
    /* comment : It stores raw, xMin, yMin, xMax, yMax, glyph id, and glyph offset for the corresponding compound glyph.*/
    /********************************************************************************************************************/
    function CompoundGlyph(raw, xMin, yMin, xMax, yMax) {
      var data, flags;
      this.raw = raw;
      this.xMin = xMin;
      this.yMin = yMin;
      this.xMax = xMax;
      this.yMax = yMax;
      this.compound = true;
      this.glyphIDs = [];
      this.glyphOffsets = [];
      data = this.raw;
      while (true) {
        flags = data.readShort();
        this.glyphOffsets.push(data.pos);
        this.glyphIDs.push(data.readUInt16());
        if (!(flags & MORE_COMPONENTS)) {
          break;
        }
        if (flags & ARG_1_AND_2_ARE_WORDS) {
          data.pos += 4;
        } else {
          data.pos += 2;
        }
        if (flags & WE_HAVE_A_TWO_BY_TWO) {
          data.pos += 8;
        } else if (flags & WE_HAVE_AN_X_AND_Y_SCALE) {
          data.pos += 4;
        } else if (flags & WE_HAVE_A_SCALE) {
          data.pos += 2;
        }
      }
    }
    /****************************************************************************************************************/
    /* function : CompoundGlypg encode                                                                              */
    /* comment : After creating a table for the characters you typed, you call directory.encode to encode the table.*/
    /****************************************************************************************************************/
    CompoundGlyph.prototype.encode = function() {
      var i, result, _len, _ref;
      result = new Data(__slice.call(this.raw.data));
      _ref = this.glyphIDs;
      for (i = 0, _len = _ref.length; i < _len; ++i) {
        result.pos = this.glyphOffsets[i];
      }
      return result.data;
    };
    return CompoundGlyph;
  })();

  var LocaTable = (function(_super) {
    __extends(LocaTable, _super);

    function LocaTable() {
      return LocaTable.__super__.constructor.apply(this, arguments);
    }
    LocaTable.prototype.tag = "loca";
    LocaTable.prototype.parse = function(data) {
      var format, i;
      data.pos = this.offset;
      format = this.file.head.indexToLocFormat;
      if (format === 0) {
        return (this.offsets = function() {
          var _ref, _results;
          _results = [];
          for (i = 0, _ref = this.length; i < _ref; i += 2) {
            _results.push(data.readUInt16() * 2);
          }
          return _results;
        }.call(this));
      } else {
        return (this.offsets = function() {
          var _ref, _results;
          _results = [];
          for (i = 0, _ref = this.length; i < _ref; i += 4) {
            _results.push(data.readUInt32());
          }
          return _results;
        }.call(this));
      }
    };
    LocaTable.prototype.indexOf = function(id) {
      return this.offsets[id];
    };
    LocaTable.prototype.lengthOf = function(id) {
      return this.offsets[id + 1] - this.offsets[id];
    };
    LocaTable.prototype.encode = function(offsets, activeGlyphs) {
      var LocaTable = new Uint32Array(this.offsets.length);
      var glyfPtr = 0;
      var listGlyf = 0;
      for (var k = 0; k < LocaTable.length; ++k) {
        LocaTable[k] = glyfPtr;
        if (listGlyf < activeGlyphs.length && activeGlyphs[listGlyf] == k) {
          ++listGlyf;
          LocaTable[k] = glyfPtr;
          var start = this.offsets[k];
          var len = this.offsets[k + 1] - start;
          if (len > 0) {
            glyfPtr += len;
          }
        }
      }
      var newLocaTable = new Array(LocaTable.length * 4);
      for (var j = 0; j < LocaTable.length; ++j) {
        newLocaTable[4 * j + 3] = LocaTable[j] & 0x000000ff;
        newLocaTable[4 * j + 2] = (LocaTable[j] & 0x0000ff00) >> 8;
        newLocaTable[4 * j + 1] = (LocaTable[j] & 0x00ff0000) >> 16;
        newLocaTable[4 * j] = (LocaTable[j] & 0xff000000) >> 24;
      }
      return newLocaTable;
    };
    return LocaTable;
  })(Table);

  /************************************************************************************/
  /* function : invert                                                                */
  /* comment : Change the object's (key: value) to create an object with (value: key).*/
  /************************************************************************************/
  var invert = function(object) {
    var key, ret, val;
    ret = {};
    for (key in object) {
      val = object[key];
      ret[val] = key;
    }
    return ret;
  };

  /*var successorOf = function (input) {
          var added, alphabet, carry, i, index, isUpperCase, last, length, next, result;
          alphabet = 'abcdefghijklmnopqrstuvwxyz';
          length = alphabet.length;
          result = input;
          i = input.length;
          while (i >= 0) {
              last = input.charAt(--i);
              if (isNaN(last)) {
                  index = alphabet.indexOf(last.toLowerCase());
                  if (index === -1) {
                      next = last;
                      carry = true;
                  }
                  else {
                      next = alphabet.charAt((index + 1) % length);
                      isUpperCase = last === last.toUpperCase();
                      if (isUpperCase) {
                          next = next.toUpperCase();
                      }
                      carry = index + 1 >= length;
                      if (carry && i === 0) {
                          added = isUpperCase ? 'A' : 'a';
                          result = added + next + result.slice(1);
                          break;
                      }
                  }
              }
              else {
                  next = +last + 1;
                  carry = next > 9;
                  if (carry) {
                      next = 0;
                  }
                  if (carry && i === 0) {
                      result = '1' + next + result.slice(1);
                      break;
                  }
              }
              result = result.slice(0, i) + next + result.slice(i + 1);
              if (!carry) {
                  break;
              }
          }
          return result;
      };*/

  var Subset = (function() {
    function Subset(font) {
      this.font = font;
      this.subset = {};
      this.unicodes = {};
      this.next = 33;
    }
    /*Subset.prototype.use = function (character) {
              var i, _i, _ref;
              if (typeof character === 'string') {
                  for (i = _i = 0, _ref = character.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
                      this.use(character.charCodeAt(i));
                  }
                  return;
              }
              if (!this.unicodes[character]) {
                  this.subset[this.next] = character;
                  return this.unicodes[character] = this.next++;
              }
          };*/
    /*Subset.prototype.encodeText = function (text) {
              var char, i, string, _i, _ref;
              string = '';
              for (i = _i = 0, _ref = text.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
                  char = this.unicodes[text.charCodeAt(i)];
                  string += String.fromCharCode(char);
              }
              return string;
          };*/
    /***************************************************************/
    /* function : generateCmap                                     */
    /* comment : Returns the unicode cmap for this font.         */
    /***************************************************************/
    Subset.prototype.generateCmap = function() {
      var mapping, roman, unicode, unicodeCmap, _ref;
      unicodeCmap = this.font.cmap.tables[0].codeMap;
      mapping = {};
      _ref = this.subset;
      for (roman in _ref) {
        unicode = _ref[roman];
        mapping[roman] = unicodeCmap[unicode];
      }
      return mapping;
    };
    /*Subset.prototype.glyphIDs = function () {
              var ret, roman, unicode, unicodeCmap, val, _ref;
              unicodeCmap = this.font.cmap.tables[0].codeMap;
              ret = [0];
              _ref = this.subset;
              for (roman in _ref) {
                  unicode = _ref[roman];
                  val = unicodeCmap[unicode];
                  if ((val != null) && __indexOf.call(ret, val) < 0) {
                      ret.push(val);
                  }
              }
              return ret.sort();
          };*/
    /******************************************************************/
    /* function : glyphsFor                                           */
    /* comment : Returns simple glyph objects for the input character.*/
    /******************************************************************/
    Subset.prototype.glyphsFor = function(glyphIDs) {
      var additionalIDs, glyph, glyphs, id, _i, _len, _ref;
      glyphs = {};
      for (_i = 0, _len = glyphIDs.length; _i < _len; _i++) {
        id = glyphIDs[_i];
        glyphs[id] = this.font.glyf.glyphFor(id);
      }
      additionalIDs = [];
      for (id in glyphs) {
        glyph = glyphs[id];
        if (glyph != null ? glyph.compound : void 0) {
          additionalIDs.push.apply(additionalIDs, glyph.glyphIDs);
        }
      }
      if (additionalIDs.length > 0) {
        _ref = this.glyphsFor(additionalIDs);
        for (id in _ref) {
          glyph = _ref[id];
          glyphs[id] = glyph;
        }
      }
      return glyphs;
    };
    /***************************************************************/
    /* function : encode                                           */
    /* comment : Encode various tables for the characters you use. */
    /***************************************************************/
    Subset.prototype.encode = function(glyID, indexToLocFormat) {
      var cmap,
        code,
        glyf,
        glyphs,
        id,
        ids,
        loca,
        new2old,
        newIDs,
        nextGlyphID,
        old2new,
        oldID,
        oldIDs,
        tables,
        _ref;
      cmap = CmapTable.encode(this.generateCmap(), "unicode");
      glyphs = this.glyphsFor(glyID);
      old2new = {
        0: 0
      };
      _ref = cmap.charMap;
      for (code in _ref) {
        ids = _ref[code];
        old2new[ids.old] = ids["new"];
      }
      nextGlyphID = cmap.maxGlyphID;
      for (oldID in glyphs) {
        if (!(oldID in old2new)) {
          old2new[oldID] = nextGlyphID++;
        }
      }
      new2old = invert(old2new);
      newIDs = Object.keys(new2old).sort(function(a, b) {
        return a - b;
      });
      oldIDs = (function() {
        var _i, _len, _results;
        _results = [];
        for (_i = 0, _len = newIDs.length; _i < _len; _i++) {
          id = newIDs[_i];
          _results.push(new2old[id]);
        }
        return _results;
      })();
      glyf = this.font.glyf.encode(glyphs, oldIDs, old2new);
      loca = this.font.loca.encode(glyf.offsets, oldIDs);
      tables = {
        cmap: this.font.cmap.raw(),
        glyf: glyf.table,
        loca: loca,
        hmtx: this.font.hmtx.raw(),
        hhea: this.font.hhea.raw(),
        maxp: this.font.maxp.raw(),
        post: this.font.post.raw(),
        name: this.font.name.raw(),
        head: this.font.head.encode(indexToLocFormat)
      };
      if (this.font.os2.exists) {
        tables["OS/2"] = this.font.os2.raw();
      }
      return this.font.directory.encode(tables);
    };
    return Subset;
  })();

  jsPDF.API.PDFObject = (function() {
    var pad;

    function PDFObject() {}
    pad = function(str, length) {
      return (Array(length + 1).join("0") + str).slice(-length);
    };
    /*****************************************************************************/
    /* function : convert                                                        */
    /* comment :Converts pdf tag's / FontBBox and array values in / W to strings */
    /*****************************************************************************/
    PDFObject.convert = function(object) {
      var e, items, key, out, val;
      if (Array.isArray(object)) {
        items = (function() {
          var _i, _len, _results;
          _results = [];
          for (_i = 0, _len = object.length; _i < _len; _i++) {
            e = object[_i];
            _results.push(PDFObject.convert(e));
          }
          return _results;
        })().join(" ");
        return "[" + items + "]";
      } else if (typeof object === "string") {
        return "/" + object;
      } else if (object != null ? object.isString : void 0) {
        return "(" + object + ")";
      } else if (object instanceof Date) {
        return (
          "(D:" +
          pad(object.getUTCFullYear(), 4) +
          pad(object.getUTCMonth(), 2) +
          pad(object.getUTCDate(), 2) +
          pad(object.getUTCHours(), 2) +
          pad(object.getUTCMinutes(), 2) +
          pad(object.getUTCSeconds(), 2) +
          "Z)"
        );
      } else if ({}.toString.call(object) === "[object Object]") {
        out = ["<<"];
        for (key in object) {
          val = object[key];
          out.push("/" + key + " " + PDFObject.convert(val));
        }
        out.push(">>");
        return out.join("\n");
      } else {
        return "" + object;
      }
    };
    return PDFObject;
  })();

  /**
   * @license
   * Copyright (c) 2012 chick307 <chick307@gmail.com>
   *
   * Licensed under the MIT License.
   * http://opensource.org/licenses/mit-license
   */

  (function(jsPDF, callback) {
    jsPDF.API.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;
          // eslint-disable-next-line no-empty
        } 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; 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;
  });

  exports.AcroForm = AcroForm;
  exports.AcroFormAppearance = AcroFormAppearance;
  exports.AcroFormButton = AcroFormButton;
  exports.AcroFormCheckBox = AcroFormCheckBox;
  exports.AcroFormChoiceField = AcroFormChoiceField;
  exports.AcroFormComboBox = AcroFormComboBox;
  exports.AcroFormEditBox = AcroFormEditBox;
  exports.AcroFormListBox = AcroFormListBox;
  exports.AcroFormPasswordField = AcroFormPasswordField;
  exports.AcroFormPushButton = AcroFormPushButton;
  exports.AcroFormRadioButton = AcroFormRadioButton;
  exports.AcroFormTextField = AcroFormTextField;
  exports.GState = GState;
  exports.ShadingPattern = ShadingPattern;
  exports.TilingPattern = TilingPattern;
  exports.default = jsPDF;
  exports.jsPDF = jsPDF;

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

})));
//# sourceMappingURL=jspdf.umd.js.map

var QRCode;!function(){function t(t){this.mode=u.MODE_8BIT_BYTE,this.data=t,this.parsedData=[];for(var e=0,r=this.data.length;r>e;e++){var o=[],i=this.data.charCodeAt(e);i>65536?(o[0]=240|(1835008&i)>>>18,o[1]=128|(258048&i)>>>12,o[2]=128|(4032&i)>>>6,o[3]=128|63&i):i>2048?(o[0]=224|(61440&i)>>>12,o[1]=128|(4032&i)>>>6,o[2]=128|63&i):i>128?(o[0]=192|(1984&i)>>>6,o[1]=128|63&i):o[0]=i,this.parsedData.push(o)}this.parsedData=Array.prototype.concat.apply([],this.parsedData),this.parsedData.length!=this.data.length&&(this.parsedData.unshift(191),this.parsedData.unshift(187),this.parsedData.unshift(239))}function e(t,e){this.typeNumber=t,this.errorCorrectLevel=e,this.modules=null,this.moduleCount=0,this.dataCache=null,this.dataList=[]}function r(t,e){if(void 0==t.length)throw new Error(t.length+"/"+e);for(var r=0;r<t.length&&0==t[r];)r++;this.num=new Array(t.length-r+e);for(var o=0;o<t.length-r;o++)this.num[o]=t[o+r]}function o(t,e){this.totalCount=t,this.dataCount=e}function i(){this.buffer=[],this.length=0}function n(){return"undefined"!=typeof CanvasRenderingContext2D}function a(){var t=!1,e=navigator.userAgent;if(/android/i.test(e)){t=!0;var r=e.toString().match(/android ([0-9]\.[0-9])/i);r&&r[1]&&(t=parseFloat(r[1]))}return t}function s(t,e){for(var r=1,o=h(t),i=0,n=p.length;n>=i;i++){var a=0;switch(e){case l.L:a=p[i][0];break;case l.M:a=p[i][1];break;case l.Q:a=p[i][2];break;case l.H:a=p[i][3]}if(a>=o)break;r++}if(r>p.length)throw new Error("Too long data");return r}function h(t){var e=encodeURI(t).toString().replace(/\%[0-9a-fA-F]{2}/g,"a");return e.length+(e.length!=t?3:0)}t.prototype={getLength:function(t){return this.parsedData.length},write:function(t){for(var e=0,r=this.parsedData.length;r>e;e++)t.put(this.parsedData[e],8)}},e.prototype={addData:function(e){var r=new t(e);this.dataList.push(r),this.dataCache=null},isDark:function(t,e){if(0>t||this.moduleCount<=t||0>e||this.moduleCount<=e)throw new Error(t+","+e);return this.modules[t][e]},getModuleCount:function(){return this.moduleCount},make:function(){this.makeImpl(!1,this.getBestMaskPattern())},makeImpl:function(t,r){this.moduleCount=4*this.typeNumber+17,this.modules=new Array(this.moduleCount);for(var o=0;o<this.moduleCount;o++){this.modules[o]=new Array(this.moduleCount);for(var i=0;i<this.moduleCount;i++)this.modules[o][i]=null}this.setupPositionProbePattern(0,0),this.setupPositionProbePattern(this.moduleCount-7,0),this.setupPositionProbePattern(0,this.moduleCount-7),this.setupPositionAdjustPattern(),this.setupTimingPattern(),this.setupTypeInfo(t,r),this.typeNumber>=7&&this.setupTypeNumber(t),null==this.dataCache&&(this.dataCache=e.createData(this.typeNumber,this.errorCorrectLevel,this.dataList)),this.mapData(this.dataCache,r)},setupPositionProbePattern:function(t,e){for(var r=-1;7>=r;r++)if(!(-1>=t+r||this.moduleCount<=t+r))for(var o=-1;7>=o;o++)-1>=e+o||this.moduleCount<=e+o||(r>=0&&6>=r&&(0==o||6==o)||o>=0&&6>=o&&(0==r||6==r)||r>=2&&4>=r&&o>=2&&4>=o?this.modules[t+r][e+o]=!0:this.modules[t+r][e+o]=!1)},getBestMaskPattern:function(){for(var t=0,e=0,r=0;8>r;r++){this.makeImpl(!0,r);var o=f.getLostPoint(this);(0==r||t>o)&&(t=o,e=r)}return e},createMovieClip:function(t,e,r){var o=t.createEmptyMovieClip(e,r),i=1;this.make();for(var n=0;n<this.modules.length;n++)for(var a=n*i,s=0;s<this.modules[n].length;s++){var h=s*i,u=this.modules[n][s];u&&(o.beginFill(0,100),o.moveTo(h,a),o.lineTo(h+i,a),o.lineTo(h+i,a+i),o.lineTo(h,a+i),o.endFill())}return o},setupTimingPattern:function(){for(var t=8;t<this.moduleCount-8;t++)null==this.modules[t][6]&&(this.modules[t][6]=t%2==0);for(var e=8;e<this.moduleCount-8;e++)null==this.modules[6][e]&&(this.modules[6][e]=e%2==0)},setupPositionAdjustPattern:function(){for(var t=f.getPatternPosition(this.typeNumber),e=0;e<t.length;e++)for(var r=0;r<t.length;r++){var o=t[e],i=t[r];if(null==this.modules[o][i])for(var n=-2;2>=n;n++)for(var a=-2;2>=a;a++)-2==n||2==n||-2==a||2==a||0==n&&0==a?this.modules[o+n][i+a]=!0:this.modules[o+n][i+a]=!1}},setupTypeNumber:function(t){for(var e=f.getBCHTypeNumber(this.typeNumber),r=0;18>r;r++){var o=!t&&1==(e>>r&1);this.modules[Math.floor(r/3)][r%3+this.moduleCount-8-3]=o}for(var r=0;18>r;r++){var o=!t&&1==(e>>r&1);this.modules[r%3+this.moduleCount-8-3][Math.floor(r/3)]=o}},setupTypeInfo:function(t,e){for(var r=this.errorCorrectLevel<<3|e,o=f.getBCHTypeInfo(r),i=0;15>i;i++){var n=!t&&1==(o>>i&1);6>i?this.modules[i][8]=n:8>i?this.modules[i+1][8]=n:this.modules[this.moduleCount-15+i][8]=n}for(var i=0;15>i;i++){var n=!t&&1==(o>>i&1);8>i?this.modules[8][this.moduleCount-i-1]=n:9>i?this.modules[8][15-i-1+1]=n:this.modules[8][15-i-1]=n}this.modules[this.moduleCount-8][8]=!t},mapData:function(t,e){for(var r=-1,o=this.moduleCount-1,i=7,n=0,a=this.moduleCount-1;a>0;a-=2)for(6==a&&a--;;){for(var s=0;2>s;s++)if(null==this.modules[o][a-s]){var h=!1;n<t.length&&(h=1==(t[n]>>>i&1));var u=f.getMask(e,o,a-s);u&&(h=!h),this.modules[o][a-s]=h,i--,-1==i&&(n++,i=7)}if(o+=r,0>o||this.moduleCount<=o){o-=r,r=-r;break}}}},e.PAD0=236,e.PAD1=17,e.createData=function(t,r,n){for(var a=o.getRSBlocks(t,r),s=new i,h=0;h<n.length;h++){var u=n[h];s.put(u.mode,4),s.put(u.getLength(),f.getLengthInBits(u.mode,t)),u.write(s)}for(var l=0,h=0;h<a.length;h++)l+=a[h].dataCount;if(s.getLengthInBits()>8*l)throw new Error("code length overflow. ("+s.getLengthInBits()+">"+8*l+")");for(s.getLengthInBits()+4<=8*l&&s.put(0,4);s.getLengthInBits()%8!=0;)s.putBit(!1);for(;;){if(s.getLengthInBits()>=8*l)break;if(s.put(e.PAD0,8),s.getLengthInBits()>=8*l)break;s.put(e.PAD1,8)}return e.createBytes(s,a)},e.createBytes=function(t,e){for(var o=0,i=0,n=0,a=new Array(e.length),s=new Array(e.length),h=0;h<e.length;h++){var u=e[h].dataCount,l=e[h].totalCount-u;i=Math.max(i,u),n=Math.max(n,l),a[h]=new Array(u);for(var g=0;g<a[h].length;g++)a[h][g]=255&t.buffer[g+o];o+=u;var d=f.getErrorCorrectPolynomial(l),c=new r(a[h],d.getLength()-1),p=c.mod(d);s[h]=new Array(d.getLength()-1);for(var g=0;g<s[h].length;g++){var m=g+p.getLength()-s[h].length;s[h][g]=m>=0?p.get(m):0}}for(var v=0,g=0;g<e.length;g++)v+=e[g].totalCount;for(var _=new Array(v),C=0,g=0;i>g;g++)for(var h=0;h<e.length;h++)g<a[h].length&&(_[C++]=a[h][g]);for(var g=0;n>g;g++)for(var h=0;h<e.length;h++)g<s[h].length&&(_[C++]=s[h][g]);return _};for(var u={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},l={L:1,M:0,Q:3,H:2},g={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},f={PATTERN_POSITION_TABLE:[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],G15:1335,G18:7973,G15_MASK:21522,getBCHTypeInfo:function(t){for(var e=t<<10;f.getBCHDigit(e)-f.getBCHDigit(f.G15)>=0;)e^=f.G15<<f.getBCHDigit(e)-f.getBCHDigit(f.G15);return(t<<10|e)^f.G15_MASK},getBCHTypeNumber:function(t){for(var e=t<<12;f.getBCHDigit(e)-f.getBCHDigit(f.G18)>=0;)e^=f.G18<<f.getBCHDigit(e)-f.getBCHDigit(f.G18);return t<<12|e},getBCHDigit:function(t){for(var e=0;0!=t;)e++,t>>>=1;return e},getPatternPosition:function(t){return f.PATTERN_POSITION_TABLE[t-1]},getMask:function(t,e,r){switch(t){case g.PATTERN000:return(e+r)%2==0;case g.PATTERN001:return e%2==0;case g.PATTERN010:return r%3==0;case g.PATTERN011:return(e+r)%3==0;case g.PATTERN100:return(Math.floor(e/2)+Math.floor(r/3))%2==0;case g.PATTERN101:return e*r%2+e*r%3==0;case g.PATTERN110:return(e*r%2+e*r%3)%2==0;case g.PATTERN111:return(e*r%3+(e+r)%2)%2==0;default:throw new Error("bad maskPattern:"+t)}},getErrorCorrectPolynomial:function(t){for(var e=new r([1],0),o=0;t>o;o++)e=e.multiply(new r([1,d.gexp(o)],0));return e},getLengthInBits:function(t,e){if(e>=1&&10>e)switch(t){case u.MODE_NUMBER:return 10;case u.MODE_ALPHA_NUM:return 9;case u.MODE_8BIT_BYTE:return 8;case u.MODE_KANJI:return 8;default:throw new Error("mode:"+t)}else if(27>e)switch(t){case u.MODE_NUMBER:return 12;case u.MODE_ALPHA_NUM:return 11;case u.MODE_8BIT_BYTE:return 16;case u.MODE_KANJI:return 10;default:throw new Error("mode:"+t)}else{if(!(41>e))throw new Error("type:"+e);switch(t){case u.MODE_NUMBER:return 14;case u.MODE_ALPHA_NUM:return 13;case u.MODE_8BIT_BYTE:return 16;case u.MODE_KANJI:return 12;default:throw new Error("mode:"+t)}}},getLostPoint:function(t){for(var e=t.getModuleCount(),r=0,o=0;e>o;o++)for(var i=0;e>i;i++){for(var n=0,a=t.isDark(o,i),s=-1;1>=s;s++)if(!(0>o+s||o+s>=e))for(var h=-1;1>=h;h++)0>i+h||i+h>=e||(0!=s||0!=h)&&a==t.isDark(o+s,i+h)&&n++;n>5&&(r+=3+n-5)}for(var o=0;e-1>o;o++)for(var i=0;e-1>i;i++){var u=0;t.isDark(o,i)&&u++,t.isDark(o+1,i)&&u++,t.isDark(o,i+1)&&u++,t.isDark(o+1,i+1)&&u++,(0==u||4==u)&&(r+=3)}for(var o=0;e>o;o++)for(var i=0;e-6>i;i++)t.isDark(o,i)&&!t.isDark(o,i+1)&&t.isDark(o,i+2)&&t.isDark(o,i+3)&&t.isDark(o,i+4)&&!t.isDark(o,i+5)&&t.isDark(o,i+6)&&(r+=40);for(var i=0;e>i;i++)for(var o=0;e-6>o;o++)t.isDark(o,i)&&!t.isDark(o+1,i)&&t.isDark(o+2,i)&&t.isDark(o+3,i)&&t.isDark(o+4,i)&&!t.isDark(o+5,i)&&t.isDark(o+6,i)&&(r+=40);for(var l=0,i=0;e>i;i++)for(var o=0;e>o;o++)t.isDark(o,i)&&l++;var g=Math.abs(100*l/e/e-50)/5;return r+=10*g}},d={glog:function(t){if(1>t)throw new Error("glog("+t+")");return d.LOG_TABLE[t]},gexp:function(t){for(;0>t;)t+=255;for(;t>=256;)t-=255;return d.EXP_TABLE[t]},EXP_TABLE:new Array(256),LOG_TABLE:new Array(256)},c=0;8>c;c++)d.EXP_TABLE[c]=1<<c;for(var c=8;256>c;c++)d.EXP_TABLE[c]=d.EXP_TABLE[c-4]^d.EXP_TABLE[c-5]^d.EXP_TABLE[c-6]^d.EXP_TABLE[c-8];for(var c=0;255>c;c++)d.LOG_TABLE[d.EXP_TABLE[c]]=c;r.prototype={get:function(t){return this.num[t]},getLength:function(){return this.num.length},multiply:function(t){for(var e=new Array(this.getLength()+t.getLength()-1),o=0;o<this.getLength();o++)for(var i=0;i<t.getLength();i++)e[o+i]^=d.gexp(d.glog(this.get(o))+d.glog(t.get(i)));return new r(e,0)},mod:function(t){if(this.getLength()-t.getLength()<0)return this;for(var e=d.glog(this.get(0))-d.glog(t.get(0)),o=new Array(this.getLength()),i=0;i<this.getLength();i++)o[i]=this.get(i);for(var i=0;i<t.getLength();i++)o[i]^=d.gexp(d.glog(t.get(i))+e);return new r(o,0).mod(t)}},o.RS_BLOCK_TABLE=[[1,26,19],[1,26,16],[1,26,13],[1,26,9],[1,44,34],[1,44,28],[1,44,22],[1,44,16],[1,70,55],[1,70,44],[2,35,17],[2,35,13],[1,100,80],[2,50,32],[2,50,24],[4,25,9],[1,134,108],[2,67,43],[2,33,15,2,34,16],[2,33,11,2,34,12],[2,86,68],[4,43,27],[4,43,19],[4,43,15],[2,98,78],[4,49,31],[2,32,14,4,33,15],[4,39,13,1,40,14],[2,121,97],[2,60,38,2,61,39],[4,40,18,2,41,19],[4,40,14,2,41,15],[2,146,116],[3,58,36,2,59,37],[4,36,16,4,37,17],[4,36,12,4,37,13],[2,86,68,2,87,69],[4,69,43,1,70,44],[6,43,19,2,44,20],[6,43,15,2,44,16],[4,101,81],[1,80,50,4,81,51],[4,50,22,4,51,23],[3,36,12,8,37,13],[2,116,92,2,117,93],[6,58,36,2,59,37],[4,46,20,6,47,21],[7,42,14,4,43,15],[4,133,107],[8,59,37,1,60,38],[8,44,20,4,45,21],[12,33,11,4,34,12],[3,145,115,1,146,116],[4,64,40,5,65,41],[11,36,16,5,37,17],[11,36,12,5,37,13],[5,109,87,1,110,88],[5,65,41,5,66,42],[5,54,24,7,55,25],[11,36,12],[5,122,98,1,123,99],[7,73,45,3,74,46],[15,43,19,2,44,20],[3,45,15,13,46,16],[1,135,107,5,136,108],[10,74,46,1,75,47],[1,50,22,15,51,23],[2,42,14,17,43,15],[5,150,120,1,151,121],[9,69,43,4,70,44],[17,50,22,1,51,23],[2,42,14,19,43,15],[3,141,113,4,142,114],[3,70,44,11,71,45],[17,47,21,4,48,22],[9,39,13,16,40,14],[3,135,107,5,136,108],[3,67,41,13,68,42],[15,54,24,5,55,25],[15,43,15,10,44,16],[4,144,116,4,145,117],[17,68,42],[17,50,22,6,51,23],[19,46,16,6,47,17],[2,139,111,7,140,112],[17,74,46],[7,54,24,16,55,25],[34,37,13],[4,151,121,5,152,122],[4,75,47,14,76,48],[11,54,24,14,55,25],[16,45,15,14,46,16],[6,147,117,4,148,118],[6,73,45,14,74,46],[11,54,24,16,55,25],[30,46,16,2,47,17],[8,132,106,4,133,107],[8,75,47,13,76,48],[7,54,24,22,55,25],[22,45,15,13,46,16],[10,142,114,2,143,115],[19,74,46,4,75,47],[28,50,22,6,51,23],[33,46,16,4,47,17],[8,152,122,4,153,123],[22,73,45,3,74,46],[8,53,23,26,54,24],[12,45,15,28,46,16],[3,147,117,10,148,118],[3,73,45,23,74,46],[4,54,24,31,55,25],[11,45,15,31,46,16],[7,146,116,7,147,117],[21,73,45,7,74,46],[1,53,23,37,54,24],[19,45,15,26,46,16],[5,145,115,10,146,116],[19,75,47,10,76,48],[15,54,24,25,55,25],[23,45,15,25,46,16],[13,145,115,3,146,116],[2,74,46,29,75,47],[42,54,24,1,55,25],[23,45,15,28,46,16],[17,145,115],[10,74,46,23,75,47],[10,54,24,35,55,25],[19,45,15,35,46,16],[17,145,115,1,146,116],[14,74,46,21,75,47],[29,54,24,19,55,25],[11,45,15,46,46,16],[13,145,115,6,146,116],[14,74,46,23,75,47],[44,54,24,7,55,25],[59,46,16,1,47,17],[12,151,121,7,152,122],[12,75,47,26,76,48],[39,54,24,14,55,25],[22,45,15,41,46,16],[6,151,121,14,152,122],[6,75,47,34,76,48],[46,54,24,10,55,25],[2,45,15,64,46,16],[17,152,122,4,153,123],[29,74,46,14,75,47],[49,54,24,10,55,25],[24,45,15,46,46,16],[4,152,122,18,153,123],[13,74,46,32,75,47],[48,54,24,14,55,25],[42,45,15,32,46,16],[20,147,117,4,148,118],[40,75,47,7,76,48],[43,54,24,22,55,25],[10,45,15,67,46,16],[19,148,118,6,149,119],[18,75,47,31,76,48],[34,54,24,34,55,25],[20,45,15,61,46,16]],o.getRSBlocks=function(t,e){var r=o.getRsBlockTable(t,e);if(void 0==r)throw new Error("bad rs block @ typeNumber:"+t+"/errorCorrectLevel:"+e);for(var i=r.length/3,n=[],a=0;i>a;a++)for(var s=r[3*a+0],h=r[3*a+1],u=r[3*a+2],l=0;s>l;l++)n.push(new o(h,u));return n},o.getRsBlockTable=function(t,e){switch(e){case l.L:return o.RS_BLOCK_TABLE[4*(t-1)+0];case l.M:return o.RS_BLOCK_TABLE[4*(t-1)+1];case l.Q:return o.RS_BLOCK_TABLE[4*(t-1)+2];case l.H:return o.RS_BLOCK_TABLE[4*(t-1)+3];default:return}},i.prototype={get:function(t){var e=Math.floor(t/8);return 1==(this.buffer[e]>>>7-t%8&1)},put:function(t,e){for(var r=0;e>r;r++)this.putBit(1==(t>>>e-r-1&1))},getLengthInBits:function(){return this.length},putBit:function(t){var e=Math.floor(this.length/8);this.buffer.length<=e&&this.buffer.push(0),t&&(this.buffer[e]|=128>>>this.length%8),this.length++}};var p=[[17,14,11,7],[32,26,20,14],[53,42,32,24],[78,62,46,34],[106,84,60,44],[134,106,74,58],[154,122,86,64],[192,152,108,84],[230,180,130,98],[271,213,151,119],[321,251,177,137],[367,287,203,155],[425,331,241,177],[458,362,258,194],[520,412,292,220],[586,450,322,250],[644,504,364,280],[718,560,394,310],[792,624,442,338],[858,666,482,382],[929,711,509,403],[1003,779,565,439],[1091,857,611,461],[1171,911,661,511],[1273,997,715,535],[1367,1059,751,593],[1465,1125,805,625],[1528,1190,868,658],[1628,1264,908,698],[1732,1370,982,742],[1840,1452,1030,790],[1952,1538,1112,842],[2068,1628,1168,898],[2188,1722,1228,958],[2303,1809,1283,983],[2431,1911,1351,1051],[2563,1989,1423,1093],[2699,2099,1499,1139],[2809,2213,1579,1219],[2953,2331,1663,1273]],m=function(){var t=function(t,e){this._el=t,this._htOption=e};return t.prototype.draw=function(t){function e(t,e){var r=document.createElementNS("http://www.w3.org/2000/svg",t);for(var o in e)e.hasOwnProperty(o)&&r.setAttribute(o,e[o]);return r}var r=this._htOption,o=this._el,i=t.getModuleCount(),n=Math.floor(r.width/i),a=Math.floor(r.height/i);this.clear();var s=e("svg",{viewBox:"0 0 "+String(i)+" "+String(i),width:"100%",height:"100%",fill:r.colorLight});s.setAttributeNS("http://www.w3.org/2000/xmlns/","xmlns:xlink","http://www.w3.org/1999/xlink"),o.appendChild(s),s.appendChild(e("rect",{fill:r.colorLight,width:"100%",height:"100%"})),s.appendChild(e("rect",{fill:r.colorDark,width:"1",height:"1",id:"template"}));for(var h=0;i>h;h++)for(var u=0;i>u;u++)if(t.isDark(h,u)){var l=e("use",{x:String(u),y:String(h)});l.setAttributeNS("http://www.w3.org/1999/xlink","href","#template"),s.appendChild(l)}},t.prototype.clear=function(){for(;this._el.hasChildNodes();)this._el.removeChild(this._el.lastChild)},t}(),v="svg"===document.documentElement.tagName.toLowerCase(),_=v?m:n()?function(){function t(){this._elImage.src=this._elCanvas.toDataURL("image/png"),this._elImage.style.display="block",this._elCanvas.style.display="none"}function e(t,e){var r=this;if(r._fFail=e,r._fSuccess=t,null===r._bSupportDataURI){var o=document.createElement("img"),i=function(){r._bSupportDataURI=!1,r._fFail&&r._fFail.call(r)},n=function(){r._bSupportDataURI=!0,r._fSuccess&&r._fSuccess.call(r)};return o.onabort=i,o.onerror=i,o.onload=n,void(o.src="data:image/gif;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==")}r._bSupportDataURI===!0&&r._fSuccess?r._fSuccess.call(r):r._bSupportDataURI===!1&&r._fFail&&r._fFail.call(r)}if(this._android&&this._android<=2.1){var r=1/window.devicePixelRatio,o=CanvasRenderingContext2D.prototype.drawImage;CanvasRenderingContext2D.prototype.drawImage=function(t,e,i,n,a,s,h,u,l){if("nodeName"in t&&/img/i.test(t.nodeName))for(var g=arguments.length-1;g>=1;g--)arguments[g]=arguments[g]*r;else"undefined"==typeof u&&(arguments[1]*=r,arguments[2]*=r,arguments[3]*=r,arguments[4]*=r);o.apply(this,arguments)}}var i=function(t,e){this._bIsPainted=!1,this._android=a(),this._htOption=e,this._elCanvas=document.createElement("canvas"),this._elCanvas.width=e.width,this._elCanvas.height=e.height,t.appendChild(this._elCanvas),this._el=t,this._oContext=this._elCanvas.getContext("2d"),this._bIsPainted=!1,this._elImage=document.createElement("img"),this._elImage.alt="Scan me!",this._elImage.style.display="none",this._el.appendChild(this._elImage),this._bSupportDataURI=null};return i.prototype.draw=function(t){var e=this._elImage,r=this._oContext,o=this._htOption,i=t.getModuleCount(),n=o.width/i,a=o.height/i,s=Math.round(n),h=Math.round(a);e.style.display="none",this.clear();for(var u=0;i>u;u++)for(var l=0;i>l;l++){var g=t.isDark(u,l),f=l*n,d=u*a;r.strokeStyle=g?o.colorDark:o.colorLight,r.lineWidth=1,r.fillStyle=g?o.colorDark:o.colorLight,r.fillRect(f,d,n,a),r.strokeRect(Math.floor(f)+.5,Math.floor(d)+.5,s,h),r.strokeRect(Math.ceil(f)-.5,Math.ceil(d)-.5,s,h)}this._bIsPainted=!0},i.prototype.makeImage=function(){this._bIsPainted&&e.call(this,t)},i.prototype.isPainted=function(){return this._bIsPainted},i.prototype.clear=function(){this._oContext.clearRect(0,0,this._elCanvas.width,this._elCanvas.height),this._bIsPainted=!1},i.prototype.round=function(t){return t?Math.floor(1e3*t)/1e3:t},i}():function(){var t=function(t,e){this._el=t,this._htOption=e};return t.prototype.draw=function(t){for(var e=this._htOption,r=this._el,o=t.getModuleCount(),i=Math.floor(e.width/o),n=Math.floor(e.height/o),a=['<table style="border:0;border-collapse:collapse;">'],s=0;o>s;s++){a.push("<tr>");for(var h=0;o>h;h++)a.push('<td style="border:0;border-collapse:collapse;padding:0;margin:0;width:'+i+"px;height:"+n+"px;background-color:"+(t.isDark(s,h)?e.colorDark:e.colorLight)+';"></td>');a.push("</tr>")}a.push("</table>"),r.innerHTML=a.join("");var u=r.childNodes[0],l=(e.width-u.offsetWidth)/2,g=(e.height-u.offsetHeight)/2;l>0&&g>0&&(u.style.margin=g+"px "+l+"px")},t.prototype.clear=function(){this._el.innerHTML=""},t}();QRCode=function(t,e){if(this._htOption={width:256,height:256,typeNumber:4,colorDark:"#000000",colorLight:"#ffffff",correctLevel:l.H},"string"==typeof e&&(e={text:e}),e)for(var r in e)this._htOption[r]=e[r];"string"==typeof t&&(t=document.getElementById(t)),this._htOption.useSVG&&(_=m),this._android=a(),this._el=t,this._oQRCode=null,this._oDrawing=new _(this._el,this._htOption),this._htOption.text&&this.makeCode(this._htOption.text)},QRCode.prototype.makeCode=function(t){this._oQRCode=new e(s(t,this._htOption.correctLevel),this._htOption.correctLevel),this._oQRCode.addData(t),this._oQRCode.make(),this._el.title=t,this._oDrawing.draw(this._oQRCode),this.makeImage()},QRCode.prototype.makeImage=function(){"function"==typeof this._oDrawing.makeImage&&(!this._android||this._android>=3)&&this._oDrawing.makeImage()},QRCode.prototype.clear=function(){this._oDrawing.clear()},QRCode.CorrectLevel=l}();

/*! rangeslider.js - v2.3.2 | (c) 2018 @andreruffert | MIT license | https://github.com/andreruffert/rangeslider.js */
(function(factory) {
    'use strict';

    if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define(['jquery'], factory);
    } else if (typeof exports === 'object') {
        // CommonJS
        module.exports = factory(require('jquery'));
    } else {
        // Browser globals
        factory(jQuery);
    }
}(function($) {
    'use strict';

    // Polyfill Number.isNaN(value)
    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN
    Number.isNaN = Number.isNaN || function(value) {
        return typeof value === 'number' && value !== value;
    };

    /**
     * Range feature detection
     * @return {Boolean}
     */
    function supportsRange() {
        var input = document.createElement('input');
        input.setAttribute('type', 'range');
        return input.type !== 'text';
    }

    var pluginName = 'rangeslider',
        pluginIdentifier = 0,
        hasInputRangeSupport = supportsRange(),
        defaults = {
            polyfill: true,
            orientation: 'horizontal',
            rangeClass: 'rangeslider',
            disabledClass: 'rangeslider--disabled',
            activeClass: 'rangeslider--active',
            horizontalClass: 'rangeslider--horizontal',
            verticalClass: 'rangeslider--vertical',
            fillClass: 'rangeslider__fill',
            handleClass: 'rangeslider__handle',
            startEvent: ['mousedown', 'touchstart', 'pointerdown'],
            moveEvent: ['mousemove', 'touchmove', 'pointermove'],
            endEvent: ['mouseup', 'touchend', 'pointerup']
        },
        constants = {
            orientation: {
                horizontal: {
                    dimension: 'width',
                    direction: 'left',
                    directionStyle: 'left',
                    coordinate: 'x'
                },
                vertical: {
                    dimension: 'height',
                    direction: 'top',
                    directionStyle: 'bottom',
                    coordinate: 'y'
                }
            }
        };

    /**
     * Delays a function for the given number of milliseconds, and then calls
     * it with the arguments supplied.
     *
     * @param  {Function} fn   [description]
     * @param  {Number}   wait [description]
     * @return {Function}
     */
    function delay(fn, wait) {
        var args = Array.prototype.slice.call(arguments, 2);
        return setTimeout(function(){ return fn.apply(null, args); }, wait);
    }

    /**
     * Returns a debounced function that will make sure the given
     * function is not triggered too much.
     *
     * @param  {Function} fn Function to debounce.
     * @param  {Number}   debounceDuration OPTIONAL. The amount of time in milliseconds for which we will debounce the function. (defaults to 100ms)
     * @return {Function}
     */
    function debounce(fn, debounceDuration) {
        debounceDuration = debounceDuration || 100;
        return function() {
            if (!fn.debouncing) {
                var args = Array.prototype.slice.apply(arguments);
                fn.lastReturnVal = fn.apply(window, args);
                fn.debouncing = true;
            }
            clearTimeout(fn.debounceTimeout);
            fn.debounceTimeout = setTimeout(function(){
                fn.debouncing = false;
            }, debounceDuration);
            return fn.lastReturnVal;
        };
    }

    /**
     * Check if a `element` is visible in the DOM
     *
     * @param  {Element}  element
     * @return {Boolean}
     */
    function isHidden(element) {
        return (
            element && (
                element.offsetWidth === 0 ||
                element.offsetHeight === 0 ||
                // Also Consider native `<details>` elements.
                element.open === false
            )
        );
    }

    /**
     * Get hidden parentNodes of an `element`
     *
     * @param  {Element} element
     * @return {[type]}
     */
    function getHiddenParentNodes(element) {
        var parents = [],
            node    = element.parentNode;

        while (isHidden(node)) {
            parents.push(node);
            node = node.parentNode;
        }
        return parents;
    }

    /**
     * Returns dimensions for an element even if it is not visible in the DOM.
     *
     * @param  {Element} element
     * @param  {String}  key     (e.g. offsetWidth ?)
     * @return {Number}
     */
    function getDimension(element, key) {
        var hiddenParentNodes       = getHiddenParentNodes(element),
            hiddenParentNodesLength = hiddenParentNodes.length,
            inlineStyle             = [],
            dimension               = element[key];

        // Used for native `<details>` elements
        function toggleOpenProperty(element) {
            if (typeof element.open !== 'undefined') {
                element.open = (element.open) ? false : true;
            }
        }

        if (hiddenParentNodesLength) {
            for (var i = 0; i < hiddenParentNodesLength; i++) {

                // Cache style attribute to restore it later.
                inlineStyle[i] = hiddenParentNodes[i].style.cssText;

                // visually hide
                if (hiddenParentNodes[i].style.setProperty) {
                    hiddenParentNodes[i].style.setProperty('display', 'block', 'important');
                } else {
                    hiddenParentNodes[i].style.cssText += ';display: block !important';
                }
                hiddenParentNodes[i].style.height = '0';
                hiddenParentNodes[i].style.overflow = 'hidden';
                hiddenParentNodes[i].style.visibility = 'hidden';
                toggleOpenProperty(hiddenParentNodes[i]);
            }

            // Update dimension
            dimension = element[key];

            for (var j = 0; j < hiddenParentNodesLength; j++) {

                // Restore the style attribute
                hiddenParentNodes[j].style.cssText = inlineStyle[j];
                toggleOpenProperty(hiddenParentNodes[j]);
            }
        }
        return dimension;
    }

    /**
     * Returns the parsed float or the default if it failed.
     *
     * @param  {String}  str
     * @param  {Number}  defaultValue
     * @return {Number}
     */
    function tryParseFloat(str, defaultValue) {
        var value = parseFloat(str);
        return Number.isNaN(value) ? defaultValue : value;
    }

    /**
     * Capitalize the first letter of string
     *
     * @param  {String} str
     * @return {String}
     */
    function ucfirst(str) {
        return str.charAt(0).toUpperCase() + str.substr(1);
    }

    /**
     * Plugin
     * @param {String} element
     * @param {Object} options
     */
    function Plugin(element, options) {
        this.$window            = $(window);
        this.$document          = $(document);
        this.$element           = $(element);
        this.options            = $.extend( {}, defaults, options );
        this.polyfill           = this.options.polyfill;
        this.orientation        = this.$element[0].getAttribute('data-orientation') || this.options.orientation;
        this.onInit             = this.options.onInit;
        this.onSlide            = this.options.onSlide;
        this.onSlideEnd         = this.options.onSlideEnd;
        this.DIMENSION          = constants.orientation[this.orientation].dimension;
        this.DIRECTION          = constants.orientation[this.orientation].direction;
        this.DIRECTION_STYLE    = constants.orientation[this.orientation].directionStyle;
        this.COORDINATE         = constants.orientation[this.orientation].coordinate;

        // Plugin should only be used as a polyfill
        if (this.polyfill) {
            // Input range support?
            if (hasInputRangeSupport) { return false; }
        }

        this.identifier = 'js-' + pluginName + '-' +(pluginIdentifier++);
        this.startEvent = this.options.startEvent.join('.' + this.identifier + ' ') + '.' + this.identifier;
        this.moveEvent  = this.options.moveEvent.join('.' + this.identifier + ' ') + '.' + this.identifier;
        this.endEvent   = this.options.endEvent.join('.' + this.identifier + ' ') + '.' + this.identifier;
        this.toFixed    = (this.step + '').replace('.', '').length - 1;
        this.$fill      = $('<div class="' + this.options.fillClass + '" />');
        this.$handle    = $('<div class="' + this.options.handleClass + '" />');
        this.$range     = $('<div class="' + this.options.rangeClass + ' ' + this.options[this.orientation + 'Class'] + '" id="' + this.identifier + '" />').insertAfter(this.$element).prepend(this.$fill, this.$handle);

        // visually hide the input
        this.$element.css({
            'position': 'absolute',
            'width': '1px',
            'height': '1px',
            'overflow': 'hidden',
            'opacity': '0'
        });

        // Store context
        this.handleDown = $.proxy(this.handleDown, this);
        this.handleMove = $.proxy(this.handleMove, this);
        this.handleEnd  = $.proxy(this.handleEnd, this);

        this.init();

        // Attach Events
        var _this = this;
        this.$window.on('resize.' + this.identifier, debounce(function() {
            // Simulate resizeEnd event.
            delay(function() { _this.update(false, false); }, 300);
        }, 20));

        this.$document.on(this.startEvent, '#' + this.identifier + ':not(.' + this.options.disabledClass + ')', this.handleDown);

        // Listen to programmatic value changes
        this.$element.on('change.' + this.identifier, function(e, data) {
            if (data && data.origin === _this.identifier) {
                return;
            }

            var value = e.target.value,
                pos = _this.getPositionFromValue(value);
            _this.setPosition(pos);
        });
    }

    Plugin.prototype.init = function() {
        this.update(true, false);

        if (this.onInit && typeof this.onInit === 'function') {
            this.onInit();
        }
    };

    Plugin.prototype.update = function(updateAttributes, triggerSlide) {
        updateAttributes = updateAttributes || false;

        if (updateAttributes) {
            this.min    = tryParseFloat(this.$element[0].getAttribute('min'), 0);
            this.max    = tryParseFloat(this.$element[0].getAttribute('max'), 100);
            this.value  = tryParseFloat(this.$element[0].value, Math.round(this.min + (this.max-this.min)/2));
            this.step   = tryParseFloat(this.$element[0].getAttribute('step'), 1);
        }

        this.handleDimension    = getDimension(this.$handle[0], 'offset' + ucfirst(this.DIMENSION));
        this.rangeDimension     = getDimension(this.$range[0], 'offset' + ucfirst(this.DIMENSION));
        this.maxHandlePos       = this.rangeDimension - this.handleDimension;
        this.grabPos            = this.handleDimension / 2;
        this.position           = this.getPositionFromValue(this.value);

        // Consider disabled state
        if (this.$element[0].disabled) {
            this.$range.addClass(this.options.disabledClass);
        } else {
            this.$range.removeClass(this.options.disabledClass);
        }

        this.setPosition(this.position, triggerSlide);
    };

    Plugin.prototype.handleDown = function(e) {
        e.preventDefault();

        // Only respond to mouse main button clicks (usually the left button)
        if (e.button && e.button !== 0) { return; }

        this.$document.on(this.moveEvent, this.handleMove);
        this.$document.on(this.endEvent, this.handleEnd);

        // add active class because Firefox is ignoring
        // the handle:active pseudo selector because of `e.preventDefault();`
        this.$range.addClass(this.options.activeClass);

        // If we click on the handle don't set the new position
        if ((' ' + e.target.className + ' ').replace(/[\n\t]/g, ' ').indexOf(this.options.handleClass) > -1) {
            return;
        }

        var pos         = this.getRelativePosition(e),
            rangePos    = this.$range[0].getBoundingClientRect()[this.DIRECTION],
            handlePos   = this.getPositionFromNode(this.$handle[0]) - rangePos,
            setPos      = (this.orientation === 'vertical') ? (this.maxHandlePos - (pos - this.grabPos)) : (pos - this.grabPos);

        this.setPosition(setPos);

        if (pos >= handlePos && pos < handlePos + this.handleDimension) {
            this.grabPos = pos - handlePos;
        }
    };

    Plugin.prototype.handleMove = function(e) {
        e.preventDefault();
        var pos = this.getRelativePosition(e);
        var setPos = (this.orientation === 'vertical') ? (this.maxHandlePos - (pos - this.grabPos)) : (pos - this.grabPos);
        this.setPosition(setPos);
    };

    Plugin.prototype.handleEnd = function(e) {
        e.preventDefault();
        this.$document.off(this.moveEvent, this.handleMove);
        this.$document.off(this.endEvent, this.handleEnd);

        this.$range.removeClass(this.options.activeClass);

        // Ok we're done fire the change event
        this.$element.trigger('change', { origin: this.identifier });

        if (this.onSlideEnd && typeof this.onSlideEnd === 'function') {
            this.onSlideEnd(this.position, this.value);
        }
    };

    Plugin.prototype.cap = function(pos, min, max) {
        if (pos < min) { return min; }
        if (pos > max) { return max; }
        return pos;
    };

    Plugin.prototype.setPosition = function(pos, triggerSlide) {
        var value, newPos;

        if (triggerSlide === undefined) {
            triggerSlide = true;
        }

        // Snapping steps
        value = this.getValueFromPosition(this.cap(pos, 0, this.maxHandlePos));
        newPos = this.getPositionFromValue(value);

        // Update ui
        this.$fill[0].style[this.DIMENSION] = (newPos + this.grabPos) + 'px';
        this.$handle[0].style[this.DIRECTION_STYLE] = newPos + 'px';
        this.setValue(value);

        // Update globals
        this.position = newPos;
        this.value = value;

        if (triggerSlide && this.onSlide && typeof this.onSlide === 'function') {
            this.onSlide(newPos, value);
        }
    };

    // Returns element position relative to the parent
    Plugin.prototype.getPositionFromNode = function(node) {
        var i = 0;
        while (node !== null) {
            i += node.offsetLeft;
            node = node.offsetParent;
        }
        return i;
    };

    Plugin.prototype.getRelativePosition = function(e) {
        // Get the offset DIRECTION relative to the viewport
        var ucCoordinate = ucfirst(this.COORDINATE),
            rangePos = this.$range[0].getBoundingClientRect()[this.DIRECTION],
            pageCoordinate = 0;

        if (typeof e.originalEvent['client' + ucCoordinate] !== 'undefined') {
            pageCoordinate = e.originalEvent['client' + ucCoordinate];
        }
        else if (
          e.originalEvent.touches &&
          e.originalEvent.touches[0] &&
          typeof e.originalEvent.touches[0]['client' + ucCoordinate] !== 'undefined'
        ) {
            pageCoordinate = e.originalEvent.touches[0]['client' + ucCoordinate];
        }
        else if(e.currentPoint && typeof e.currentPoint[this.COORDINATE] !== 'undefined') {
            pageCoordinate = e.currentPoint[this.COORDINATE];
        }

        return pageCoordinate - rangePos;
    };

    Plugin.prototype.getPositionFromValue = function(value) {
        var percentage, pos;
        percentage = (value - this.min)/(this.max - this.min);
        pos = (!Number.isNaN(percentage)) ? percentage * this.maxHandlePos : 0;
        return pos;
    };

    Plugin.prototype.getValueFromPosition = function(pos) {
        var percentage, value;
        percentage = ((pos) / (this.maxHandlePos || 1));
        value = this.step * Math.round(percentage * (this.max - this.min) / this.step) + this.min;
        return Number((value).toFixed(this.toFixed));
    };

    Plugin.prototype.setValue = function(value) {
        if (value === this.value && this.$element[0].value !== '') {
            return;
        }

        // Set the new value and fire the `input` event
        this.$element
            .val(value)
            .trigger('input', { origin: this.identifier });
    };

    Plugin.prototype.destroy = function() {
        this.$document.off('.' + this.identifier);
        this.$window.off('.' + this.identifier);

        this.$element
            .off('.' + this.identifier)
            .removeAttr('style')
            .removeData('plugin_' + pluginName);

        // Remove the generated markup
        if (this.$range && this.$range.length) {
            this.$range[0].parentNode.removeChild(this.$range[0]);
        }
    };

    // A really lightweight plugin wrapper around the constructor,
    // preventing against multiple instantiations
    $.fn[pluginName] = function(options) {
        var args = Array.prototype.slice.call(arguments, 1);

        return this.each(function() {
            var $this = $(this),
                data  = $this.data('plugin_' + pluginName);

            // Create a new instance.
            if (!data) {
                $this.data('plugin_' + pluginName, (data = new Plugin(this, options)));
            }

            // Make it possible to access methods from public.
            // e.g `$element.rangeslider('method');`
            if (typeof options === 'string') {
                data[options].apply(data, args);
            }
        });
    };

    return 'rangeslider.js is available in jQuery context e.g $(selector).rangeslider(options);';

}));

// Spectrum Colorpicker v1.8.1
// https://github.com/bgrins/spectrum
// Author: Brian Grinstead
// License: MIT

(function (factory) {
    "use strict";

    if (typeof define === 'function' && define.amd) { // AMD
        define(['jquery'], factory);
    }
    else if (typeof exports == "object" && typeof module == "object") { // CommonJS
        module.exports = factory(require('jquery'));
    }
    else { // Browser
        factory(jQuery);
    }
})(function($, undefined) {
    "use strict";

    var defaultOpts = {

        // Callbacks
        beforeShow: noop,
        move: noop,
        change: noop,
        show: noop,
        hide: noop,

        // Options
        color: false,
        flat: false,
        showInput: false,
        allowEmpty: false,
        showButtons: true,
        clickoutFiresChange: true,
        showInitial: false,
        showPalette: false,
        showPaletteOnly: false,
        hideAfterPaletteSelect: false,
        togglePaletteOnly: false,
        showSelectionPalette: true,
        localStorageKey: false,
        appendTo: "body",
        maxSelectionSize: 7,
        cancelText: "cancel",
        chooseText: "choose",
        togglePaletteMoreText: "more",
        togglePaletteLessText: "less",
        clearText: "Clear Color Selection",
        noColorSelectedText: "No Color Selected",
        preferredFormat: false,
        className: "", // Deprecated - use containerClassName and replacerClassName instead.
        containerClassName: "",
        replacerClassName: "",
        showAlpha: false,
        theme: "sp-light",
        palette: [["#ffffff", "#000000", "#ff0000", "#ff8000", "#ffff00", "#008000", "#0000ff", "#4b0082", "#9400d3"]],
        selectionPalette: [],
        disabled: false,
        offset: null
    },
    spectrums = [],
    IE = !!/msie/i.exec( window.navigator.userAgent ),
    rgbaSupport = (function() {
        function contains( str, substr ) {
            return !!~('' + str).indexOf(substr);
        }

        var elem = document.createElement('div');
        var style = elem.style;
        style.cssText = 'background-color:rgba(0,0,0,.5)';
        return contains(style.backgroundColor, 'rgba') || contains(style.backgroundColor, 'hsla');
    })(),
    replaceInput = [
        "<div class='sp-replacer'>",
            "<div class='sp-preview'><div class='sp-preview-inner'></div></div>",
            "<div class='sp-dd'>&#9660;</div>",
        "</div>"
    ].join(''),
    markup = (function () {

        // IE does not support gradients with multiple stops, so we need to simulate
        //  that for the rainbow slider with 8 divs that each have a single gradient
        var gradientFix = "";
        if (IE) {
            for (var i = 1; i <= 6; i++) {
                gradientFix += "<div class='sp-" + i + "'></div>";
            }
        }

        return [
            "<div class='sp-container sp-hidden'>",
                "<div class='sp-palette-container'>",
                    "<div class='sp-palette sp-thumb sp-cf'></div>",
                    "<div class='sp-palette-button-container sp-cf'>",
                        "<button type='button' class='sp-palette-toggle'></button>",
                    "</div>",
                "</div>",
                "<div class='sp-picker-container'>",
                    "<div class='sp-top sp-cf'>",
                        "<div class='sp-fill'></div>",
                        "<div class='sp-top-inner'>",
                            "<div class='sp-color'>",
                                "<div class='sp-sat'>",
                                    "<div class='sp-val'>",
                                        "<div class='sp-dragger'></div>",
                                    "</div>",
                                "</div>",
                            "</div>",
                            "<div class='sp-clear sp-clear-display'>",
                            "</div>",
                            "<div class='sp-hue'>",
                                "<div class='sp-slider'></div>",
                                gradientFix,
                            "</div>",
                        "</div>",
                        "<div class='sp-alpha'><div class='sp-alpha-inner'><div class='sp-alpha-handle'></div></div></div>",
                    "</div>",
                    "<div class='sp-input-container sp-cf'>",
                        "<input class='sp-input' type='text' spellcheck='false'  />",
                    "</div>",
                    "<div class='sp-initial sp-thumb sp-cf'></div>",
                    "<div class='sp-button-container sp-cf'>",
                        "<a class='sp-cancel' href='#'></a>",
                        "<button type='button' class='sp-choose'></button>",
                    "</div>",
                "</div>",
            "</div>"
        ].join("");
    })();

    function paletteTemplate (p, color, className, opts) {
        var html = [];
        for (var i = 0; i < p.length; i++) {
            var current = p[i];
            if(current) {
                var tiny = tinycolor(current);
                var c = tiny.toHsl().l < 0.5 ? "sp-thumb-el sp-thumb-dark" : "sp-thumb-el sp-thumb-light";
                c += (tinycolor.equals(color, current)) ? " sp-thumb-active" : "";
                var formattedString = tiny.toString(opts.preferredFormat || "rgb");
                var swatchStyle = rgbaSupport ? ("background-color:" + tiny.toRgbString()) : "filter:" + tiny.toFilter();
                html.push('<span title="' + formattedString + '" data-color="' + tiny.toRgbString() + '" class="' + c + '"><span class="sp-thumb-inner" style="' + swatchStyle + ';"></span></span>');
            } else {
                var cls = 'sp-clear-display';
                html.push($('<div />')
                    .append($('<span data-color="" style="background-color:transparent;" class="' + cls + '"></span>')
                        .attr('title', opts.noColorSelectedText)
                    )
                    .html()
                );
            }
        }
        return "<div class='sp-cf " + className + "'>" + html.join('') + "</div>";
    }

    function hideAll() {
        for (var i = 0; i < spectrums.length; i++) {
            if (spectrums[i]) {
                spectrums[i].hide();
            }
        }
    }

    function instanceOptions(o, callbackContext) {
        var opts = $.extend({}, defaultOpts, o);
        opts.callbacks = {
            'move': bind(opts.move, callbackContext),
            'change': bind(opts.change, callbackContext),
            'show': bind(opts.show, callbackContext),
            'hide': bind(opts.hide, callbackContext),
            'beforeShow': bind(opts.beforeShow, callbackContext)
        };

        return opts;
    }

    function spectrum(element, o) {

        var opts = instanceOptions(o, element),
            flat = opts.flat,
            showSelectionPalette = opts.showSelectionPalette,
            localStorageKey = opts.localStorageKey,
            theme = opts.theme,
            callbacks = opts.callbacks,
            resize = throttle(reflow, 10),
            visible = false,
            isDragging = false,
            dragWidth = 0,
            dragHeight = 0,
            dragHelperHeight = 0,
            slideHeight = 0,
            slideWidth = 0,
            alphaWidth = 0,
            alphaSlideHelperWidth = 0,
            slideHelperHeight = 0,
            currentHue = 0,
            currentSaturation = 0,
            currentValue = 0,
            currentAlpha = 1,
            palette = [],
            paletteArray = [],
            paletteLookup = {},
            selectionPalette = opts.selectionPalette.slice(0),
            maxSelectionSize = opts.maxSelectionSize,
            draggingClass = "sp-dragging",
            shiftMovementDirection = null;

        var doc = element.ownerDocument,
            body = doc.body,
            boundElement = $(element),
            disabled = false,
            container = $(markup, doc).addClass(theme),
            pickerContainer = container.find(".sp-picker-container"),
            dragger = container.find(".sp-color"),
            dragHelper = container.find(".sp-dragger"),
            slider = container.find(".sp-hue"),
            slideHelper = container.find(".sp-slider"),
            alphaSliderInner = container.find(".sp-alpha-inner"),
            alphaSlider = container.find(".sp-alpha"),
            alphaSlideHelper = container.find(".sp-alpha-handle"),
            textInput = container.find(".sp-input"),
            paletteContainer = container.find(".sp-palette"),
            initialColorContainer = container.find(".sp-initial"),
            cancelButton = container.find(".sp-cancel"),
            clearButton = container.find(".sp-clear"),
            chooseButton = container.find(".sp-choose"),
            toggleButton = container.find(".sp-palette-toggle"),
            isInput = boundElement.is("input"),
            isInputTypeColor = isInput && boundElement.attr("type") === "color" && inputTypeColorSupport(),
            shouldReplace = isInput && !flat,
            replacer = (shouldReplace) ? $(replaceInput).addClass(theme).addClass(opts.className).addClass(opts.replacerClassName) : $([]),
            offsetElement = (shouldReplace) ? replacer : boundElement,
            previewElement = replacer.find(".sp-preview-inner"),
            initialColor = opts.color || (isInput && boundElement.val()),
            colorOnShow = false,
            currentPreferredFormat = opts.preferredFormat,
            clickoutFiresChange = !opts.showButtons || opts.clickoutFiresChange,
            isEmpty = !initialColor,
            allowEmpty = opts.allowEmpty && !isInputTypeColor;

        function applyOptions() {

            if (opts.showPaletteOnly) {
                opts.showPalette = true;
            }

            toggleButton.text(opts.showPaletteOnly ? opts.togglePaletteMoreText : opts.togglePaletteLessText);

            if (opts.palette) {
                palette = opts.palette.slice(0);
                paletteArray = Array.isArray(palette[0]) ? palette : [palette];
                paletteLookup = {};
                for (var i = 0; i < paletteArray.length; i++) {
                    for (var j = 0; j < paletteArray[i].length; j++) {
                        var rgb = tinycolor(paletteArray[i][j]).toRgbString();
                        paletteLookup[rgb] = true;
                    }
                }
            }

            container.toggleClass("sp-flat", flat);
            container.toggleClass("sp-input-disabled", !opts.showInput);
            container.toggleClass("sp-alpha-enabled", opts.showAlpha);
            container.toggleClass("sp-clear-enabled", allowEmpty);
            container.toggleClass("sp-buttons-disabled", !opts.showButtons);
            container.toggleClass("sp-palette-buttons-disabled", !opts.togglePaletteOnly);
            container.toggleClass("sp-palette-disabled", !opts.showPalette);
            container.toggleClass("sp-palette-only", opts.showPaletteOnly);
            container.toggleClass("sp-initial-disabled", !opts.showInitial);
            container.addClass(opts.className).addClass(opts.containerClassName);

            reflow();
        }

        function initialize() {

            if (IE) {
                container.find("*:not(input)").attr("unselectable", "on");
            }

            applyOptions();

            if (shouldReplace) {
                boundElement.after(replacer).hide();
            }

            if (!allowEmpty) {
                clearButton.hide();
            }

            if (flat) {
                boundElement.after(container).hide();
            }
            else {

                var appendTo = opts.appendTo === "parent" ? boundElement.parent() : $(opts.appendTo);
                if (appendTo.length !== 1) {
                    appendTo = $("body");
                }

                appendTo.append(container);
            }

            updateSelectionPaletteFromStorage();

            offsetElement.on("click.spectrum touchstart.spectrum", function (e) {
                if (!disabled) {
                    toggle();
                }

                e.stopPropagation();

                if (!$(e.target).is("input")) {
                    e.preventDefault();
                }
            });

            if(boundElement.is(":disabled") || (opts.disabled === true)) {
                disable();
            }

            // Prevent clicks from bubbling up to document.  This would cause it to be hidden.
            container.on("click", stopPropagation);

            // Handle user typed input
            textInput.on("change", setFromTextInput);
            textInput.on("paste", function () {
                setTimeout(setFromTextInput, 1);
            });
            textInput.on("keydown", function (e) { if (e.keyCode == 13) { setFromTextInput(); } });

            cancelButton.text(opts.cancelText);
            cancelButton.on("click.spectrum", function (e) {
                e.stopPropagation();
                e.preventDefault();
                revert();
                hide();
            });

            clearButton.attr("title", opts.clearText);
            clearButton.on("click.spectrum", function (e) {
                e.stopPropagation();
                e.preventDefault();
                isEmpty = true;
                move();

                if(flat) {
                    //for the flat style, this is a change event
                    updateOriginalInput(true);
                }
            });

            chooseButton.text(opts.chooseText);
            chooseButton.on("click.spectrum", function (e) {
                e.stopPropagation();
                e.preventDefault();

                if (IE && textInput.is(":focus")) {
                    textInput.trigger('change');
                }

                if (isValid()) {
                    updateOriginalInput(true);
                    hide();
                }
            });

            toggleButton.text(opts.showPaletteOnly ? opts.togglePaletteMoreText : opts.togglePaletteLessText);
            toggleButton.on("click.spectrum", function (e) {
                e.stopPropagation();
                e.preventDefault();

                opts.showPaletteOnly = !opts.showPaletteOnly;

                // To make sure the Picker area is drawn on the right, next to the
                // Palette area (and not below the palette), first move the Palette
                // to the left to make space for the picker, plus 5px extra.
                // The 'applyOptions' function puts the whole container back into place
                // and takes care of the button-text and the sp-palette-only CSS class.
                if (!opts.showPaletteOnly && !flat) {
                    container.css('left', '-=' + (pickerContainer.outerWidth(true) + 5));
                }
                applyOptions();
            });

            draggable(alphaSlider, function (dragX, dragY, e) {
                currentAlpha = (dragX / alphaWidth);
                isEmpty = false;
                if (e.shiftKey) {
                    currentAlpha = Math.round(currentAlpha * 10) / 10;
                }

                move();
            }, dragStart, dragStop);

            draggable(slider, function (dragX, dragY) {
                currentHue = parseFloat(dragY / slideHeight);
                isEmpty = false;
                if (!opts.showAlpha) {
                    currentAlpha = 1;
                }
                move();
            }, dragStart, dragStop);

            draggable(dragger, function (dragX, dragY, e) {

                // shift+drag should snap the movement to either the x or y axis.
                if (!e.shiftKey) {
                    shiftMovementDirection = null;
                }
                else if (!shiftMovementDirection) {
                    var oldDragX = currentSaturation * dragWidth;
                    var oldDragY = dragHeight - (currentValue * dragHeight);
                    var furtherFromX = Math.abs(dragX - oldDragX) > Math.abs(dragY - oldDragY);

                    shiftMovementDirection = furtherFromX ? "x" : "y";
                }

                var setSaturation = !shiftMovementDirection || shiftMovementDirection === "x";
                var setValue = !shiftMovementDirection || shiftMovementDirection === "y";

                if (setSaturation) {
                    currentSaturation = parseFloat(dragX / dragWidth);
                }
                if (setValue) {
                    currentValue = parseFloat((dragHeight - dragY) / dragHeight);
                }

                isEmpty = false;
                if (!opts.showAlpha) {
                    currentAlpha = 1;
                }

                move();

            }, dragStart, dragStop);

            if (!!initialColor) {
                set(initialColor);

                // In case color was black - update the preview UI and set the format
                // since the set function will not run (default color is black).
                updateUI();
                currentPreferredFormat = opts.preferredFormat || tinycolor(initialColor).format;

                addColorToSelectionPalette(initialColor);
            }
            else {
                updateUI();
            }

            if (flat) {
                show();
            }

            function paletteElementClick(e) {
                if (e.data && e.data.ignore) {
                    set($(e.target).closest(".sp-thumb-el").data("color"));
                    move();
                }
                else {
                    set($(e.target).closest(".sp-thumb-el").data("color"));
                    move();

                    // If the picker is going to close immediately, a palette selection
                    // is a change.  Otherwise, it's a move only.
                    if (opts.hideAfterPaletteSelect) {
                        updateOriginalInput(true);
                        hide();
                    } else {
                        updateOriginalInput();
                    }
                }

                return false;
            }

            var paletteEvent = IE ? "mousedown.spectrum" : "click.spectrum touchstart.spectrum";
            paletteContainer.on(paletteEvent, ".sp-thumb-el", paletteElementClick);
            initialColorContainer.on(paletteEvent, ".sp-thumb-el:nth-child(1)", { ignore: true }, paletteElementClick);
        }

        function updateSelectionPaletteFromStorage() {

            if (localStorageKey && window.localStorage) {

                // Migrate old palettes over to new format.  May want to remove this eventually.
                try {
                    var oldPalette = window.localStorage[localStorageKey].split(",#");
                    if (oldPalette.length > 1) {
                        delete window.localStorage[localStorageKey];
                        $.each(oldPalette, function(i, c) {
                             addColorToSelectionPalette(c);
                        });
                    }
                }
                catch(e) { }

                try {
                    selectionPalette = window.localStorage[localStorageKey].split(";");
                }
                catch (e) { }
            }
        }

        function addColorToSelectionPalette(color) {
            if (showSelectionPalette) {
                var rgb = tinycolor(color).toRgbString();
                if (!paletteLookup[rgb] && $.inArray(rgb, selectionPalette) === -1) {
                    selectionPalette.push(rgb);
                    while(selectionPalette.length > maxSelectionSize) {
                        selectionPalette.shift();
                    }
                }

                if (localStorageKey && window.localStorage) {
                    try {
                        window.localStorage[localStorageKey] = selectionPalette.join(";");
                    }
                    catch(e) { }
                }
            }
        }

        function getUniqueSelectionPalette() {
            var unique = [];
            if (opts.showPalette) {
                for (var i = 0; i < selectionPalette.length; i++) {
                    var rgb = tinycolor(selectionPalette[i]).toRgbString();

                    if (!paletteLookup[rgb]) {
                        unique.push(selectionPalette[i]);
                    }
                }
            }

            return unique.reverse().slice(0, opts.maxSelectionSize);
        }

        function drawPalette() {

            var currentColor = get();

            var html = $.map(paletteArray, function (palette, i) {
                return paletteTemplate(palette, currentColor, "sp-palette-row sp-palette-row-" + i, opts);
            });

            updateSelectionPaletteFromStorage();

            if (selectionPalette) {
                html.push(paletteTemplate(getUniqueSelectionPalette(), currentColor, "sp-palette-row sp-palette-row-selection", opts));
            }

            paletteContainer.html(html.join(""));
        }

        function drawInitial() {
            if (opts.showInitial) {
                var initial = colorOnShow;
                var current = get();
                initialColorContainer.html(paletteTemplate([initial, current], current, "sp-palette-row-initial", opts));
            }
        }

        function dragStart() {
            if (dragHeight <= 0 || dragWidth <= 0 || slideHeight <= 0) {
                reflow();
            }
            isDragging = true;
            container.addClass(draggingClass);
            shiftMovementDirection = null;
            boundElement.trigger('dragstart.spectrum', [ get() ]);
        }

        function dragStop() {
            isDragging = false;
            container.removeClass(draggingClass);
            boundElement.trigger('dragstop.spectrum', [ get() ]);
        }

        function setFromTextInput() {

            var value = textInput.val();

            if ((value === null || value === "") && allowEmpty) {
                set(null);
                move();
                updateOriginalInput();
            }
            else {
                var tiny = tinycolor(value);
                if (tiny.isValid()) {
                    set(tiny);
                    move();
                    updateOriginalInput();
                }
                else {
                    textInput.addClass("sp-validation-error");
                }
            }
        }

        function toggle() {
            if (visible) {
                hide();
            }
            else {
                show();
            }
        }

        function show() {
            var event = $.Event('beforeShow.spectrum');

            if (visible) {
                reflow();
                return;
            }

            boundElement.trigger(event, [ get() ]);

            if (callbacks.beforeShow(get()) === false || event.isDefaultPrevented()) {
                return;
            }

            hideAll();
            visible = true;

            $(doc).on("keydown.spectrum", onkeydown);
            $(doc).on("click.spectrum", clickout);
            $(window).on("resize.spectrum", resize);
            replacer.addClass("sp-active");
            container.removeClass("sp-hidden");

            reflow();
            updateUI();

            colorOnShow = get();

            drawInitial();
            callbacks.show(colorOnShow);
            boundElement.trigger('show.spectrum', [ colorOnShow ]);
        }

        function onkeydown(e) {
            // Close on ESC
            if (e.keyCode === 27) {
                hide();
            }
        }

        function clickout(e) {
            // Return on right click.
            if (e.button == 2) { return; }

            // If a drag event was happening during the mouseup, don't hide
            // on click.
            if (isDragging) { return; }

            if (clickoutFiresChange) {
                updateOriginalInput(true);
            }
            else {
                revert();
            }
            hide();
        }

        function hide() {
            // Return if hiding is unnecessary
            if (!visible || flat) { return; }
            visible = false;

            $(doc).off("keydown.spectrum", onkeydown);
            $(doc).off("click.spectrum", clickout);
            $(window).off("resize.spectrum", resize);

            replacer.removeClass("sp-active");
            container.addClass("sp-hidden");

            callbacks.hide(get());
            boundElement.trigger('hide.spectrum', [ get() ]);
        }

        function revert() {
            set(colorOnShow, true);
            updateOriginalInput(true);
        }

        function set(color, ignoreFormatChange) {
            if (tinycolor.equals(color, get())) {
                // Update UI just in case a validation error needs
                // to be cleared.
                updateUI();
                return;
            }

            var newColor, newHsv;
            if (!color && allowEmpty) {
                isEmpty = true;
            } else {
                isEmpty = false;
                newColor = tinycolor(color);
                newHsv = newColor.toHsv();

                currentHue = (newHsv.h % 360) / 360;
                currentSaturation = newHsv.s;
                currentValue = newHsv.v;
                currentAlpha = newHsv.a;
            }
            updateUI();

            if (newColor && newColor.isValid() && !ignoreFormatChange) {
                currentPreferredFormat = opts.preferredFormat || newColor.getFormat();
            }
        }

        function get(opts) {
            opts = opts || { };

            if (allowEmpty && isEmpty) {
                return null;
            }

            return tinycolor.fromRatio({
                h: currentHue,
                s: currentSaturation,
                v: currentValue,
                a: Math.round(currentAlpha * 1000) / 1000
            }, { format: opts.format || currentPreferredFormat });
        }

        function isValid() {
            return !textInput.hasClass("sp-validation-error");
        }

        function move() {
            updateUI();

            callbacks.move(get());
            boundElement.trigger('move.spectrum', [ get() ]);
        }

        function updateUI() {

            textInput.removeClass("sp-validation-error");

            updateHelperLocations();

            // Update dragger background color (gradients take care of saturation and value).
            var flatColor = tinycolor.fromRatio({ h: currentHue, s: 1, v: 1 });
            dragger.css("background-color", flatColor.toHexString());

            // Get a format that alpha will be included in (hex and names ignore alpha)
            var format = currentPreferredFormat;
            if (currentAlpha < 1 && !(currentAlpha === 0 && format === "name")) {
                if (format === "hex" || format === "hex3" || format === "hex6" || format === "name") {
                    format = "rgb";
                }
            }

            var realColor = get({ format: format }),
                displayColor = '';

             //reset background info for preview element
            previewElement.removeClass("sp-clear-display");
            previewElement.css('background-color', 'transparent');

            if (!realColor && allowEmpty) {
                // Update the replaced elements background with icon indicating no color selection
                previewElement.addClass("sp-clear-display");
            }
            else {
                var realHex = realColor.toHexString(),
                    realRgb = realColor.toRgbString();

                // Update the replaced elements background color (with actual selected color)
                if (rgbaSupport || realColor.alpha === 1) {
                    previewElement.css("background-color", realRgb);
                }
                else {
                    previewElement.css("background-color", "transparent");
                    previewElement.css("filter", realColor.toFilter());
                }

                if (opts.showAlpha) {
                    var rgb = realColor.toRgb();
                    rgb.a = 0;
                    var realAlpha = tinycolor(rgb).toRgbString();
                    var gradient = "linear-gradient(left, " + realAlpha + ", " + realHex + ")";

                    if (IE) {
                        alphaSliderInner.css("filter", tinycolor(realAlpha).toFilter({ gradientType: 1 }, realHex));
                    }
                    else {
                        alphaSliderInner.css("background", "-webkit-" + gradient);
                        alphaSliderInner.css("background", "-moz-" + gradient);
                        alphaSliderInner.css("background", "-ms-" + gradient);
                        // Use current syntax gradient on unprefixed property.
                        alphaSliderInner.css("background",
                            "linear-gradient(to right, " + realAlpha + ", " + realHex + ")");
                    }
                }

                displayColor = realColor.toString(format);
            }

            // Update the text entry input as it changes happen
            if (opts.showInput) {
                textInput.val(displayColor);
            }

            if (opts.showPalette) {
                drawPalette();
            }

            drawInitial();
        }

        function updateHelperLocations() {
            var s = currentSaturation;
            var v = currentValue;

            if(allowEmpty && isEmpty) {
                //if selected color is empty, hide the helpers
                alphaSlideHelper.hide();
                slideHelper.hide();
                dragHelper.hide();
            }
            else {
                //make sure helpers are visible
                alphaSlideHelper.show();
                slideHelper.show();
                dragHelper.show();

                // Where to show the little circle in that displays your current selected color
                var dragX = s * dragWidth;
                var dragY = dragHeight - (v * dragHeight);
                dragX = Math.max(
                    -dragHelperHeight,
                    Math.min(dragWidth - dragHelperHeight, dragX - dragHelperHeight)
                );
                dragY = Math.max(
                    -dragHelperHeight,
                    Math.min(dragHeight - dragHelperHeight, dragY - dragHelperHeight)
                );
                dragHelper.css({
                    "top": dragY + "px",
                    "left": dragX + "px"
                });

                var alphaX = currentAlpha * alphaWidth;
                alphaSlideHelper.css({
                    "left": (alphaX - (alphaSlideHelperWidth / 2)) + "px"
                });

                // Where to show the bar that displays your current selected hue
                var slideY = (currentHue) * slideHeight;
                slideHelper.css({
                    "top": (slideY - slideHelperHeight) + "px"
                });
            }
        }

        function updateOriginalInput(fireCallback) {
            var color = get(),
                displayColor = '',
                hasChanged = !tinycolor.equals(color, colorOnShow);

            if (color) {
                displayColor = color.toString(currentPreferredFormat);
                // Update the selection palette with the current color
                addColorToSelectionPalette(color);
            }

            if (isInput) {
                boundElement.val(displayColor);
            }

            if (fireCallback && hasChanged) {
                callbacks.change(color);
                boundElement.trigger('change', [ color ]);
            }
        }

        function reflow() {
            if (!visible) {
                return; // Calculations would be useless and wouldn't be reliable anyways
            }
            dragWidth = dragger.width();
            dragHeight = dragger.height();
            dragHelperHeight = dragHelper.height();
            slideWidth = slider.width();
            slideHeight = slider.height();
            slideHelperHeight = slideHelper.height();
            alphaWidth = alphaSlider.width();
            alphaSlideHelperWidth = alphaSlideHelper.width();

            if (!flat) {
                container.css("position", "absolute");
                if (opts.offset) {
                    container.offset(opts.offset);
                } else {
                    container.offset(getOffset(container, offsetElement));
                }
            }

            updateHelperLocations();

            if (opts.showPalette) {
                drawPalette();
            }

            boundElement.trigger('reflow.spectrum');
        }

        function destroy() {
            boundElement.show();
            offsetElement.off("click.spectrum touchstart.spectrum");
            container.remove();
            replacer.remove();
            spectrums[spect.id] = null;
        }

        function option(optionName, optionValue) {
            if (optionName === undefined) {
                return $.extend({}, opts);
            }
            if (optionValue === undefined) {
                return opts[optionName];
            }

            opts[optionName] = optionValue;

            if (optionName === "preferredFormat") {
                currentPreferredFormat = opts.preferredFormat;
            }
            applyOptions();
        }

        function enable() {
            disabled = false;
            boundElement.attr("disabled", false);
            offsetElement.removeClass("sp-disabled");
        }

        function disable() {
            hide();
            disabled = true;
            boundElement.attr("disabled", true);
            offsetElement.addClass("sp-disabled");
        }

        function setOffset(coord) {
            opts.offset = coord;
            reflow();
        }

        initialize();

        var spect = {
            show: show,
            hide: hide,
            toggle: toggle,
            reflow: reflow,
            option: option,
            enable: enable,
            disable: disable,
            offset: setOffset,
            set: function (c) {
                set(c);
                updateOriginalInput();
            },
            get: get,
            destroy: destroy,
            container: container
        };

        spect.id = spectrums.push(spect) - 1;

        return spect;
    }

    /**
    * checkOffset - get the offset below/above and left/right element depending on screen position
    * Thanks https://github.com/jquery/jquery-ui/blob/master/ui/jquery.ui.datepicker.js
    */
    function getOffset(picker, input) {
        var extraY = 0;
        var dpWidth = picker.outerWidth();
        var dpHeight = picker.outerHeight();
        var inputHeight = input.outerHeight();
        var doc = picker[0].ownerDocument;
        var docElem = doc.documentElement;
        var viewWidth = docElem.clientWidth + $(doc).scrollLeft();
        var viewHeight = docElem.clientHeight + $(doc).scrollTop();
        var offset = input.offset();
        var offsetLeft = offset.left;
        var offsetTop = offset.top;

        offsetTop += inputHeight;

        offsetLeft -=
            Math.min(offsetLeft, (offsetLeft + dpWidth > viewWidth && viewWidth > dpWidth) ?
            Math.abs(offsetLeft + dpWidth - viewWidth) : 0);

        offsetTop -=
            Math.min(offsetTop, ((offsetTop + dpHeight > viewHeight && viewHeight > dpHeight) ?
            Math.abs(dpHeight + inputHeight - extraY) : extraY));

        return {
            top: offsetTop,
            bottom: offset.bottom,
            left: offsetLeft,
            right: offset.right,
            width: offset.width,
            height: offset.height
        };
    }

    /**
    * noop - do nothing
    */
    function noop() {

    }

    /**
    * stopPropagation - makes the code only doing this a little easier to read in line
    */
    function stopPropagation(e) {
        e.stopPropagation();
    }

    /**
    * Create a function bound to a given object
    * Thanks to underscore.js
    */
    function bind(func, obj) {
        var slice = Array.prototype.slice;
        var args = slice.call(arguments, 2);
        return function () {
            return func.apply(obj, args.concat(slice.call(arguments)));
        };
    }

    /**
    * Lightweight drag helper.  Handles containment within the element, so that
    * when dragging, the x is within [0,element.width] and y is within [0,element.height]
    */
    function draggable(element, onmove, onstart, onstop) {
        onmove = onmove || function () { };
        onstart = onstart || function () { };
        onstop = onstop || function () { };
        var doc = document;
        var dragging = false;
        var offset = {};
        var maxHeight = 0;
        var maxWidth = 0;
        var hasTouch = ('ontouchstart' in window);

        var duringDragEvents = {};
        duringDragEvents["selectstart"] = prevent;
        duringDragEvents["dragstart"] = prevent;
        duringDragEvents["touchmove mousemove"] = move;
        duringDragEvents["touchend mouseup"] = stop;

        function prevent(e) {
            if (e.stopPropagation) {
                e.stopPropagation();
            }
            if (e.preventDefault) {
                e.preventDefault();
            }
            e.returnValue = false;
        }

        function move(e) {
            if (dragging) {
                // Mouseup happened outside of window
                if (IE && doc.documentMode < 9 && !e.button) {
                    return stop();
                }

                var t0 = e.originalEvent && e.originalEvent.touches && e.originalEvent.touches[0];
                var pageX = t0 && t0.pageX || e.pageX;
                var pageY = t0 && t0.pageY || e.pageY;

                var dragX = Math.max(0, Math.min(pageX - offset.left, maxWidth));
                var dragY = Math.max(0, Math.min(pageY - offset.top, maxHeight));

                if (hasTouch) {
                    // Stop scrolling in iOS
                    prevent(e);
                }

                onmove.apply(element, [dragX, dragY, e]);
            }
        }

        function start(e) {
            var rightclick = (e.which) ? (e.which == 3) : (e.button == 2);

            if (!rightclick && !dragging) {
                if (onstart.apply(element, arguments) !== false) {
                    dragging = true;
                    maxHeight = $(element).height();
                    maxWidth = $(element).width();
                    offset = $(element).offset();

                    $(doc).on(duringDragEvents);
                    $(doc.body).addClass("sp-dragging");

                    move(e);

                    prevent(e);
                }
            }
        }

        function stop() {
            if (dragging) {
                $(doc).off(duringDragEvents);
                $(doc.body).removeClass("sp-dragging");

                // Wait a tick before notifying observers to allow the click event
                // to fire in Chrome.
                setTimeout(function() {
                    onstop.apply(element, arguments);
                }, 0);
            }
            dragging = false;
        }

        $(element).on("touchstart mousedown", start);
    }

    function throttle(func, wait, debounce) {
        var timeout;
        return function () {
            var context = this, args = arguments;
            var throttler = function () {
                timeout = null;
                func.apply(context, args);
            };
            if (debounce) clearTimeout(timeout);
            if (debounce || !timeout) timeout = setTimeout(throttler, wait);
        };
    }

    function inputTypeColorSupport() {
        return $.fn.spectrum.inputTypeColorSupport();
    }

    /**
    * Define a jQuery plugin
    */
    var dataID = "spectrum.id";
    $.fn.spectrum = function (opts, extra) {

        if (typeof opts == "string") {

            var returnValue = this;
            var args = Array.prototype.slice.call( arguments, 1 );

            this.each(function () {
                var spect = spectrums[$(this).data(dataID)];
                if (spect) {
                    var method = spect[opts];
                    if (!method) {
                        throw new Error( "Spectrum: no such method: '" + opts + "'" );
                    }

                    if (opts == "get") {
                        returnValue = spect.get();
                    }
                    else if (opts == "container") {
                        returnValue = spect.container;
                    }
                    else if (opts == "option") {
                        returnValue = spect.option.apply(spect, args);
                    }
                    else if (opts == "destroy") {
                        spect.destroy();
                        $(this).removeData(dataID);
                    }
                    else {
                        method.apply(spect, args);
                    }
                }
            });

            return returnValue;
        }

        // Initializing a new instance of spectrum
        return this.spectrum("destroy").each(function () {
            var options = $.extend({}, $(this).data(), opts);
            var spect = spectrum(this, options);
            $(this).data(dataID, spect.id);
        });
    };

    $.fn.spectrum.load = true;
    $.fn.spectrum.loadOpts = {};
    $.fn.spectrum.draggable = draggable;
    $.fn.spectrum.defaults = defaultOpts;
    $.fn.spectrum.inputTypeColorSupport = function inputTypeColorSupport() {
        if (typeof inputTypeColorSupport._cachedResult === "undefined") {
            var colorInput = $("<input type='color'/>")[0]; // if color element is supported, value will default to not null
            inputTypeColorSupport._cachedResult = colorInput.type === "color" && colorInput.value !== "";
        }
        return inputTypeColorSupport._cachedResult;
    };

    $.spectrum = { };
    $.spectrum.localization = { };
    $.spectrum.palettes = { };

    $.fn.spectrum.processNativeColorInputs = function () {
        var colorInputs = $("input[type=color]");
        if (colorInputs.length && !inputTypeColorSupport()) {
            colorInputs.spectrum({
                preferredFormat: "hex6"
            });
        }
    };

    // TinyColor v1.1.2
    // https://github.com/bgrins/TinyColor
    // Brian Grinstead, MIT License

    (function() {

    var trimLeft = /^[\s,#]+/,
        trimRight = /\s+$/,
        tinyCounter = 0,
        math = Math,
        mathRound = math.round,
        mathMin = math.min,
        mathMax = math.max,
        mathRandom = math.random;

    var tinycolor = function(color, opts) {

        color = (color) ? color : '';
        opts = opts || { };

        // If input is already a tinycolor, return itself
        if (color instanceof tinycolor) {
           return color;
        }
        // If we are called as a function, call using new instead
        if (!(this instanceof tinycolor)) {
            return new tinycolor(color, opts);
        }

        var rgb = inputToRGB(color);
        this._originalInput = color;
        this._r = rgb.r;
        this._g = rgb.g;
        this._b = rgb.b;
        this._a = rgb.a;
        this._roundA = mathRound(1000 * this._a) / 1000;
        this._format = opts.format || rgb.format;
        this._gradientType = opts.gradientType;

        // Don't let the range of [0,255] come back in [0,1].
        // Potentially lose a little bit of precision here, but will fix issues where
        // .5 gets interpreted as half of the total, instead of half of 1
        // If it was supposed to be 128, this was already taken care of by `inputToRgb`
        if (this._r < 1) { this._r = mathRound(this._r); }
        if (this._g < 1) { this._g = mathRound(this._g); }
        if (this._b < 1) { this._b = mathRound(this._b); }

        this._ok = rgb.ok;
        this._tc_id = tinyCounter++;
    };

    tinycolor.prototype = {
        isDark: function() {
            return this.getBrightness() < 128;
        },
        isLight: function() {
            return !this.isDark();
        },
        isValid: function() {
            return this._ok;
        },
        getOriginalInput: function() {
          return this._originalInput;
        },
        getFormat: function() {
            return this._format;
        },
        getAlpha: function() {
            return this._a;
        },
        getBrightness: function() {
            var rgb = this.toRgb();
            return (rgb.r * 299 + rgb.g * 587 + rgb.b * 114) / 1000;
        },
        setAlpha: function(value) {
            this._a = boundAlpha(value);
            this._roundA = mathRound(1000 * this._a) / 1000;
            return this;
        },
        toHsv: function() {
            var hsv = rgbToHsv(this._r, this._g, this._b);
            return { h: hsv.h * 360, s: hsv.s, v: hsv.v, a: this._a };
        },
        toHsvString: function() {
            var hsv = rgbToHsv(this._r, this._g, this._b);
            var h = mathRound(hsv.h * 360), s = mathRound(hsv.s * 100), v = mathRound(hsv.v * 100);
            return (this._a == 1) ?
              "hsv("  + h + ", " + s + "%, " + v + "%)" :
              "hsva(" + h + ", " + s + "%, " + v + "%, "+ this._roundA + ")";
        },
        toHsl: function() {
            var hsl = rgbToHsl(this._r, this._g, this._b);
            return { h: hsl.h * 360, s: hsl.s, l: hsl.l, a: this._a };
        },
        toHslString: function() {
            var hsl = rgbToHsl(this._r, this._g, this._b);
            var h = mathRound(hsl.h * 360), s = mathRound(hsl.s * 100), l = mathRound(hsl.l * 100);
            return (this._a == 1) ?
              "hsl("  + h + ", " + s + "%, " + l + "%)" :
              "hsla(" + h + ", " + s + "%, " + l + "%, "+ this._roundA + ")";
        },
        toHex: function(allow3Char) {
            return rgbToHex(this._r, this._g, this._b, allow3Char);
        },
        toHexString: function(allow3Char) {
            return '#' + this.toHex(allow3Char);
        },
        toHex8: function() {
            return rgbaToHex(this._r, this._g, this._b, this._a);
        },
        toHex8String: function() {
            return '#' + this.toHex8();
        },
        toRgb: function() {
            return { r: mathRound(this._r), g: mathRound(this._g), b: mathRound(this._b), a: this._a };
        },
        toRgbString: function() {
            return (this._a == 1) ?
              "rgb("  + mathRound(this._r) + ", " + mathRound(this._g) + ", " + mathRound(this._b) + ")" :
              "rgba(" + mathRound(this._r) + ", " + mathRound(this._g) + ", " + mathRound(this._b) + ", " + this._roundA + ")";
        },
        toPercentageRgb: function() {
            return { r: mathRound(bound01(this._r, 255) * 100) + "%", g: mathRound(bound01(this._g, 255) * 100) + "%", b: mathRound(bound01(this._b, 255) * 100) + "%", a: this._a };
        },
        toPercentageRgbString: function() {
            return (this._a == 1) ?
              "rgb("  + mathRound(bound01(this._r, 255) * 100) + "%, " + mathRound(bound01(this._g, 255) * 100) + "%, " + mathRound(bound01(this._b, 255) * 100) + "%)" :
              "rgba(" + mathRound(bound01(this._r, 255) * 100) + "%, " + mathRound(bound01(this._g, 255) * 100) + "%, " + mathRound(bound01(this._b, 255) * 100) + "%, " + this._roundA + ")";
        },
        toName: function() {
            if (this._a === 0) {
                return "transparent";
            }

            if (this._a < 1) {
                return false;
            }

            return hexNames[rgbToHex(this._r, this._g, this._b, true)] || false;
        },
        toFilter: function(secondColor) {
            var hex8String = '#' + rgbaToHex(this._r, this._g, this._b, this._a);
            var secondHex8String = hex8String;
            var gradientType = this._gradientType ? "GradientType = 1, " : "";

            if (secondColor) {
                var s = tinycolor(secondColor);
                secondHex8String = s.toHex8String();
            }

            return "progid:DXImageTransform.Microsoft.gradient("+gradientType+"startColorstr="+hex8String+",endColorstr="+secondHex8String+")";
        },
        toString: function(format) {
            var formatSet = !!format;
            format = format || this._format;

            var formattedString = false;
            var hasAlpha = this._a < 1 && this._a >= 0;
            var needsAlphaFormat = !formatSet && hasAlpha && (format === "hex" || format === "hex6" || format === "hex3" || format === "name");

            if (needsAlphaFormat) {
                // Special case for "transparent", all other non-alpha formats
                // will return rgba when there is transparency.
                if (format === "name" && this._a === 0) {
                    return this.toName();
                }
                return this.toRgbString();
            }
            if (format === "rgb") {
                formattedString = this.toRgbString();
            }
            if (format === "prgb") {
                formattedString = this.toPercentageRgbString();
            }
            if (format === "hex" || format === "hex6") {
                formattedString = this.toHexString();
            }
            if (format === "hex3") {
                formattedString = this.toHexString(true);
            }
            if (format === "hex8") {
                formattedString = this.toHex8String();
            }
            if (format === "name") {
                formattedString = this.toName();
            }
            if (format === "hsl") {
                formattedString = this.toHslString();
            }
            if (format === "hsv") {
                formattedString = this.toHsvString();
            }

            return formattedString || this.toHexString();
        },

        _applyModification: function(fn, args) {
            var color = fn.apply(null, [this].concat([].slice.call(args)));
            this._r = color._r;
            this._g = color._g;
            this._b = color._b;
            this.setAlpha(color._a);
            return this;
        },
        lighten: function() {
            return this._applyModification(lighten, arguments);
        },
        brighten: function() {
            return this._applyModification(brighten, arguments);
        },
        darken: function() {
            return this._applyModification(darken, arguments);
        },
        desaturate: function() {
            return this._applyModification(desaturate, arguments);
        },
        saturate: function() {
            return this._applyModification(saturate, arguments);
        },
        greyscale: function() {
            return this._applyModification(greyscale, arguments);
        },
        spin: function() {
            return this._applyModification(spin, arguments);
        },

        _applyCombination: function(fn, args) {
            return fn.apply(null, [this].concat([].slice.call(args)));
        },
        analogous: function() {
            return this._applyCombination(analogous, arguments);
        },
        complement: function() {
            return this._applyCombination(complement, arguments);
        },
        monochromatic: function() {
            return this._applyCombination(monochromatic, arguments);
        },
        splitcomplement: function() {
            return this._applyCombination(splitcomplement, arguments);
        },
        triad: function() {
            return this._applyCombination(triad, arguments);
        },
        tetrad: function() {
            return this._applyCombination(tetrad, arguments);
        }
    };

    // If input is an object, force 1 into "1.0" to handle ratios properly
    // String input requires "1.0" as input, so 1 will be treated as 1
    tinycolor.fromRatio = function(color, opts) {
        if (typeof color == "object") {
            var newColor = {};
            for (var i in color) {
                if (color.hasOwnProperty(i)) {
                    if (i === "a") {
                        newColor[i] = color[i];
                    }
                    else {
                        newColor[i] = convertToPercentage(color[i]);
                    }
                }
            }
            color = newColor;
        }

        return tinycolor(color, opts);
    };

    // Given a string or object, convert that input to RGB
    // Possible string inputs:
    //
    //     "red"
    //     "#f00" or "f00"
    //     "#ff0000" or "ff0000"
    //     "#ff000000" or "ff000000"
    //     "rgb 255 0 0" or "rgb (255, 0, 0)"
    //     "rgb 1.0 0 0" or "rgb (1, 0, 0)"
    //     "rgba (255, 0, 0, 1)" or "rgba 255, 0, 0, 1"
    //     "rgba (1.0, 0, 0, 1)" or "rgba 1.0, 0, 0, 1"
    //     "hsl(0, 100%, 50%)" or "hsl 0 100% 50%"
    //     "hsla(0, 100%, 50%, 1)" or "hsla 0 100% 50%, 1"
    //     "hsv(0, 100%, 100%)" or "hsv 0 100% 100%"
    //
    function inputToRGB(color) {

        var rgb = { r: 0, g: 0, b: 0 };
        var a = 1;
        var ok = false;
        var format = false;

        if (typeof color == "string") {
            color = stringInputToObject(color);
        }

        if (typeof color == "object") {
            if (color.hasOwnProperty("r") && color.hasOwnProperty("g") && color.hasOwnProperty("b")) {
                rgb = rgbToRgb(color.r, color.g, color.b);
                ok = true;
                format = String(color.r).substr(-1) === "%" ? "prgb" : "rgb";
            }
            else if (color.hasOwnProperty("h") && color.hasOwnProperty("s") && color.hasOwnProperty("v")) {
                color.s = convertToPercentage(color.s);
                color.v = convertToPercentage(color.v);
                rgb = hsvToRgb(color.h, color.s, color.v);
                ok = true;
                format = "hsv";
            }
            else if (color.hasOwnProperty("h") && color.hasOwnProperty("s") && color.hasOwnProperty("l")) {
                color.s = convertToPercentage(color.s);
                color.l = convertToPercentage(color.l);
                rgb = hslToRgb(color.h, color.s, color.l);
                ok = true;
                format = "hsl";
            }

            if (color.hasOwnProperty("a")) {
                a = color.a;
            }
        }

        a = boundAlpha(a);

        return {
            ok: ok,
            format: color.format || format,
            r: mathMin(255, mathMax(rgb.r, 0)),
            g: mathMin(255, mathMax(rgb.g, 0)),
            b: mathMin(255, mathMax(rgb.b, 0)),
            a: a
        };
    }


    // Conversion Functions
    // --------------------

    // `rgbToHsl`, `rgbToHsv`, `hslToRgb`, `hsvToRgb` modified from:
    // <http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript>

    // `rgbToRgb`
    // Handle bounds / percentage checking to conform to CSS color spec
    // <http://www.w3.org/TR/css3-color/>
    // *Assumes:* r, g, b in [0, 255] or [0, 1]
    // *Returns:* { r, g, b } in [0, 255]
    function rgbToRgb(r, g, b){
        return {
            r: bound01(r, 255) * 255,
            g: bound01(g, 255) * 255,
            b: bound01(b, 255) * 255
        };
    }

    // `rgbToHsl`
    // Converts an RGB color value to HSL.
    // *Assumes:* r, g, and b are contained in [0, 255] or [0, 1]
    // *Returns:* { h, s, l } in [0,1]
    function rgbToHsl(r, g, b) {

        r = bound01(r, 255);
        g = bound01(g, 255);
        b = bound01(b, 255);

        var max = mathMax(r, g, b), min = mathMin(r, g, b);
        var h, s, l = (max + min) / 2;

        if(max == min) {
            h = s = 0; // achromatic
        }
        else {
            var d = max - min;
            s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
            switch(max) {
                case r: h = (g - b) / d + (g < b ? 6 : 0); break;
                case g: h = (b - r) / d + 2; break;
                case b: h = (r - g) / d + 4; break;
            }

            h /= 6;
        }

        return { h: h, s: s, l: l };
    }

    // `hslToRgb`
    // Converts an HSL color value to RGB.
    // *Assumes:* h is contained in [0, 1] or [0, 360] and s and l are contained [0, 1] or [0, 100]
    // *Returns:* { r, g, b } in the set [0, 255]
    function hslToRgb(h, s, l) {
        var r, g, b;

        h = bound01(h, 360);
        s = bound01(s, 100);
        l = bound01(l, 100);

        function hue2rgb(p, q, t) {
            if(t < 0) t += 1;
            if(t > 1) t -= 1;
            if(t < 1/6) return p + (q - p) * 6 * t;
            if(t < 1/2) return q;
            if(t < 2/3) return p + (q - p) * (2/3 - t) * 6;
            return p;
        }

        if(s === 0) {
            r = g = b = l; // achromatic
        }
        else {
            var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
            var p = 2 * l - q;
            r = hue2rgb(p, q, h + 1/3);
            g = hue2rgb(p, q, h);
            b = hue2rgb(p, q, h - 1/3);
        }

        return { r: r * 255, g: g * 255, b: b * 255 };
    }

    // `rgbToHsv`
    // Converts an RGB color value to HSV
    // *Assumes:* r, g, and b are contained in the set [0, 255] or [0, 1]
    // *Returns:* { h, s, v } in [0,1]
    function rgbToHsv(r, g, b) {

        r = bound01(r, 255);
        g = bound01(g, 255);
        b = bound01(b, 255);

        var max = mathMax(r, g, b), min = mathMin(r, g, b);
        var h, s, v = max;

        var d = max - min;
        s = max === 0 ? 0 : d / max;

        if(max == min) {
            h = 0; // achromatic
        }
        else {
            switch(max) {
                case r: h = (g - b) / d + (g < b ? 6 : 0); break;
                case g: h = (b - r) / d + 2; break;
                case b: h = (r - g) / d + 4; break;
            }
            h /= 6;
        }
        return { h: h, s: s, v: v };
    }

    // `hsvToRgb`
    // Converts an HSV color value to RGB.
    // *Assumes:* h is contained in [0, 1] or [0, 360] and s and v are contained in [0, 1] or [0, 100]
    // *Returns:* { r, g, b } in the set [0, 255]
     function hsvToRgb(h, s, v) {

        h = bound01(h, 360) * 6;
        s = bound01(s, 100);
        v = bound01(v, 100);

        var i = math.floor(h),
            f = h - i,
            p = v * (1 - s),
            q = v * (1 - f * s),
            t = v * (1 - (1 - f) * s),
            mod = i % 6,
            r = [v, q, p, p, t, v][mod],
            g = [t, v, v, q, p, p][mod],
            b = [p, p, t, v, v, q][mod];

        return { r: r * 255, g: g * 255, b: b * 255 };
    }

    // `rgbToHex`
    // Converts an RGB color to hex
    // Assumes r, g, and b are contained in the set [0, 255]
    // Returns a 3 or 6 character hex
    function rgbToHex(r, g, b, allow3Char) {

        var hex = [
            pad2(mathRound(r).toString(16)),
            pad2(mathRound(g).toString(16)),
            pad2(mathRound(b).toString(16))
        ];

        // Return a 3 character hex if possible
        if (allow3Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1)) {
            return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0);
        }

        return hex.join("");
    }
        // `rgbaToHex`
        // Converts an RGBA color plus alpha transparency to hex
        // Assumes r, g, b and a are contained in the set [0, 255]
        // Returns an 8 character hex
        function rgbaToHex(r, g, b, a) {

            var hex = [
                pad2(convertDecimalToHex(a)),
                pad2(mathRound(r).toString(16)),
                pad2(mathRound(g).toString(16)),
                pad2(mathRound(b).toString(16))
            ];

            return hex.join("");
        }

    // `equals`
    // Can be called with any tinycolor input
    tinycolor.equals = function (color1, color2) {
        if (!color1 || !color2) { return false; }
        return tinycolor(color1).toRgbString() == tinycolor(color2).toRgbString();
    };
    tinycolor.random = function() {
        return tinycolor.fromRatio({
            r: mathRandom(),
            g: mathRandom(),
            b: mathRandom()
        });
    };


    // Modification Functions
    // ----------------------
    // Thanks to less.js for some of the basics here
    // <https://github.com/cloudhead/less.js/blob/master/lib/less/functions.js>

    function desaturate(color, amount) {
        amount = (amount === 0) ? 0 : (amount || 10);
        var hsl = tinycolor(color).toHsl();
        hsl.s -= amount / 100;
        hsl.s = clamp01(hsl.s);
        return tinycolor(hsl);
    }

    function saturate(color, amount) {
        amount = (amount === 0) ? 0 : (amount || 10);
        var hsl = tinycolor(color).toHsl();
        hsl.s += amount / 100;
        hsl.s = clamp01(hsl.s);
        return tinycolor(hsl);
    }

    function greyscale(color) {
        return tinycolor(color).desaturate(100);
    }

    function lighten (color, amount) {
        amount = (amount === 0) ? 0 : (amount || 10);
        var hsl = tinycolor(color).toHsl();
        hsl.l += amount / 100;
        hsl.l = clamp01(hsl.l);
        return tinycolor(hsl);
    }

    function brighten(color, amount) {
        amount = (amount === 0) ? 0 : (amount || 10);
        var rgb = tinycolor(color).toRgb();
        rgb.r = mathMax(0, mathMin(255, rgb.r - mathRound(255 * - (amount / 100))));
        rgb.g = mathMax(0, mathMin(255, rgb.g - mathRound(255 * - (amount / 100))));
        rgb.b = mathMax(0, mathMin(255, rgb.b - mathRound(255 * - (amount / 100))));
        return tinycolor(rgb);
    }

    function darken (color, amount) {
        amount = (amount === 0) ? 0 : (amount || 10);
        var hsl = tinycolor(color).toHsl();
        hsl.l -= amount / 100;
        hsl.l = clamp01(hsl.l);
        return tinycolor(hsl);
    }

    // Spin takes a positive or negative amount within [-360, 360] indicating the change of hue.
    // Values outside of this range will be wrapped into this range.
    function spin(color, amount) {
        var hsl = tinycolor(color).toHsl();
        var hue = (mathRound(hsl.h) + amount) % 360;
        hsl.h = hue < 0 ? 360 + hue : hue;
        return tinycolor(hsl);
    }

    // Combination Functions
    // ---------------------
    // Thanks to jQuery xColor for some of the ideas behind these
    // <https://github.com/infusion/jQuery-xcolor/blob/master/jquery.xcolor.js>

    function complement(color) {
        var hsl = tinycolor(color).toHsl();
        hsl.h = (hsl.h + 180) % 360;
        return tinycolor(hsl);
    }

    function triad(color) {
        var hsl = tinycolor(color).toHsl();
        var h = hsl.h;
        return [
            tinycolor(color),
            tinycolor({ h: (h + 120) % 360, s: hsl.s, l: hsl.l }),
            tinycolor({ h: (h + 240) % 360, s: hsl.s, l: hsl.l })
        ];
    }

    function tetrad(color) {
        var hsl = tinycolor(color).toHsl();
        var h = hsl.h;
        return [
            tinycolor(color),
            tinycolor({ h: (h + 90) % 360, s: hsl.s, l: hsl.l }),
            tinycolor({ h: (h + 180) % 360, s: hsl.s, l: hsl.l }),
            tinycolor({ h: (h + 270) % 360, s: hsl.s, l: hsl.l })
        ];
    }

    function splitcomplement(color) {
        var hsl = tinycolor(color).toHsl();
        var h = hsl.h;
        return [
            tinycolor(color),
            tinycolor({ h: (h + 72) % 360, s: hsl.s, l: hsl.l}),
            tinycolor({ h: (h + 216) % 360, s: hsl.s, l: hsl.l})
        ];
    }

    function analogous(color, results, slices) {
        results = results || 6;
        slices = slices || 30;

        var hsl = tinycolor(color).toHsl();
        var part = 360 / slices;
        var ret = [tinycolor(color)];

        for (hsl.h = ((hsl.h - (part * results >> 1)) + 720) % 360; --results; ) {
            hsl.h = (hsl.h + part) % 360;
            ret.push(tinycolor(hsl));
        }
        return ret;
    }

    function monochromatic(color, results) {
        results = results || 6;
        var hsv = tinycolor(color).toHsv();
        var h = hsv.h, s = hsv.s, v = hsv.v;
        var ret = [];
        var modification = 1 / results;

        while (results--) {
            ret.push(tinycolor({ h: h, s: s, v: v}));
            v = (v + modification) % 1;
        }

        return ret;
    }

    // Utility Functions
    // ---------------------

    tinycolor.mix = function(color1, color2, amount) {
        amount = (amount === 0) ? 0 : (amount || 50);

        var rgb1 = tinycolor(color1).toRgb();
        var rgb2 = tinycolor(color2).toRgb();

        var p = amount / 100;
        var w = p * 2 - 1;
        var a = rgb2.a - rgb1.a;

        var w1;

        if (w * a == -1) {
            w1 = w;
        } else {
            w1 = (w + a) / (1 + w * a);
        }

        w1 = (w1 + 1) / 2;

        var w2 = 1 - w1;

        var rgba = {
            r: rgb2.r * w1 + rgb1.r * w2,
            g: rgb2.g * w1 + rgb1.g * w2,
            b: rgb2.b * w1 + rgb1.b * w2,
            a: rgb2.a * p  + rgb1.a * (1 - p)
        };

        return tinycolor(rgba);
    };


    // Readability Functions
    // ---------------------
    // <http://www.w3.org/TR/AERT#color-contrast>

    // `readability`
    // Analyze the 2 colors and returns an object with the following properties:
    //    `brightness`: difference in brightness between the two colors
    //    `color`: difference in color/hue between the two colors
    tinycolor.readability = function(color1, color2) {
        var c1 = tinycolor(color1);
        var c2 = tinycolor(color2);
        var rgb1 = c1.toRgb();
        var rgb2 = c2.toRgb();
        var brightnessA = c1.getBrightness();
        var brightnessB = c2.getBrightness();
        var colorDiff = (
            Math.max(rgb1.r, rgb2.r) - Math.min(rgb1.r, rgb2.r) +
            Math.max(rgb1.g, rgb2.g) - Math.min(rgb1.g, rgb2.g) +
            Math.max(rgb1.b, rgb2.b) - Math.min(rgb1.b, rgb2.b)
        );

        return {
            brightness: Math.abs(brightnessA - brightnessB),
            color: colorDiff
        };
    };

    // `readable`
    // http://www.w3.org/TR/AERT#color-contrast
    // Ensure that foreground and background color combinations provide sufficient contrast.
    // *Example*
    //    tinycolor.isReadable("#000", "#111") => false
    tinycolor.isReadable = function(color1, color2) {
        var readability = tinycolor.readability(color1, color2);
        return readability.brightness > 125 && readability.color > 500;
    };

    // `mostReadable`
    // Given a base color and a list of possible foreground or background
    // colors for that base, returns the most readable color.
    // *Example*
    //    tinycolor.mostReadable("#123", ["#fff", "#000"]) => "#000"
    tinycolor.mostReadable = function(baseColor, colorList) {
        var bestColor = null;
        var bestScore = 0;
        var bestIsReadable = false;
        for (var i=0; i < colorList.length; i++) {

            // We normalize both around the "acceptable" breaking point,
            // but rank brightness constrast higher than hue.

            var readability = tinycolor.readability(baseColor, colorList[i]);
            var readable = readability.brightness > 125 && readability.color > 500;
            var score = 3 * (readability.brightness / 125) + (readability.color / 500);

            if ((readable && ! bestIsReadable) ||
                (readable && bestIsReadable && score > bestScore) ||
                ((! readable) && (! bestIsReadable) && score > bestScore)) {
                bestIsReadable = readable;
                bestScore = score;
                bestColor = tinycolor(colorList[i]);
            }
        }
        return bestColor;
    };


    // Big List of Colors
    // ------------------
    // <http://www.w3.org/TR/css3-color/#svg-color>
    var names = tinycolor.names = {
        aliceblue: "f0f8ff",
        antiquewhite: "faebd7",
        aqua: "0ff",
        aquamarine: "7fffd4",
        azure: "f0ffff",
        beige: "f5f5dc",
        bisque: "ffe4c4",
        black: "000",
        blanchedalmond: "ffebcd",
        blue: "00f",
        blueviolet: "8a2be2",
        brown: "a52a2a",
        burlywood: "deb887",
        burntsienna: "ea7e5d",
        cadetblue: "5f9ea0",
        chartreuse: "7fff00",
        chocolate: "d2691e",
        coral: "ff7f50",
        cornflowerblue: "6495ed",
        cornsilk: "fff8dc",
        crimson: "dc143c",
        cyan: "0ff",
        darkblue: "00008b",
        darkcyan: "008b8b",
        darkgoldenrod: "b8860b",
        darkgray: "a9a9a9",
        darkgreen: "006400",
        darkgrey: "a9a9a9",
        darkkhaki: "bdb76b",
        darkmagenta: "8b008b",
        darkolivegreen: "556b2f",
        darkorange: "ff8c00",
        darkorchid: "9932cc",
        darkred: "8b0000",
        darksalmon: "e9967a",
        darkseagreen: "8fbc8f",
        darkslateblue: "483d8b",
        darkslategray: "2f4f4f",
        darkslategrey: "2f4f4f",
        darkturquoise: "00ced1",
        darkviolet: "9400d3",
        deeppink: "ff1493",
        deepskyblue: "00bfff",
        dimgray: "696969",
        dimgrey: "696969",
        dodgerblue: "1e90ff",
        firebrick: "b22222",
        floralwhite: "fffaf0",
        forestgreen: "228b22",
        fuchsia: "f0f",
        gainsboro: "dcdcdc",
        ghostwhite: "f8f8ff",
        gold: "ffd700",
        goldenrod: "daa520",
        gray: "808080",
        green: "008000",
        greenyellow: "adff2f",
        grey: "808080",
        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",
        lightgray: "d3d3d3",
        lightgreen: "90ee90",
        lightgrey: "d3d3d3",
        lightpink: "ffb6c1",
        lightsalmon: "ffa07a",
        lightseagreen: "20b2aa",
        lightskyblue: "87cefa",
        lightslategray: "789",
        lightslategrey: "789",
        lightsteelblue: "b0c4de",
        lightyellow: "ffffe0",
        lime: "0f0",
        limegreen: "32cd32",
        linen: "faf0e6",
        magenta: "f0f",
        maroon: "800000",
        mediumaquamarine: "66cdaa",
        mediumblue: "0000cd",
        mediumorchid: "ba55d3",
        mediumpurple: "9370db",
        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: "db7093",
        papayawhip: "ffefd5",
        peachpuff: "ffdab9",
        peru: "cd853f",
        pink: "ffc0cb",
        plum: "dda0dd",
        powderblue: "b0e0e6",
        purple: "800080",
        rebeccapurple: "663399",
        red: "f00",
        rosybrown: "bc8f8f",
        royalblue: "4169e1",
        saddlebrown: "8b4513",
        salmon: "fa8072",
        sandybrown: "f4a460",
        seagreen: "2e8b57",
        seashell: "fff5ee",
        sienna: "a0522d",
        silver: "c0c0c0",
        skyblue: "87ceeb",
        slateblue: "6a5acd",
        slategray: "708090",
        slategrey: "708090",
        snow: "fffafa",
        springgreen: "00ff7f",
        steelblue: "4682b4",
        tan: "d2b48c",
        teal: "008080",
        thistle: "d8bfd8",
        tomato: "ff6347",
        turquoise: "40e0d0",
        violet: "ee82ee",
        wheat: "f5deb3",
        white: "fff",
        whitesmoke: "f5f5f5",
        yellow: "ff0",
        yellowgreen: "9acd32"
    };

    // Make it easy to access colors via `hexNames[hex]`
    var hexNames = tinycolor.hexNames = flip(names);


    // Utilities
    // ---------

    // `{ 'name1': 'val1' }` becomes `{ 'val1': 'name1' }`
    function flip(o) {
        var flipped = { };
        for (var i in o) {
            if (o.hasOwnProperty(i)) {
                flipped[o[i]] = i;
            }
        }
        return flipped;
    }

    // Return a valid alpha value [0,1] with all invalid values being set to 1
    function boundAlpha(a) {
        a = parseFloat(a);

        if (isNaN(a) || a < 0 || a > 1) {
            a = 1;
        }

        return a;
    }

    // Take input from [0, n] and return it as [0, 1]
    function bound01(n, max) {
        if (isOnePointZero(n)) { n = "100%"; }

        var processPercent = isPercentage(n);
        n = mathMin(max, mathMax(0, parseFloat(n)));

        // Automatically convert percentage into number
        if (processPercent) {
            n = parseInt(n * max, 10) / 100;
        }

        // Handle floating point rounding errors
        if ((math.abs(n - max) < 0.000001)) {
            return 1;
        }

        // Convert into [0, 1] range if it isn't already
        return (n % max) / parseFloat(max);
    }

    // Force a number between 0 and 1
    function clamp01(val) {
        return mathMin(1, mathMax(0, val));
    }

    // Parse a base-16 hex value into a base-10 integer
    function parseIntFromHex(val) {
        return parseInt(val, 16);
    }

    // Need to handle 1.0 as 100%, since once it is a number, there is no difference between it and 1
    // <http://stackoverflow.com/questions/7422072/javascript-how-to-detect-number-as-a-decimal-including-1-0>
    function isOnePointZero(n) {
        return typeof n == "string" && n.indexOf('.') != -1 && parseFloat(n) === 1;
    }

    // Check to see if string passed in is a percentage
    function isPercentage(n) {
        return typeof n === "string" && n.indexOf('%') != -1;
    }

    // Force a hex value to have 2 characters
    function pad2(c) {
        return c.length == 1 ? '0' + c : '' + c;
    }

    // Replace a decimal with it's percentage value
    function convertToPercentage(n) {
        if (n <= 1) {
            n = (n * 100) + "%";
        }

        return n;
    }

    // Converts a decimal to a hex value
    function convertDecimalToHex(d) {
        return Math.round(parseFloat(d) * 255).toString(16);
    }
    // Converts a hex value to a decimal
    function convertHexToDecimal(h) {
        return (parseIntFromHex(h) / 255);
    }

    var matchers = (function() {

        // <http://www.w3.org/TR/css3-values/#integers>
        var CSS_INTEGER = "[-\\+]?\\d+%?";

        // <http://www.w3.org/TR/css3-values/#number-value>
        var CSS_NUMBER = "[-\\+]?\\d*\\.\\d+%?";

        // Allow positive/negative integer/number.  Don't capture the either/or, just the entire outcome.
        var CSS_UNIT = "(?:" + CSS_NUMBER + ")|(?:" + CSS_INTEGER + ")";

        // Actual matching.
        // Parentheses and commas are optional, but not required.
        // Whitespace can take the place of commas or opening paren
        var PERMISSIVE_MATCH3 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?";
        var PERMISSIVE_MATCH4 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?";

        return {
            rgb: new RegExp("rgb" + PERMISSIVE_MATCH3),
            rgba: new RegExp("rgba" + PERMISSIVE_MATCH4),
            hsl: new RegExp("hsl" + PERMISSIVE_MATCH3),
            hsla: new RegExp("hsla" + PERMISSIVE_MATCH4),
            hsv: new RegExp("hsv" + PERMISSIVE_MATCH3),
            hsva: new RegExp("hsva" + PERMISSIVE_MATCH4),
            hex3: /^([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,
            hex6: /^([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/,
            hex8: /^([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/
        };
    })();

    // `stringInputToObject`
    // Permissive string parsing.  Take in a number of formats, and output an object
    // based on detected format.  Returns `{ r, g, b }` or `{ h, s, l }` or `{ h, s, v}`
    function stringInputToObject(color) {

        color = color.replace(trimLeft,'').replace(trimRight, '').toLowerCase();
        var named = false;
        if (names[color]) {
            color = names[color];
            named = true;
        }
        else if (color == 'transparent') {
            return { r: 0, g: 0, b: 0, a: 0, format: "name" };
        }

        // Try to match string input using regular expressions.
        // Keep most of the number bounding out of this function - don't worry about [0,1] or [0,100] or [0,360]
        // Just return an object and let the conversion functions handle that.
        // This way the result will be the same whether the tinycolor is initialized with string or object.
        var match;
        if ((match = matchers.rgb.exec(color))) {
            return { r: match[1], g: match[2], b: match[3] };
        }
        if ((match = matchers.rgba.exec(color))) {
            return { r: match[1], g: match[2], b: match[3], a: match[4] };
        }
        if ((match = matchers.hsl.exec(color))) {
            return { h: match[1], s: match[2], l: match[3] };
        }
        if ((match = matchers.hsla.exec(color))) {
            return { h: match[1], s: match[2], l: match[3], a: match[4] };
        }
        if ((match = matchers.hsv.exec(color))) {
            return { h: match[1], s: match[2], v: match[3] };
        }
        if ((match = matchers.hsva.exec(color))) {
            return { h: match[1], s: match[2], v: match[3], a: match[4] };
        }
        if ((match = matchers.hex8.exec(color))) {
            return {
                a: convertHexToDecimal(match[1]),
                r: parseIntFromHex(match[2]),
                g: parseIntFromHex(match[3]),
                b: parseIntFromHex(match[4]),
                format: named ? "name" : "hex8"
            };
        }
        if ((match = matchers.hex6.exec(color))) {
            return {
                r: parseIntFromHex(match[1]),
                g: parseIntFromHex(match[2]),
                b: parseIntFromHex(match[3]),
                format: named ? "name" : "hex"
            };
        }
        if ((match = matchers.hex3.exec(color))) {
            return {
                r: parseIntFromHex(match[1] + '' + match[1]),
                g: parseIntFromHex(match[2] + '' + match[2]),
                b: parseIntFromHex(match[3] + '' + match[3]),
                format: named ? "name" : "hex"
            };
        }

        return false;
    }

    window.tinycolor = tinycolor;
    })();

    $(function () {
        if ($.fn.spectrum.load) {
            $.fn.spectrum.processNativeColorInputs();
        }
    });

});

/* Web Font Loader v1.6.27 - (c) Adobe Systems, Google. License: Apache 2.0 */(function(){function aa(a,b,c){return a.call.apply(a.bind,arguments)}function ba(a,b,c){if(!a)throw Error();if(2<arguments.length){var d=Array.prototype.slice.call(arguments,2);return function(){var c=Array.prototype.slice.call(arguments);Array.prototype.unshift.apply(c,d);return a.apply(b,c)}}return function(){return a.apply(b,arguments)}}function p(a,b,c){p=Function.prototype.bind&&-1!=Function.prototype.bind.toString().indexOf("native code")?aa:ba;return p.apply(null,arguments)}var q=Date.now||function(){return+new Date};function ca(a,b){this.a=a;this.m=b||a;this.c=this.m.document}var da=!!window.FontFace;function t(a,b,c,d){b=a.c.createElement(b);if(c)for(var e in c)c.hasOwnProperty(e)&&("style"==e?b.style.cssText=c[e]:b.setAttribute(e,c[e]));d&&b.appendChild(a.c.createTextNode(d));return b}function u(a,b,c){a=a.c.getElementsByTagName(b)[0];a||(a=document.documentElement);a.insertBefore(c,a.lastChild)}function v(a){a.parentNode&&a.parentNode.removeChild(a)}
function w(a,b,c){b=b||[];c=c||[];for(var d=a.className.split(/\s+/),e=0;e<b.length;e+=1){for(var f=!1,g=0;g<d.length;g+=1)if(b[e]===d[g]){f=!0;break}f||d.push(b[e])}b=[];for(e=0;e<d.length;e+=1){f=!1;for(g=0;g<c.length;g+=1)if(d[e]===c[g]){f=!0;break}f||b.push(d[e])}a.className=b.join(" ").replace(/\s+/g," ").replace(/^\s+|\s+$/,"")}function y(a,b){for(var c=a.className.split(/\s+/),d=0,e=c.length;d<e;d++)if(c[d]==b)return!0;return!1}
function z(a){if("string"===typeof a.f)return a.f;var b=a.m.location.protocol;"about:"==b&&(b=a.a.location.protocol);return"https:"==b?"https:":"http:"}function ea(a){return a.m.location.hostname||a.a.location.hostname}
function A(a,b,c){function d(){k&&e&&f&&(k(g),k=null)}b=t(a,"link",{rel:"stylesheet",href:b,media:"all"});var e=!1,f=!0,g=null,k=c||null;da?(b.onload=function(){e=!0;d()},b.onerror=function(){e=!0;g=Error("Stylesheet failed to load");d()}):setTimeout(function(){e=!0;d()},0);u(a,"head",b)}
function B(a,b,c,d){var e=a.c.getElementsByTagName("head")[0];if(e){var f=t(a,"script",{src:b}),g=!1;f.onload=f.onreadystatechange=function(){g||this.readyState&&"loaded"!=this.readyState&&"complete"!=this.readyState||(g=!0,c&&c(null),f.onload=f.onreadystatechange=null,"HEAD"==f.parentNode.tagName&&e.removeChild(f))};e.appendChild(f);setTimeout(function(){g||(g=!0,c&&c(Error("Script load timeout")))},d||5E3);return f}return null};function C(){this.a=0;this.c=null}function D(a){a.a++;return function(){a.a--;E(a)}}function F(a,b){a.c=b;E(a)}function E(a){0==a.a&&a.c&&(a.c(),a.c=null)};function G(a){this.a=a||"-"}G.prototype.c=function(a){for(var b=[],c=0;c<arguments.length;c++)b.push(arguments[c].replace(/[\W_]+/g,"").toLowerCase());return b.join(this.a)};function H(a,b){this.c=a;this.f=4;this.a="n";var c=(b||"n4").match(/^([nio])([1-9])$/i);c&&(this.a=c[1],this.f=parseInt(c[2],10))}function fa(a){return I(a)+" "+(a.f+"00")+" 300px "+J(a.c)}function J(a){var b=[];a=a.split(/,\s*/);for(var c=0;c<a.length;c++){var d=a[c].replace(/['"]/g,"");-1!=d.indexOf(" ")||/^\d/.test(d)?b.push("'"+d+"'"):b.push(d)}return b.join(",")}function K(a){return a.a+a.f}function I(a){var b="normal";"o"===a.a?b="oblique":"i"===a.a&&(b="italic");return b}
function ga(a){var b=4,c="n",d=null;a&&((d=a.match(/(normal|oblique|italic)/i))&&d[1]&&(c=d[1].substr(0,1).toLowerCase()),(d=a.match(/([1-9]00|normal|bold)/i))&&d[1]&&(/bold/i.test(d[1])?b=7:/[1-9]00/.test(d[1])&&(b=parseInt(d[1].substr(0,1),10))));return c+b};function ha(a,b){this.c=a;this.f=a.m.document.documentElement;this.h=b;this.a=new G("-");this.j=!1!==b.events;this.g=!1!==b.classes}function ia(a){a.g&&w(a.f,[a.a.c("wf","loading")]);L(a,"loading")}function M(a){if(a.g){var b=y(a.f,a.a.c("wf","active")),c=[],d=[a.a.c("wf","loading")];b||c.push(a.a.c("wf","inactive"));w(a.f,c,d)}L(a,"inactive")}function L(a,b,c){if(a.j&&a.h[b])if(c)a.h[b](c.c,K(c));else a.h[b]()};function ja(){this.c={}}function ka(a,b,c){var d=[],e;for(e in b)if(b.hasOwnProperty(e)){var f=a.c[e];f&&d.push(f(b[e],c))}return d};function N(a,b){this.c=a;this.f=b;this.a=t(this.c,"span",{"aria-hidden":"true"},this.f)}function O(a){u(a.c,"body",a.a)}function P(a){return"display:block;position:absolute;top:-9999px;left:-9999px;font-size:300px;width:auto;height:auto;line-height:normal;margin:0;padding:0;font-variant:normal;white-space:nowrap;font-family:"+J(a.c)+";"+("font-style:"+I(a)+";font-weight:"+(a.f+"00")+";")};function Q(a,b,c,d,e,f){this.g=a;this.j=b;this.a=d;this.c=c;this.f=e||3E3;this.h=f||void 0}Q.prototype.start=function(){var a=this.c.m.document,b=this,c=q(),d=new Promise(function(d,e){function k(){q()-c>=b.f?e():a.fonts.load(fa(b.a),b.h).then(function(a){1<=a.length?d():setTimeout(k,25)},function(){e()})}k()}),e=new Promise(function(a,d){setTimeout(d,b.f)});Promise.race([e,d]).then(function(){b.g(b.a)},function(){b.j(b.a)})};function R(a,b,c,d,e,f,g){this.v=a;this.B=b;this.c=c;this.a=d;this.s=g||"BESbswy";this.f={};this.w=e||3E3;this.u=f||null;this.o=this.j=this.h=this.g=null;this.g=new N(this.c,this.s);this.h=new N(this.c,this.s);this.j=new N(this.c,this.s);this.o=new N(this.c,this.s);a=new H(this.a.c+",serif",K(this.a));a=P(a);this.g.a.style.cssText=a;a=new H(this.a.c+",sans-serif",K(this.a));a=P(a);this.h.a.style.cssText=a;a=new H("serif",K(this.a));a=P(a);this.j.a.style.cssText=a;a=new H("sans-serif",K(this.a));a=
P(a);this.o.a.style.cssText=a;O(this.g);O(this.h);O(this.j);O(this.o)}var S={D:"serif",C:"sans-serif"},T=null;function U(){if(null===T){var a=/AppleWebKit\/([0-9]+)(?:\.([0-9]+))/.exec(window.navigator.userAgent);T=!!a&&(536>parseInt(a[1],10)||536===parseInt(a[1],10)&&11>=parseInt(a[2],10))}return T}R.prototype.start=function(){this.f.serif=this.j.a.offsetWidth;this.f["sans-serif"]=this.o.a.offsetWidth;this.A=q();la(this)};
function ma(a,b,c){for(var d in S)if(S.hasOwnProperty(d)&&b===a.f[S[d]]&&c===a.f[S[d]])return!0;return!1}function la(a){var b=a.g.a.offsetWidth,c=a.h.a.offsetWidth,d;(d=b===a.f.serif&&c===a.f["sans-serif"])||(d=U()&&ma(a,b,c));d?q()-a.A>=a.w?U()&&ma(a,b,c)&&(null===a.u||a.u.hasOwnProperty(a.a.c))?V(a,a.v):V(a,a.B):na(a):V(a,a.v)}function na(a){setTimeout(p(function(){la(this)},a),50)}function V(a,b){setTimeout(p(function(){v(this.g.a);v(this.h.a);v(this.j.a);v(this.o.a);b(this.a)},a),0)};function W(a,b,c){this.c=a;this.a=b;this.f=0;this.o=this.j=!1;this.s=c}var X=null;W.prototype.g=function(a){var b=this.a;b.g&&w(b.f,[b.a.c("wf",a.c,K(a).toString(),"active")],[b.a.c("wf",a.c,K(a).toString(),"loading"),b.a.c("wf",a.c,K(a).toString(),"inactive")]);L(b,"fontactive",a);this.o=!0;oa(this)};
W.prototype.h=function(a){var b=this.a;if(b.g){var c=y(b.f,b.a.c("wf",a.c,K(a).toString(),"active")),d=[],e=[b.a.c("wf",a.c,K(a).toString(),"loading")];c||d.push(b.a.c("wf",a.c,K(a).toString(),"inactive"));w(b.f,d,e)}L(b,"fontinactive",a);oa(this)};function oa(a){0==--a.f&&a.j&&(a.o?(a=a.a,a.g&&w(a.f,[a.a.c("wf","active")],[a.a.c("wf","loading"),a.a.c("wf","inactive")]),L(a,"active")):M(a.a))};function pa(a){this.j=a;this.a=new ja;this.h=0;this.f=this.g=!0}pa.prototype.load=function(a){this.c=new ca(this.j,a.context||this.j);this.g=!1!==a.events;this.f=!1!==a.classes;qa(this,new ha(this.c,a),a)};
function ra(a,b,c,d,e){var f=0==--a.h;(a.f||a.g)&&setTimeout(function(){var a=e||null,k=d||null||{};if(0===c.length&&f)M(b.a);else{b.f+=c.length;f&&(b.j=f);var h,m=[];for(h=0;h<c.length;h++){var l=c[h],n=k[l.c],r=b.a,x=l;r.g&&w(r.f,[r.a.c("wf",x.c,K(x).toString(),"loading")]);L(r,"fontloading",x);r=null;if(null===X)if(window.FontFace){var x=/Gecko.*Firefox\/(\d+)/.exec(window.navigator.userAgent),ya=/OS X.*Version\/10\..*Safari/.exec(window.navigator.userAgent)&&/Apple/.exec(window.navigator.vendor);
X=x?42<parseInt(x[1],10):ya?!1:!0}else X=!1;X?r=new Q(p(b.g,b),p(b.h,b),b.c,l,b.s,n):r=new R(p(b.g,b),p(b.h,b),b.c,l,b.s,a,n);m.push(r)}for(h=0;h<m.length;h++)m[h].start()}},0)}function qa(a,b,c){var d=[],e=c.timeout;ia(b);var d=ka(a.a,c,a.c),f=new W(a.c,b,e);a.h=d.length;b=0;for(c=d.length;b<c;b++)d[b].load(function(b,d,c){ra(a,f,b,d,c)})};function sa(a,b){this.c=a;this.a=b}function ta(a,b,c){var d=z(a.c);a=(a.a.api||"fast.fonts.net/jsapi").replace(/^.*http(s?):(\/\/)?/,"");return d+"//"+a+"/"+b+".js"+(c?"?v="+c:"")}
sa.prototype.load=function(a){function b(){if(f["__mti_fntLst"+d]){var c=f["__mti_fntLst"+d](),e=[],h;if(c)for(var m=0;m<c.length;m++){var l=c[m].fontfamily;void 0!=c[m].fontStyle&&void 0!=c[m].fontWeight?(h=c[m].fontStyle+c[m].fontWeight,e.push(new H(l,h))):e.push(new H(l))}a(e)}else setTimeout(function(){b()},50)}var c=this,d=c.a.projectId,e=c.a.version;if(d){var f=c.c.m;B(this.c,ta(c,d,e),function(e){e?a([]):(f["__MonotypeConfiguration__"+d]=function(){return c.a},b())}).id="__MonotypeAPIScript__"+
d}else a([])};function ua(a,b){this.c=a;this.a=b}ua.prototype.load=function(a){var b,c,d=this.a.urls||[],e=this.a.families||[],f=this.a.testStrings||{},g=new C;b=0;for(c=d.length;b<c;b++)A(this.c,d[b],D(g));var k=[];b=0;for(c=e.length;b<c;b++)if(d=e[b].split(":"),d[1])for(var h=d[1].split(","),m=0;m<h.length;m+=1)k.push(new H(d[0],h[m]));else k.push(new H(d[0]));F(g,function(){a(k,f)})};function va(a,b,c){a?this.c=a:this.c=b+wa;this.a=[];this.f=[];this.g=c||""}var wa="//fonts.googleapis.com/css";function xa(a,b){for(var c=b.length,d=0;d<c;d++){var e=b[d].split(":");3==e.length&&a.f.push(e.pop());var f="";2==e.length&&""!=e[1]&&(f=":");a.a.push(e.join(f))}}
function za(a){if(0==a.a.length)throw Error("No fonts to load!");if(-1!=a.c.indexOf("kit="))return a.c;for(var b=a.a.length,c=[],d=0;d<b;d++)c.push(a.a[d].replace(/ /g,"+"));b=a.c+"?family="+c.join("%7C");0<a.f.length&&(b+="&subset="+a.f.join(","));0<a.g.length&&(b+="&text="+encodeURIComponent(a.g));return b};function Aa(a){this.f=a;this.a=[];this.c={}}
var Ba={latin:"BESbswy","latin-ext":"\u00e7\u00f6\u00fc\u011f\u015f",cyrillic:"\u0439\u044f\u0416",greek:"\u03b1\u03b2\u03a3",khmer:"\u1780\u1781\u1782",Hanuman:"\u1780\u1781\u1782"},Ca={thin:"1",extralight:"2","extra-light":"2",ultralight:"2","ultra-light":"2",light:"3",regular:"4",book:"4",medium:"5","semi-bold":"6",semibold:"6","demi-bold":"6",demibold:"6",bold:"7","extra-bold":"8",extrabold:"8","ultra-bold":"8",ultrabold:"8",black:"9",heavy:"9",l:"3",r:"4",b:"7"},Da={i:"i",italic:"i",n:"n",normal:"n"},
Ea=/^(thin|(?:(?:extra|ultra)-?)?light|regular|book|medium|(?:(?:semi|demi|extra|ultra)-?)?bold|black|heavy|l|r|b|[1-9]00)?(n|i|normal|italic)?$/;
function Fa(a){for(var b=a.f.length,c=0;c<b;c++){var d=a.f[c].split(":"),e=d[0].replace(/\+/g," "),f=["n4"];if(2<=d.length){var g;var k=d[1];g=[];if(k)for(var k=k.split(","),h=k.length,m=0;m<h;m++){var l;l=k[m];if(l.match(/^[\w-]+$/)){var n=Ea.exec(l.toLowerCase());if(null==n)l="";else{l=n[2];l=null==l||""==l?"n":Da[l];n=n[1];if(null==n||""==n)n="4";else var r=Ca[n],n=r?r:isNaN(n)?"4":n.substr(0,1);l=[l,n].join("")}}else l="";l&&g.push(l)}0<g.length&&(f=g);3==d.length&&(d=d[2],g=[],d=d?d.split(","):
g,0<d.length&&(d=Ba[d[0]])&&(a.c[e]=d))}a.c[e]||(d=Ba[e])&&(a.c[e]=d);for(d=0;d<f.length;d+=1)a.a.push(new H(e,f[d]))}};function Ga(a,b){this.c=a;this.a=b}var Ha={Arimo:!0,Cousine:!0,Tinos:!0};Ga.prototype.load=function(a){var b=new C,c=this.c,d=new va(this.a.api,z(c),this.a.text),e=this.a.families;xa(d,e);var f=new Aa(e);Fa(f);A(c,za(d),D(b));F(b,function(){a(f.a,f.c,Ha)})};function Ia(a,b){this.c=a;this.a=b}Ia.prototype.load=function(a){var b=this.a.id,c=this.c.m;b?B(this.c,(this.a.api||"https://use.typekit.net")+"/"+b+".js",function(b){if(b)a([]);else if(c.Typekit&&c.Typekit.config&&c.Typekit.config.fn){b=c.Typekit.config.fn;for(var e=[],f=0;f<b.length;f+=2)for(var g=b[f],k=b[f+1],h=0;h<k.length;h++)e.push(new H(g,k[h]));try{c.Typekit.load({events:!1,classes:!1,async:!0})}catch(m){}a(e)}},2E3):a([])};function Ja(a,b){this.c=a;this.f=b;this.a=[]}Ja.prototype.load=function(a){var b=this.f.id,c=this.c.m,d=this;b?(c.__webfontfontdeckmodule__||(c.__webfontfontdeckmodule__={}),c.__webfontfontdeckmodule__[b]=function(b,c){for(var g=0,k=c.fonts.length;g<k;++g){var h=c.fonts[g];d.a.push(new H(h.name,ga("font-weight:"+h.weight+";font-style:"+h.style)))}a(d.a)},B(this.c,z(this.c)+(this.f.api||"//f.fontdeck.com/s/css/js/")+ea(this.c)+"/"+b+".js",function(b){b&&a([])})):a([])};var Y=new pa(window);Y.a.c.custom=function(a,b){return new ua(b,a)};Y.a.c.fontdeck=function(a,b){return new Ja(b,a)};Y.a.c.monotype=function(a,b){return new sa(b,a)};Y.a.c.typekit=function(a,b){return new Ia(b,a)};Y.a.c.google=function(a,b){return new Ga(b,a)};var Z={load:p(Y.load,Y)};"function"===typeof define&&define.amd?define(function(){return Z}):"undefined"!==typeof module&&module.exports?module.exports=Z:(window.WebFont=Z,window.WebFontConfig&&Y.load(window.WebFontConfig));}());