var _typeof2=typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"?function(obj){return typeof obj;}:function(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj;};/*!
 * pixi.js - v4.3.2
 * Compiled Mon, 09 Jan 2017 14:35:08 UTC
 *
 * pixi.js is licensed under the MIT License.
 * http://www.opensource.org/licenses/mit-license
 */(function(f){if((typeof exports==="undefined"?"undefined":_typeof2(exports))==="object"&&typeof module!=="undefined"){module.exports=f();}else if(typeof define==="function"&&define.amd){define([],f);}else{var g;if(typeof window!=="undefined"){g=window;}else if(typeof global!=="undefined"){g=global;}else if(typeof self!=="undefined"){g=self;}else{g=this;}g.PIXI=f();}})(function(){var define,module,exports;return function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f;}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e);},l,l.exports,e,t,n,r);}return n[o].exports;}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++){s(r[o]);}return s;}({1:[function(require,module,exports){/**
 * Bit twiddling hacks for JavaScript.
 *
 * Author: Mikola Lysenko
 *
 * Ported from Stanford bit twiddling hack library:
 *    http://graphics.stanford.edu/~seander/bithacks.html
 */"use strict";"use restrict";//Number of bits in an integer
var INT_BITS=32;//Constants
exports.INT_BITS=INT_BITS;exports.INT_MAX=0x7fffffff;exports.INT_MIN=-1<<INT_BITS-1;//Returns -1, 0, +1 depending on sign of x
exports.sign=function(v){return(v>0)-(v<0);};//Computes absolute value of integer
exports.abs=function(v){var mask=v>>INT_BITS-1;return(v^mask)-mask;};//Computes minimum of integers x and y
exports.min=function(x,y){return y^(x^y)&-(x<y);};//Computes maximum of integers x and y
exports.max=function(x,y){return x^(x^y)&-(x<y);};//Checks if a number is a power of two
exports.isPow2=function(v){return!(v&v-1)&&!!v;};//Computes log base 2 of v
exports.log2=function(v){var r,shift;r=(v>0xFFFF)<<4;v>>>=r;shift=(v>0xFF)<<3;v>>>=shift;r|=shift;shift=(v>0xF)<<2;v>>>=shift;r|=shift;shift=(v>0x3)<<1;v>>>=shift;r|=shift;return r|v>>1;};//Computes log base 10 of v
exports.log10=function(v){return v>=1000000000?9:v>=100000000?8:v>=10000000?7:v>=1000000?6:v>=100000?5:v>=10000?4:v>=1000?3:v>=100?2:v>=10?1:0;};//Counts number of bits
exports.popCount=function(v){v=v-(v>>>1&0x55555555);v=(v&0x33333333)+(v>>>2&0x33333333);return(v+(v>>>4)&0xF0F0F0F)*0x1010101>>>24;};//Counts number of trailing zeros
function countTrailingZeros(v){var c=32;v&=-v;if(v)c--;if(v&0x0000FFFF)c-=16;if(v&0x00FF00FF)c-=8;if(v&0x0F0F0F0F)c-=4;if(v&0x33333333)c-=2;if(v&0x55555555)c-=1;return c;}exports.countTrailingZeros=countTrailingZeros;//Rounds to next power of 2
exports.nextPow2=function(v){v+=v===0;--v;v|=v>>>1;v|=v>>>2;v|=v>>>4;v|=v>>>8;v|=v>>>16;return v+1;};//Rounds down to previous power of 2
exports.prevPow2=function(v){v|=v>>>1;v|=v>>>2;v|=v>>>4;v|=v>>>8;v|=v>>>16;return v-(v>>>1);};//Computes parity of word
exports.parity=function(v){v^=v>>>16;v^=v>>>8;v^=v>>>4;v&=0xf;return 0x6996>>>v&1;};var REVERSE_TABLE=new Array(256);(function(tab){for(var i=0;i<256;++i){var v=i,r=i,s=7;for(v>>>=1;v;v>>>=1){r<<=1;r|=v&1;--s;}tab[i]=r<<s&0xff;}})(REVERSE_TABLE);//Reverse bits in a 32 bit word
exports.reverse=function(v){return REVERSE_TABLE[v&0xff]<<24|REVERSE_TABLE[v>>>8&0xff]<<16|REVERSE_TABLE[v>>>16&0xff]<<8|REVERSE_TABLE[v>>>24&0xff];};//Interleave bits of 2 coordinates with 16 bits.  Useful for fast quadtree codes
exports.interleave2=function(x,y){x&=0xFFFF;x=(x|x<<8)&0x00FF00FF;x=(x|x<<4)&0x0F0F0F0F;x=(x|x<<2)&0x33333333;x=(x|x<<1)&0x55555555;y&=0xFFFF;y=(y|y<<8)&0x00FF00FF;y=(y|y<<4)&0x0F0F0F0F;y=(y|y<<2)&0x33333333;y=(y|y<<1)&0x55555555;return x|y<<1;};//Extracts the nth interleaved component
exports.deinterleave2=function(v,n){v=v>>>n&0x55555555;v=(v|v>>>1)&0x33333333;v=(v|v>>>2)&0x0F0F0F0F;v=(v|v>>>4)&0x00FF00FF;v=(v|v>>>16)&0x000FFFF;return v<<16>>16;};//Interleave bits of 3 coordinates, each with 10 bits.  Useful for fast octree codes
exports.interleave3=function(x,y,z){x&=0x3FF;x=(x|x<<16)&4278190335;x=(x|x<<8)&251719695;x=(x|x<<4)&3272356035;x=(x|x<<2)&1227133513;y&=0x3FF;y=(y|y<<16)&4278190335;y=(y|y<<8)&251719695;y=(y|y<<4)&3272356035;y=(y|y<<2)&1227133513;x|=y<<1;z&=0x3FF;z=(z|z<<16)&4278190335;z=(z|z<<8)&251719695;z=(z|z<<4)&3272356035;z=(z|z<<2)&1227133513;return x|z<<2;};//Extracts nth interleaved component of a 3-tuple
exports.deinterleave3=function(v,n){v=v>>>n&1227133513;v=(v|v>>>2)&3272356035;v=(v|v>>>4)&251719695;v=(v|v>>>8)&4278190335;v=(v|v>>>16)&0x3FF;return v<<22>>22;};//Computes next combination in colexicographic order (this is mistakenly called nextPermutation on the bit twiddling hacks page)
exports.nextCombination=function(v){var t=v|v-1;return t+1|(~t&-~t)-1>>>countTrailingZeros(v)+1;};},{}],2:[function(require,module,exports){'use strict';module.exports=earcut;function earcut(data,holeIndices,dim){dim=dim||2;var hasHoles=holeIndices&&holeIndices.length,outerLen=hasHoles?holeIndices[0]*dim:data.length,outerNode=linkedList(data,0,outerLen,dim,true),triangles=[];if(!outerNode)return triangles;var minX,minY,maxX,maxY,x,y,size;if(hasHoles)outerNode=eliminateHoles(data,holeIndices,outerNode,dim);// if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
if(data.length>80*dim){minX=maxX=data[0];minY=maxY=data[1];for(var i=dim;i<outerLen;i+=dim){x=data[i];y=data[i+1];if(x<minX)minX=x;if(y<minY)minY=y;if(x>maxX)maxX=x;if(y>maxY)maxY=y;}// minX, minY and size are later used to transform coords into integers for z-order calculation
size=Math.max(maxX-minX,maxY-minY);}earcutLinked(outerNode,triangles,dim,minX,minY,size);return triangles;}// create a circular doubly linked list from polygon points in the specified winding order
function linkedList(data,start,end,dim,clockwise){var i,last;if(clockwise===signedArea(data,start,end,dim)>0){for(i=start;i<end;i+=dim){last=insertNode(i,data[i],data[i+1],last);}}else{for(i=end-dim;i>=start;i-=dim){last=insertNode(i,data[i],data[i+1],last);}}if(last&&equals(last,last.next)){removeNode(last);last=last.next;}return last;}// eliminate colinear or duplicate points
function filterPoints(start,end){if(!start)return start;if(!end)end=start;var p=start,again;do{again=false;if(!p.steiner&&(equals(p,p.next)||area(p.prev,p,p.next)===0)){removeNode(p);p=end=p.prev;if(p===p.next)return null;again=true;}else{p=p.next;}}while(again||p!==end);return end;}// main ear slicing loop which triangulates a polygon (given as a linked list)
function earcutLinked(ear,triangles,dim,minX,minY,size,pass){if(!ear)return;// interlink polygon nodes in z-order
if(!pass&&size)indexCurve(ear,minX,minY,size);var stop=ear,prev,next;// iterate through ears, slicing them one by one
while(ear.prev!==ear.next){prev=ear.prev;next=ear.next;if(size?isEarHashed(ear,minX,minY,size):isEar(ear)){// cut off the triangle
triangles.push(prev.i/dim);triangles.push(ear.i/dim);triangles.push(next.i/dim);removeNode(ear);// skipping the next vertice leads to less sliver triangles
ear=next.next;stop=next.next;continue;}ear=next;// if we looped through the whole remaining polygon and can't find any more ears
if(ear===stop){// try filtering points and slicing again
if(!pass){earcutLinked(filterPoints(ear),triangles,dim,minX,minY,size,1);// if this didn't work, try curing all small self-intersections locally
}else if(pass===1){ear=cureLocalIntersections(ear,triangles,dim);earcutLinked(ear,triangles,dim,minX,minY,size,2);// as a last resort, try splitting the remaining polygon into two
}else if(pass===2){splitEarcut(ear,triangles,dim,minX,minY,size);}break;}}}// check whether a polygon node forms a valid ear with adjacent nodes
function isEar(ear){var a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return false;// reflex, can't be an ear
// now make sure we don't have other points inside the potential ear
var p=ear.next.next;while(p!==ear.prev){if(pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return false;p=p.next;}return true;}function isEarHashed(ear,minX,minY,size){var a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return false;// reflex, can't be an ear
// triangle bbox; min & max are calculated like this for speed
var minTX=a.x<b.x?a.x<c.x?a.x:c.x:b.x<c.x?b.x:c.x,minTY=a.y<b.y?a.y<c.y?a.y:c.y:b.y<c.y?b.y:c.y,maxTX=a.x>b.x?a.x>c.x?a.x:c.x:b.x>c.x?b.x:c.x,maxTY=a.y>b.y?a.y>c.y?a.y:c.y:b.y>c.y?b.y:c.y;// z-order range for the current triangle bbox;
var minZ=zOrder(minTX,minTY,minX,minY,size),maxZ=zOrder(maxTX,maxTY,minX,minY,size);// first look for points inside the triangle in increasing z-order
var p=ear.nextZ;while(p&&p.z<=maxZ){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return false;p=p.nextZ;}// then look for points in decreasing z-order
p=ear.prevZ;while(p&&p.z>=minZ){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return false;p=p.prevZ;}return true;}// go through all polygon nodes and cure small local self-intersections
function cureLocalIntersections(start,triangles,dim){var p=start;do{var a=p.prev,b=p.next.next;if(!equals(a,b)&&intersects(a,p,p.next,b)&&locallyInside(a,b)&&locallyInside(b,a)){triangles.push(a.i/dim);triangles.push(p.i/dim);triangles.push(b.i/dim);// remove two nodes involved
removeNode(p);removeNode(p.next);p=start=b;}p=p.next;}while(p!==start);return p;}// try splitting polygon into two and triangulate them independently
function splitEarcut(start,triangles,dim,minX,minY,size){// look for a valid diagonal that divides the polygon into two
var a=start;do{var b=a.next.next;while(b!==a.prev){if(a.i!==b.i&&isValidDiagonal(a,b)){// split the polygon in two by the diagonal
var c=splitPolygon(a,b);// filter colinear points around the cuts
a=filterPoints(a,a.next);c=filterPoints(c,c.next);// run earcut on each half
earcutLinked(a,triangles,dim,minX,minY,size);earcutLinked(c,triangles,dim,minX,minY,size);return;}b=b.next;}a=a.next;}while(a!==start);}// link every hole into the outer loop, producing a single-ring polygon without holes
function eliminateHoles(data,holeIndices,outerNode,dim){var queue=[],i,len,start,end,list;for(i=0,len=holeIndices.length;i<len;i++){start=holeIndices[i]*dim;end=i<len-1?holeIndices[i+1]*dim:data.length;list=linkedList(data,start,end,dim,false);if(list===list.next)list.steiner=true;queue.push(getLeftmost(list));}queue.sort(compareX);// process holes from left to right
for(i=0;i<queue.length;i++){eliminateHole(queue[i],outerNode);outerNode=filterPoints(outerNode,outerNode.next);}return outerNode;}function compareX(a,b){return a.x-b.x;}// find a bridge between vertices that connects hole with an outer ring and and link it
function eliminateHole(hole,outerNode){outerNode=findHoleBridge(hole,outerNode);if(outerNode){var b=splitPolygon(outerNode,hole);filterPoints(b,b.next);}}// David Eberly's algorithm for finding a bridge between hole and outer polygon
function findHoleBridge(hole,outerNode){var p=outerNode,hx=hole.x,hy=hole.y,qx=-Infinity,m;// find a segment intersected by a ray from the hole's leftmost point to the left;
// segment's endpoint with lesser x will be potential connection point
do{if(hy<=p.y&&hy>=p.next.y){var x=p.x+(hy-p.y)*(p.next.x-p.x)/(p.next.y-p.y);if(x<=hx&&x>qx){qx=x;if(x===hx){if(hy===p.y)return p;if(hy===p.next.y)return p.next;}m=p.x<p.next.x?p:p.next;}}p=p.next;}while(p!==outerNode);if(!m)return null;if(hx===qx)return m.prev;// hole touches outer segment; pick lower endpoint
// look for points inside the triangle of hole point, segment intersection and endpoint;
// if there are no points found, we have a valid connection;
// otherwise choose the point of the minimum angle with the ray as connection point
var stop=m,mx=m.x,my=m.y,tanMin=Infinity,tan;p=m.next;while(p!==stop){if(hx>=p.x&&p.x>=mx&&pointInTriangle(hy<my?hx:qx,hy,mx,my,hy<my?qx:hx,hy,p.x,p.y)){tan=Math.abs(hy-p.y)/(hx-p.x);// tangential
if((tan<tanMin||tan===tanMin&&p.x>m.x)&&locallyInside(p,hole)){m=p;tanMin=tan;}}p=p.next;}return m;}// interlink polygon nodes in z-order
function indexCurve(start,minX,minY,size){var p=start;do{if(p.z===null)p.z=zOrder(p.x,p.y,minX,minY,size);p.prevZ=p.prev;p.nextZ=p.next;p=p.next;}while(p!==start);p.prevZ.nextZ=null;p.prevZ=null;sortLinked(p);}// Simon Tatham's linked list merge sort algorithm
// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
function sortLinked(list){var i,p,q,e,tail,numMerges,pSize,qSize,inSize=1;do{p=list;list=null;tail=null;numMerges=0;while(p){numMerges++;q=p;pSize=0;for(i=0;i<inSize;i++){pSize++;q=q.nextZ;if(!q)break;}qSize=inSize;while(pSize>0||qSize>0&&q){if(pSize===0){e=q;q=q.nextZ;qSize--;}else if(qSize===0||!q){e=p;p=p.nextZ;pSize--;}else if(p.z<=q.z){e=p;p=p.nextZ;pSize--;}else{e=q;q=q.nextZ;qSize--;}if(tail)tail.nextZ=e;else list=e;e.prevZ=tail;tail=e;}p=q;}tail.nextZ=null;inSize*=2;}while(numMerges>1);return list;}// z-order of a point given coords and size of the data bounding box
function zOrder(x,y,minX,minY,size){// coords are transformed into non-negative 15-bit integer range
x=32767*(x-minX)/size;y=32767*(y-minY)/size;x=(x|x<<8)&0x00FF00FF;x=(x|x<<4)&0x0F0F0F0F;x=(x|x<<2)&0x33333333;x=(x|x<<1)&0x55555555;y=(y|y<<8)&0x00FF00FF;y=(y|y<<4)&0x0F0F0F0F;y=(y|y<<2)&0x33333333;y=(y|y<<1)&0x55555555;return x|y<<1;}// find the leftmost node of a polygon ring
function getLeftmost(start){var p=start,leftmost=start;do{if(p.x<leftmost.x)leftmost=p;p=p.next;}while(p!==start);return leftmost;}// check if a point lies within a convex triangle
function pointInTriangle(ax,ay,bx,by,cx,cy,px,py){return(cx-px)*(ay-py)-(ax-px)*(cy-py)>=0&&(ax-px)*(by-py)-(bx-px)*(ay-py)>=0&&(bx-px)*(cy-py)-(cx-px)*(by-py)>=0;}// check if a diagonal between two polygon nodes is valid (lies in polygon interior)
function isValidDiagonal(a,b){return a.next.i!==b.i&&a.prev.i!==b.i&&!intersectsPolygon(a,b)&&locallyInside(a,b)&&locallyInside(b,a)&&middleInside(a,b);}// signed area of a triangle
function area(p,q,r){return(q.y-p.y)*(r.x-q.x)-(q.x-p.x)*(r.y-q.y);}// check if two points are equal
function equals(p1,p2){return p1.x===p2.x&&p1.y===p2.y;}// check if two segments intersect
function intersects(p1,q1,p2,q2){if(equals(p1,q1)&&equals(p2,q2)||equals(p1,q2)&&equals(p2,q1))return true;return area(p1,q1,p2)>0!==area(p1,q1,q2)>0&&area(p2,q2,p1)>0!==area(p2,q2,q1)>0;}// check if a polygon diagonal intersects any polygon segments
function intersectsPolygon(a,b){var p=a;do{if(p.i!==a.i&&p.next.i!==a.i&&p.i!==b.i&&p.next.i!==b.i&&intersects(p,p.next,a,b))return true;p=p.next;}while(p!==a);return false;}// check if a polygon diagonal is locally inside the polygon
function locallyInside(a,b){return area(a.prev,a,a.next)<0?area(a,b,a.next)>=0&&area(a,a.prev,b)>=0:area(a,b,a.prev)<0||area(a,a.next,b)<0;}// check if the middle point of a polygon diagonal is inside the polygon
function middleInside(a,b){var p=a,inside=false,px=(a.x+b.x)/2,py=(a.y+b.y)/2;do{if(p.y>py!==p.next.y>py&&px<(p.next.x-p.x)*(py-p.y)/(p.next.y-p.y)+p.x)inside=!inside;p=p.next;}while(p!==a);return inside;}// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
// if one belongs to the outer ring and another to a hole, it merges it into a single ring
function splitPolygon(a,b){var a2=new Node(a.i,a.x,a.y),b2=new Node(b.i,b.x,b.y),an=a.next,bp=b.prev;a.next=b;b.prev=a;a2.next=an;an.prev=a2;b2.next=a2;a2.prev=b2;bp.next=b2;b2.prev=bp;return b2;}// create a node and optionally link it with previous one (in a circular doubly linked list)
function insertNode(i,x,y,last){var p=new Node(i,x,y);if(!last){p.prev=p;p.next=p;}else{p.next=last.next;p.prev=last;last.next.prev=p;last.next=p;}return p;}function removeNode(p){p.next.prev=p.prev;p.prev.next=p.next;if(p.prevZ)p.prevZ.nextZ=p.nextZ;if(p.nextZ)p.nextZ.prevZ=p.prevZ;}function Node(i,x,y){// vertice index in coordinates array
this.i=i;// vertex coordinates
this.x=x;this.y=y;// previous and next vertice nodes in a polygon ring
this.prev=null;this.next=null;// z-order curve value
this.z=null;// previous and next nodes in z-order
this.prevZ=null;this.nextZ=null;// indicates whether this is a steiner point
this.steiner=false;}// return a percentage difference between the polygon area and its triangulation area;
// used to verify correctness of triangulation
earcut.deviation=function(data,holeIndices,dim,triangles){var hasHoles=holeIndices&&holeIndices.length;var outerLen=hasHoles?holeIndices[0]*dim:data.length;var polygonArea=Math.abs(signedArea(data,0,outerLen,dim));if(hasHoles){for(var i=0,len=holeIndices.length;i<len;i++){var start=holeIndices[i]*dim;var end=i<len-1?holeIndices[i+1]*dim:data.length;polygonArea-=Math.abs(signedArea(data,start,end,dim));}}var trianglesArea=0;for(i=0;i<triangles.length;i+=3){var a=triangles[i]*dim;var b=triangles[i+1]*dim;var c=triangles[i+2]*dim;trianglesArea+=Math.abs((data[a]-data[c])*(data[b+1]-data[a+1])-(data[a]-data[b])*(data[c+1]-data[a+1]));}return polygonArea===0&&trianglesArea===0?0:Math.abs((trianglesArea-polygonArea)/polygonArea);};function signedArea(data,start,end,dim){var sum=0;for(var i=start,j=end-dim;i<end;i+=dim){sum+=(data[j]-data[i])*(data[i+1]+data[j+1]);j=i;}return sum;}// turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
earcut.flatten=function(data){var dim=data[0][0].length,result={vertices:[],holes:[],dimensions:dim},holeIndex=0;for(var i=0;i<data.length;i++){for(var j=0;j<data[i].length;j++){for(var d=0;d<dim;d++){result.vertices.push(data[i][j][d]);}}if(i>0){holeIndex+=data[i-1].length;result.holes.push(holeIndex);}}return result;};},{}],3:[function(require,module,exports){'use strict';var has=Object.prototype.hasOwnProperty,prefix='~';/**
 * Constructor to create a storage for our `EE` objects.
 * An `Events` instance is a plain object whose properties are event names.
 *
 * @constructor
 * @api private
 */function Events(){}//
// We try to not inherit from `Object.prototype`. In some engines creating an
// instance in this way is faster than calling `Object.create(null)` directly.
// If `Object.create(null)` is not supported we prefix the event names with a
// character to make sure that the built-in object properties are not
// overridden or used as an attack vector.
//
if(Object.create){Events.prototype=Object.create(null);//
// This hack is needed because the `__proto__` property is still inherited in
// some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.
//
if(!new Events().__proto__)prefix=false;}/**
 * Representation of a single event listener.
 *
 * @param {Function} fn The listener function.
 * @param {Mixed} context The context to invoke the listener with.
 * @param {Boolean} [once=false] Specify if the listener is a one-time listener.
 * @constructor
 * @api private
 */function EE(fn,context,once){this.fn=fn;this.context=context;this.once=once||false;}/**
 * Minimal `EventEmitter` interface that is molded against the Node.js
 * `EventEmitter` interface.
 *
 * @constructor
 * @api public
 */function EventEmitter(){this._events=new Events();this._eventsCount=0;}/**
 * Return an array listing the events for which the emitter has registered
 * listeners.
 *
 * @returns {Array}
 * @api public
 */EventEmitter.prototype.eventNames=function eventNames(){var names=[],events,name;if(this._eventsCount===0)return names;for(name in events=this._events){if(has.call(events,name))names.push(prefix?name.slice(1):name);}if(Object.getOwnPropertySymbols){return names.concat(Object.getOwnPropertySymbols(events));}return names;};/**
 * Return the listeners registered for a given event.
 *
 * @param {String|Symbol} event The event name.
 * @param {Boolean} exists Only check if there are listeners.
 * @returns {Array|Boolean}
 * @api public
 */EventEmitter.prototype.listeners=function listeners(event,exists){var evt=prefix?prefix+event:event,available=this._events[evt];if(exists)return!!available;if(!available)return[];if(available.fn)return[available.fn];for(var i=0,l=available.length,ee=new Array(l);i<l;i++){ee[i]=available[i].fn;}return ee;};/**
 * Calls each of the listeners registered for a given event.
 *
 * @param {String|Symbol} event The event name.
 * @returns {Boolean} `true` if the event had listeners, else `false`.
 * @api public
 */EventEmitter.prototype.emit=function emit(event,a1,a2,a3,a4,a5){var evt=prefix?prefix+event:event;if(!this._events[evt])return false;var listeners=this._events[evt],len=arguments.length,args,i;if(listeners.fn){if(listeners.once)this.removeListener(event,listeners.fn,undefined,true);switch(len){case 1:return listeners.fn.call(listeners.context),true;case 2:return listeners.fn.call(listeners.context,a1),true;case 3:return listeners.fn.call(listeners.context,a1,a2),true;case 4:return listeners.fn.call(listeners.context,a1,a2,a3),true;case 5:return listeners.fn.call(listeners.context,a1,a2,a3,a4),true;case 6:return listeners.fn.call(listeners.context,a1,a2,a3,a4,a5),true;}for(i=1,args=new Array(len-1);i<len;i++){args[i-1]=arguments[i];}listeners.fn.apply(listeners.context,args);}else{var length=listeners.length,j;for(i=0;i<length;i++){if(listeners[i].once)this.removeListener(event,listeners[i].fn,undefined,true);switch(len){case 1:listeners[i].fn.call(listeners[i].context);break;case 2:listeners[i].fn.call(listeners[i].context,a1);break;case 3:listeners[i].fn.call(listeners[i].context,a1,a2);break;case 4:listeners[i].fn.call(listeners[i].context,a1,a2,a3);break;default:if(!args)for(j=1,args=new Array(len-1);j<len;j++){args[j-1]=arguments[j];}listeners[i].fn.apply(listeners[i].context,args);}}}return true;};/**
 * Add a listener for a given event.
 *
 * @param {String|Symbol} event The event name.
 * @param {Function} fn The listener function.
 * @param {Mixed} [context=this] The context to invoke the listener with.
 * @returns {EventEmitter} `this`.
 * @api public
 */EventEmitter.prototype.on=function on(event,fn,context){var listener=new EE(fn,context||this),evt=prefix?prefix+event:event;if(!this._events[evt])this._events[evt]=listener,this._eventsCount++;else if(!this._events[evt].fn)this._events[evt].push(listener);else this._events[evt]=[this._events[evt],listener];return this;};/**
 * Add a one-time listener for a given event.
 *
 * @param {String|Symbol} event The event name.
 * @param {Function} fn The listener function.
 * @param {Mixed} [context=this] The context to invoke the listener with.
 * @returns {EventEmitter} `this`.
 * @api public
 */EventEmitter.prototype.once=function once(event,fn,context){var listener=new EE(fn,context||this,true),evt=prefix?prefix+event:event;if(!this._events[evt])this._events[evt]=listener,this._eventsCount++;else if(!this._events[evt].fn)this._events[evt].push(listener);else this._events[evt]=[this._events[evt],listener];return this;};/**
 * Remove the listeners of a given event.
 *
 * @param {String|Symbol} event The event name.
 * @param {Function} fn Only remove the listeners that match this function.
 * @param {Mixed} context Only remove the listeners that have this context.
 * @param {Boolean} once Only remove one-time listeners.
 * @returns {EventEmitter} `this`.
 * @api public
 */EventEmitter.prototype.removeListener=function removeListener(event,fn,context,once){var evt=prefix?prefix+event:event;if(!this._events[evt])return this;if(!fn){if(--this._eventsCount===0)this._events=new Events();else delete this._events[evt];return this;}var listeners=this._events[evt];if(listeners.fn){if(listeners.fn===fn&&(!once||listeners.once)&&(!context||listeners.context===context)){if(--this._eventsCount===0)this._events=new Events();else delete this._events[evt];}}else{for(var i=0,events=[],length=listeners.length;i<length;i++){if(listeners[i].fn!==fn||once&&!listeners[i].once||context&&listeners[i].context!==context){events.push(listeners[i]);}}//
// Reset the array, or remove it completely if we have no more listeners.
//
if(events.length)this._events[evt]=events.length===1?events[0]:events;else if(--this._eventsCount===0)this._events=new Events();else delete this._events[evt];}return this;};/**
 * Remove all listeners, or those of the specified event.
 *
 * @param {String|Symbol} [event] The event name.
 * @returns {EventEmitter} `this`.
 * @api public
 */EventEmitter.prototype.removeAllListeners=function removeAllListeners(event){var evt;if(event){evt=prefix?prefix+event:event;if(this._events[evt]){if(--this._eventsCount===0)this._events=new Events();else delete this._events[evt];}}else{this._events=new Events();this._eventsCount=0;}return this;};//
// Alias methods names because people roll like that.
//
EventEmitter.prototype.off=EventEmitter.prototype.removeListener;EventEmitter.prototype.addListener=EventEmitter.prototype.on;//
// This function doesn't apply anymore.
//
EventEmitter.prototype.setMaxListeners=function setMaxListeners(){return this;};//
// Expose the prefix.
//
EventEmitter.prefixed=prefix;//
// Allow `EventEmitter` to be imported as module namespace.
//
EventEmitter.EventEmitter=EventEmitter;//
// Expose the module.
//
if('undefined'!==typeof module){module.exports=EventEmitter;}},{}],4:[function(require,module,exports){/**
 * isMobile.js v0.4.0
 *
 * A simple library to detect Apple phones and tablets,
 * Android phones and tablets, other mobile devices (like blackberry, mini-opera and windows phone),
 * and any kind of seven inch device, via user agent sniffing.
 *
 * @author: Kai Mallea (kmallea@gmail.com)
 *
 * @license: http://creativecommons.org/publicdomain/zero/1.0/
 */(function(global){var apple_phone=/iPhone/i,apple_ipod=/iPod/i,apple_tablet=/iPad/i,android_phone=/(?=.*\bAndroid\b)(?=.*\bMobile\b)/i,// Match 'Android' AND 'Mobile'
android_tablet=/Android/i,amazon_phone=/(?=.*\bAndroid\b)(?=.*\bSD4930UR\b)/i,amazon_tablet=/(?=.*\bAndroid\b)(?=.*\b(?:KFOT|KFTT|KFJWI|KFJWA|KFSOWI|KFTHWI|KFTHWA|KFAPWI|KFAPWA|KFARWI|KFASWI|KFSAWI|KFSAWA)\b)/i,windows_phone=/IEMobile/i,windows_tablet=/(?=.*\bWindows\b)(?=.*\bARM\b)/i,// Match 'Windows' AND 'ARM'
other_blackberry=/BlackBerry/i,other_blackberry_10=/BB10/i,other_opera=/Opera Mini/i,other_chrome=/(CriOS|Chrome)(?=.*\bMobile\b)/i,other_firefox=/(?=.*\bFirefox\b)(?=.*\bMobile\b)/i,// Match 'Firefox' AND 'Mobile'
seven_inch=new RegExp('(?:'+// Non-capturing group
'Nexus 7'+// Nexus 7
'|'+// OR
'BNTV250'+// B&N Nook Tablet 7 inch
'|'+// OR
'Kindle Fire'+// Kindle Fire
'|'+// OR
'Silk'+// Kindle Fire, Silk Accelerated
'|'+// OR
'GT-P1000'+// Galaxy Tab 7 inch
')',// End non-capturing group
'i');// Case-insensitive matching
var match=function match(regex,userAgent){return regex.test(userAgent);};var IsMobileClass=function IsMobileClass(userAgent){var ua=userAgent||navigator.userAgent;// Facebook mobile app's integrated browser adds a bunch of strings that
// match everything. Strip it out if it exists.
var tmp=ua.split('[FBAN');if(typeof tmp[1]!=='undefined'){ua=tmp[0];}// Twitter mobile app's integrated browser on iPad adds a "Twitter for
// iPhone" string. Same probable happens on other tablet platforms.
// This will confuse detection so strip it out if it exists.
tmp=ua.split('Twitter');if(typeof tmp[1]!=='undefined'){ua=tmp[0];}this.apple={phone:match(apple_phone,ua),ipod:match(apple_ipod,ua),tablet:!match(apple_phone,ua)&&match(apple_tablet,ua),device:match(apple_phone,ua)||match(apple_ipod,ua)||match(apple_tablet,ua)};this.amazon={phone:match(amazon_phone,ua),tablet:!match(amazon_phone,ua)&&match(amazon_tablet,ua),device:match(amazon_phone,ua)||match(amazon_tablet,ua)};this.android={phone:match(amazon_phone,ua)||match(android_phone,ua),tablet:!match(amazon_phone,ua)&&!match(android_phone,ua)&&(match(amazon_tablet,ua)||match(android_tablet,ua)),device:match(amazon_phone,ua)||match(amazon_tablet,ua)||match(android_phone,ua)||match(android_tablet,ua)};this.windows={phone:match(windows_phone,ua),tablet:match(windows_tablet,ua),device:match(windows_phone,ua)||match(windows_tablet,ua)};this.other={blackberry:match(other_blackberry,ua),blackberry10:match(other_blackberry_10,ua),opera:match(other_opera,ua),firefox:match(other_firefox,ua),chrome:match(other_chrome,ua),device:match(other_blackberry,ua)||match(other_blackberry_10,ua)||match(other_opera,ua)||match(other_firefox,ua)||match(other_chrome,ua)};this.seven_inch=match(seven_inch,ua);this.any=this.apple.device||this.android.device||this.windows.device||this.other.device||this.seven_inch;// excludes 'other' devices and ipods, targeting touchscreen phones
this.phone=this.apple.phone||this.android.phone||this.windows.phone;// excludes 7 inch devices, classifying as phone or tablet is left to the user
this.tablet=this.apple.tablet||this.android.tablet||this.windows.tablet;if(typeof window==='undefined'){return this;}};var instantiate=function instantiate(){var IM=new IsMobileClass();IM.Class=IsMobileClass;return IM;};if(typeof module!=='undefined'&&module.exports&&typeof window==='undefined'){//node
module.exports=IsMobileClass;}else if(typeof module!=='undefined'&&module.exports&&typeof window!=='undefined'){//browserify
module.exports=instantiate();}else if(typeof define==='function'&&define.amd){//AMD
define('isMobile',[],global.isMobile=instantiate());}else{global.isMobile=instantiate();}})(this);},{}],5:[function(require,module,exports){'use strict';/* eslint-disable no-unused-vars */var hasOwnProperty=Object.prototype.hasOwnProperty;var propIsEnumerable=Object.prototype.propertyIsEnumerable;function toObject(val){if(val===null||val===undefined){throw new TypeError('Object.assign cannot be called with null or undefined');}return Object(val);}function shouldUseNative(){try{if(!Object.assign){return false;}// Detect buggy property enumeration order in older V8 versions.
// https://bugs.chromium.org/p/v8/issues/detail?id=4118
var test1=new String('abc');// eslint-disable-line
test1[5]='de';if(Object.getOwnPropertyNames(test1)[0]==='5'){return false;}// https://bugs.chromium.org/p/v8/issues/detail?id=3056
var test2={};for(var i=0;i<10;i++){test2['_'+String.fromCharCode(i)]=i;}var order2=Object.getOwnPropertyNames(test2).map(function(n){return test2[n];});if(order2.join('')!=='0123456789'){return false;}// https://bugs.chromium.org/p/v8/issues/detail?id=3056
var test3={};'abcdefghijklmnopqrst'.split('').forEach(function(letter){test3[letter]=letter;});if(Object.keys(Object.assign({},test3)).join('')!=='abcdefghijklmnopqrst'){return false;}return true;}catch(e){// We don't expect any of the above to throw, but better to be safe.
return false;}}module.exports=shouldUseNative()?Object.assign:function(target,source){var from;var to=toObject(target);var symbols;for(var s=1;s<arguments.length;s++){from=Object(arguments[s]);for(var key in from){if(hasOwnProperty.call(from,key)){to[key]=from[key];}}if(Object.getOwnPropertySymbols){symbols=Object.getOwnPropertySymbols(from);for(var i=0;i<symbols.length;i++){if(propIsEnumerable.call(from,symbols[i])){to[symbols[i]]=from[symbols[i]];}}}}return to;};},{}],6:[function(require,module,exports){var EMPTY_ARRAY_BUFFER=new ArrayBuffer(0);/**
 * Helper class to create a webGL buffer
 *
 * @class
 * @memberof PIXI.glCore
 * @param gl {WebGLRenderingContext} The current WebGL rendering context
 * @param type {gl.ARRAY_BUFFER | gl.ELEMENT_ARRAY_BUFFER} @mat
 * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data
 * @param drawType {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW}
 */var Buffer=function Buffer(gl,type,data,drawType){/**
     * The current WebGL rendering context
     *
     * @member {WebGLRenderingContext}
     */this.gl=gl;/**
     * The WebGL buffer, created upon instantiation
     *
     * @member {WebGLBuffer}
     */this.buffer=gl.createBuffer();/**
     * The type of the buffer
     *
     * @member {gl.ARRAY_BUFFER|gl.ELEMENT_ARRAY_BUFFER}
     */this.type=type||gl.ARRAY_BUFFER;/**
     * The draw type of the buffer
     *
     * @member {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW}
     */this.drawType=drawType||gl.STATIC_DRAW;/**
     * The data in the buffer, as a typed array
     *
     * @member {ArrayBuffer| SharedArrayBuffer|ArrayBufferView}
     */this.data=EMPTY_ARRAY_BUFFER;if(data){this.upload(data);}};/**
 * Uploads the buffer to the GPU
 * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data to upload
 * @param offset {Number} if only a subset of the data should be uploaded, this is the amount of data to subtract
 * @param dontBind {Boolean} whether to bind the buffer before uploading it
 */Buffer.prototype.upload=function(data,offset,dontBind){// todo - needed?
if(!dontBind)this.bind();var gl=this.gl;data=data||this.data;offset=offset||0;if(this.data.byteLength>=data.byteLength){gl.bufferSubData(this.type,offset,data);}else{gl.bufferData(this.type,data,this.drawType);}this.data=data;};/**
 * Binds the buffer
 *
 */Buffer.prototype.bind=function(){var gl=this.gl;gl.bindBuffer(this.type,this.buffer);};Buffer.createVertexBuffer=function(gl,data,drawType){return new Buffer(gl,gl.ARRAY_BUFFER,data,drawType);};Buffer.createIndexBuffer=function(gl,data,drawType){return new Buffer(gl,gl.ELEMENT_ARRAY_BUFFER,data,drawType);};Buffer.create=function(gl,type,data,drawType){return new Buffer(gl,type,data,drawType);};/**
 * Destroys the buffer
 *
 */Buffer.prototype.destroy=function(){this.gl.deleteBuffer(this.buffer);};module.exports=Buffer;},{}],7:[function(require,module,exports){var Texture=require('./GLTexture');/**
 * Helper class to create a webGL Framebuffer
 *
 * @class
 * @memberof PIXI.glCore
 * @param gl {WebGLRenderingContext} The current WebGL rendering context
 * @param width {Number} the width of the drawing area of the frame buffer
 * @param height {Number} the height of the drawing area of the frame buffer
 */var Framebuffer=function Framebuffer(gl,width,height){/**
     * The current WebGL rendering context
     *
     * @member {WebGLRenderingContext}
     */this.gl=gl;/**
     * The frame buffer
     *
     * @member {WebGLFramebuffer}
     */this.framebuffer=gl.createFramebuffer();/**
     * The stencil buffer
     *
     * @member {WebGLRenderbuffer}
     */this.stencil=null;/**
     * The stencil buffer
     *
     * @member {PIXI.glCore.GLTexture}
     */this.texture=null;/**
     * The width of the drawing area of the buffer
     *
     * @member {Number}
     */this.width=width||100;/**
     * The height of the drawing area of the buffer
     *
     * @member {Number}
     */this.height=height||100;};/**
 * Adds a texture to the frame buffer
 * @param texture {PIXI.glCore.GLTexture}
 */Framebuffer.prototype.enableTexture=function(texture){var gl=this.gl;this.texture=texture||new Texture(gl);this.texture.bind();//gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA,  this.width, this.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
this.bind();gl.framebufferTexture2D(gl.FRAMEBUFFER,gl.COLOR_ATTACHMENT0,gl.TEXTURE_2D,this.texture.texture,0);};/**
 * Initialises the stencil buffer
 */Framebuffer.prototype.enableStencil=function(){if(this.stencil)return;var gl=this.gl;this.stencil=gl.createRenderbuffer();gl.bindRenderbuffer(gl.RENDERBUFFER,this.stencil);// TODO.. this is depth AND stencil?
gl.framebufferRenderbuffer(gl.FRAMEBUFFER,gl.DEPTH_STENCIL_ATTACHMENT,gl.RENDERBUFFER,this.stencil);gl.renderbufferStorage(gl.RENDERBUFFER,gl.DEPTH_STENCIL,this.width,this.height);};/**
 * Erases the drawing area and fills it with a colour
 * @param  r {Number} the red value of the clearing colour
 * @param  g {Number} the green value of the clearing colour
 * @param  b {Number} the blue value of the clearing colour
 * @param  a {Number} the alpha value of the clearing colour
 */Framebuffer.prototype.clear=function(r,g,b,a){this.bind();var gl=this.gl;gl.clearColor(r,g,b,a);gl.clear(gl.COLOR_BUFFER_BIT);};/**
 * Binds the frame buffer to the WebGL context
 */Framebuffer.prototype.bind=function(){var gl=this.gl;gl.bindFramebuffer(gl.FRAMEBUFFER,this.framebuffer);};/**
 * Unbinds the frame buffer to the WebGL context
 */Framebuffer.prototype.unbind=function(){var gl=this.gl;gl.bindFramebuffer(gl.FRAMEBUFFER,null);};/**
 * Resizes the drawing area of the buffer to the given width and height
 * @param  width  {Number} the new width
 * @param  height {Number} the new height
 */Framebuffer.prototype.resize=function(width,height){var gl=this.gl;this.width=width;this.height=height;if(this.texture){this.texture.uploadData(null,width,height);}if(this.stencil){// update the stencil buffer width and height
gl.bindRenderbuffer(gl.RENDERBUFFER,this.stencil);gl.renderbufferStorage(gl.RENDERBUFFER,gl.DEPTH_STENCIL,width,height);}};/**
 * Destroys this buffer
 */Framebuffer.prototype.destroy=function(){var gl=this.gl;//TODO
if(this.texture){this.texture.destroy();}gl.deleteFramebuffer(this.framebuffer);this.gl=null;this.stencil=null;this.texture=null;};/**
 * Creates a frame buffer with a texture containing the given data
 * @static
 * @param gl {WebGLRenderingContext} The current WebGL rendering context
 * @param width {Number} the width of the drawing area of the frame buffer
 * @param height {Number} the height of the drawing area of the frame buffer
 * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data
 */Framebuffer.createRGBA=function(gl,width,height,data){var texture=Texture.fromData(gl,null,width,height);texture.enableNearestScaling();texture.enableWrapClamp();//now create the framebuffer object and attach the texture to it.
var fbo=new Framebuffer(gl,width,height);fbo.enableTexture(texture);fbo.unbind();return fbo;};/**
 * Creates a frame buffer with a texture containing the given data
 * @static
 * @param gl {WebGLRenderingContext} The current WebGL rendering context
 * @param width {Number} the width of the drawing area of the frame buffer
 * @param height {Number} the height of the drawing area of the frame buffer
 * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data
 */Framebuffer.createFloat32=function(gl,width,height,data){// create a new texture..
var texture=new Texture.fromData(gl,data,width,height);texture.enableNearestScaling();texture.enableWrapClamp();//now create the framebuffer object and attach the texture to it.
var fbo=new Framebuffer(gl,width,height);fbo.enableTexture(texture);fbo.unbind();return fbo;};module.exports=Framebuffer;},{"./GLTexture":9}],8:[function(require,module,exports){var compileProgram=require('./shader/compileProgram'),extractAttributes=require('./shader/extractAttributes'),extractUniforms=require('./shader/extractUniforms'),generateUniformAccessObject=require('./shader/generateUniformAccessObject');/**
 * Helper class to create a webGL Shader
 *
 * @class
 * @memberof PIXI.glCore
 * @param gl {WebGLRenderingContext}
 * @param vertexSrc {string|string[]} The vertex shader source as an array of strings.
 * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings.
 */var Shader=function Shader(gl,vertexSrc,fragmentSrc){/**
	 * The current WebGL rendering context
	 *
	 * @member {WebGLRenderingContext}
	 */this.gl=gl;/**
	 * The shader program
	 *
	 * @member {WebGLProgram}
	 */// First compile the program..
this.program=compileProgram(gl,vertexSrc,fragmentSrc);/**
	 * The attributes of the shader as an object containing the following properties
	 * {
	 * 	type,
	 * 	size,
	 * 	location,
	 * 	pointer
	 * }
	 * @member {Object}
	 */// next extract the attributes
this.attributes=extractAttributes(gl,this.program);var uniformData=extractUniforms(gl,this.program);/**
	 * The uniforms of the shader as an object containing the following properties
	 * {
	 * 	gl,
	 * 	data
	 * }
	 * @member {Object}
	 */this.uniforms=generateUniformAccessObject(gl,uniformData);};/**
 * Uses this shader
 */Shader.prototype.bind=function(){this.gl.useProgram(this.program);};/**
 * Destroys this shader
 * TODO
 */Shader.prototype.destroy=function(){// var gl = this.gl;
};module.exports=Shader;},{"./shader/compileProgram":14,"./shader/extractAttributes":16,"./shader/extractUniforms":17,"./shader/generateUniformAccessObject":18}],9:[function(require,module,exports){/**
 * Helper class to create a WebGL Texture
 *
 * @class
 * @memberof PIXI.glCore
 * @param gl {WebGLRenderingContext} The current WebGL context
 * @param width {number} the width of the texture
 * @param height {number} the height of the texture
 * @param format {number} the pixel format of the texture. defaults to gl.RGBA
 * @param type {number} the gl type of the texture. defaults to gl.UNSIGNED_BYTE
 */var Texture=function Texture(gl,width,height,format,type){/**
	 * The current WebGL rendering context
	 *
	 * @member {WebGLRenderingContext}
	 */this.gl=gl;/**
	 * The WebGL texture
	 *
	 * @member {WebGLTexture}
	 */this.texture=gl.createTexture();/**
	 * If mipmapping was used for this texture, enable and disable with enableMipmap()
	 *
	 * @member {Boolean}
	 */// some settings..
this.mipmap=false;/**
	 * Set to true to enable pre-multiplied alpha
	 *
	 * @member {Boolean}
	 */this.premultiplyAlpha=false;/**
	 * The width of texture
	 *
	 * @member {Number}
	 */this.width=width||-1;/**
	 * The height of texture
	 *
	 * @member {Number}
	 */this.height=height||-1;/**
	 * The pixel format of the texture. defaults to gl.RGBA
	 *
	 * @member {Number}
	 */this.format=format||gl.RGBA;/**
	 * The gl type of the texture. defaults to gl.UNSIGNED_BYTE
	 *
	 * @member {Number}
	 */this.type=type||gl.UNSIGNED_BYTE;};/**
 * Uploads this texture to the GPU
 * @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture
 */Texture.prototype.upload=function(source){this.bind();var gl=this.gl;gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha);var newWidth=source.videoWidth||source.width;var newHeight=source.videoHeight||source.height;if(newHeight!==this.height||newWidth!==this.width){gl.texImage2D(gl.TEXTURE_2D,0,this.format,this.format,this.type,source);}else{gl.texSubImage2D(gl.TEXTURE_2D,0,0,0,this.format,this.type,source);}// if the source is a video, we need to use the videoWidth / videoHeight properties as width / height will be incorrect.
this.width=newWidth;this.height=newHeight;};var FLOATING_POINT_AVAILABLE=false;/**
 * Use a data source and uploads this texture to the GPU
 * @param data {TypedArray} the data to upload to the texture
 * @param width {number} the new width of the texture
 * @param height {number} the new height of the texture
 */Texture.prototype.uploadData=function(data,width,height){this.bind();var gl=this.gl;if(data instanceof Float32Array){if(!FLOATING_POINT_AVAILABLE){var ext=gl.getExtension("OES_texture_float");if(ext){FLOATING_POINT_AVAILABLE=true;}else{throw new Error('floating point textures not available');}}this.type=gl.FLOAT;}else{// TODO support for other types
this.type=gl.UNSIGNED_BYTE;}// what type of data?
gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha);if(width!==this.width||height!==this.height){gl.texImage2D(gl.TEXTURE_2D,0,this.format,width,height,0,this.format,this.type,data||null);}else{gl.texSubImage2D(gl.TEXTURE_2D,0,0,0,width,height,this.format,this.type,data||null);}this.width=width;this.height=height;//	texSubImage2D
};/**
 * Binds the texture
 * @param  location
 */Texture.prototype.bind=function(location){var gl=this.gl;if(location!==undefined){gl.activeTexture(gl.TEXTURE0+location);}gl.bindTexture(gl.TEXTURE_2D,this.texture);};/**
 * Unbinds the texture
 */Texture.prototype.unbind=function(){var gl=this.gl;gl.bindTexture(gl.TEXTURE_2D,null);};/**
 * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation
 */Texture.prototype.minFilter=function(linear){var gl=this.gl;this.bind();if(this.mipmap){gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MIN_FILTER,linear?gl.LINEAR_MIPMAP_LINEAR:gl.NEAREST_MIPMAP_NEAREST);}else{gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MIN_FILTER,linear?gl.LINEAR:gl.NEAREST);}};/**
 * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation
 */Texture.prototype.magFilter=function(linear){var gl=this.gl;this.bind();gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MAG_FILTER,linear?gl.LINEAR:gl.NEAREST);};/**
 * Enables mipmapping
 */Texture.prototype.enableMipmap=function(){var gl=this.gl;this.bind();this.mipmap=true;gl.generateMipmap(gl.TEXTURE_2D);};/**
 * Enables linear filtering
 */Texture.prototype.enableLinearScaling=function(){this.minFilter(true);this.magFilter(true);};/**
 * Enables nearest neighbour interpolation
 */Texture.prototype.enableNearestScaling=function(){this.minFilter(false);this.magFilter(false);};/**
 * Enables clamping on the texture so WebGL will not repeat it
 */Texture.prototype.enableWrapClamp=function(){var gl=this.gl;this.bind();gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_S,gl.CLAMP_TO_EDGE);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_T,gl.CLAMP_TO_EDGE);};/**
 * Enable tiling on the texture
 */Texture.prototype.enableWrapRepeat=function(){var gl=this.gl;this.bind();gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_S,gl.REPEAT);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_T,gl.REPEAT);};Texture.prototype.enableWrapMirrorRepeat=function(){var gl=this.gl;this.bind();gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_S,gl.MIRRORED_REPEAT);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_T,gl.MIRRORED_REPEAT);};/**
 * Destroys this texture
 */Texture.prototype.destroy=function(){var gl=this.gl;//TODO
gl.deleteTexture(this.texture);};/**
 * @static
 * @param gl {WebGLRenderingContext} The current WebGL context
 * @param source {HTMLImageElement|ImageData} the source image of the texture
 * @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha
 */Texture.fromSource=function(gl,source,premultiplyAlpha){var texture=new Texture(gl);texture.premultiplyAlpha=premultiplyAlpha||false;texture.upload(source);return texture;};/**
 * @static
 * @param gl {WebGLRenderingContext} The current WebGL context
 * @param data {TypedArray} the data to upload to the texture
 * @param width {number} the new width of the texture
 * @param height {number} the new height of the texture
 */Texture.fromData=function(gl,data,width,height){//console.log(data, width, height);
var texture=new Texture(gl);texture.uploadData(data,width,height);return texture;};module.exports=Texture;},{}],10:[function(require,module,exports){// state object//
var setVertexAttribArrays=require('./setVertexAttribArrays');/**
 * Helper class to work with WebGL VertexArrayObjects (vaos)
 * Only works if WebGL extensions are enabled (they usually are)
 *
 * @class
 * @memberof PIXI.glCore
 * @param gl {WebGLRenderingContext} The current WebGL rendering context
 */function VertexArrayObject(gl,state){this.nativeVaoExtension=null;if(!VertexArrayObject.FORCE_NATIVE){this.nativeVaoExtension=gl.getExtension('OES_vertex_array_object')||gl.getExtension('MOZ_OES_vertex_array_object')||gl.getExtension('WEBKIT_OES_vertex_array_object');}this.nativeState=state;if(this.nativeVaoExtension){this.nativeVao=this.nativeVaoExtension.createVertexArrayOES();var maxAttribs=gl.getParameter(gl.MAX_VERTEX_ATTRIBS);// VAO - overwrite the state..
this.nativeState={tempAttribState:new Array(maxAttribs),attribState:new Array(maxAttribs)};}/**
     * The current WebGL rendering context
     *
     * @member {WebGLRenderingContext}
     */this.gl=gl;/**
     * An array of attributes
     *
     * @member {Array}
     */this.attributes=[];/**
     * @member {PIXI.glCore.GLBuffer}
     */this.indexBuffer=null;/**
     * A boolean flag
     *
     * @member {Boolean}
     */this.dirty=false;}VertexArrayObject.prototype.constructor=VertexArrayObject;module.exports=VertexArrayObject;/**
* Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!)
* If you find on older devices that things have gone a bit weird then set this to true.
*//**
 * Lets the VAO know if you should use the WebGL extension or the native methods.
 * Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!)
 * If you find on older devices that things have gone a bit weird then set this to true.
 * @static
 * @property {Boolean} FORCE_NATIVE
 */VertexArrayObject.FORCE_NATIVE=false;/**
 * Binds the buffer
 */VertexArrayObject.prototype.bind=function(){if(this.nativeVao){this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao);if(this.dirty){this.dirty=false;this.activate();}}else{this.activate();}return this;};/**
 * Unbinds the buffer
 */VertexArrayObject.prototype.unbind=function(){if(this.nativeVao){this.nativeVaoExtension.bindVertexArrayOES(null);}return this;};/**
 * Uses this vao
 */VertexArrayObject.prototype.activate=function(){var gl=this.gl;var lastBuffer=null;for(var i=0;i<this.attributes.length;i++){var attrib=this.attributes[i];if(lastBuffer!==attrib.buffer){attrib.buffer.bind();lastBuffer=attrib.buffer;}//attrib.attribute.pointer(attrib.type, attrib.normalized, attrib.stride, attrib.start);
gl.vertexAttribPointer(attrib.attribute.location,attrib.attribute.size,attrib.type||gl.FLOAT,attrib.normalized||false,attrib.stride||0,attrib.start||0);}setVertexAttribArrays(gl,this.attributes,this.nativeState);this.indexBuffer.bind();return this;};/**
 *
 * @param buffer     {PIXI.gl.GLBuffer}
 * @param attribute  {*}
 * @param type       {String}
 * @param normalized {Boolean}
 * @param stride     {Number}
 * @param start      {Number}
 */VertexArrayObject.prototype.addAttribute=function(buffer,attribute,type,normalized,stride,start){this.attributes.push({buffer:buffer,attribute:attribute,location:attribute.location,type:type||this.gl.FLOAT,normalized:normalized||false,stride:stride||0,start:start||0});this.dirty=true;return this;};/**
 *
 * @param buffer   {PIXI.gl.GLBuffer}
 */VertexArrayObject.prototype.addIndex=function(buffer/*, options*/){this.indexBuffer=buffer;this.dirty=true;return this;};/**
 * Unbinds this vao and disables it
 */VertexArrayObject.prototype.clear=function(){// var gl = this.gl;
// TODO - should this function unbind after clear?
// for now, no but lets see what happens in the real world!
if(this.nativeVao){this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao);}this.attributes.length=0;this.indexBuffer=null;return this;};/**
 * @param type  {Number}
 * @param size  {Number}
 * @param start {Number}
 */VertexArrayObject.prototype.draw=function(type,size,start){var gl=this.gl;gl.drawElements(type,size,gl.UNSIGNED_SHORT,start||0);return this;};/**
 * Destroy this vao
 */VertexArrayObject.prototype.destroy=function(){// lose references
this.gl=null;this.indexBuffer=null;this.attributes=null;this.nativeState=null;if(this.nativeVao){this.nativeVaoExtension.deleteVertexArrayOES(this.nativeVao);}this.nativeVaoExtension=null;this.nativeVao=null;};},{"./setVertexAttribArrays":13}],11:[function(require,module,exports){/**
 * Helper class to create a webGL Context
 *
 * @class
 * @memberof PIXI.glCore
 * @param canvas {HTMLCanvasElement} the canvas element that we will get the context from
 * @param options {Object} An options object that gets passed in to the canvas element containing the context attributes,
 *                         see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available
 * @return {WebGLRenderingContext} the WebGL context
 */var createContext=function createContext(canvas,options){var gl=canvas.getContext('webgl',options)||canvas.getContext('experimental-webgl',options);if(!gl){// fail, not able to get a context
throw new Error('This browser does not support webGL. Try using the canvas renderer');}return gl;};module.exports=createContext;},{}],12:[function(require,module,exports){var gl={createContext:require('./createContext'),setVertexAttribArrays:require('./setVertexAttribArrays'),GLBuffer:require('./GLBuffer'),GLFramebuffer:require('./GLFramebuffer'),GLShader:require('./GLShader'),GLTexture:require('./GLTexture'),VertexArrayObject:require('./VertexArrayObject'),shader:require('./shader')};// Export for Node-compatible environments
if(typeof module!=='undefined'&&module.exports){// Export the module
module.exports=gl;}// Add to the browser window pixi.gl
if(typeof window!=='undefined'){// add the window object
window.PIXI=window.PIXI||{};window.PIXI.glCore=gl;}},{"./GLBuffer":6,"./GLFramebuffer":7,"./GLShader":8,"./GLTexture":9,"./VertexArrayObject":10,"./createContext":11,"./setVertexAttribArrays":13,"./shader":19}],13:[function(require,module,exports){// var GL_MAP = {};
/**
 * @param gl {WebGLRenderingContext} The current WebGL context
 * @param attribs {*}
 * @param state {*}
 */var setVertexAttribArrays=function setVertexAttribArrays(gl,attribs,state){var i;if(state){var tempAttribState=state.tempAttribState,attribState=state.attribState;for(i=0;i<tempAttribState.length;i++){tempAttribState[i]=false;}// set the new attribs
for(i=0;i<attribs.length;i++){tempAttribState[attribs[i].attribute.location]=true;}for(i=0;i<attribState.length;i++){if(attribState[i]!==tempAttribState[i]){attribState[i]=tempAttribState[i];if(state.attribState[i]){gl.enableVertexAttribArray(i);}else{gl.disableVertexAttribArray(i);}}}}else{for(i=0;i<attribs.length;i++){var attrib=attribs[i];gl.enableVertexAttribArray(attrib.attribute.location);}}};module.exports=setVertexAttribArrays;},{}],14:[function(require,module,exports){/**
 * @class
 * @memberof PIXI.glCore.shader
 * @param gl {WebGLRenderingContext} The current WebGL context {WebGLProgram}
 * @param vertexSrc {string|string[]} The vertex shader source as an array of strings.
 * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings.
 * @return {WebGLProgram} the shader program
 */var compileProgram=function compileProgram(gl,vertexSrc,fragmentSrc){var glVertShader=compileShader(gl,gl.VERTEX_SHADER,vertexSrc);var glFragShader=compileShader(gl,gl.FRAGMENT_SHADER,fragmentSrc);var program=gl.createProgram();gl.attachShader(program,glVertShader);gl.attachShader(program,glFragShader);gl.linkProgram(program);// if linking fails, then log and cleanup
if(!gl.getProgramParameter(program,gl.LINK_STATUS)){console.error('Pixi.js Error: Could not initialize shader.');console.error('gl.VALIDATE_STATUS',gl.getProgramParameter(program,gl.VALIDATE_STATUS));console.error('gl.getError()',gl.getError());// if there is a program info log, log it
if(gl.getProgramInfoLog(program)!==''){console.warn('Pixi.js Warning: gl.getProgramInfoLog()',gl.getProgramInfoLog(program));}gl.deleteProgram(program);program=null;}// clean up some shaders
gl.deleteShader(glVertShader);gl.deleteShader(glFragShader);return program;};/**
 * @private
 * @param gl {WebGLRenderingContext} The current WebGL context {WebGLProgram}
 * @param type {Number} the type, can be either VERTEX_SHADER or FRAGMENT_SHADER
 * @param vertexSrc {string|string[]} The vertex shader source as an array of strings.
 * @return {WebGLShader} the shader
 */var compileShader=function compileShader(gl,type,src){var shader=gl.createShader(type);gl.shaderSource(shader,src);gl.compileShader(shader);if(!gl.getShaderParameter(shader,gl.COMPILE_STATUS)){console.log(gl.getShaderInfoLog(shader));return null;}return shader;};module.exports=compileProgram;},{}],15:[function(require,module,exports){/**
 * @class
 * @memberof PIXI.glCore.shader
 * @param type {String} Type of value
 * @param size {Number}
 */var defaultValue=function defaultValue(type,size){switch(type){case'float':return 0;case'vec2':return new Float32Array(2*size);case'vec3':return new Float32Array(3*size);case'vec4':return new Float32Array(4*size);case'int':case'sampler2D':return 0;case'ivec2':return new Int32Array(2*size);case'ivec3':return new Int32Array(3*size);case'ivec4':return new Int32Array(4*size);case'bool':return false;case'bvec2':return booleanArray(2*size);case'bvec3':return booleanArray(3*size);case'bvec4':return booleanArray(4*size);case'mat2':return new Float32Array([1,0,0,1]);case'mat3':return new Float32Array([1,0,0,0,1,0,0,0,1]);case'mat4':return new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);}};var booleanArray=function booleanArray(size){var array=new Array(size);for(var i=0;i<array.length;i++){array[i]=false;}return array;};module.exports=defaultValue;},{}],16:[function(require,module,exports){var mapType=require('./mapType');var mapSize=require('./mapSize');/**
 * Extracts the attributes
 * @class
 * @memberof PIXI.glCore.shader
 * @param gl {WebGLRenderingContext} The current WebGL rendering context
 * @param program {WebGLProgram} The shader program to get the attributes from
 * @return attributes {Object}
 */var extractAttributes=function extractAttributes(gl,program){var attributes={};var totalAttributes=gl.getProgramParameter(program,gl.ACTIVE_ATTRIBUTES);for(var i=0;i<totalAttributes;i++){var attribData=gl.getActiveAttrib(program,i);var type=mapType(gl,attribData.type);attributes[attribData.name]={type:type,size:mapSize(type),location:gl.getAttribLocation(program,attribData.name),//TODO - make an attribute object
pointer:pointer};}return attributes;};var pointer=function pointer(type,normalized,stride,start){// console.log(this.location)
gl.vertexAttribPointer(this.location,this.size,type||gl.FLOAT,normalized||false,stride||0,start||0);};module.exports=extractAttributes;},{"./mapSize":20,"./mapType":21}],17:[function(require,module,exports){var mapType=require('./mapType');var defaultValue=require('./defaultValue');/**
 * Extracts the uniforms
 * @class
 * @memberof PIXI.glCore.shader
 * @param gl {WebGLRenderingContext} The current WebGL rendering context
 * @param program {WebGLProgram} The shader program to get the uniforms from
 * @return uniforms {Object}
 */var extractUniforms=function extractUniforms(gl,program){var uniforms={};var totalUniforms=gl.getProgramParameter(program,gl.ACTIVE_UNIFORMS);for(var i=0;i<totalUniforms;i++){var uniformData=gl.getActiveUniform(program,i);var name=uniformData.name.replace(/\[.*?\]/,"");var type=mapType(gl,uniformData.type);uniforms[name]={type:type,size:uniformData.size,location:gl.getUniformLocation(program,name),value:defaultValue(type,uniformData.size)};}return uniforms;};module.exports=extractUniforms;},{"./defaultValue":15,"./mapType":21}],18:[function(require,module,exports){/**
 * Extracts the attributes
 * @class
 * @memberof PIXI.glCore.shader
 * @param gl {WebGLRenderingContext} The current WebGL rendering context
 * @param uniforms {Array} @mat ?
 * @return attributes {Object}
 */var generateUniformAccessObject=function generateUniformAccessObject(gl,uniformData){// this is the object we will be sending back.
// an object hierachy will be created for structs
var uniforms={data:{}};uniforms.gl=gl;var uniformKeys=Object.keys(uniformData);for(var i=0;i<uniformKeys.length;i++){var fullName=uniformKeys[i];var nameTokens=fullName.split('.');var name=nameTokens[nameTokens.length-1];var uniformGroup=getUniformGroup(nameTokens,uniforms);var uniform=uniformData[fullName];uniformGroup.data[name]=uniform;uniformGroup.gl=gl;Object.defineProperty(uniformGroup,name,{get:generateGetter(name),set:generateSetter(name,uniform)});}return uniforms;};var generateGetter=function generateGetter(name){var template=getterTemplate.replace('%%',name);return new Function(template);// jshint ignore:line
};var generateSetter=function generateSetter(name,uniform){var template=setterTemplate.replace(/%%/g,name);var setTemplate;if(uniform.size===1){setTemplate=GLSL_TO_SINGLE_SETTERS[uniform.type];}else{setTemplate=GLSL_TO_ARRAY_SETTERS[uniform.type];}if(setTemplate){template+="\nthis.gl."+setTemplate+";";}return new Function('value',template);// jshint ignore:line
};var getUniformGroup=function getUniformGroup(nameTokens,uniform){var cur=uniform;for(var i=0;i<nameTokens.length-1;i++){var o=cur[nameTokens[i]]||{data:{}};cur[nameTokens[i]]=o;cur=o;}return cur;};var getterTemplate=['return this.data.%%.value;'].join('\n');var setterTemplate=['this.data.%%.value = value;','var location = this.data.%%.location;'].join('\n');var GLSL_TO_SINGLE_SETTERS={'float':'uniform1f(location, value)','vec2':'uniform2f(location, value[0], value[1])','vec3':'uniform3f(location, value[0], value[1], value[2])','vec4':'uniform4f(location, value[0], value[1], value[2], value[3])','int':'uniform1i(location, value)','ivec2':'uniform2i(location, value[0], value[1])','ivec3':'uniform3i(location, value[0], value[1], value[2])','ivec4':'uniform4i(location, value[0], value[1], value[2], value[3])','bool':'uniform1i(location, value)','bvec2':'uniform2i(location, value[0], value[1])','bvec3':'uniform3i(location, value[0], value[1], value[2])','bvec4':'uniform4i(location, value[0], value[1], value[2], value[3])','mat2':'uniformMatrix2fv(location, false, value)','mat3':'uniformMatrix3fv(location, false, value)','mat4':'uniformMatrix4fv(location, false, value)','sampler2D':'uniform1i(location, value)'};var GLSL_TO_ARRAY_SETTERS={'float':'uniform1fv(location, value)','vec2':'uniform2fv(location, value)','vec3':'uniform3fv(location, value)','vec4':'uniform4fv(location, value)','int':'uniform1iv(location, value)','ivec2':'uniform2iv(location, value)','ivec3':'uniform3iv(location, value)','ivec4':'uniform4iv(location, value)','bool':'uniform1iv(location, value)','bvec2':'uniform2iv(location, value)','bvec3':'uniform3iv(location, value)','bvec4':'uniform4iv(location, value)','sampler2D':'uniform1iv(location, value)'};module.exports=generateUniformAccessObject;},{}],19:[function(require,module,exports){module.exports={compileProgram:require('./compileProgram'),defaultValue:require('./defaultValue'),extractAttributes:require('./extractAttributes'),extractUniforms:require('./extractUniforms'),generateUniformAccessObject:require('./generateUniformAccessObject'),mapSize:require('./mapSize'),mapType:require('./mapType')};},{"./compileProgram":14,"./defaultValue":15,"./extractAttributes":16,"./extractUniforms":17,"./generateUniformAccessObject":18,"./mapSize":20,"./mapType":21}],20:[function(require,module,exports){/**
 * @class
 * @memberof PIXI.glCore.shader
 * @param type {String}
 * @return {Number}
 */var mapSize=function mapSize(type){return GLSL_TO_SIZE[type];};var GLSL_TO_SIZE={'float':1,'vec2':2,'vec3':3,'vec4':4,'int':1,'ivec2':2,'ivec3':3,'ivec4':4,'bool':1,'bvec2':2,'bvec3':3,'bvec4':4,'mat2':4,'mat3':9,'mat4':16,'sampler2D':1};module.exports=mapSize;},{}],21:[function(require,module,exports){var mapSize=function mapSize(gl,type){if(!GL_TABLE){var typeNames=Object.keys(GL_TO_GLSL_TYPES);GL_TABLE={};for(var i=0;i<typeNames.length;++i){var tn=typeNames[i];GL_TABLE[gl[tn]]=GL_TO_GLSL_TYPES[tn];}}return GL_TABLE[type];};var GL_TABLE=null;var GL_TO_GLSL_TYPES={'FLOAT':'float','FLOAT_VEC2':'vec2','FLOAT_VEC3':'vec3','FLOAT_VEC4':'vec4','INT':'int','INT_VEC2':'ivec2','INT_VEC3':'ivec3','INT_VEC4':'ivec4','BOOL':'bool','BOOL_VEC2':'bvec2','BOOL_VEC3':'bvec3','BOOL_VEC4':'bvec4','FLOAT_MAT2':'mat2','FLOAT_MAT3':'mat3','FLOAT_MAT4':'mat4','SAMPLER_2D':'sampler2D'};module.exports=mapSize;},{}],22:[function(require,module,exports){(function(process){// Copyright Joyent, Inc. and other Node contributors.
//
// 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.
// resolves . and .. elements in a path array with directory names there
// must be no slashes, empty elements, or device names (c:\) in the array
// (so also no leading and trailing slashes - it does not distinguish
// relative and absolute paths)
function normalizeArray(parts,allowAboveRoot){// if the path tries to go above the root, `up` ends up > 0
var up=0;for(var i=parts.length-1;i>=0;i--){var last=parts[i];if(last==='.'){parts.splice(i,1);}else if(last==='..'){parts.splice(i,1);up++;}else if(up){parts.splice(i,1);up--;}}// if the path is allowed to go above the root, restore leading ..s
if(allowAboveRoot){for(;up--;up){parts.unshift('..');}}return parts;}// Split a filename into [root, dir, basename, ext], unix version
// 'root' is just a slash, or nothing.
var splitPathRe=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;var splitPath=function splitPath(filename){return splitPathRe.exec(filename).slice(1);};// path.resolve([from ...], to)
// posix version
exports.resolve=function(){var resolvedPath='',resolvedAbsolute=false;for(var i=arguments.length-1;i>=-1&&!resolvedAbsolute;i--){var path=i>=0?arguments[i]:process.cwd();// Skip empty and invalid entries
if(typeof path!=='string'){throw new TypeError('Arguments to path.resolve must be strings');}else if(!path){continue;}resolvedPath=path+'/'+resolvedPath;resolvedAbsolute=path.charAt(0)==='/';}// At this point the path should be resolved to a full absolute path, but
// handle relative paths to be safe (might happen when process.cwd() fails)
// Normalize the path
resolvedPath=normalizeArray(filter(resolvedPath.split('/'),function(p){return!!p;}),!resolvedAbsolute).join('/');return(resolvedAbsolute?'/':'')+resolvedPath||'.';};// path.normalize(path)
// posix version
exports.normalize=function(path){var isAbsolute=exports.isAbsolute(path),trailingSlash=substr(path,-1)==='/';// Normalize the path
path=normalizeArray(filter(path.split('/'),function(p){return!!p;}),!isAbsolute).join('/');if(!path&&!isAbsolute){path='.';}if(path&&trailingSlash){path+='/';}return(isAbsolute?'/':'')+path;};// posix version
exports.isAbsolute=function(path){return path.charAt(0)==='/';};// posix version
exports.join=function(){var paths=Array.prototype.slice.call(arguments,0);return exports.normalize(filter(paths,function(p,index){if(typeof p!=='string'){throw new TypeError('Arguments to path.join must be strings');}return p;}).join('/'));};// path.relative(from, to)
// posix version
exports.relative=function(from,to){from=exports.resolve(from).substr(1);to=exports.resolve(to).substr(1);function trim(arr){var start=0;for(;start<arr.length;start++){if(arr[start]!=='')break;}var end=arr.length-1;for(;end>=0;end--){if(arr[end]!=='')break;}if(start>end)return[];return arr.slice(start,end-start+1);}var fromParts=trim(from.split('/'));var toParts=trim(to.split('/'));var length=Math.min(fromParts.length,toParts.length);var samePartsLength=length;for(var i=0;i<length;i++){if(fromParts[i]!==toParts[i]){samePartsLength=i;break;}}var outputParts=[];for(var i=samePartsLength;i<fromParts.length;i++){outputParts.push('..');}outputParts=outputParts.concat(toParts.slice(samePartsLength));return outputParts.join('/');};exports.sep='/';exports.delimiter=':';exports.dirname=function(path){var result=splitPath(path),root=result[0],dir=result[1];if(!root&&!dir){// No dirname whatsoever
return'.';}if(dir){// It has a dirname, strip trailing slash
dir=dir.substr(0,dir.length-1);}return root+dir;};exports.basename=function(path,ext){var f=splitPath(path)[2];// TODO: make this comparison case-insensitive on windows?
if(ext&&f.substr(-1*ext.length)===ext){f=f.substr(0,f.length-ext.length);}return f;};exports.extname=function(path){return splitPath(path)[3];};function filter(xs,f){if(xs.filter)return xs.filter(f);var res=[];for(var i=0;i<xs.length;i++){if(f(xs[i],i,xs))res.push(xs[i]);}return res;}// String.prototype.substr - negative index don't work in IE8
var substr='ab'.substr(-1)==='b'?function(str,start,len){return str.substr(start,len);}:function(str,start,len){if(start<0)start=str.length+start;return str.substr(start,len);};}).call(this,require('_process'));},{"_process":23}],23:[function(require,module,exports){// shim for using process in browser
var process=module.exports={};// cached from whatever global is present so that test runners that stub it
// don't break things.  But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals.  It's inside a
// function because try/catches deoptimize in certain engines.
var cachedSetTimeout;var cachedClearTimeout;function defaultSetTimout(){throw new Error('setTimeout has not been defined');}function defaultClearTimeout(){throw new Error('clearTimeout has not been defined');}(function(){try{if(typeof setTimeout==='function'){cachedSetTimeout=setTimeout;}else{cachedSetTimeout=defaultSetTimout;}}catch(e){cachedSetTimeout=defaultSetTimout;}try{if(typeof clearTimeout==='function'){cachedClearTimeout=clearTimeout;}else{cachedClearTimeout=defaultClearTimeout;}}catch(e){cachedClearTimeout=defaultClearTimeout;}})();function runTimeout(fun){if(cachedSetTimeout===setTimeout){//normal enviroments in sane situations
return setTimeout(fun,0);}// if setTimeout wasn't available but was latter defined
if((cachedSetTimeout===defaultSetTimout||!cachedSetTimeout)&&setTimeout){cachedSetTimeout=setTimeout;return setTimeout(fun,0);}try{// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedSetTimeout(fun,0);}catch(e){try{// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedSetTimeout.call(null,fun,0);}catch(e){// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
return cachedSetTimeout.call(this,fun,0);}}}function runClearTimeout(marker){if(cachedClearTimeout===clearTimeout){//normal enviroments in sane situations
return clearTimeout(marker);}// if clearTimeout wasn't available but was latter defined
if((cachedClearTimeout===defaultClearTimeout||!cachedClearTimeout)&&clearTimeout){cachedClearTimeout=clearTimeout;return clearTimeout(marker);}try{// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedClearTimeout(marker);}catch(e){try{// When we are in I.E. but the script has been evaled so I.E. doesn't  trust the global object when called normally
return cachedClearTimeout.call(null,marker);}catch(e){// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
// Some versions of I.E. have different rules for clearTimeout vs setTimeout
return cachedClearTimeout.call(this,marker);}}}var queue=[];var draining=false;var currentQueue;var queueIndex=-1;function cleanUpNextTick(){if(!draining||!currentQueue){return;}draining=false;if(currentQueue.length){queue=currentQueue.concat(queue);}else{queueIndex=-1;}if(queue.length){drainQueue();}}function drainQueue(){if(draining){return;}var timeout=runTimeout(cleanUpNextTick);draining=true;var len=queue.length;while(len){currentQueue=queue;queue=[];while(++queueIndex<len){if(currentQueue){currentQueue[queueIndex].run();}}queueIndex=-1;len=queue.length;}currentQueue=null;draining=false;runClearTimeout(timeout);}process.nextTick=function(fun){var args=new Array(arguments.length-1);if(arguments.length>1){for(var i=1;i<arguments.length;i++){args[i-1]=arguments[i];}}queue.push(new Item(fun,args));if(queue.length===1&&!draining){runTimeout(drainQueue);}};// v8 likes predictible objects
function Item(fun,array){this.fun=fun;this.array=array;}Item.prototype.run=function(){this.fun.apply(null,this.array);};process.title='browser';process.browser=true;process.env={};process.argv=[];process.version='';// empty string to avoid regexp issues
process.versions={};function noop(){}process.on=noop;process.addListener=noop;process.once=noop;process.off=noop;process.removeListener=noop;process.removeAllListeners=noop;process.emit=noop;process.binding=function(name){throw new Error('process.binding is not supported');};process.cwd=function(){return'/';};process.chdir=function(dir){throw new Error('process.chdir is not supported');};process.umask=function(){return 0;};},{}],24:[function(require,module,exports){(function(global){/*! https://mths.be/punycode v1.4.1 by @mathias */;(function(root){/** Detect free variables */var freeExports=(typeof exports==="undefined"?"undefined":_typeof2(exports))=='object'&&exports&&!exports.nodeType&&exports;var freeModule=(typeof module==="undefined"?"undefined":_typeof2(module))=='object'&&module&&!module.nodeType&&module;var freeGlobal=(typeof global==="undefined"?"undefined":_typeof2(global))=='object'&&global;if(freeGlobal.global===freeGlobal||freeGlobal.window===freeGlobal||freeGlobal.self===freeGlobal){root=freeGlobal;}/**
	 * The `punycode` object.
	 * @name punycode
	 * @type Object
	 */var punycode,/** Highest positive signed 32-bit float value */maxInt=2147483647,// aka. 0x7FFFFFFF or 2^31-1
/** Bootstring parameters */base=36,tMin=1,tMax=26,skew=38,damp=700,initialBias=72,initialN=128,// 0x80
delimiter='-',// '\x2D'
/** Regular expressions */regexPunycode=/^xn--/,regexNonASCII=/[^\x20-\x7E]/,// unprintable ASCII chars + non-ASCII chars
regexSeparators=/[\x2E\u3002\uFF0E\uFF61]/g,// RFC 3490 separators
/** Error messages */errors={'overflow':'Overflow: input needs wider integers to process','not-basic':'Illegal input >= 0x80 (not a basic code point)','invalid-input':'Invalid input'},/** Convenience shortcuts */baseMinusTMin=base-tMin,floor=Math.floor,stringFromCharCode=String.fromCharCode,/** Temporary variable */key;/*--------------------------------------------------------------------------*//**
	 * A generic error utility function.
	 * @private
	 * @param {String} type The error type.
	 * @returns {Error} Throws a `RangeError` with the applicable error message.
	 */function error(type){throw new RangeError(errors[type]);}/**
	 * A generic `Array#map` utility function.
	 * @private
	 * @param {Array} array The array to iterate over.
	 * @param {Function} callback The function that gets called for every array
	 * item.
	 * @returns {Array} A new array of values returned by the callback function.
	 */function map(array,fn){var length=array.length;var result=[];while(length--){result[length]=fn(array[length]);}return result;}/**
	 * A simple `Array#map`-like wrapper to work with domain name strings or email
	 * addresses.
	 * @private
	 * @param {String} domain The domain name or email address.
	 * @param {Function} callback The function that gets called for every
	 * character.
	 * @returns {Array} A new string of characters returned by the callback
	 * function.
	 */function mapDomain(string,fn){var parts=string.split('@');var result='';if(parts.length>1){// In email addresses, only the domain name should be punycoded. Leave
// the local part (i.e. everything up to `@`) intact.
result=parts[0]+'@';string=parts[1];}// Avoid `split(regex)` for IE8 compatibility. See #17.
string=string.replace(regexSeparators,'\x2E');var labels=string.split('.');var encoded=map(labels,fn).join('.');return result+encoded;}/**
	 * Creates an array containing the numeric code points of each Unicode
	 * character in the string. While JavaScript uses UCS-2 internally,
	 * this function will convert a pair of surrogate halves (each of which
	 * UCS-2 exposes as separate characters) into a single code point,
	 * matching UTF-16.
	 * @see `punycode.ucs2.encode`
	 * @see <https://mathiasbynens.be/notes/javascript-encoding>
	 * @memberOf punycode.ucs2
	 * @name decode
	 * @param {String} string The Unicode input string (UCS-2).
	 * @returns {Array} The new array of code points.
	 */function ucs2decode(string){var output=[],counter=0,length=string.length,value,extra;while(counter<length){value=string.charCodeAt(counter++);if(value>=0xD800&&value<=0xDBFF&&counter<length){// high surrogate, and there is a next character
extra=string.charCodeAt(counter++);if((extra&0xFC00)==0xDC00){// low surrogate
output.push(((value&0x3FF)<<10)+(extra&0x3FF)+0x10000);}else{// unmatched surrogate; only append this code unit, in case the next
// code unit is the high surrogate of a surrogate pair
output.push(value);counter--;}}else{output.push(value);}}return output;}/**
	 * Creates a string based on an array of numeric code points.
	 * @see `punycode.ucs2.decode`
	 * @memberOf punycode.ucs2
	 * @name encode
	 * @param {Array} codePoints The array of numeric code points.
	 * @returns {String} The new Unicode string (UCS-2).
	 */function ucs2encode(array){return map(array,function(value){var output='';if(value>0xFFFF){value-=0x10000;output+=stringFromCharCode(value>>>10&0x3FF|0xD800);value=0xDC00|value&0x3FF;}output+=stringFromCharCode(value);return output;}).join('');}/**
	 * Converts a basic code point into a digit/integer.
	 * @see `digitToBasic()`
	 * @private
	 * @param {Number} codePoint The basic numeric code point value.
	 * @returns {Number} The numeric value of a basic code point (for use in
	 * representing integers) in the range `0` to `base - 1`, or `base` if
	 * the code point does not represent a value.
	 */function basicToDigit(codePoint){if(codePoint-48<10){return codePoint-22;}if(codePoint-65<26){return codePoint-65;}if(codePoint-97<26){return codePoint-97;}return base;}/**
	 * Converts a digit/integer into a basic code point.
	 * @see `basicToDigit()`
	 * @private
	 * @param {Number} digit The numeric value of a basic code point.
	 * @returns {Number} The basic code point whose value (when used for
	 * representing integers) is `digit`, which needs to be in the range
	 * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
	 * used; else, the lowercase form is used. The behavior is undefined
	 * if `flag` is non-zero and `digit` has no uppercase form.
	 */function digitToBasic(digit,flag){//  0..25 map to ASCII a..z or A..Z
// 26..35 map to ASCII 0..9
return digit+22+75*(digit<26)-((flag!=0)<<5);}/**
	 * Bias adaptation function as per section 3.4 of RFC 3492.
	 * https://tools.ietf.org/html/rfc3492#section-3.4
	 * @private
	 */function adapt(delta,numPoints,firstTime){var k=0;delta=firstTime?floor(delta/damp):delta>>1;delta+=floor(delta/numPoints);for(;/* no initialization */delta>baseMinusTMin*tMax>>1;k+=base){delta=floor(delta/baseMinusTMin);}return floor(k+(baseMinusTMin+1)*delta/(delta+skew));}/**
	 * Converts a Punycode string of ASCII-only symbols to a string of Unicode
	 * symbols.
	 * @memberOf punycode
	 * @param {String} input The Punycode string of ASCII-only symbols.
	 * @returns {String} The resulting string of Unicode symbols.
	 */function decode(input){// Don't use UCS-2
var output=[],inputLength=input.length,out,i=0,n=initialN,bias=initialBias,basic,j,index,oldi,w,k,digit,t,/** Cached calculation results */baseMinusT;// Handle the basic code points: let `basic` be the number of input code
// points before the last delimiter, or `0` if there is none, then copy
// the first basic code points to the output.
basic=input.lastIndexOf(delimiter);if(basic<0){basic=0;}for(j=0;j<basic;++j){// if it's not a basic code point
if(input.charCodeAt(j)>=0x80){error('not-basic');}output.push(input.charCodeAt(j));}// Main decoding loop: start just after the last delimiter if any basic code
// points were copied; start at the beginning otherwise.
for(index=basic>0?basic+1:0;index<inputLength;)/* no final expression */{// `index` is the index of the next character to be consumed.
// Decode a generalized variable-length integer into `delta`,
// which gets added to `i`. The overflow checking is easier
// if we increase `i` as we go, then subtract off its starting
// value at the end to obtain `delta`.
for(oldi=i,w=1,k=base;;/* no condition */k+=base){if(index>=inputLength){error('invalid-input');}digit=basicToDigit(input.charCodeAt(index++));if(digit>=base||digit>floor((maxInt-i)/w)){error('overflow');}i+=digit*w;t=k<=bias?tMin:k>=bias+tMax?tMax:k-bias;if(digit<t){break;}baseMinusT=base-t;if(w>floor(maxInt/baseMinusT)){error('overflow');}w*=baseMinusT;}out=output.length+1;bias=adapt(i-oldi,out,oldi==0);// `i` was supposed to wrap around from `out` to `0`,
// incrementing `n` each time, so we'll fix that now:
if(floor(i/out)>maxInt-n){error('overflow');}n+=floor(i/out);i%=out;// Insert `n` at position `i` of the output
output.splice(i++,0,n);}return ucs2encode(output);}/**
	 * Converts a string of Unicode symbols (e.g. a domain name label) to a
	 * Punycode string of ASCII-only symbols.
	 * @memberOf punycode
	 * @param {String} input The string of Unicode symbols.
	 * @returns {String} The resulting Punycode string of ASCII-only symbols.
	 */function encode(input){var n,delta,handledCPCount,basicLength,bias,j,m,q,k,t,currentValue,output=[],/** `inputLength` will hold the number of code points in `input`. */inputLength,/** Cached calculation results */handledCPCountPlusOne,baseMinusT,qMinusT;// Convert the input in UCS-2 to Unicode
input=ucs2decode(input);// Cache the length
inputLength=input.length;// Initialize the state
n=initialN;delta=0;bias=initialBias;// Handle the basic code points
for(j=0;j<inputLength;++j){currentValue=input[j];if(currentValue<0x80){output.push(stringFromCharCode(currentValue));}}handledCPCount=basicLength=output.length;// `handledCPCount` is the number of code points that have been handled;
// `basicLength` is the number of basic code points.
// Finish the basic string - if it is not empty - with a delimiter
if(basicLength){output.push(delimiter);}// Main encoding loop:
while(handledCPCount<inputLength){// All non-basic code points < n have been handled already. Find the next
// larger one:
for(m=maxInt,j=0;j<inputLength;++j){currentValue=input[j];if(currentValue>=n&&currentValue<m){m=currentValue;}}// Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
// but guard against overflow
handledCPCountPlusOne=handledCPCount+1;if(m-n>floor((maxInt-delta)/handledCPCountPlusOne)){error('overflow');}delta+=(m-n)*handledCPCountPlusOne;n=m;for(j=0;j<inputLength;++j){currentValue=input[j];if(currentValue<n&&++delta>maxInt){error('overflow');}if(currentValue==n){// Represent delta as a generalized variable-length integer
for(q=delta,k=base;;/* no condition */k+=base){t=k<=bias?tMin:k>=bias+tMax?tMax:k-bias;if(q<t){break;}qMinusT=q-t;baseMinusT=base-t;output.push(stringFromCharCode(digitToBasic(t+qMinusT%baseMinusT,0)));q=floor(qMinusT/baseMinusT);}output.push(stringFromCharCode(digitToBasic(q,0)));bias=adapt(delta,handledCPCountPlusOne,handledCPCount==basicLength);delta=0;++handledCPCount;}}++delta;++n;}return output.join('');}/**
	 * Converts a Punycode string representing a domain name or an email address
	 * to Unicode. Only the Punycoded parts of the input will be converted, i.e.
	 * it doesn't matter if you call it on a string that has already been
	 * converted to Unicode.
	 * @memberOf punycode
	 * @param {String} input The Punycoded domain name or email address to
	 * convert to Unicode.
	 * @returns {String} The Unicode representation of the given Punycode
	 * string.
	 */function toUnicode(input){return mapDomain(input,function(string){return regexPunycode.test(string)?decode(string.slice(4).toLowerCase()):string;});}/**
	 * Converts a Unicode string representing a domain name or an email address to
	 * Punycode. Only the non-ASCII parts of the domain name will be converted,
	 * i.e. it doesn't matter if you call it with a domain that's already in
	 * ASCII.
	 * @memberOf punycode
	 * @param {String} input The domain name or email address to convert, as a
	 * Unicode string.
	 * @returns {String} The Punycode representation of the given domain name or
	 * email address.
	 */function toASCII(input){return mapDomain(input,function(string){return regexNonASCII.test(string)?'xn--'+encode(string):string;});}/*--------------------------------------------------------------------------*//** Define the public API */punycode={/**
		 * A string representing the current Punycode.js version number.
		 * @memberOf punycode
		 * @type String
		 */'version':'1.4.1',/**
		 * An object of methods to convert from JavaScript's internal character
		 * representation (UCS-2) to Unicode code points, and back.
		 * @see <https://mathiasbynens.be/notes/javascript-encoding>
		 * @memberOf punycode
		 * @type Object
		 */'ucs2':{'decode':ucs2decode,'encode':ucs2encode},'decode':decode,'encode':encode,'toASCII':toASCII,'toUnicode':toUnicode};/** Expose `punycode` */// Some AMD build optimizers, like r.js, check for specific condition patterns
// like the following:
if(typeof define=='function'&&_typeof2(define.amd)=='object'&&define.amd){define('punycode',function(){return punycode;});}else if(freeExports&&freeModule){if(module.exports==freeExports){// in Node.js, io.js, or RingoJS v0.8.0+
freeModule.exports=punycode;}else{// in Narwhal or RingoJS v0.7.0-
for(key in punycode){punycode.hasOwnProperty(key)&&(freeExports[key]=punycode[key]);}}}else{// in Rhino or a web browser
root.punycode=punycode;}})(this);}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{});},{}],25:[function(require,module,exports){// Copyright Joyent, Inc. and other Node contributors.
//
// 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.
'use strict';// If obj.hasOwnProperty has been overridden, then calling
// obj.hasOwnProperty(prop) will break.
// See: https://github.com/joyent/node/issues/1707
function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop);}module.exports=function(qs,sep,eq,options){sep=sep||'&';eq=eq||'=';var obj={};if(typeof qs!=='string'||qs.length===0){return obj;}var regexp=/\+/g;qs=qs.split(sep);var maxKeys=1000;if(options&&typeof options.maxKeys==='number'){maxKeys=options.maxKeys;}var len=qs.length;// maxKeys <= 0 means that we should not limit keys count
if(maxKeys>0&&len>maxKeys){len=maxKeys;}for(var i=0;i<len;++i){var x=qs[i].replace(regexp,'%20'),idx=x.indexOf(eq),kstr,vstr,k,v;if(idx>=0){kstr=x.substr(0,idx);vstr=x.substr(idx+1);}else{kstr=x;vstr='';}k=decodeURIComponent(kstr);v=decodeURIComponent(vstr);if(!hasOwnProperty(obj,k)){obj[k]=v;}else if(isArray(obj[k])){obj[k].push(v);}else{obj[k]=[obj[k],v];}}return obj;};var isArray=Array.isArray||function(xs){return Object.prototype.toString.call(xs)==='[object Array]';};},{}],26:[function(require,module,exports){// Copyright Joyent, Inc. and other Node contributors.
//
// 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.
'use strict';var stringifyPrimitive=function stringifyPrimitive(v){switch(typeof v==="undefined"?"undefined":_typeof2(v)){case'string':return v;case'boolean':return v?'true':'false';case'number':return isFinite(v)?v:'';default:return'';}};module.exports=function(obj,sep,eq,name){sep=sep||'&';eq=eq||'=';if(obj===null){obj=undefined;}if((typeof obj==="undefined"?"undefined":_typeof2(obj))==='object'){return map(objectKeys(obj),function(k){var ks=encodeURIComponent(stringifyPrimitive(k))+eq;if(isArray(obj[k])){return map(obj[k],function(v){return ks+encodeURIComponent(stringifyPrimitive(v));}).join(sep);}else{return ks+encodeURIComponent(stringifyPrimitive(obj[k]));}}).join(sep);}if(!name)return'';return encodeURIComponent(stringifyPrimitive(name))+eq+encodeURIComponent(stringifyPrimitive(obj));};var isArray=Array.isArray||function(xs){return Object.prototype.toString.call(xs)==='[object Array]';};function map(xs,f){if(xs.map)return xs.map(f);var res=[];for(var i=0;i<xs.length;i++){res.push(f(xs[i],i));}return res;}var objectKeys=Object.keys||function(obj){var res=[];for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))res.push(key);}return res;};},{}],27:[function(require,module,exports){'use strict';exports.decode=exports.parse=require('./decode');exports.encode=exports.stringify=require('./encode');},{"./decode":25,"./encode":26}],28:[function(require,module,exports){// Copyright Joyent, Inc. and other Node contributors.
//
// 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.
'use strict';var punycode=require('punycode');var util=require('./util');exports.parse=urlParse;exports.resolve=urlResolve;exports.resolveObject=urlResolveObject;exports.format=urlFormat;exports.Url=Url;function Url(){this.protocol=null;this.slashes=null;this.auth=null;this.host=null;this.port=null;this.hostname=null;this.hash=null;this.search=null;this.query=null;this.pathname=null;this.path=null;this.href=null;}// Reference: RFC 3986, RFC 1808, RFC 2396
// define these here so at least they only have to be
// compiled once on the first module load.
var protocolPattern=/^([a-z0-9.+-]+:)/i,portPattern=/:[0-9]*$/,// Special case for a simple path URL
simplePathPattern=/^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,// RFC 2396: characters reserved for delimiting URLs.
// We actually just auto-escape these.
delims=['<','>','"','`',' ','\r','\n','\t'],// RFC 2396: characters not allowed for various reasons.
unwise=['{','}','|','\\','^','`'].concat(delims),// Allowed by RFCs, but cause of XSS attacks.  Always escape these.
autoEscape=['\''].concat(unwise),// Characters that are never ever allowed in a hostname.
// Note that any invalid chars are also handled, but these
// are the ones that are *expected* to be seen, so we fast-path
// them.
nonHostChars=['%','/','?',';','#'].concat(autoEscape),hostEndingChars=['/','?','#'],hostnameMaxLen=255,hostnamePartPattern=/^[+a-z0-9A-Z_-]{0,63}$/,hostnamePartStart=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,// protocols that can allow "unsafe" and "unwise" chars.
unsafeProtocol={'javascript':true,'javascript:':true},// protocols that never have a hostname.
hostlessProtocol={'javascript':true,'javascript:':true},// protocols that always contain a // bit.
slashedProtocol={'http':true,'https':true,'ftp':true,'gopher':true,'file':true,'http:':true,'https:':true,'ftp:':true,'gopher:':true,'file:':true},querystring=require('querystring');function urlParse(url,parseQueryString,slashesDenoteHost){if(url&&util.isObject(url)&&url instanceof Url)return url;var u=new Url();u.parse(url,parseQueryString,slashesDenoteHost);return u;}Url.prototype.parse=function(url,parseQueryString,slashesDenoteHost){if(!util.isString(url)){throw new TypeError("Parameter 'url' must be a string, not "+(typeof url==="undefined"?"undefined":_typeof2(url)));}// Copy chrome, IE, opera backslash-handling behavior.
// Back slashes before the query string get converted to forward slashes
// See: https://code.google.com/p/chromium/issues/detail?id=25916
var queryIndex=url.indexOf('?'),splitter=queryIndex!==-1&&queryIndex<url.indexOf('#')?'?':'#',uSplit=url.split(splitter),slashRegex=/\\/g;uSplit[0]=uSplit[0].replace(slashRegex,'/');url=uSplit.join(splitter);var rest=url;// trim before proceeding.
// This is to support parse stuff like "  http://foo.com  \n"
rest=rest.trim();if(!slashesDenoteHost&&url.split('#').length===1){// Try fast path regexp
var simplePath=simplePathPattern.exec(rest);if(simplePath){this.path=rest;this.href=rest;this.pathname=simplePath[1];if(simplePath[2]){this.search=simplePath[2];if(parseQueryString){this.query=querystring.parse(this.search.substr(1));}else{this.query=this.search.substr(1);}}else if(parseQueryString){this.search='';this.query={};}return this;}}var proto=protocolPattern.exec(rest);if(proto){proto=proto[0];var lowerProto=proto.toLowerCase();this.protocol=lowerProto;rest=rest.substr(proto.length);}// figure out if it's got a host
// user@server is *always* interpreted as a hostname, and url
// resolution will treat //foo/bar as host=foo,path=bar because that's
// how the browser resolves relative URLs.
if(slashesDenoteHost||proto||rest.match(/^\/\/[^@\/]+@[^@\/]+/)){var slashes=rest.substr(0,2)==='//';if(slashes&&!(proto&&hostlessProtocol[proto])){rest=rest.substr(2);this.slashes=true;}}if(!hostlessProtocol[proto]&&(slashes||proto&&!slashedProtocol[proto])){// there's a hostname.
// the first instance of /, ?, ;, or # ends the host.
//
// If there is an @ in the hostname, then non-host chars *are* allowed
// to the left of the last @ sign, unless some host-ending character
// comes *before* the @-sign.
// URLs are obnoxious.
//
// ex:
// http://a@b@c/ => user:a@b host:c
// http://a@b?@c => user:a host:c path:/?@c
// v0.12 TODO(isaacs): This is not quite how Chrome does things.
// Review our test case against browsers more comprehensively.
// find the first instance of any hostEndingChars
var hostEnd=-1;for(var i=0;i<hostEndingChars.length;i++){var hec=rest.indexOf(hostEndingChars[i]);if(hec!==-1&&(hostEnd===-1||hec<hostEnd))hostEnd=hec;}// at this point, either we have an explicit point where the
// auth portion cannot go past, or the last @ char is the decider.
var auth,atSign;if(hostEnd===-1){// atSign can be anywhere.
atSign=rest.lastIndexOf('@');}else{// atSign must be in auth portion.
// http://a@b/c@d => host:b auth:a path:/c@d
atSign=rest.lastIndexOf('@',hostEnd);}// Now we have a portion which is definitely the auth.
// Pull that off.
if(atSign!==-1){auth=rest.slice(0,atSign);rest=rest.slice(atSign+1);this.auth=decodeURIComponent(auth);}// the host is the remaining to the left of the first non-host char
hostEnd=-1;for(var i=0;i<nonHostChars.length;i++){var hec=rest.indexOf(nonHostChars[i]);if(hec!==-1&&(hostEnd===-1||hec<hostEnd))hostEnd=hec;}// if we still have not hit it, then the entire thing is a host.
if(hostEnd===-1)hostEnd=rest.length;this.host=rest.slice(0,hostEnd);rest=rest.slice(hostEnd);// pull out port.
this.parseHost();// we've indicated that there is a hostname,
// so even if it's empty, it has to be present.
this.hostname=this.hostname||'';// if hostname begins with [ and ends with ]
// assume that it's an IPv6 address.
var ipv6Hostname=this.hostname[0]==='['&&this.hostname[this.hostname.length-1]===']';// validate a little.
if(!ipv6Hostname){var hostparts=this.hostname.split(/\./);for(var i=0,l=hostparts.length;i<l;i++){var part=hostparts[i];if(!part)continue;if(!part.match(hostnamePartPattern)){var newpart='';for(var j=0,k=part.length;j<k;j++){if(part.charCodeAt(j)>127){// we replace non-ASCII char with a temporary placeholder
// we need this to make sure size of hostname is not
// broken by replacing non-ASCII by nothing
newpart+='x';}else{newpart+=part[j];}}// we test again with ASCII char only
if(!newpart.match(hostnamePartPattern)){var validParts=hostparts.slice(0,i);var notHost=hostparts.slice(i+1);var bit=part.match(hostnamePartStart);if(bit){validParts.push(bit[1]);notHost.unshift(bit[2]);}if(notHost.length){rest='/'+notHost.join('.')+rest;}this.hostname=validParts.join('.');break;}}}}if(this.hostname.length>hostnameMaxLen){this.hostname='';}else{// hostnames are always lower case.
this.hostname=this.hostname.toLowerCase();}if(!ipv6Hostname){// IDNA Support: Returns a punycoded representation of "domain".
// It only converts parts of the domain name that
// have non-ASCII characters, i.e. it doesn't matter if
// you call it with a domain that already is ASCII-only.
this.hostname=punycode.toASCII(this.hostname);}var p=this.port?':'+this.port:'';var h=this.hostname||'';this.host=h+p;this.href+=this.host;// strip [ and ] from the hostname
// the host field still retains them, though
if(ipv6Hostname){this.hostname=this.hostname.substr(1,this.hostname.length-2);if(rest[0]!=='/'){rest='/'+rest;}}}// now rest is set to the post-host stuff.
// chop off any delim chars.
if(!unsafeProtocol[lowerProto]){// First, make 100% sure that any "autoEscape" chars get
// escaped, even if encodeURIComponent doesn't think they
// need to be.
for(var i=0,l=autoEscape.length;i<l;i++){var ae=autoEscape[i];if(rest.indexOf(ae)===-1)continue;var esc=encodeURIComponent(ae);if(esc===ae){esc=escape(ae);}rest=rest.split(ae).join(esc);}}// chop off from the tail first.
var hash=rest.indexOf('#');if(hash!==-1){// got a fragment string.
this.hash=rest.substr(hash);rest=rest.slice(0,hash);}var qm=rest.indexOf('?');if(qm!==-1){this.search=rest.substr(qm);this.query=rest.substr(qm+1);if(parseQueryString){this.query=querystring.parse(this.query);}rest=rest.slice(0,qm);}else if(parseQueryString){// no query string, but parseQueryString still requested
this.search='';this.query={};}if(rest)this.pathname=rest;if(slashedProtocol[lowerProto]&&this.hostname&&!this.pathname){this.pathname='/';}//to support http.request
if(this.pathname||this.search){var p=this.pathname||'';var s=this.search||'';this.path=p+s;}// finally, reconstruct the href based on what has been validated.
this.href=this.format();return this;};// format a parsed object into a url string
function urlFormat(obj){// ensure it's an object, and not a string url.
// If it's an obj, this is a no-op.
// this way, you can call url_format() on strings
// to clean up potentially wonky urls.
if(util.isString(obj))obj=urlParse(obj);if(!(obj instanceof Url))return Url.prototype.format.call(obj);return obj.format();}Url.prototype.format=function(){var auth=this.auth||'';if(auth){auth=encodeURIComponent(auth);auth=auth.replace(/%3A/i,':');auth+='@';}var protocol=this.protocol||'',pathname=this.pathname||'',hash=this.hash||'',host=false,query='';if(this.host){host=auth+this.host;}else if(this.hostname){host=auth+(this.hostname.indexOf(':')===-1?this.hostname:'['+this.hostname+']');if(this.port){host+=':'+this.port;}}if(this.query&&util.isObject(this.query)&&Object.keys(this.query).length){query=querystring.stringify(this.query);}var search=this.search||query&&'?'+query||'';if(protocol&&protocol.substr(-1)!==':')protocol+=':';// only the slashedProtocols get the //.  Not mailto:, xmpp:, etc.
// unless they had them to begin with.
if(this.slashes||(!protocol||slashedProtocol[protocol])&&host!==false){host='//'+(host||'');if(pathname&&pathname.charAt(0)!=='/')pathname='/'+pathname;}else if(!host){host='';}if(hash&&hash.charAt(0)!=='#')hash='#'+hash;if(search&&search.charAt(0)!=='?')search='?'+search;pathname=pathname.replace(/[?#]/g,function(match){return encodeURIComponent(match);});search=search.replace('#','%23');return protocol+host+pathname+search+hash;};function urlResolve(source,relative){return urlParse(source,false,true).resolve(relative);}Url.prototype.resolve=function(relative){return this.resolveObject(urlParse(relative,false,true)).format();};function urlResolveObject(source,relative){if(!source)return relative;return urlParse(source,false,true).resolveObject(relative);}Url.prototype.resolveObject=function(relative){if(util.isString(relative)){var rel=new Url();rel.parse(relative,false,true);relative=rel;}var result=new Url();var tkeys=Object.keys(this);for(var tk=0;tk<tkeys.length;tk++){var tkey=tkeys[tk];result[tkey]=this[tkey];}// hash is always overridden, no matter what.
// even href="" will remove it.
result.hash=relative.hash;// if the relative url is empty, then there's nothing left to do here.
if(relative.href===''){result.href=result.format();return result;}// hrefs like //foo/bar always cut to the protocol.
if(relative.slashes&&!relative.protocol){// take everything except the protocol from relative
var rkeys=Object.keys(relative);for(var rk=0;rk<rkeys.length;rk++){var rkey=rkeys[rk];if(rkey!=='protocol')result[rkey]=relative[rkey];}//urlParse appends trailing / to urls like http://www.example.com
if(slashedProtocol[result.protocol]&&result.hostname&&!result.pathname){result.path=result.pathname='/';}result.href=result.format();return result;}if(relative.protocol&&relative.protocol!==result.protocol){// if it's a known url protocol, then changing
// the protocol does weird things
// first, if it's not file:, then we MUST have a host,
// and if there was a path
// to begin with, then we MUST have a path.
// if it is file:, then the host is dropped,
// because that's known to be hostless.
// anything else is assumed to be absolute.
if(!slashedProtocol[relative.protocol]){var keys=Object.keys(relative);for(var v=0;v<keys.length;v++){var k=keys[v];result[k]=relative[k];}result.href=result.format();return result;}result.protocol=relative.protocol;if(!relative.host&&!hostlessProtocol[relative.protocol]){var relPath=(relative.pathname||'').split('/');while(relPath.length&&!(relative.host=relPath.shift())){}if(!relative.host)relative.host='';if(!relative.hostname)relative.hostname='';if(relPath[0]!=='')relPath.unshift('');if(relPath.length<2)relPath.unshift('');result.pathname=relPath.join('/');}else{result.pathname=relative.pathname;}result.search=relative.search;result.query=relative.query;result.host=relative.host||'';result.auth=relative.auth;result.hostname=relative.hostname||relative.host;result.port=relative.port;// to support http.request
if(result.pathname||result.search){var p=result.pathname||'';var s=result.search||'';result.path=p+s;}result.slashes=result.slashes||relative.slashes;result.href=result.format();return result;}var isSourceAbs=result.pathname&&result.pathname.charAt(0)==='/',isRelAbs=relative.host||relative.pathname&&relative.pathname.charAt(0)==='/',mustEndAbs=isRelAbs||isSourceAbs||result.host&&relative.pathname,removeAllDots=mustEndAbs,srcPath=result.pathname&&result.pathname.split('/')||[],relPath=relative.pathname&&relative.pathname.split('/')||[],psychotic=result.protocol&&!slashedProtocol[result.protocol];// if the url is a non-slashed url, then relative
// links like ../.. should be able
// to crawl up to the hostname, as well.  This is strange.
// result.protocol has already been set by now.
// Later on, put the first path part into the host field.
if(psychotic){result.hostname='';result.port=null;if(result.host){if(srcPath[0]==='')srcPath[0]=result.host;else srcPath.unshift(result.host);}result.host='';if(relative.protocol){relative.hostname=null;relative.port=null;if(relative.host){if(relPath[0]==='')relPath[0]=relative.host;else relPath.unshift(relative.host);}relative.host=null;}mustEndAbs=mustEndAbs&&(relPath[0]===''||srcPath[0]==='');}if(isRelAbs){// it's absolute.
result.host=relative.host||relative.host===''?relative.host:result.host;result.hostname=relative.hostname||relative.hostname===''?relative.hostname:result.hostname;result.search=relative.search;result.query=relative.query;srcPath=relPath;// fall through to the dot-handling below.
}else if(relPath.length){// it's relative
// throw away the existing file, and take the new path instead.
if(!srcPath)srcPath=[];srcPath.pop();srcPath=srcPath.concat(relPath);result.search=relative.search;result.query=relative.query;}else if(!util.isNullOrUndefined(relative.search)){// just pull out the search.
// like href='?foo'.
// Put this after the other two cases because it simplifies the booleans
if(psychotic){result.hostname=result.host=srcPath.shift();//occationaly the auth can get stuck only in host
//this especially happens in cases like
//url.resolveObject('mailto:local1@domain1', 'local2@domain2')
var authInHost=result.host&&result.host.indexOf('@')>0?result.host.split('@'):false;if(authInHost){result.auth=authInHost.shift();result.host=result.hostname=authInHost.shift();}}result.search=relative.search;result.query=relative.query;//to support http.request
if(!util.isNull(result.pathname)||!util.isNull(result.search)){result.path=(result.pathname?result.pathname:'')+(result.search?result.search:'');}result.href=result.format();return result;}if(!srcPath.length){// no path at all.  easy.
// we've already handled the other stuff above.
result.pathname=null;//to support http.request
if(result.search){result.path='/'+result.search;}else{result.path=null;}result.href=result.format();return result;}// if a url ENDs in . or .., then it must get a trailing slash.
// however, if it ends in anything else non-slashy,
// then it must NOT get a trailing slash.
var last=srcPath.slice(-1)[0];var hasTrailingSlash=(result.host||relative.host||srcPath.length>1)&&(last==='.'||last==='..')||last==='';// strip single dots, resolve double dots to parent dir
// if the path tries to go above the root, `up` ends up > 0
var up=0;for(var i=srcPath.length;i>=0;i--){last=srcPath[i];if(last==='.'){srcPath.splice(i,1);}else if(last==='..'){srcPath.splice(i,1);up++;}else if(up){srcPath.splice(i,1);up--;}}// if the path is allowed to go above the root, restore leading ..s
if(!mustEndAbs&&!removeAllDots){for(;up--;up){srcPath.unshift('..');}}if(mustEndAbs&&srcPath[0]!==''&&(!srcPath[0]||srcPath[0].charAt(0)!=='/')){srcPath.unshift('');}if(hasTrailingSlash&&srcPath.join('/').substr(-1)!=='/'){srcPath.push('');}var isAbsolute=srcPath[0]===''||srcPath[0]&&srcPath[0].charAt(0)==='/';// put the host back
if(psychotic){result.hostname=result.host=isAbsolute?'':srcPath.length?srcPath.shift():'';//occationaly the auth can get stuck only in host
//this especially happens in cases like
//url.resolveObject('mailto:local1@domain1', 'local2@domain2')
var authInHost=result.host&&result.host.indexOf('@')>0?result.host.split('@'):false;if(authInHost){result.auth=authInHost.shift();result.host=result.hostname=authInHost.shift();}}mustEndAbs=mustEndAbs||result.host&&srcPath.length;if(mustEndAbs&&!isAbsolute){srcPath.unshift('');}if(!srcPath.length){result.pathname=null;result.path=null;}else{result.pathname=srcPath.join('/');}//to support request.http
if(!util.isNull(result.pathname)||!util.isNull(result.search)){result.path=(result.pathname?result.pathname:'')+(result.search?result.search:'');}result.auth=relative.auth||result.auth;result.slashes=result.slashes||relative.slashes;result.href=result.format();return result;};Url.prototype.parseHost=function(){var host=this.host;var port=portPattern.exec(host);if(port){port=port[0];if(port!==':'){this.port=port.substr(1);}host=host.substr(0,host.length-port.length);}if(host)this.hostname=host;};},{"./util":29,"punycode":24,"querystring":27}],29:[function(require,module,exports){'use strict';module.exports={isString:function isString(arg){return typeof arg==='string';},isObject:function isObject(arg){return(typeof arg==="undefined"?"undefined":_typeof2(arg))==='object'&&arg!==null;},isNull:function isNull(arg){return arg===null;},isNullOrUndefined:function isNullOrUndefined(arg){return arg==null;}};},{}],30:[function(require,module,exports){'use strict';exports.__esModule=true;var _typeof=typeof Symbol==="function"&&_typeof2(Symbol.iterator)==="symbol"?function(obj){return typeof obj==="undefined"?"undefined":_typeof2(obj);}:function(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj==="undefined"?"undefined":_typeof2(obj);};var _miniSignals=require('mini-signals');var _miniSignals2=_interopRequireDefault(_miniSignals);var _parseUri=require('parse-uri');var _parseUri2=_interopRequireDefault(_parseUri);var _async=require('./async');var async=_interopRequireWildcard(_async);var _Resource=require('./Resource');var _Resource2=_interopRequireDefault(_Resource);function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj;}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key];}}newObj.default=obj;return newObj;}}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}// some constants
var MAX_PROGRESS=100;var rgxExtractUrlHash=/(#[\w\-]+)?$/;/**
 * Manages the state and loading of multiple resources to load.
 *
 * @class
 */var Loader=function(){/**
     * @param {string} [baseUrl=''] - The base url for all resources loaded by this loader.
     * @param {number} [concurrency=10] - The number of resources to load concurrently.
     */function Loader(){var _this=this;var baseUrl=arguments.length>0&&arguments[0]!==undefined?arguments[0]:'';var concurrency=arguments.length>1&&arguments[1]!==undefined?arguments[1]:10;_classCallCheck(this,Loader);/**
         * The base url for all resources loaded by this loader.
         *
         * @member {string}
         */this.baseUrl=baseUrl;/**
         * The progress percent of the loader going through the queue.
         *
         * @member {number}
         */this.progress=0;/**
         * Loading state of the loader, true if it is currently loading resources.
         *
         * @member {boolean}
         */this.loading=false;/**
         * A querystring to append to every URL added to the loader.
         *
         * This should be a valid query string *without* the question-mark (`?`). The loader will
         * also *not* escape values for you. Make sure to escape your parameters with
         * [`encodeURIComponent`](https://mdn.io/encodeURIComponent) before assigning this property.
         *
         * @example
         *
         * ```js
         * const loader = new Loader();
         *
         * loader.defaultQueryString = 'user=me&password=secret';
         *
         * // This will request 'image.png?user=me&password=secret'
         * loader.add('image.png').load();
         *
         * loader.reset();
         *
         * // This will request 'image.png?v=1&user=me&password=secret'
         * loader.add('iamge.png?v=1').load();
         * ```
         */this.defaultQueryString='';/**
         * The middleware to run before loading each resource.
         *
         * @member {function[]}
         */this._beforeMiddleware=[];/**
         * The middleware to run after loading each resource.
         *
         * @member {function[]}
         */this._afterMiddleware=[];/**
         * The `_loadResource` function bound with this object context.
         *
         * @private
         * @member {function}
         * @param {Resource} r - The resource to load
         * @param {Function} d - The dequeue function
         * @return {undefined}
         */this._boundLoadResource=function(r,d){return _this._loadResource(r,d);};/**
         * The resources waiting to be loaded.
         *
         * @private
         * @member {Resource[]}
         */this._queue=async.queue(this._boundLoadResource,concurrency);this._queue.pause();/**
         * All the resources for this loader keyed by name.
         *
         * @member {object<string, Resource>}
         */this.resources={};/**
         * Dispatched once per loaded or errored resource.
         *
         * The callback looks like {@link Loader.OnProgressSignal}.
         *
         * @member {Signal}
         */this.onProgress=new _miniSignals2.default();/**
         * Dispatched once per errored resource.
         *
         * The callback looks like {@link Loader.OnErrorSignal}.
         *
         * @member {Signal}
         */this.onError=new _miniSignals2.default();/**
         * Dispatched once per loaded resource.
         *
         * The callback looks like {@link Loader.OnLoadSignal}.
         *
         * @member {Signal}
         */this.onLoad=new _miniSignals2.default();/**
         * Dispatched when the loader begins to process the queue.
         *
         * The callback looks like {@link Loader.OnStartSignal}.
         *
         * @member {Signal}
         */this.onStart=new _miniSignals2.default();/**
         * Dispatched when the queued resources all load.
         *
         * The callback looks like {@link Loader.OnCompleteSignal}.
         *
         * @member {Signal}
         */this.onComplete=new _miniSignals2.default();/**
         * When the progress changes the loader and resource are disaptched.
         *
         * @memberof Loader
         * @callback OnProgressSignal
         * @param {Loader} loader - The loader the progress is advancing on.
         * @param {Resource} resource - The resource that has completed or failed to cause the progress to advance.
         *//**
         * When an error occurrs the loader and resource are disaptched.
         *
         * @memberof Loader
         * @callback OnErrorSignal
         * @param {Loader} loader - The loader the error happened in.
         * @param {Resource} resource - The resource that caused the error.
         *//**
         * When a load completes the loader and resource are disaptched.
         *
         * @memberof Loader
         * @callback OnLoadSignal
         * @param {Loader} loader - The loader that laoded the resource.
         * @param {Resource} resource - The resource that has completed loading.
         *//**
         * When the loader starts loading resources it dispatches this callback.
         *
         * @memberof Loader
         * @callback OnStartSignal
         * @param {Loader} loader - The loader that has started loading resources.
         *//**
         * When the loader completes loading resources it dispatches this callback.
         *
         * @memberof Loader
         * @callback OnCompleteSignal
         * @param {Loader} loader - The loader that has finished loading resources.
         */}/**
     * Adds a resource (or multiple resources) to the loader queue.
     *
     * This function can take a wide variety of different parameters. The only thing that is always
     * required the url to load. All the following will work:
     *
     * ```js
     * loader
     *     // normal param syntax
     *     .add('key', 'http://...', function () {})
     *     .add('http://...', function () {})
     *     .add('http://...')
     *
     *     // object syntax
     *     .add({
     *         name: 'key2',
     *         url: 'http://...'
     *     }, function () {})
     *     .add({
     *         url: 'http://...'
     *     }, function () {})
     *     .add({
     *         name: 'key3',
     *         url: 'http://...'
     *         onComplete: function () {}
     *     })
     *     .add({
     *         url: 'https://...',
     *         onComplete: function () {},
     *         crossOrigin: true
     *     })
     *
     *     // you can also pass an array of objects or urls or both
     *     .add([
     *         { name: 'key4', url: 'http://...', onComplete: function () {} },
     *         { url: 'http://...', onComplete: function () {} },
     *         'http://...'
     *     ])
     *
     *     // and you can use both params and options
     *     .add('key', 'http://...', { crossOrigin: true }, function () {})
     *     .add('http://...', { crossOrigin: true }, function () {});
     * ```
     *
     * @param {string} [name] - The name of the resource to load, if not passed the url is used.
     * @param {string} [url] - The url for this resource, relative to the baseUrl of this loader.
     * @param {object} [options] - The options for the load.
     * @param {boolean} [options.crossOrigin] - Is this request cross-origin? Default is to determine automatically.
     * @param {Resource.LOAD_TYPE} [options.loadType=Resource.LOAD_TYPE.XHR] - How should this resource be loaded?
     * @param {Resource.XHR_RESPONSE_TYPE} [options.xhrType=Resource.XHR_RESPONSE_TYPE.DEFAULT] - How should
     *      the data being loaded be interpreted when using XHR?
     * @param {object} [options.metadata] - Extra configuration for middleware and the Resource object.
     * @param {HTMLImageElement|HTMLAudioElement|HTMLVideoElement} [options.metadata.loadElement=null] - The
     *      element to use for loading, instead of creating one.
     * @param {boolean} [options.metadata.skipSource=false] - Skips adding source(s) to the load element. This
     *      is useful if you want to pass in a `loadElement` that you already added load sources to.
     * @param {function} [cb] - Function to call when this specific resource completes loading.
     * @return {Loader} Returns itself.
     */Loader.prototype.add=function add(name,url,options,cb){// special case of an array of objects or urls
if(Array.isArray(name)){for(var i=0;i<name.length;++i){this.add(name[i]);}return this;}// if an object is passed instead of params
if((typeof name==='undefined'?'undefined':_typeof(name))==='object'){cb=url||name.callback||name.onComplete;options=name;url=name.url;name=name.name||name.key||name.url;}// case where no name is passed shift all args over by one.
if(typeof url!=='string'){cb=options;options=url;url=name;}// now that we shifted make sure we have a proper url.
if(typeof url!=='string'){throw new Error('No url passed to add resource to loader.');}// options are optional so people might pass a function and no options
if(typeof options==='function'){cb=options;options=null;}// if loading already you can only add resources that have a parent.
if(this.loading&&(!options||!options.parentResource)){throw new Error('Cannot add resources while the loader is running.');}// check if resource already exists.
if(this.resources[name]){throw new Error('Resource named "'+name+'" already exists.');}// add base url if this isn't an absolute url
url=this._prepareUrl(url);// create the store the resource
this.resources[name]=new _Resource2.default(name,url,options);if(typeof cb==='function'){this.resources[name].onAfterMiddleware.once(cb);}// if loading make sure to adjust progress chunks for that parent and its children
if(this.loading){var parent=options.parentResource;var fullChunk=parent.progressChunk*(parent.children.length+1);// +1 for parent
var eachChunk=fullChunk/(parent.children.length+2);// +2 for parent & new child
parent.children.push(this.resources[name]);parent.progressChunk=eachChunk;for(var _i=0;_i<parent.children.length;++_i){parent.children[_i].progressChunk=eachChunk;}}// add the resource to the queue
this._queue.push(this.resources[name]);return this;};/**
     * Sets up a middleware function that will run *before* the
     * resource is loaded.
     *
     * @method before
     * @param {function} fn - The middleware function to register.
     * @return {Loader} Returns itself.
     */Loader.prototype.pre=function pre(fn){this._beforeMiddleware.push(fn);return this;};/**
     * Sets up a middleware function that will run *after* the
     * resource is loaded.
     *
     * @alias use
     * @method after
     * @param {function} fn - The middleware function to register.
     * @return {Loader} Returns itself.
     */Loader.prototype.use=function use(fn){this._afterMiddleware.push(fn);return this;};/**
     * Resets the queue of the loader to prepare for a new load.
     *
     * @return {Loader} Returns itself.
     */Loader.prototype.reset=function reset(){this.progress=0;this.loading=false;this._queue.kill();this._queue.pause();// abort all resource loads
for(var k in this.resources){var res=this.resources[k];if(res._onLoadBinding){res._onLoadBinding.detach();}if(res.isLoading){res.abort();}}this.resources={};return this;};/**
     * Starts loading the queued resources.
     *
     * @param {function} [cb] - Optional callback that will be bound to the `complete` event.
     * @return {Loader} Returns itself.
     */Loader.prototype.load=function load(cb){// register complete callback if they pass one
if(typeof cb==='function'){this.onComplete.once(cb);}// if the queue has already started we are done here
if(this.loading){return this;}// distribute progress chunks
var chunk=100/this._queue._tasks.length;for(var i=0;i<this._queue._tasks.length;++i){this._queue._tasks[i].data.progressChunk=chunk;}// update loading state
this.loading=true;// notify of start
this.onStart.dispatch(this);// start loading
this._queue.resume();return this;};/**
     * Prepares a url for usage based on the configuration of this object
     *
     * @private
     * @param {string} url - The url to prepare.
     * @return {string} The prepared url.
     */Loader.prototype._prepareUrl=function _prepareUrl(url){var parsedUrl=(0,_parseUri2.default)(url,{strictMode:true});var result=void 0;// absolute url, just use it as is.
if(parsedUrl.protocol||!parsedUrl.path||url.indexOf('//')===0){result=url;}// if baseUrl doesn't end in slash and url doesn't start with slash, then add a slash inbetween
else if(this.baseUrl.length&&this.baseUrl.lastIndexOf('/')!==this.baseUrl.length-1&&url.charAt(0)!=='/'){result=this.baseUrl+'/'+url;}else{result=this.baseUrl+url;}// if we need to add a default querystring, there is a bit more work
if(this.defaultQueryString){var hash=rgxExtractUrlHash.exec(result)[0];result=result.substr(0,result.length-hash.length);if(result.indexOf('?')!==-1){result+='&'+this.defaultQueryString;}else{result+='?'+this.defaultQueryString;}result+=hash;}return result;};/**
     * Loads a single resource.
     *
     * @private
     * @param {Resource} resource - The resource to load.
     * @param {function} dequeue - The function to call when we need to dequeue this item.
     */Loader.prototype._loadResource=function _loadResource(resource,dequeue){var _this2=this;resource._dequeue=dequeue;// run before middleware
async.eachSeries(this._beforeMiddleware,function(fn,next){fn.call(_this2,resource,function(){// if the before middleware marks the resource as complete,
// break and don't process any more before middleware
next(resource.isComplete?{}:null);});},function(){if(resource.isComplete){_this2._onLoad(resource);}else{resource._onLoadBinding=resource.onComplete.once(_this2._onLoad,_this2);resource.load();}});};/**
     * Called once each resource has loaded.
     *
     * @private
     */Loader.prototype._onComplete=function _onComplete(){this.loading=false;this.onComplete.dispatch(this,this.resources);};/**
     * Called each time a resources is loaded.
     *
     * @private
     * @param {Resource} resource - The resource that was loaded
     */Loader.prototype._onLoad=function _onLoad(resource){var _this3=this;resource._onLoadBinding=null;// run middleware, this *must* happen before dequeue so sub-assets get added properly
async.eachSeries(this._afterMiddleware,function(fn,next){fn.call(_this3,resource,next);},function(){resource.onAfterMiddleware.dispatch(resource);_this3.progress+=resource.progressChunk;_this3.onProgress.dispatch(_this3,resource);if(resource.error){_this3.onError.dispatch(resource.error,_this3,resource);}else{_this3.onLoad.dispatch(_this3,resource);}// remove this resource from the async queue
resource._dequeue();// do completion check
if(_this3._queue.idle()){_this3.progress=MAX_PROGRESS;_this3._onComplete();}});};return Loader;}();exports.default=Loader;},{"./Resource":31,"./async":32,"mini-signals":36,"parse-uri":37}],31:[function(require,module,exports){'use strict';exports.__esModule=true;var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor);}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor;};}();var _parseUri=require('parse-uri');var _parseUri2=_interopRequireDefault(_parseUri);var _miniSignals=require('mini-signals');var _miniSignals2=_interopRequireDefault(_miniSignals);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}// tests is CORS is supported in XHR, if not we need to use XDR
var useXdr=!!(window.XDomainRequest&&!('withCredentials'in new XMLHttpRequest()));var tempAnchor=null;// some status constants
var STATUS_NONE=0;var STATUS_OK=200;var STATUS_EMPTY=204;// noop
function _noop(){}/* empty *//**
 * Manages the state and loading of a resource and all child resources.
 *
 * @class
 */var Resource=function(){/**
     * Sets the load type to be used for a specific extension.
     *
     * @static
     * @param {string} extname - The extension to set the type for, e.g. "png" or "fnt"
     * @param {Resource.LOAD_TYPE} loadType - The load type to set it to.
     */Resource.setExtensionLoadType=function setExtensionLoadType(extname,loadType){setExtMap(Resource._loadTypeMap,extname,loadType);};/**
     * Sets the load type to be used for a specific extension.
     *
     * @static
     * @param {string} extname - The extension to set the type for, e.g. "png" or "fnt"
     * @param {Resource.XHR_RESPONSE_TYPE} xhrType - The xhr type to set it to.
     */Resource.setExtensionXhrType=function setExtensionXhrType(extname,xhrType){setExtMap(Resource._xhrTypeMap,extname,xhrType);};/**
     * @param {string} name - The name of the resource to load.
     * @param {string|string[]} url - The url for this resource, for audio/video loads you can pass
     *      an array of sources.
     * @param {object} [options] - The options for the load.
     * @param {string|boolean} [options.crossOrigin] - Is this request cross-origin? Default is to
     *      determine automatically.
     * @param {Resource.LOAD_TYPE} [options.loadType=Resource.LOAD_TYPE.XHR] - How should this resource
     *      be loaded?
     * @param {Resource.XHR_RESPONSE_TYPE} [options.xhrType=Resource.XHR_RESPONSE_TYPE.DEFAULT] - How
     *      should the data being loaded be interpreted when using XHR?
     * @param {object} [options.metadata] - Extra configuration for middleware and the Resource object.
     * @param {HTMLImageElement|HTMLAudioElement|HTMLVideoElement} [options.metadata.loadElement=null] - The
     *      element to use for loading, instead of creating one.
     * @param {boolean} [options.metadata.skipSource=false] - Skips adding source(s) to the load element. This
     *      is useful if you want to pass in a `loadElement` that you already added load sources to.
     */function Resource(name,url,options){_classCallCheck(this,Resource);if(typeof name!=='string'||typeof url!=='string'){throw new Error('Both name and url are required for constructing a resource.');}options=options||{};/**
         * The state flags of this resource.
         *
         * @member {number}
         */this._flags=0;// set data url flag, needs to be set early for some _determineX checks to work.
this._setFlag(Resource.STATUS_FLAGS.DATA_URL,url.indexOf('data:')===0);/**
         * The name of this resource.
         *
         * @member {string}
         * @readonly
         */this.name=name;/**
         * The url used to load this resource.
         *
         * @member {string}
         * @readonly
         */this.url=url;/**
         * The data that was loaded by the resource.
         *
         * @member {any}
         */this.data=null;/**
         * Is this request cross-origin? If unset, determined automatically.
         *
         * @member {string}
         */this.crossOrigin=options.crossOrigin===true?'anonymous':options.crossOrigin;/**
         * The method of loading to use for this resource.
         *
         * @member {Resource.LOAD_TYPE}
         */this.loadType=options.loadType||this._determineLoadType();/**
         * The type used to load the resource via XHR. If unset, determined automatically.
         *
         * @member {string}
         */this.xhrType=options.xhrType;/**
         * Extra info for middleware, and controlling specifics about how the resource loads.
         *
         * Note that if you pass in a `loadElement`, the Resource class takes ownership of it.
         * Meaning it will modify it as it sees fit.
         *
         * @member {object}
         * @property {HTMLImageElement|HTMLAudioElement|HTMLVideoElement} [loadElement=null] - The
         *  element to use for loading, instead of creating one.
         * @property {boolean} [skipSource=false] - Skips adding source(s) to the load element. This
         *  is useful if you want to pass in a `loadElement` that you already added load sources
         *  to.
         */this.metadata=options.metadata||{};/**
         * The error that occurred while loading (if any).
         *
         * @member {Error}
         * @readonly
         */this.error=null;/**
         * The XHR object that was used to load this resource. This is only set
         * when `loadType` is `Resource.LOAD_TYPE.XHR`.
         *
         * @member {XMLHttpRequest}
         * @readonly
         */this.xhr=null;/**
         * The child resources this resource owns.
         *
         * @member {Resource[]}
         * @readonly
         */this.children=[];/**
         * The resource type.
         *
         * @member {Resource.TYPE}
         * @readonly
         */this.type=Resource.TYPE.UNKNOWN;/**
         * The progress chunk owned by this resource.
         *
         * @member {number}
         * @readonly
         */this.progressChunk=0;/**
         * The `dequeue` method that will be used a storage place for the async queue dequeue method
         * used privately by the loader.
         *
         * @private
         * @member {function}
         */this._dequeue=_noop;/**
         * Used a storage place for the on load binding used privately by the loader.
         *
         * @private
         * @member {function}
         */this._onLoadBinding=null;/**
         * The `complete` function bound to this resource's context.
         *
         * @private
         * @member {function}
         */this._boundComplete=this.complete.bind(this);/**
         * The `_onError` function bound to this resource's context.
         *
         * @private
         * @member {function}
         */this._boundOnError=this._onError.bind(this);/**
         * The `_onProgress` function bound to this resource's context.
         *
         * @private
         * @member {function}
         */this._boundOnProgress=this._onProgress.bind(this);// xhr callbacks
this._boundXhrOnError=this._xhrOnError.bind(this);this._boundXhrOnAbort=this._xhrOnAbort.bind(this);this._boundXhrOnLoad=this._xhrOnLoad.bind(this);this._boundXdrOnTimeout=this._xdrOnTimeout.bind(this);/**
         * Dispatched when the resource beings to load.
         *
         * The callback looks like {@link Resource.OnStartSignal}.
         *
         * @member {Signal}
         */this.onStart=new _miniSignals2.default();/**
         * Dispatched each time progress of this resource load updates.
         * Not all resources types and loader systems can support this event
         * so sometimes it may not be available. If the resource
         * is being loaded on a modern browser, using XHR, and the remote server
         * properly sets Content-Length headers, then this will be available.
         *
         * The callback looks like {@link Resource.OnProgressSignal}.
         *
         * @member {Signal}
         */this.onProgress=new _miniSignals2.default();/**
         * Dispatched once this resource has loaded, if there was an error it will
         * be in the `error` property.
         *
         * The callback looks like {@link Resource.OnCompleteSignal}.
         *
         * @member {Signal}
         */this.onComplete=new _miniSignals2.default();/**
         * Dispatched after this resource has had all the *after* middleware run on it.
         *
         * The callback looks like {@link Resource.OnCompleteSignal}.
         *
         * @member {Signal}
         */this.onAfterMiddleware=new _miniSignals2.default();/**
         * When the resource starts to load.
         *
         * @memberof Resource
         * @callback OnStartSignal
         * @param {Resource} resource - The resource that the event happened on.
         *//**
         * When the resource reports loading progress.
         *
         * @memberof Resource
         * @callback OnProgressSignal
         * @param {Resource} resource - The resource that the event happened on.
         * @param {number} percentage - The progress of the load in the range [0, 1].
         *//**
         * When the resource finishes loading.
         *
         * @memberof Resource
         * @callback OnCompleteSignal
         * @param {Resource} resource - The resource that the event happened on.
         */}/**
     * Stores whether or not this url is a data url.
     *
     * @member {boolean}
     * @readonly
     *//**
     * Marks the resource as complete.
     *
     */Resource.prototype.complete=function complete(){// TODO: Clean this up in a wrapper or something...gross....
if(this.data&&this.data.removeEventListener){this.data.removeEventListener('error',this._boundOnError,false);this.data.removeEventListener('load',this._boundComplete,false);this.data.removeEventListener('progress',this._boundOnProgress,false);this.data.removeEventListener('canplaythrough',this._boundComplete,false);}if(this.xhr){if(this.xhr.removeEventListener){this.xhr.removeEventListener('error',this._boundXhrOnError,false);this.xhr.removeEventListener('abort',this._boundXhrOnAbort,false);this.xhr.removeEventListener('progress',this._boundOnProgress,false);this.xhr.removeEventListener('load',this._boundXhrOnLoad,false);}else{this.xhr.onerror=null;this.xhr.ontimeout=null;this.xhr.onprogress=null;this.xhr.onload=null;}}if(this.isComplete){throw new Error('Complete called again for an already completed resource.');}this._setFlag(Resource.STATUS_FLAGS.COMPLETE,true);this._setFlag(Resource.STATUS_FLAGS.LOADING,false);this.onComplete.dispatch(this);};/**
     * Aborts the loading of this resource, with an optional message.
     *
     * @param {string} message - The message to use for the error
     */Resource.prototype.abort=function abort(message){// abort can be called multiple times, ignore subsequent calls.
if(this.error){return;}// store error
this.error=new Error(message);// abort the actual loading
if(this.xhr){this.xhr.abort();}else if(this.xdr){this.xdr.abort();}else if(this.data){// single source
if(this.data.src){this.data.src=Resource.EMPTY_GIF;}// multi-source
else{while(this.data.firstChild){this.data.removeChild(this.data.firstChild);}}}// done now.
this.complete();};/**
     * Kicks off loading of this resource. This method is asynchronous.
     *
     * @param {function} [cb] - Optional callback to call once the resource is loaded.
     */Resource.prototype.load=function load(cb){var _this=this;if(this.isLoading){return;}if(this.isComplete){if(cb){setTimeout(function(){return cb(_this);},1);}return;}else if(cb){this.onComplete.once(cb);}this._setFlag(Resource.STATUS_FLAGS.LOADING,true);this.onStart.dispatch(this);// if unset, determine the value
if(this.crossOrigin===false||typeof this.crossOrigin!=='string'){this.crossOrigin=this._determineCrossOrigin(this.url);}switch(this.loadType){case Resource.LOAD_TYPE.IMAGE:this.type=Resource.TYPE.IMAGE;this._loadElement('image');break;case Resource.LOAD_TYPE.AUDIO:this.type=Resource.TYPE.AUDIO;this._loadSourceElement('audio');break;case Resource.LOAD_TYPE.VIDEO:this.type=Resource.TYPE.VIDEO;this._loadSourceElement('video');break;case Resource.LOAD_TYPE.XHR:/* falls through */default:if(useXdr&&this.crossOrigin){this._loadXdr();}else{this._loadXhr();}break;}};/**
     * Checks if the flag is set.
     *
     * @private
     * @param {number} flag - The flag to check.
     * @return {boolean} True if the flag is set.
     */Resource.prototype._hasFlag=function _hasFlag(flag){return!!(this._flags&flag);};/**
     * (Un)Sets the flag.
     *
     * @private
     * @param {number} flag - The flag to (un)set.
     * @param {boolean} value - Whether to set or (un)set the flag.
     */Resource.prototype._setFlag=function _setFlag(flag,value){this._flags=value?this._flags|flag:this._flags&~flag;};/**
     * Loads this resources using an element that has a single source,
     * like an HTMLImageElement.
     *
     * @private
     * @param {string} type - The type of element to use.
     */Resource.prototype._loadElement=function _loadElement(type){if(this.metadata.loadElement){this.data=this.metadata.loadElement;}else if(type==='image'&&typeof window.Image!=='undefined'){this.data=new Image();}else{this.data=document.createElement(type);}if(this.crossOrigin){this.data.crossOrigin=this.crossOrigin;}if(!this.metadata.skipSource){this.data.src=this.url;}this.data.addEventListener('error',this._boundOnError,false);this.data.addEventListener('load',this._boundComplete,false);this.data.addEventListener('progress',this._boundOnProgress,false);};/**
     * Loads this resources using an element that has multiple sources,
     * like an HTMLAudioElement or HTMLVideoElement.
     *
     * @private
     * @param {string} type - The type of element to use.
     */Resource.prototype._loadSourceElement=function _loadSourceElement(type){if(this.metadata.loadElement){this.data=this.metadata.loadElement;}else if(type==='audio'&&typeof window.Audio!=='undefined'){this.data=new Audio();}else{this.data=document.createElement(type);}if(this.data===null){this.abort('Unsupported element: '+type);return;}if(!this.metadata.skipSource){// support for CocoonJS Canvas+ runtime, lacks document.createElement('source')
if(navigator.isCocoonJS){this.data.src=Array.isArray(this.url)?this.url[0]:this.url;}else if(Array.isArray(this.url)){for(var i=0;i<this.url.length;++i){this.data.appendChild(this._createSource(type,this.url[i]));}}else{this.data.appendChild(this._createSource(type,this.url));}}this.data.addEventListener('error',this._boundOnError,false);this.data.addEventListener('load',this._boundComplete,false);this.data.addEventListener('progress',this._boundOnProgress,false);this.data.addEventListener('canplaythrough',this._boundComplete,false);this.data.load();};/**
     * Loads this resources using an XMLHttpRequest.
     *
     * @private
     */Resource.prototype._loadXhr=function _loadXhr(){// if unset, determine the value
if(typeof this.xhrType!=='string'){this.xhrType=this._determineXhrType();}var xhr=this.xhr=new XMLHttpRequest();// set the request type and url
xhr.open('GET',this.url,true);// load json as text and parse it ourselves. We do this because some browsers
// *cough* safari *cough* can't deal with it.
if(this.xhrType===Resource.XHR_RESPONSE_TYPE.JSON||this.xhrType===Resource.XHR_RESPONSE_TYPE.DOCUMENT){xhr.responseType=Resource.XHR_RESPONSE_TYPE.TEXT;}else{xhr.responseType=this.xhrType;}xhr.addEventListener('error',this._boundXhrOnError,false);xhr.addEventListener('abort',this._boundXhrOnAbort,false);xhr.addEventListener('progress',this._boundOnProgress,false);xhr.addEventListener('load',this._boundXhrOnLoad,false);xhr.send();};/**
     * Loads this resources using an XDomainRequest. This is here because we need to support IE9 (gross).
     *
     * @private
     */Resource.prototype._loadXdr=function _loadXdr(){// if unset, determine the value
if(typeof this.xhrType!=='string'){this.xhrType=this._determineXhrType();}var xdr=this.xhr=new XDomainRequest();// XDomainRequest has a few quirks. Occasionally it will abort requests
// A way to avoid this is to make sure ALL callbacks are set even if not used
// More info here: http://stackoverflow.com/questions/15786966/xdomainrequest-aborts-post-on-ie-9
xdr.timeout=5000;xdr.onerror=this._boundXhrOnError;xdr.ontimeout=this._boundXdrOnTimeout;xdr.onprogress=this._boundOnProgress;xdr.onload=this._boundXhrOnLoad;xdr.open('GET',this.url,true);// Note: The xdr.send() call is wrapped in a timeout to prevent an
// issue with the interface where some requests are lost if multiple
// XDomainRequests are being sent at the same time.
// Some info here: https://github.com/photonstorm/phaser/issues/1248
setTimeout(function(){return xdr.send();},1);};/**
     * Creates a source used in loading via an element.
     *
     * @private
     * @param {string} type - The element type (video or audio).
     * @param {string} url - The source URL to load from.
     * @param {string} [mime] - The mime type of the video
     * @return {HTMLSourceElement} The source element.
     */Resource.prototype._createSource=function _createSource(type,url,mime){if(!mime){mime=type+'/'+url.substr(url.lastIndexOf('.')+1);}var source=document.createElement('source');source.src=url;source.type=mime;return source;};/**
     * Called if a load errors out.
     *
     * @param {Event} event - The error event from the element that emits it.
     * @private
     */Resource.prototype._onError=function _onError(event){this.abort('Failed to load element using: '+event.target.nodeName);};/**
     * Called if a load progress event fires for xhr/xdr.
     *
     * @private
     * @param {XMLHttpRequestProgressEvent|Event} event - Progress event.
     */Resource.prototype._onProgress=function _onProgress(event){if(event&&event.lengthComputable){this.onProgress.dispatch(this,event.loaded/event.total);}};/**
     * Called if an error event fires for xhr/xdr.
     *
     * @private
     * @param {XMLHttpRequestErrorEvent|Event} event - Error event.
     */Resource.prototype._xhrOnError=function _xhrOnError(){var xhr=this.xhr;this.abort(reqType(xhr)+' Request failed. Status: '+xhr.status+', text: "'+xhr.statusText+'"');};/**
     * Called if an abort event fires for xhr.
     *
     * @private
     * @param {XMLHttpRequestAbortEvent} event - Abort Event
     */Resource.prototype._xhrOnAbort=function _xhrOnAbort(){this.abort(reqType(this.xhr)+' Request was aborted by the user.');};/**
     * Called if a timeout event fires for xdr.
     *
     * @private
     * @param {Event} event - Timeout event.
     */Resource.prototype._xdrOnTimeout=function _xdrOnTimeout(){this.abort(reqType(this.xhr)+' Request timed out.');};/**
     * Called when data successfully loads from an xhr/xdr request.
     *
     * @private
     * @param {XMLHttpRequestLoadEvent|Event} event - Load event
     */Resource.prototype._xhrOnLoad=function _xhrOnLoad(){var xhr=this.xhr;var status=typeof xhr.status==='undefined'?xhr.status:STATUS_OK;// XDR has no `.status`, assume 200.
// status can be 0 when using the `file://` protocol so we also check if a response is set
if(status===STATUS_OK||status===STATUS_EMPTY||status===STATUS_NONE&&xhr.responseText.length>0){// if text, just return it
if(this.xhrType===Resource.XHR_RESPONSE_TYPE.TEXT){this.data=xhr.responseText;this.type=Resource.TYPE.TEXT;}// if json, parse into json object
else if(this.xhrType===Resource.XHR_RESPONSE_TYPE.JSON){try{this.data=JSON.parse(xhr.responseText);this.type=Resource.TYPE.JSON;}catch(e){this.abort('Error trying to parse loaded json: '+e);return;}}// if xml, parse into an xml document or div element
else if(this.xhrType===Resource.XHR_RESPONSE_TYPE.DOCUMENT){try{if(window.DOMParser){var domparser=new DOMParser();this.data=domparser.parseFromString(xhr.responseText,'text/xml');}else{var div=document.createElement('div');div.innerHTML=xhr.responseText;this.data=div;}this.type=Resource.TYPE.XML;}catch(e){this.abort('Error trying to parse loaded xml: '+e);return;}}// other types just return the response
else{this.data=xhr.response||xhr.responseText;}}else{this.abort('['+xhr.status+'] '+xhr.statusText+': '+xhr.responseURL);return;}this.complete();};/**
     * Sets the `crossOrigin` property for this resource based on if the url
     * for this resource is cross-origin. If crossOrigin was manually set, this
     * function does nothing.
     *
     * @private
     * @param {string} url - The url to test.
     * @param {object} [loc=window.location] - The location object to test against.
     * @return {string} The crossOrigin value to use (or empty string for none).
     */Resource.prototype._determineCrossOrigin=function _determineCrossOrigin(url,loc){// data: and javascript: urls are considered same-origin
if(url.indexOf('data:')===0){return'';}// default is window.location
loc=loc||window.location;if(!tempAnchor){tempAnchor=document.createElement('a');}// let the browser determine the full href for the url of this resource and then
// parse with the node url lib, we can't use the properties of the anchor element
// because they don't work in IE9 :(
tempAnchor.href=url;url=(0,_parseUri2.default)(tempAnchor.href,{strictMode:true});var samePort=!url.port&&loc.port===''||url.port===loc.port;var protocol=url.protocol?url.protocol+':':'';// if cross origin
if(url.host!==loc.hostname||!samePort||protocol!==loc.protocol){return'anonymous';}return'';};/**
     * Determines the responseType of an XHR request based on the extension of the
     * resource being loaded.
     *
     * @private
     * @return {Resource.XHR_RESPONSE_TYPE} The responseType to use.
     */Resource.prototype._determineXhrType=function _determineXhrType(){return Resource._xhrTypeMap[this._getExtension()]||Resource.XHR_RESPONSE_TYPE.TEXT;};/**
     * Determines the loadType of a resource based on the extension of the
     * resource being loaded.
     *
     * @private
     * @return {Resource.LOAD_TYPE} The loadType to use.
     */Resource.prototype._determineLoadType=function _determineLoadType(){return Resource._loadTypeMap[this._getExtension()]||Resource.LOAD_TYPE.XHR;};/**
     * Extracts the extension (sans '.') of the file being loaded by the resource.
     *
     * @private
     * @return {string} The extension.
     */Resource.prototype._getExtension=function _getExtension(){var url=this.url;var ext='';if(this.isDataUrl){var slashIndex=url.indexOf('/');ext=url.substring(slashIndex+1,url.indexOf(';',slashIndex));}else{var queryStart=url.indexOf('?');if(queryStart!==-1){url=url.substring(0,queryStart);}ext=url.substring(url.lastIndexOf('.')+1);}return ext.toLowerCase();};/**
     * Determines the mime type of an XHR request based on the responseType of
     * resource being loaded.
     *
     * @private
     * @param {Resource.XHR_RESPONSE_TYPE} type - The type to get a mime type for.
     * @return {string} The mime type to use.
     */Resource.prototype._getMimeFromXhrType=function _getMimeFromXhrType(type){switch(type){case Resource.XHR_RESPONSE_TYPE.BUFFER:return'application/octet-binary';case Resource.XHR_RESPONSE_TYPE.BLOB:return'application/blob';case Resource.XHR_RESPONSE_TYPE.DOCUMENT:return'application/xml';case Resource.XHR_RESPONSE_TYPE.JSON:return'application/json';case Resource.XHR_RESPONSE_TYPE.DEFAULT:case Resource.XHR_RESPONSE_TYPE.TEXT:/* falls through */default:return'text/plain';}};_createClass(Resource,[{key:'isDataUrl',get:function get(){return this._hasFlag(Resource.STATUS_FLAGS.DATA_URL);}/**
         * Describes if this resource has finished loading. Is true when the resource has completely
         * loaded.
         *
         * @member {boolean}
         * @readonly
         */},{key:'isComplete',get:function get(){return this._hasFlag(Resource.STATUS_FLAGS.COMPLETE);}/**
         * Describes if this resource is currently loading. Is true when the resource starts loading,
         * and is false again when complete.
         *
         * @member {boolean}
         * @readonly
         */},{key:'isLoading',get:function get(){return this._hasFlag(Resource.STATUS_FLAGS.LOADING);}}]);return Resource;}();/**
 * The types of resources a resource could represent.
 *
 * @static
 * @readonly
 * @enum {number}
 */exports.default=Resource;Resource.STATUS_FLAGS={NONE:0,DATA_URL:1<<0,COMPLETE:1<<1,LOADING:1<<2};/**
 * The types of resources a resource could represent.
 *
 * @static
 * @readonly
 * @enum {number}
 */Resource.TYPE={UNKNOWN:0,JSON:1,XML:2,IMAGE:3,AUDIO:4,VIDEO:5,TEXT:6};/**
 * The types of loading a resource can use.
 *
 * @static
 * @readonly
 * @enum {number}
 */Resource.LOAD_TYPE={/** Uses XMLHttpRequest to load the resource. */XHR:1,/** Uses an `Image` object to load the resource. */IMAGE:2,/** Uses an `Audio` object to load the resource. */AUDIO:3,/** Uses a `Video` object to load the resource. */VIDEO:4};/**
 * The XHR ready states, used internally.
 *
 * @static
 * @readonly
 * @enum {string}
 */Resource.XHR_RESPONSE_TYPE={/** string */DEFAULT:'text',/** ArrayBuffer */BUFFER:'arraybuffer',/** Blob */BLOB:'blob',/** Document */DOCUMENT:'document',/** Object */JSON:'json',/** String */TEXT:'text'};Resource._loadTypeMap={// images
gif:Resource.LOAD_TYPE.IMAGE,png:Resource.LOAD_TYPE.IMAGE,bmp:Resource.LOAD_TYPE.IMAGE,jpg:Resource.LOAD_TYPE.IMAGE,jpeg:Resource.LOAD_TYPE.IMAGE,tif:Resource.LOAD_TYPE.IMAGE,tiff:Resource.LOAD_TYPE.IMAGE,webp:Resource.LOAD_TYPE.IMAGE,tga:Resource.LOAD_TYPE.IMAGE,svg:Resource.LOAD_TYPE.IMAGE,'svg+xml':Resource.LOAD_TYPE.IMAGE,// for SVG data urls
// audio
mp3:Resource.LOAD_TYPE.AUDIO,ogg:Resource.LOAD_TYPE.AUDIO,wav:Resource.LOAD_TYPE.AUDIO,// videos
mp4:Resource.LOAD_TYPE.VIDEO,webm:Resource.LOAD_TYPE.VIDEO};Resource._xhrTypeMap={// xml
xhtml:Resource.XHR_RESPONSE_TYPE.DOCUMENT,html:Resource.XHR_RESPONSE_TYPE.DOCUMENT,htm:Resource.XHR_RESPONSE_TYPE.DOCUMENT,xml:Resource.XHR_RESPONSE_TYPE.DOCUMENT,tmx:Resource.XHR_RESPONSE_TYPE.DOCUMENT,svg:Resource.XHR_RESPONSE_TYPE.DOCUMENT,// This was added to handle Tiled Tileset XML, but .tsx is also a TypeScript React Component.
// Since it is way less likely for people to be loading TypeScript files instead of Tiled files,
// this should probably be fine.
tsx:Resource.XHR_RESPONSE_TYPE.DOCUMENT,// images
gif:Resource.XHR_RESPONSE_TYPE.BLOB,png:Resource.XHR_RESPONSE_TYPE.BLOB,bmp:Resource.XHR_RESPONSE_TYPE.BLOB,jpg:Resource.XHR_RESPONSE_TYPE.BLOB,jpeg:Resource.XHR_RESPONSE_TYPE.BLOB,tif:Resource.XHR_RESPONSE_TYPE.BLOB,tiff:Resource.XHR_RESPONSE_TYPE.BLOB,webp:Resource.XHR_RESPONSE_TYPE.BLOB,tga:Resource.XHR_RESPONSE_TYPE.BLOB,// json
json:Resource.XHR_RESPONSE_TYPE.JSON,// text
text:Resource.XHR_RESPONSE_TYPE.TEXT,txt:Resource.XHR_RESPONSE_TYPE.TEXT,// fonts
ttf:Resource.XHR_RESPONSE_TYPE.BUFFER,otf:Resource.XHR_RESPONSE_TYPE.BUFFER};// We can't set the `src` attribute to empty string, so on abort we set it to this 1px transparent gif
Resource.EMPTY_GIF='data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==';/**
 * Quick helper to set a value on one of the extension maps. Ensures there is no
 * dot at the start of the extension.
 *
 * @ignore
 * @param {object} map - The map to set on.
 * @param {string} extname - The extension (or key) to set.
 * @param {number} val - The value to set.
 */function setExtMap(map,extname,val){if(extname&&extname.indexOf('.')===0){extname=extname.substring(1);}if(!extname){return;}map[extname]=val;}/**
 * Quick helper to get string xhr type.
 *
 * @ignore
 * @param {XMLHttpRequest|XDomainRequest} xhr - The request to check.
 * @return {string} The type.
 */function reqType(xhr){return xhr.toString().replace('object ','');}},{"mini-signals":36,"parse-uri":37}],32:[function(require,module,exports){'use strict';exports.__esModule=true;exports.eachSeries=eachSeries;exports.queue=queue;/**
 * Smaller version of the async library constructs.
 *
 */function _noop(){}/* empty *//**
 * Iterates an array in series.
 *
 * @param {*[]} array - Array to iterate.
 * @param {function} iterator - Function to call for each element.
 * @param {function} callback - Function to call when done, or on error.
 */function eachSeries(array,iterator,callback){var i=0;var len=array.length;(function next(err){if(err||i===len){if(callback){callback(err);}return;}iterator(array[i++],next);})();}/**
 * Ensures a function is only called once.
 *
 * @param {function} fn - The function to wrap.
 * @return {function} The wrapping function.
 */function onlyOnce(fn){return function onceWrapper(){if(fn===null){throw new Error('Callback was already called.');}var callFn=fn;fn=null;callFn.apply(this,arguments);};}/**
 * Async queue implementation,
 *
 * @param {function} worker - The worker function to call for each task.
 * @param {number} concurrency - How many workers to run in parrallel.
 * @return {*} The async queue object.
 */function queue(worker,concurrency){if(concurrency==null){// eslint-disable-line no-eq-null,eqeqeq
concurrency=1;}else if(concurrency===0){throw new Error('Concurrency must not be zero');}var workers=0;var q={_tasks:[],concurrency:concurrency,saturated:_noop,unsaturated:_noop,buffer:concurrency/4,empty:_noop,drain:_noop,error:_noop,started:false,paused:false,push:function push(data,callback){_insert(data,false,callback);},kill:function kill(){workers=0;q.drain=_noop;q.started=false;q._tasks=[];},unshift:function unshift(data,callback){_insert(data,true,callback);},process:function process(){while(!q.paused&&workers<q.concurrency&&q._tasks.length){var task=q._tasks.shift();if(q._tasks.length===0){q.empty();}workers+=1;if(workers===q.concurrency){q.saturated();}worker(task.data,onlyOnce(_next(task)));}},length:function length(){return q._tasks.length;},running:function running(){return workers;},idle:function idle(){return q._tasks.length+workers===0;},pause:function pause(){if(q.paused===true){return;}q.paused=true;},resume:function resume(){if(q.paused===false){return;}q.paused=false;// Need to call q.process once per concurrent
// worker to preserve full concurrency after pause
for(var w=1;w<=q.concurrency;w++){q.process();}}};function _insert(data,insertAtFront,callback){if(callback!=null&&typeof callback!=='function'){// eslint-disable-line no-eq-null,eqeqeq
throw new Error('task callback must be a function');}q.started=true;if(data==null&&q.idle()){// eslint-disable-line no-eq-null,eqeqeq
// call drain immediately if there are no tasks
setTimeout(function(){return q.drain();},1);return;}var item={data:data,callback:typeof callback==='function'?callback:_noop};if(insertAtFront){q._tasks.unshift(item);}else{q._tasks.push(item);}setTimeout(function(){return q.process();},1);}function _next(task){return function next(){workers-=1;task.callback.apply(task,arguments);if(arguments[0]!=null){// eslint-disable-line no-eq-null,eqeqeq
q.error(arguments[0],task.data);}if(workers<=q.concurrency-q.buffer){q.unsaturated();}if(q.idle()){q.drain();}q.process();};}return q;}},{}],33:[function(require,module,exports){'use strict';exports.__esModule=true;exports.encodeBinary=encodeBinary;var _keyStr='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';function encodeBinary(input){var output='';var inx=0;while(inx<input.length){// Fill byte buffer array
var bytebuffer=[0,0,0];var encodedCharIndexes=[0,0,0,0];for(var jnx=0;jnx<bytebuffer.length;++jnx){if(inx<input.length){// throw away high-order byte, as documented at:
// https://developer.mozilla.org/En/Using_XMLHttpRequest#Handling_binary_data
bytebuffer[jnx]=input.charCodeAt(inx++)&0xff;}else{bytebuffer[jnx]=0;}}// Get each encoded character, 6 bits at a time
// index 1: first 6 bits
encodedCharIndexes[0]=bytebuffer[0]>>2;// index 2: second 6 bits (2 least significant bits from input byte 1 + 4 most significant bits from byte 2)
encodedCharIndexes[1]=(bytebuffer[0]&0x3)<<4|bytebuffer[1]>>4;// index 3: third 6 bits (4 least significant bits from input byte 2 + 2 most significant bits from byte 3)
encodedCharIndexes[2]=(bytebuffer[1]&0x0f)<<2|bytebuffer[2]>>6;// index 3: forth 6 bits (6 least significant bits from input byte 3)
encodedCharIndexes[3]=bytebuffer[2]&0x3f;// Determine whether padding happened, and adjust accordingly
var paddingBytes=inx-(input.length-1);switch(paddingBytes){case 2:// Set last 2 characters to padding char
encodedCharIndexes[3]=64;encodedCharIndexes[2]=64;break;case 1:// Set last character to padding char
encodedCharIndexes[3]=64;break;default:break;// No padding - proceed
}// Now we will grab each appropriate character out of our keystring
// based on our index array and append it to the output string
for(var _jnx=0;_jnx<encodedCharIndexes.length;++_jnx){output+=_keyStr.charAt(encodedCharIndexes[_jnx]);}}return output;}},{}],34:[function(require,module,exports){'use strict';exports.__esModule=true;var _Loader=require('./Loader');var _Loader2=_interopRequireDefault(_Loader);var _Resource=require('./Resource');var _Resource2=_interopRequireDefault(_Resource);var _async=require('./async');var async=_interopRequireWildcard(_async);var _b=require('./b64');var b64=_interopRequireWildcard(_b);function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj;}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key];}}newObj.default=obj;return newObj;}}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}_Loader2.default.Resource=_Resource2.default;_Loader2.default.async=async;_Loader2.default.base64=b64;// export manually, and also as default
module.exports=_Loader2.default;// eslint-disable-line no-undef
exports.default=_Loader2.default;},{"./Loader":30,"./Resource":31,"./async":32,"./b64":33}],35:[function(require,module,exports){'use strict';exports.__esModule=true;var _typeof=typeof Symbol==="function"&&_typeof2(Symbol.iterator)==="symbol"?function(obj){return typeof obj==="undefined"?"undefined":_typeof2(obj);}:function(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj==="undefined"?"undefined":_typeof2(obj);};exports.blobMiddlewareFactory=blobMiddlewareFactory;var _Resource=require('../../Resource');var _Resource2=_interopRequireDefault(_Resource);var _b=require('../../b64');var _b2=_interopRequireDefault(_b);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}var Url=window.URL||window.webkitURL;// a middleware for transforming XHR loaded Blobs into more useful objects
function blobMiddlewareFactory(){return function blobMiddleware(resource,next){if(!resource.data){next();return;}// if this was an XHR load of a blob
if(resource.xhr&&resource.xhrType===_Resource2.default.XHR_RESPONSE_TYPE.BLOB){// if there is no blob support we probably got a binary string back
if(!window.Blob||typeof resource.data==='string'){var type=resource.xhr.getResponseHeader('content-type');// this is an image, convert the binary string into a data url
if(type&&type.indexOf('image')===0){resource.data=new Image();resource.data.src='data:'+type+';base64,'+_b2.default.encodeBinary(resource.xhr.responseText);resource.type=_Resource2.default.TYPE.IMAGE;// wait until the image loads and then callback
resource.data.onload=function(){resource.data.onload=null;next();};// next will be called on load
return;}}// if content type says this is an image, then we should transform the blob into an Image object
else if(resource.data.type.indexOf('image')===0){var _ret=function(){var src=Url.createObjectURL(resource.data);resource.blob=resource.data;resource.data=new Image();resource.data.src=src;resource.type=_Resource2.default.TYPE.IMAGE;// cleanup the no longer used blob after the image loads
// TODO: Is this correct? Will the image be invalid after revoking?
resource.data.onload=function(){Url.revokeObjectURL(src);resource.data.onload=null;next();};// next will be called on load.
return{v:void 0};}();if((typeof _ret==='undefined'?'undefined':_typeof(_ret))==="object")return _ret.v;}}next();};}},{"../../Resource":31,"../../b64":33}],36:[function(require,module,exports){'use strict';Object.defineProperty(exports,'__esModule',{value:true});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if('value'in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor);}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor;};}();function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError('Cannot call a class as a function');}}var MiniSignalBinding=function(){function MiniSignalBinding(fn,once,thisArg){if(once===undefined)once=false;_classCallCheck(this,MiniSignalBinding);this._fn=fn;this._once=once;this._thisArg=thisArg;this._next=this._prev=this._owner=null;}_createClass(MiniSignalBinding,[{key:'detach',value:function detach(){if(this._owner===null)return false;this._owner.detach(this);return true;}}]);return MiniSignalBinding;}();function _addMiniSignalBinding(self,node){if(!self._head){self._head=node;self._tail=node;}else{self._tail._next=node;node._prev=self._tail;self._tail=node;}node._owner=self;return node;}var MiniSignal=function(){function MiniSignal(){_classCallCheck(this,MiniSignal);this._head=this._tail=undefined;}_createClass(MiniSignal,[{key:'handlers',value:function handlers(){var exists=arguments.length<=0||arguments[0]===undefined?false:arguments[0];var node=this._head;if(exists)return!!node;var ee=[];while(node){ee.push(node);node=node._next;}return ee;}},{key:'has',value:function has(node){if(!(node instanceof MiniSignalBinding)){throw new Error('MiniSignal#has(): First arg must be a MiniSignalBinding object.');}return node._owner===this;}},{key:'dispatch',value:function dispatch(){var node=this._head;if(!node)return false;while(node){if(node._once)this.detach(node);node._fn.apply(node._thisArg,arguments);node=node._next;}return true;}},{key:'add',value:function add(fn){var thisArg=arguments.length<=1||arguments[1]===undefined?null:arguments[1];if(typeof fn!=='function'){throw new Error('MiniSignal#add(): First arg must be a Function.');}return _addMiniSignalBinding(this,new MiniSignalBinding(fn,false,thisArg));}},{key:'once',value:function once(fn){var thisArg=arguments.length<=1||arguments[1]===undefined?null:arguments[1];if(typeof fn!=='function'){throw new Error('MiniSignal#once(): First arg must be a Function.');}return _addMiniSignalBinding(this,new MiniSignalBinding(fn,true,thisArg));}},{key:'detach',value:function detach(node){if(!(node instanceof MiniSignalBinding)){throw new Error('MiniSignal#detach(): First arg must be a MiniSignalBinding object.');}if(node._owner!==this)return this;if(node._prev)node._prev._next=node._next;if(node._next)node._next._prev=node._prev;if(node===this._head){this._head=node._next;if(node._next===null){this._tail=null;}}else if(node===this._tail){this._tail=node._prev;this._tail._next=null;}node._owner=null;return this;}},{key:'detachAll',value:function detachAll(){var node=this._head;if(!node)return this;this._head=this._tail=null;while(node){node._owner=null;node=node._next;}return this;}}]);return MiniSignal;}();MiniSignal.MiniSignalBinding=MiniSignalBinding;exports['default']=MiniSignal;module.exports=exports['default'];},{}],37:[function(require,module,exports){'use strict';module.exports=function parseURI(str,opts){opts=opts||{};var o={key:['source','protocol','authority','userInfo','user','password','host','port','relative','path','directory','file','query','anchor'],q:{name:'queryKey',parser:/(?:^|&)([^&=]*)=?([^&]*)/g},parser:{strict:/^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,loose:/^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/}};var m=o.parser[opts.strictMode?'strict':'loose'].exec(str);var uri={};var i=14;while(i--){uri[o.key[i]]=m[i]||'';}uri[o.q.name]={};uri[o.key[12]].replace(o.q.parser,function($0,$1,$2){if($1)uri[o.q.name][$1]=$2;});return uri;};},{}],38:[function(require,module,exports){'use strict';exports.__esModule=true;var _core=require('../core');var core=_interopRequireWildcard(_core);var _ismobilejs=require('ismobilejs');var _ismobilejs2=_interopRequireDefault(_ismobilejs);var _accessibleTarget=require('./accessibleTarget');var _accessibleTarget2=_interopRequireDefault(_accessibleTarget);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj;}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key];}}newObj.default=obj;return newObj;}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}// add some extra variables to the container..
Object.assign(core.DisplayObject.prototype,_accessibleTarget2.default);var KEY_CODE_TAB=9;var DIV_TOUCH_SIZE=100;var DIV_TOUCH_POS_X=0;var DIV_TOUCH_POS_Y=0;var DIV_TOUCH_ZINDEX=2;var DIV_HOOK_SIZE=1;var DIV_HOOK_POS_X=-1000;var DIV_HOOK_POS_Y=-1000;var DIV_HOOK_ZINDEX=2;/**
 * The Accessibility manager reacreates the ability to tab and and have content read by screen
 * readers. This is very important as it can possibly help people with disabilities access pixi
 * content.
 *
 * Much like interaction any DisplayObject can be made accessible. This manager will map the
 * events as if the mouse was being used, minimizing the efferot required to implement.
 *
 * @class
 * @memberof PIXI
 */var AccessibilityManager=function(){/**
     * @param {PIXI.CanvasRenderer|PIXI.WebGLRenderer} renderer - A reference to the current renderer
     */function AccessibilityManager(renderer){_classCallCheck(this,AccessibilityManager);if((_ismobilejs2.default.tablet||_ismobilejs2.default.phone)&&!navigator.isCocoonJS){this.createTouchHook();}// first we create a div that will sit over the pixi element. This is where the div overlays will go.
var div=document.createElement('div');div.style.width=DIV_TOUCH_SIZE+'px';div.style.height=DIV_TOUCH_SIZE+'px';div.style.position='absolute';div.style.top=DIV_TOUCH_POS_X+'px';div.style.left=DIV_TOUCH_POS_Y+'px';div.style.zIndex=DIV_TOUCH_ZINDEX;/**
         * This is the dom element that will sit over the pixi element. This is where the div overlays will go.
         *
         * @type {HTMLElement}
         * @private
         */this.div=div;/**
         * A simple pool for storing divs.
         *
         * @type {*}
         * @private
         */this.pool=[];/**
         * This is a tick used to check if an object is no longer being rendered.
         *
         * @type {Number}
         * @private
         */this.renderId=0;/**
         * Setting this to true will visually show the divs
         *
         * @type {boolean}
         */this.debug=false;/**
         * The renderer this accessibility manager works for.
         *
         * @member {PIXI.SystemRenderer}
         */this.renderer=renderer;/**
         * The array of currently active accessible items.
         *
         * @member {Array<*>}
         * @private
         */this.children=[];/**
         * pre-bind the functions
         *
         * @private
         */this._onKeyDown=this._onKeyDown.bind(this);this._onMouseMove=this._onMouseMove.bind(this);/**
         * stores the state of the manager. If there are no accessible objects or the mouse is moving the will be false.
         *
         * @member {Array<*>}
         * @private
         */this.isActive=false;this.isMobileAccessabillity=false;// let listen for tab.. once pressed we can fire up and show the accessibility layer
window.addEventListener('keydown',this._onKeyDown,false);}/**
     * Creates the touch hooks.
     *
     */AccessibilityManager.prototype.createTouchHook=function createTouchHook(){var _this=this;var hookDiv=document.createElement('button');hookDiv.style.width=DIV_HOOK_SIZE+'px';hookDiv.style.height=DIV_HOOK_SIZE+'px';hookDiv.style.position='absolute';hookDiv.style.top=DIV_HOOK_POS_X+'px';hookDiv.style.left=DIV_HOOK_POS_Y+'px';hookDiv.style.zIndex=DIV_HOOK_ZINDEX;hookDiv.style.backgroundColor='#FF0000';hookDiv.title='HOOK DIV';hookDiv.addEventListener('focus',function(){_this.isMobileAccessabillity=true;_this.activate();document.body.removeChild(hookDiv);});document.body.appendChild(hookDiv);};/**
     * Activating will cause the Accessibility layer to be shown. This is called when a user
     * preses the tab key
     *
     * @private
     */AccessibilityManager.prototype.activate=function activate(){if(this.isActive){return;}this.isActive=true;window.document.addEventListener('mousemove',this._onMouseMove,true);window.removeEventListener('keydown',this._onKeyDown,false);this.renderer.on('postrender',this.update,this);if(this.renderer.view.parentNode){this.renderer.view.parentNode.appendChild(this.div);}};/**
     * Deactivating will cause the Accessibility layer to be hidden. This is called when a user moves
     * the mouse
     *
     * @private
     */AccessibilityManager.prototype.deactivate=function deactivate(){if(!this.isActive||this.isMobileAccessabillity){return;}this.isActive=false;window.document.removeEventListener('mousemove',this._onMouseMove);window.addEventListener('keydown',this._onKeyDown,false);this.renderer.off('postrender',this.update);if(this.div.parentNode){this.div.parentNode.removeChild(this.div);}};/**
     * This recursive function will run throught he scene graph and add any new accessible objects to the DOM layer.
     *
     * @private
     * @param {PIXI.Container} displayObject - The DisplayObject to check.
     */AccessibilityManager.prototype.updateAccessibleObjects=function updateAccessibleObjects(displayObject){if(!displayObject.visible){return;}if(displayObject.accessible&&displayObject.interactive){if(!displayObject._accessibleActive){this.addChild(displayObject);}displayObject.renderId=this.renderId;}var children=displayObject.children;for(var i=children.length-1;i>=0;i--){this.updateAccessibleObjects(children[i]);}};/**
     * Before each render this function will ensure that all divs are mapped correctly to their DisplayObjects.
     *
     * @private
     */AccessibilityManager.prototype.update=function update(){if(!this.renderer.renderingToScreen){return;}// update children...
this.updateAccessibleObjects(this.renderer._lastObjectRendered);var rect=this.renderer.view.getBoundingClientRect();var sx=rect.width/this.renderer.width;var sy=rect.height/this.renderer.height;var div=this.div;div.style.left=rect.left+'px';div.style.top=rect.top+'px';div.style.width=this.renderer.width+'px';div.style.height=this.renderer.height+'px';for(var i=0;i<this.children.length;i++){var child=this.children[i];if(child.renderId!==this.renderId){child._accessibleActive=false;core.utils.removeItems(this.children,i,1);this.div.removeChild(child._accessibleDiv);this.pool.push(child._accessibleDiv);child._accessibleDiv=null;i--;if(this.children.length===0){this.deactivate();}}else{// map div to display..
div=child._accessibleDiv;var hitArea=child.hitArea;var wt=child.worldTransform;if(child.hitArea){div.style.left=(wt.tx+hitArea.x*wt.a)*sx+'px';div.style.top=(wt.ty+hitArea.y*wt.d)*sy+'px';div.style.width=hitArea.width*wt.a*sx+'px';div.style.height=hitArea.height*wt.d*sy+'px';}else{hitArea=child.getBounds();this.capHitArea(hitArea);div.style.left=hitArea.x*sx+'px';div.style.top=hitArea.y*sy+'px';div.style.width=hitArea.width*sx+'px';div.style.height=hitArea.height*sy+'px';}}}// increment the render id..
this.renderId++;};/**
     * TODO: docs.
     *
     * @param {Rectangle} hitArea - TODO docs
     */AccessibilityManager.prototype.capHitArea=function capHitArea(hitArea){if(hitArea.x<0){hitArea.width+=hitArea.x;hitArea.x=0;}if(hitArea.y<0){hitArea.height+=hitArea.y;hitArea.y=0;}if(hitArea.x+hitArea.width>this.renderer.width){hitArea.width=this.renderer.width-hitArea.x;}if(hitArea.y+hitArea.height>this.renderer.height){hitArea.height=this.renderer.height-hitArea.y;}};/**
     * Adds a DisplayObject to the accessibility manager
     *
     * @private
     * @param {DisplayObject} displayObject - The child to make accessible.
     */AccessibilityManager.prototype.addChild=function addChild(displayObject){//    this.activate();
var div=this.pool.pop();if(!div){div=document.createElement('button');div.style.width=DIV_TOUCH_SIZE+'px';div.style.height=DIV_TOUCH_SIZE+'px';div.style.backgroundColor=this.debug?'rgba(255,0,0,0.5)':'transparent';div.style.position='absolute';div.style.zIndex=DIV_TOUCH_ZINDEX;div.style.borderStyle='none';div.addEventListener('click',this._onClick.bind(this));div.addEventListener('focus',this._onFocus.bind(this));div.addEventListener('focusout',this._onFocusOut.bind(this));}if(displayObject.accessibleTitle){div.title=displayObject.accessibleTitle;}else if(!displayObject.accessibleTitle&&!displayObject.accessibleHint){div.title='displayObject '+this.tabIndex;}if(displayObject.accessibleHint){div.setAttribute('aria-label',displayObject.accessibleHint);}//
displayObject._accessibleActive=true;displayObject._accessibleDiv=div;div.displayObject=displayObject;this.children.push(displayObject);this.div.appendChild(displayObject._accessibleDiv);displayObject._accessibleDiv.tabIndex=displayObject.tabIndex;};/**
     * Maps the div button press to pixi's InteractionManager (click)
     *
     * @private
     * @param {MouseEvent} e - The click event.
     */AccessibilityManager.prototype._onClick=function _onClick(e){var interactionManager=this.renderer.plugins.interaction;interactionManager.dispatchEvent(e.target.displayObject,'click',interactionManager.eventData);};/**
     * Maps the div focus events to pixis InteractionManager (mouseover)
     *
     * @private
     * @param {FocusEvent} e - The focus event.
     */AccessibilityManager.prototype._onFocus=function _onFocus(e){var interactionManager=this.renderer.plugins.interaction;interactionManager.dispatchEvent(e.target.displayObject,'mouseover',interactionManager.eventData);};/**
     * Maps the div focus events to pixis InteractionManager (mouseout)
     *
     * @private
     * @param {FocusEvent} e - The focusout event.
     */AccessibilityManager.prototype._onFocusOut=function _onFocusOut(e){var interactionManager=this.renderer.plugins.interaction;interactionManager.dispatchEvent(e.target.displayObject,'mouseout',interactionManager.eventData);};/**
     * Is called when a key is pressed
     *
     * @private
     * @param {KeyboardEvent} e - The keydown event.
     */AccessibilityManager.prototype._onKeyDown=function _onKeyDown(e){if(e.keyCode!==KEY_CODE_TAB){return;}this.activate();};/**
     * Is called when the mouse moves across the renderer element
     *
     * @private
     */AccessibilityManager.prototype._onMouseMove=function _onMouseMove(){this.deactivate();};/**
     * Destroys the accessibility manager
     *
     */AccessibilityManager.prototype.destroy=function destroy(){this.div=null;for(var i=0;i<this.children.length;i++){this.children[i].div=null;}window.document.removeEventListener('mousemove',this._onMouseMove);window.removeEventListener('keydown',this._onKeyDown);this.pool=null;this.children=null;this.renderer=null;};return AccessibilityManager;}();exports.default=AccessibilityManager;core.WebGLRenderer.registerPlugin('accessibility',AccessibilityManager);core.CanvasRenderer.registerPlugin('accessibility',AccessibilityManager);},{"../core":61,"./accessibleTarget":39,"ismobilejs":4}],39:[function(require,module,exports){"use strict";exports.__esModule=true;/**
 * Default property values of accessible objects
 * used by {@link PIXI.accessibility.AccessibilityManager}.
 *
 * @mixin
 * @name accessibleTarget
 * @memberof PIXI
 * @example
 *      function MyObject() {}
 *
 *      Object.assign(
 *          MyObject.prototype,
 *          PIXI.accessibility.accessibleTarget
 *      );
 */exports.default={/**
   *  Flag for if the object is accessible. If true AccessibilityManager will overlay a
   *   shadow div with attributes set
   *
   * @member {boolean}
   */accessible:false,/**
   * Sets the title attribute of the shadow div
   * If accessibleTitle AND accessibleHint has not been this will default to 'displayObject [tabIndex]'
   *
   * @member {string}
   */accessibleTitle:null,/**
   * Sets the aria-label attribute of the shadow div
   *
   * @member {string}
   */accessibleHint:null,/**
   * @todo Needs docs.
   */tabIndex:0,/**
   * @todo Needs docs.
   */_accessibleActive:false,/**
   * @todo Needs docs.
   */_accessibleDiv:false};},{}],40:[function(require,module,exports){'use strict';exports.__esModule=true;var _accessibleTarget=require('./accessibleTarget');Object.defineProperty(exports,'accessibleTarget',{enumerable:true,get:function get(){return _interopRequireDefault(_accessibleTarget).default;}});var _AccessibilityManager=require('./AccessibilityManager');Object.defineProperty(exports,'AccessibilityManager',{enumerable:true,get:function get(){return _interopRequireDefault(_AccessibilityManager).default;}});function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}},{"./AccessibilityManager":38,"./accessibleTarget":39}],41:[function(require,module,exports){'use strict';exports.__esModule=true;var _pixiGlCore=require('pixi-gl-core');var _settings=require('./settings');var _settings2=_interopRequireDefault(_settings);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return call&&((typeof call==="undefined"?"undefined":_typeof2(call))==="object"||typeof call==="function")?call:self;}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof2(superClass)));}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass;}var PRECISION=_settings2.default.PRECISION;function checkPrecision(src){if(src instanceof Array){if(src[0].substring(0,9)!=='precision'){var copy=src.slice(0);copy.unshift('precision '+PRECISION+' float;');return copy;}}else if(src.substring(0,9)!=='precision'){return'precision '+PRECISION+' float;\n'+src;}return src;}/**
 * Wrapper class, webGL Shader for Pixi.
 * Adds precision string if vertexSrc or fragmentSrc have no mention of it.
 *
 * @class
 * @extends GLShader
 * @memberof PIXI
 */var Shader=function(_GLShader){_inherits(Shader,_GLShader);/**
     *
     * @param {WebGLRenderingContext} gl - The current WebGL rendering context
     * @param {string|string[]} vertexSrc - The vertex shader source as an array of strings.
     * @param {string|string[]} fragmentSrc - The fragment shader source as an array of strings.
     */function Shader(gl,vertexSrc,fragmentSrc){_classCallCheck(this,Shader);return _possibleConstructorReturn(this,_GLShader.call(this,gl,checkPrecision(vertexSrc),checkPrecision(fragmentSrc)));}return Shader;}(_pixiGlCore.GLShader);exports.default=Shader;},{"./settings":97,"pixi-gl-core":12}],42:[function(require,module,exports){'use strict';exports.__esModule=true;/**
 * String of the current PIXI version.
 *
 * @static
 * @constant
 * @memberof PIXI
 * @name VERSION
 * @type {string}
 */var VERSION=exports.VERSION='4.3.2';/**
 * Two Pi.
 *
 * @static
 * @constant
 * @memberof PIXI
 * @type {number}
 */var PI_2=exports.PI_2=Math.PI*2;/**
 * Conversion factor for converting radians to degrees.
 *
 * @static
 * @constant
 * @memberof PIXI
 * @type {number}
 */var RAD_TO_DEG=exports.RAD_TO_DEG=180/Math.PI;/**
 * Conversion factor for converting degrees to radians.
 *
 * @static
 * @constant
 * @memberof PIXI
 * @type {number}
 */var DEG_TO_RAD=exports.DEG_TO_RAD=Math.PI/180;/**
 * Constant to identify the Renderer Type.
 *
 * @static
 * @constant
 * @memberof PIXI
 * @name RENDERER_TYPE
 * @type {object}
 * @property {number} UNKNOWN - Unknown render type.
 * @property {number} WEBGL - WebGL render type.
 * @property {number} CANVAS - Canvas render type.
 */var RENDERER_TYPE=exports.RENDERER_TYPE={UNKNOWN:0,WEBGL:1,CANVAS:2};/**
 * Various blend modes supported by PIXI.
 *
 * IMPORTANT - The WebGL renderer only supports the NORMAL, ADD, MULTIPLY and SCREEN blend modes.
 * Anything else will silently act like NORMAL.
 *
 * @static
 * @constant
 * @memberof PIXI
 * @name BLEND_MODES
 * @type {object}
 * @property {number} NORMAL
 * @property {number} ADD
 * @property {number} MULTIPLY
 * @property {number} SCREEN
 * @property {number} OVERLAY
 * @property {number} DARKEN
 * @property {number} LIGHTEN
 * @property {number} COLOR_DODGE
 * @property {number} COLOR_BURN
 * @property {number} HARD_LIGHT
 * @property {number} SOFT_LIGHT
 * @property {number} DIFFERENCE
 * @property {number} EXCLUSION
 * @property {number} HUE
 * @property {number} SATURATION
 * @property {number} COLOR
 * @property {number} LUMINOSITY
 */var BLEND_MODES=exports.BLEND_MODES={NORMAL:0,ADD:1,MULTIPLY:2,SCREEN:3,OVERLAY:4,DARKEN:5,LIGHTEN:6,COLOR_DODGE:7,COLOR_BURN:8,HARD_LIGHT:9,SOFT_LIGHT:10,DIFFERENCE:11,EXCLUSION:12,HUE:13,SATURATION:14,COLOR:15,LUMINOSITY:16};/**
 * Various webgl draw modes. These can be used to specify which GL drawMode to use
 * under certain situations and renderers.
 *
 * @static
 * @constant
 * @memberof PIXI
 * @name DRAW_MODES
 * @type {object}
 * @property {number} POINTS
 * @property {number} LINES
 * @property {number} LINE_LOOP
 * @property {number} LINE_STRIP
 * @property {number} TRIANGLES
 * @property {number} TRIANGLE_STRIP
 * @property {number} TRIANGLE_FAN
 */var DRAW_MODES=exports.DRAW_MODES={POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6};/**
 * The scale modes that are supported by pixi.
 *
 * The {@link PIXI.settings.SCALE_MODE} scale mode affects the default scaling mode of future operations.
 * It can be re-assigned to either LINEAR or NEAREST, depending upon suitability.
 *
 * @static
 * @constant
 * @memberof PIXI
 * @name SCALE_MODES
 * @type {object}
 * @property {number} LINEAR Smooth scaling
 * @property {number} NEAREST Pixelating scaling
 */var SCALE_MODES=exports.SCALE_MODES={LINEAR:0,NEAREST:1};/**
 * The wrap modes that are supported by pixi.
 *
 * The {@link PIXI.settings.WRAP_MODE} wrap mode affects the default wraping mode of future operations.
 * It can be re-assigned to either CLAMP or REPEAT, depending upon suitability.
 * If the texture is non power of two then clamp will be used regardless as webGL can
 * only use REPEAT if the texture is po2.
 *
 * This property only affects WebGL.
 *
 * @static
 * @constant
 * @name WRAP_MODES
 * @memberof PIXI
 * @type {object}
 * @property {number} CLAMP - The textures uvs are clamped
 * @property {number} REPEAT - The texture uvs tile and repeat
 * @property {number} MIRRORED_REPEAT - The texture uvs tile and repeat with mirroring
 */var WRAP_MODES=exports.WRAP_MODES={CLAMP:0,REPEAT:1,MIRRORED_REPEAT:2};/**
 * The gc modes that are supported by pixi.
 *
 * The {@link PIXI.settings.GC_MODE} Garbage Collection mode for pixi textures is AUTO
 * If set to GC_MODE, the renderer will occasianally check textures usage. If they are not
 * used for a specified period of time they will be removed from the GPU. They will of course
 * be uploaded again when they are required. This is a silent behind the scenes process that
 * should ensure that the GPU does not  get filled up.
 *
 * Handy for mobile devices!
 * This property only affects WebGL.
 *
 * @static
 * @constant
 * @name GC_MODES
 * @memberof PIXI
 * @type {object}
 * @property {number} AUTO - Garbage collection will happen periodically automatically
 * @property {number} MANUAL - Garbage collection will need to be called manually
 */var GC_MODES=exports.GC_MODES={AUTO:0,MANUAL:1};/**
 * Regexp for image type by extension.
 *
 * @static
 * @constant
 * @memberof PIXI
 * @type {RegExp|string}
 * @example `image.png`
 */var URL_FILE_EXTENSION=exports.URL_FILE_EXTENSION=/\.(\w{3,4})(?:$|\?|#)/i;/**
 * Regexp for data URI.
 * Based on: {@link https://github.com/ragingwind/data-uri-regex}
 *
 * @static
 * @constant
 * @name DATA_URI
 * @memberof PIXI
 * @type {RegExp|string}
 * @example data:image/png;base64
 */var DATA_URI=exports.DATA_URI=/^\s*data:(?:([\w-]+)\/([\w+.-]+))?(?:;(charset=[\w-]+|base64))?,(.*)/i;/**
 * Regexp for SVG size.
 *
 * @static
 * @constant
 * @name SVG_SIZE
 * @memberof PIXI
 * @type {RegExp|string}
 * @example &lt;svg width="100" height="100"&gt;&lt;/svg&gt;
 */var SVG_SIZE=exports.SVG_SIZE=/<svg[^>]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*>/i;// eslint-disable-line max-len
/**
 * Constants that identify shapes, mainly to prevent `instanceof` calls.
 *
 * @static
 * @constant
 * @name SHAPES
 * @memberof PIXI
 * @type {object}
 * @property {number} POLY Polygon
 * @property {number} RECT Rectangle
 * @property {number} CIRC Circle
 * @property {number} ELIP Ellipse
 * @property {number} RREC Rounded Rectangle
 */var SHAPES=exports.SHAPES={POLY:0,RECT:1,CIRC:2,ELIP:3,RREC:4};/**
 * Constants that specify float precision in shaders.
 *
 * @static
 * @constant
 * @name PRECISION
 * @memberof PIXI
 * @type {object}
 * @property {string} LOW='lowp'
 * @property {string} MEDIUM='mediump'
 * @property {string} HIGH='highp'
 */var PRECISION=exports.PRECISION={LOW:'lowp',MEDIUM:'mediump',HIGH:'highp'};/**
 * Constants that specify the transform type.
 *
 * @static
 * @constant
 * @name TRANSFORM_MODE
 * @memberof PIXI
 * @type {object}
 * @property {number} STATIC
 * @property {number} DYNAMIC
 */var TRANSFORM_MODE=exports.TRANSFORM_MODE={STATIC:0,DYNAMIC:1};/**
 * Constants that define the type of gradient on text.
 *
 * @static
 * @constant
 * @name TEXT_GRADIENT
 * @memberof PIXI
 * @type {object}
 * @property {number} LINEAR_VERTICAL Vertical gradient
 * @property {number} LINEAR_HORIZONTAL Linear gradient
 */var TEXT_GRADIENT=exports.TEXT_GRADIENT={LINEAR_VERTICAL:0,LINEAR_HORIZONTAL:1};},{}],43:[function(require,module,exports){'use strict';exports.__esModule=true;var _math=require('../math');function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}/**
 * 'Builder' pattern for bounds rectangles
 * Axis-Aligned Bounding Box
 * It is not a shape! Its mutable thing, no 'EMPTY' or that kind of problems
 *
 * @class
 * @memberof PIXI
 */var Bounds=function(){/**
     *
     */function Bounds(){_classCallCheck(this,Bounds);/**
         * @member {number}
         * @default 0
         */this.minX=Infinity;/**
         * @member {number}
         * @default 0
         */this.minY=Infinity;/**
         * @member {number}
         * @default 0
         */this.maxX=-Infinity;/**
         * @member {number}
         * @default 0
         */this.maxY=-Infinity;this.rect=null;}/**
     * Checks if bounds are empty.
     *
     * @return {boolean} True if empty.
     */Bounds.prototype.isEmpty=function isEmpty(){return this.minX>this.maxX||this.minY>this.maxY;};/**
     * Clears the bounds and resets.
     *
     */Bounds.prototype.clear=function clear(){this.updateID++;this.minX=Infinity;this.minY=Infinity;this.maxX=-Infinity;this.maxY=-Infinity;};/**
     * Can return Rectangle.EMPTY constant, either construct new rectangle, either use your rectangle
     * It is not guaranteed that it will return tempRect
     *
     * @param {PIXI.Rectangle} rect - temporary object will be used if AABB is not empty
     * @returns {PIXI.Rectangle} A rectangle of the bounds
     */Bounds.prototype.getRectangle=function getRectangle(rect){if(this.minX>this.maxX||this.minY>this.maxY){return _math.Rectangle.EMPTY;}rect=rect||new _math.Rectangle(0,0,1,1);rect.x=this.minX;rect.y=this.minY;rect.width=this.maxX-this.minX;rect.height=this.maxY-this.minY;return rect;};/**
     * This function should be inlined when its possible.
     *
     * @param {PIXI.Point} point - The point to add.
     */Bounds.prototype.addPoint=function addPoint(point){this.minX=Math.min(this.minX,point.x);this.maxX=Math.max(this.maxX,point.x);this.minY=Math.min(this.minY,point.y);this.maxY=Math.max(this.maxY,point.y);};/**
     * Adds a quad, not transformed
     *
     * @param {Float32Array} vertices - The verts to add.
     */Bounds.prototype.addQuad=function addQuad(vertices){var minX=this.minX;var minY=this.minY;var maxX=this.maxX;var maxY=this.maxY;var x=vertices[0];var y=vertices[1];minX=x<minX?x:minX;minY=y<minY?y:minY;maxX=x>maxX?x:maxX;maxY=y>maxY?y:maxY;x=vertices[2];y=vertices[3];minX=x<minX?x:minX;minY=y<minY?y:minY;maxX=x>maxX?x:maxX;maxY=y>maxY?y:maxY;x=vertices[4];y=vertices[5];minX=x<minX?x:minX;minY=y<minY?y:minY;maxX=x>maxX?x:maxX;maxY=y>maxY?y:maxY;x=vertices[6];y=vertices[7];minX=x<minX?x:minX;minY=y<minY?y:minY;maxX=x>maxX?x:maxX;maxY=y>maxY?y:maxY;this.minX=minX;this.minY=minY;this.maxX=maxX;this.maxY=maxY;};/**
     * Adds sprite frame, transformed.
     *
     * @param {PIXI.TransformBase} transform - TODO
     * @param {number} x0 - TODO
     * @param {number} y0 - TODO
     * @param {number} x1 - TODO
     * @param {number} y1 - TODO
     */Bounds.prototype.addFrame=function addFrame(transform,x0,y0,x1,y1){var matrix=transform.worldTransform;var a=matrix.a;var b=matrix.b;var c=matrix.c;var d=matrix.d;var tx=matrix.tx;var ty=matrix.ty;var minX=this.minX;var minY=this.minY;var maxX=this.maxX;var maxY=this.maxY;var x=a*x0+c*y0+tx;var y=b*x0+d*y0+ty;minX=x<minX?x:minX;minY=y<minY?y:minY;maxX=x>maxX?x:maxX;maxY=y>maxY?y:maxY;x=a*x1+c*y0+tx;y=b*x1+d*y0+ty;minX=x<minX?x:minX;minY=y<minY?y:minY;maxX=x>maxX?x:maxX;maxY=y>maxY?y:maxY;x=a*x0+c*y1+tx;y=b*x0+d*y1+ty;minX=x<minX?x:minX;minY=y<minY?y:minY;maxX=x>maxX?x:maxX;maxY=y>maxY?y:maxY;x=a*x1+c*y1+tx;y=b*x1+d*y1+ty;minX=x<minX?x:minX;minY=y<minY?y:minY;maxX=x>maxX?x:maxX;maxY=y>maxY?y:maxY;this.minX=minX;this.minY=minY;this.maxX=maxX;this.maxY=maxY;};/**
     * Add an array of vertices
     *
     * @param {PIXI.TransformBase} transform - TODO
     * @param {Float32Array} vertices - TODO
     * @param {number} beginOffset - TODO
     * @param {number} endOffset - TODO
     */Bounds.prototype.addVertices=function addVertices(transform,vertices,beginOffset,endOffset){var matrix=transform.worldTransform;var a=matrix.a;var b=matrix.b;var c=matrix.c;var d=matrix.d;var tx=matrix.tx;var ty=matrix.ty;var minX=this.minX;var minY=this.minY;var maxX=this.maxX;var maxY=this.maxY;for(var i=beginOffset;i<endOffset;i+=2){var rawX=vertices[i];var rawY=vertices[i+1];var x=a*rawX+c*rawY+tx;var y=d*rawY+b*rawX+ty;minX=x<minX?x:minX;minY=y<minY?y:minY;maxX=x>maxX?x:maxX;maxY=y>maxY?y:maxY;}this.minX=minX;this.minY=minY;this.maxX=maxX;this.maxY=maxY;};/**
     * Adds other Bounds
     *
     * @param {PIXI.Bounds} bounds - TODO
     */Bounds.prototype.addBounds=function addBounds(bounds){var minX=this.minX;var minY=this.minY;var maxX=this.maxX;var maxY=this.maxY;this.minX=bounds.minX<minX?bounds.minX:minX;this.minY=bounds.minY<minY?bounds.minY:minY;this.maxX=bounds.maxX>maxX?bounds.maxX:maxX;this.maxY=bounds.maxY>maxY?bounds.maxY:maxY;};/**
     * Adds other Bounds, masked with Bounds
     *
     * @param {PIXI.Bounds} bounds - TODO
     * @param {PIXI.Bounds} mask - TODO
     */Bounds.prototype.addBoundsMask=function addBoundsMask(bounds,mask){var _minX=bounds.minX>mask.minX?bounds.minX:mask.minX;var _minY=bounds.minY>mask.minY?bounds.minY:mask.minY;var _maxX=bounds.maxX<mask.maxX?bounds.maxX:mask.maxX;var _maxY=bounds.maxY<mask.maxY?bounds.maxY:mask.maxY;if(_minX<=_maxX&&_minY<=_maxY){var minX=this.minX;var minY=this.minY;var maxX=this.maxX;var maxY=this.maxY;this.minX=_minX<minX?_minX:minX;this.minY=_minY<minY?_minY:minY;this.maxX=_maxX>maxX?_maxX:maxX;this.maxY=_maxY>maxY?_maxY:maxY;}};/**
     * Adds other Bounds, masked with Rectangle
     *
     * @param {PIXI.Bounds} bounds - TODO
     * @param {PIXI.Rectangle} area - TODO
     */Bounds.prototype.addBoundsArea=function addBoundsArea(bounds,area){var _minX=bounds.minX>area.x?bounds.minX:area.x;var _minY=bounds.minY>area.y?bounds.minY:area.y;var _maxX=bounds.maxX<area.x+area.width?bounds.maxX:area.x+area.width;var _maxY=bounds.maxY<area.y+area.height?bounds.maxY:area.y+area.height;if(_minX<=_maxX&&_minY<=_maxY){var minX=this.minX;var minY=this.minY;var maxX=this.maxX;var maxY=this.maxY;this.minX=_minX<minX?_minX:minX;this.minY=_minY<minY?_minY:minY;this.maxX=_maxX>maxX?_maxX:maxX;this.maxY=_maxY>maxY?_maxY:maxY;}};return Bounds;}();exports.default=Bounds;},{"../math":66}],44:[function(require,module,exports){'use strict';exports.__esModule=true;var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor);}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor;};}();var _utils=require('../utils');var _DisplayObject2=require('./DisplayObject');var _DisplayObject3=_interopRequireDefault(_DisplayObject2);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return call&&((typeof call==="undefined"?"undefined":_typeof2(call))==="object"||typeof call==="function")?call:self;}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof2(superClass)));}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass;}/**
 * A Container represents a collection of display objects.
 * It is the base class of all display objects that act as a container for other objects.
 *
 *```js
 * let container = new PIXI.Container();
 * container.addChild(sprite);
 * ```
 *
 * @class
 * @extends PIXI.DisplayObject
 * @memberof PIXI
 */var Container=function(_DisplayObject){_inherits(Container,_DisplayObject);/**
     *
     */function Container(){_classCallCheck(this,Container);/**
         * The array of children of this container.
         *
         * @member {PIXI.DisplayObject[]}
         * @readonly
         */var _this=_possibleConstructorReturn(this,_DisplayObject.call(this));_this.children=[];return _this;}/**
     * Overridable method that can be used by Container subclasses whenever the children array is modified
     *
     * @private
     */Container.prototype.onChildrenChange=function onChildrenChange(){}/* empty *//**
     * Adds one or more children to the container.
     *
     * Multiple items can be added like so: `myContainer.addChild(thingOne, thingTwo, thingThree)`
     *
     * @param {...PIXI.DisplayObject} child - The DisplayObject(s) to add to the container
     * @return {PIXI.DisplayObject} The first child that was added.
     */;Container.prototype.addChild=function addChild(child){var argumentsLength=arguments.length;// if there is only one argument we can bypass looping through the them
if(argumentsLength>1){// loop through the arguments property and add all children
// use it the right way (.length and [i]) so that this function can still be optimised by JS runtimes
for(var i=0;i<argumentsLength;i++){this.addChild(arguments[i]);}}else{// if the child has a parent then lets remove it as Pixi objects can only exist in one place
if(child.parent){child.parent.removeChild(child);}child.parent=this;// ensure a transform will be recalculated..
this.transform._parentID=-1;this._boundsID++;this.children.push(child);// TODO - lets either do all callbacks or all events.. not both!
this.onChildrenChange(this.children.length-1);child.emit('added',this);}return child;};/**
     * Adds a child to the container at a specified index. If the index is out of bounds an error will be thrown
     *
     * @param {PIXI.DisplayObject} child - The child to add
     * @param {number} index - The index to place the child in
     * @return {PIXI.DisplayObject} The child that was added.
     */Container.prototype.addChildAt=function addChildAt(child,index){if(index<0||index>this.children.length){throw new Error(child+'addChildAt: The index '+index+' supplied is out of bounds '+this.children.length);}if(child.parent){child.parent.removeChild(child);}child.parent=this;this.children.splice(index,0,child);// TODO - lets either do all callbacks or all events.. not both!
this.onChildrenChange(index);child.emit('added',this);return child;};/**
     * Swaps the position of 2 Display Objects within this container.
     *
     * @param {PIXI.DisplayObject} child - First display object to swap
     * @param {PIXI.DisplayObject} child2 - Second display object to swap
     */Container.prototype.swapChildren=function swapChildren(child,child2){if(child===child2){return;}var index1=this.getChildIndex(child);var index2=this.getChildIndex(child2);this.children[index1]=child2;this.children[index2]=child;this.onChildrenChange(index1<index2?index1:index2);};/**
     * Returns the index position of a child DisplayObject instance
     *
     * @param {PIXI.DisplayObject} child - The DisplayObject instance to identify
     * @return {number} The index position of the child display object to identify
     */Container.prototype.getChildIndex=function getChildIndex(child){var index=this.children.indexOf(child);if(index===-1){throw new Error('The supplied DisplayObject must be a child of the caller');}return index;};/**
     * Changes the position of an existing child in the display object container
     *
     * @param {PIXI.DisplayObject} child - The child DisplayObject instance for which you want to change the index number
     * @param {number} index - The resulting index number for the child display object
     */Container.prototype.setChildIndex=function setChildIndex(child,index){if(index<0||index>=this.children.length){throw new Error('The supplied index is out of bounds');}var currentIndex=this.getChildIndex(child);(0,_utils.removeItems)(this.children,currentIndex,1);// remove from old position
this.children.splice(index,0,child);// add at new position
this.onChildrenChange(index);};/**
     * Returns the child at the specified index
     *
     * @param {number} index - The index to get the child at
     * @return {PIXI.DisplayObject} The child at the given index, if any.
     */Container.prototype.getChildAt=function getChildAt(index){if(index<0||index>=this.children.length){throw new Error('getChildAt: Index ('+index+') does not exist.');}return this.children[index];};/**
     * Removes one or more children from the container.
     *
     * @param {...PIXI.DisplayObject} child - The DisplayObject(s) to remove
     * @return {PIXI.DisplayObject} The first child that was removed.
     */Container.prototype.removeChild=function removeChild(child){var argumentsLength=arguments.length;// if there is only one argument we can bypass looping through the them
if(argumentsLength>1){// loop through the arguments property and add all children
// use it the right way (.length and [i]) so that this function can still be optimised by JS runtimes
for(var i=0;i<argumentsLength;i++){this.removeChild(arguments[i]);}}else{var index=this.children.indexOf(child);if(index===-1)return null;child.parent=null;(0,_utils.removeItems)(this.children,index,1);// ensure a transform will be recalculated..
this.transform._parentID=-1;this._boundsID++;// TODO - lets either do all callbacks or all events.. not both!
this.onChildrenChange(index);child.emit('removed',this);}return child;};/**
     * Removes a child from the specified index position.
     *
     * @param {number} index - The index to get the child from
     * @return {PIXI.DisplayObject} The child that was removed.
     */Container.prototype.removeChildAt=function removeChildAt(index){var child=this.getChildAt(index);child.parent=null;(0,_utils.removeItems)(this.children,index,1);// TODO - lets either do all callbacks or all events.. not both!
this.onChildrenChange(index);child.emit('removed',this);return child;};/**
     * Removes all children from this container that are within the begin and end indexes.
     *
     * @param {number} [beginIndex=0] - The beginning position.
     * @param {number} [endIndex=this.children.length] - The ending position. Default value is size of the container.
     * @returns {DisplayObject[]} List of removed children
     */Container.prototype.removeChildren=function removeChildren(){var beginIndex=arguments.length<=0||arguments[0]===undefined?0:arguments[0];var endIndex=arguments[1];var begin=beginIndex;var end=typeof endIndex==='number'?endIndex:this.children.length;var range=end-begin;var removed=void 0;if(range>0&&range<=end){removed=this.children.splice(begin,range);for(var i=0;i<removed.length;++i){removed[i].parent=null;}this.onChildrenChange(beginIndex);for(var _i=0;_i<removed.length;++_i){removed[_i].emit('removed',this);}return removed;}else if(range===0&&this.children.length===0){return[];}throw new RangeError('removeChildren: numeric values are outside the acceptable range.');};/**
     * Updates the transform on all children of this container for rendering
     *
     * @private
     */Container.prototype.updateTransform=function updateTransform(){this._boundsID++;this.transform.updateTransform(this.parent.transform);// TODO: check render flags, how to process stuff here
this.worldAlpha=this.alpha*this.parent.worldAlpha;for(var i=0,j=this.children.length;i<j;++i){var child=this.children[i];if(child.visible){child.updateTransform();}}};/**
     * Recalculates the bounds of the container.
     *
     */Container.prototype.calculateBounds=function calculateBounds(){this._bounds.clear();this._calculateBounds();for(var i=0;i<this.children.length;i++){var child=this.children[i];if(!child.visible||!child.renderable){continue;}child.calculateBounds();// TODO: filter+mask, need to mask both somehow
if(child._mask){child._mask.calculateBounds();this._bounds.addBoundsMask(child._bounds,child._mask._bounds);}else if(child.filterArea){this._bounds.addBoundsArea(child._bounds,child.filterArea);}else{this._bounds.addBounds(child._bounds);}}this._lastBoundsID=this._boundsID;};/**
     * Recalculates the bounds of the object. Override this to
     * calculate the bounds of the specific object (not including children).
     *
     */Container.prototype._calculateBounds=function _calculateBounds(){}// FILL IN//
/**
     * Renders the object using the WebGL renderer
     *
     * @param {PIXI.WebGLRenderer} renderer - The renderer
     */;Container.prototype.renderWebGL=function renderWebGL(renderer){// if the object is not visible or the alpha is 0 then no need to render this element
if(!this.visible||this.worldAlpha<=0||!this.renderable){return;}// do a quick check to see if this element has a mask or a filter.
if(this._mask||this._filters){this.renderAdvancedWebGL(renderer);}else{this._renderWebGL(renderer);// simple render children!
for(var i=0,j=this.children.length;i<j;++i){this.children[i].renderWebGL(renderer);}}};/**
     * Render the object using the WebGL renderer and advanced features.
     *
     * @private
     * @param {PIXI.WebGLRenderer} renderer - The renderer
     */Container.prototype.renderAdvancedWebGL=function renderAdvancedWebGL(renderer){renderer.flush();var filters=this._filters;var mask=this._mask;// push filter first as we need to ensure the stencil buffer is correct for any masking
if(filters){if(!this._enabledFilters){this._enabledFilters=[];}this._enabledFilters.length=0;for(var i=0;i<filters.length;i++){if(filters[i].enabled){this._enabledFilters.push(filters[i]);}}if(this._enabledFilters.length){renderer.filterManager.pushFilter(this,this._enabledFilters);}}if(mask){renderer.maskManager.pushMask(this,this._mask);}// add this object to the batch, only rendered if it has a texture.
this._renderWebGL(renderer);// now loop through the children and make sure they get rendered
for(var _i2=0,j=this.children.length;_i2<j;_i2++){this.children[_i2].renderWebGL(renderer);}renderer.flush();if(mask){renderer.maskManager.popMask(this,this._mask);}if(filters&&this._enabledFilters&&this._enabledFilters.length){renderer.filterManager.popFilter();}};/**
     * To be overridden by the subclasses.
     *
     * @private
     * @param {PIXI.WebGLRenderer} renderer - The renderer
     */Container.prototype._renderWebGL=function _renderWebGL(renderer)// eslint-disable-line no-unused-vars
{}// this is where content itself gets rendered...
/**
     * To be overridden by the subclass
     *
     * @private
     * @param {PIXI.CanvasRenderer} renderer - The renderer
     */;Container.prototype._renderCanvas=function _renderCanvas(renderer)// eslint-disable-line no-unused-vars
{}// this is where content itself gets rendered...
/**
     * Renders the object using the Canvas renderer
     *
     * @param {PIXI.CanvasRenderer} renderer - The renderer
     */;Container.prototype.renderCanvas=function renderCanvas(renderer){// if not visible or the alpha is 0 then no need to render this
if(!this.visible||this.worldAlpha<=0||!this.renderable){return;}if(this._mask){renderer.maskManager.pushMask(this._mask);}this._renderCanvas(renderer);for(var i=0,j=this.children.length;i<j;++i){this.children[i].renderCanvas(renderer);}if(this._mask){renderer.maskManager.popMask(renderer);}};/**
     * Removes all internal references and listeners as well as removes children from the display list.
     * Do not use a Container after calling `destroy`.
     *
     * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options
     *  have been set to that value
     * @param {boolean} [options.children=false] - if set to true, all the children will have their destroy
     *  method called as well. 'options' will be passed on to those calls.
     */Container.prototype.destroy=function destroy(options){_DisplayObject.prototype.destroy.call(this);var destroyChildren=typeof options==='boolean'?options:options&&options.children;var oldChildren=this.removeChildren(0,this.children.length);if(destroyChildren){for(var i=0;i<oldChildren.length;++i){oldChildren[i].destroy(options);}}};/**
     * The width of the Container, setting this will actually modify the scale to achieve the value set
     *
     * @member {number}
     * @memberof PIXI.Container#
     */_createClass(Container,[{key:'width',get:function get(){return this.scale.x*this.getLocalBounds().width;}/**
         * Sets the width of the container by modifying the scale.
         *
         * @param {number} value - The value to set to.
         */,set:function set(value){var width=this.getLocalBounds().width;if(width!==0){this.scale.x=value/width;}else{this.scale.x=1;}this._width=value;}/**
         * The height of the Container, setting this will actually modify the scale to achieve the value set
         *
         * @member {number}
         * @memberof PIXI.Container#
         */},{key:'height',get:function get(){return this.scale.y*this.getLocalBounds().height;}/**
         * Sets the height of the container by modifying the scale.
         *
         * @param {number} value - The value to set to.
         */,set:function set(value){var height=this.getLocalBounds().height;if(height!==0){this.scale.y=value/height;}else{this.scale.y=1;}this._height=value;}}]);return Container;}(_DisplayObject3.default);// performance increase to avoid using call.. (10x faster)
exports.default=Container;Container.prototype.containerUpdateTransform=Container.prototype.updateTransform;},{"../utils":117,"./DisplayObject":45}],45:[function(require,module,exports){'use strict';exports.__esModule=true;var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor);}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor;};}();var _eventemitter=require('eventemitter3');var _eventemitter2=_interopRequireDefault(_eventemitter);var _const=require('../const');var _settings=require('../settings');var _settings2=_interopRequireDefault(_settings);var _TransformStatic=require('./TransformStatic');var _TransformStatic2=_interopRequireDefault(_TransformStatic);var _Transform=require('./Transform');var _Transform2=_interopRequireDefault(_Transform);var _Bounds=require('./Bounds');var _Bounds2=_interopRequireDefault(_Bounds);var _math=require('../math');function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return call&&((typeof call==="undefined"?"undefined":_typeof2(call))==="object"||typeof call==="function")?call:self;}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof2(superClass)));}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass;}// _tempDisplayObjectParent = new DisplayObject();
/**
 * The base class for all objects that are rendered on the screen.
 * This is an abstract class and should not be used on its own rather it should be extended.
 *
 * @class
 * @extends EventEmitter
 * @mixes PIXI.interaction.interactiveTarget
 * @memberof PIXI
 */var DisplayObject=function(_EventEmitter){_inherits(DisplayObject,_EventEmitter);/**
     *
     */function DisplayObject(){_classCallCheck(this,DisplayObject);var _this=_possibleConstructorReturn(this,_EventEmitter.call(this));var TransformClass=_settings2.default.TRANSFORM_MODE===_const.TRANSFORM_MODE.STATIC?_TransformStatic2.default:_Transform2.default;_this.tempDisplayObjectParent=null;// TODO: need to create Transform from factory
/**
         * World transform and local transform of this object.
         * This will become read-only later, please do not assign anything there unless you know what are you doing
         *
         * @member {PIXI.TransformBase}
         */_this.transform=new TransformClass();/**
         * The opacity of the object.
         *
         * @member {number}
         */_this.alpha=1;/**
         * The visibility of the object. If false the object will not be drawn, and
         * the updateTransform function will not be called.
         *
         * Only affects recursive calls from parent. You can ask for bounds or call updateTransform manually
         *
         * @member {boolean}
         */_this.visible=true;/**
         * Can this object be rendered, if false the object will not be drawn but the updateTransform
         * methods will still be called.
         *
         * Only affects recursive calls from parent. You can ask for bounds manually
         *
         * @member {boolean}
         */_this.renderable=true;/**
         * The display object container that contains this display object.
         *
         * @member {PIXI.Container}
         * @readonly
         */_this.parent=null;/**
         * The multiplied alpha of the displayObject
         *
         * @member {number}
         * @readonly
         */_this.worldAlpha=1;/**
         * The area the filter is applied to. This is used as more of an optimisation
         * rather than figuring out the dimensions of the displayObject each frame you can set this rectangle
         *
         * Also works as an interaction mask
         *
         * @member {PIXI.Rectangle}
         */_this.filterArea=null;_this._filters=null;_this._enabledFilters=null;/**
         * The bounds object, this is used to calculate and store the bounds of the displayObject
         *
         * @member {PIXI.Rectangle}
         * @private
         */_this._bounds=new _Bounds2.default();_this._boundsID=0;_this._lastBoundsID=-1;_this._boundsRect=null;_this._localBoundsRect=null;/**
         * The original, cached mask of the object
         *
         * @member {PIXI.Rectangle}
         * @private
         */_this._mask=null;return _this;}/**
     * @private
     * @member {PIXI.DisplayObject}
     *//**
     * Updates the object transform for rendering
     *
     * TODO - Optimization pass!
     */DisplayObject.prototype.updateTransform=function updateTransform(){this.transform.updateTransform(this.parent.transform);// multiply the alphas..
this.worldAlpha=this.alpha*this.parent.worldAlpha;this._bounds.updateID++;};/**
     * recursively updates transform of all objects from the root to this one
     * internal function for toLocal()
     */DisplayObject.prototype._recursivePostUpdateTransform=function _recursivePostUpdateTransform(){if(this.parent){this.parent._recursivePostUpdateTransform();this.transform.updateTransform(this.parent.transform);}else{this.transform.updateTransform(this._tempDisplayObjectParent.transform);}};/**
     * Retrieves the bounds of the displayObject as a rectangle object.
     *
     * @param {boolean} skipUpdate - setting to true will stop the transforms of the scene graph from
     *  being updated. This means the calculation returned MAY be out of date BUT will give you a
     *  nice performance boost
     * @param {PIXI.Rectangle} rect - Optional rectangle to store the result of the bounds calculation
     * @return {PIXI.Rectangle} the rectangular bounding area
     */DisplayObject.prototype.getBounds=function getBounds(skipUpdate,rect){if(!skipUpdate){if(!this.parent){this.parent=this._tempDisplayObjectParent;this.updateTransform();this.parent=null;}else{this._recursivePostUpdateTransform();this.updateTransform();}}if(this._boundsID!==this._lastBoundsID){this.calculateBounds();}if(!rect){if(!this._boundsRect){this._boundsRect=new _math.Rectangle();}rect=this._boundsRect;}return this._bounds.getRectangle(rect);};/**
     * Retrieves the local bounds of the displayObject as a rectangle object
     *
     * @param {PIXI.Rectangle} [rect] - Optional rectangle to store the result of the bounds calculation
     * @return {PIXI.Rectangle} the rectangular bounding area
     */DisplayObject.prototype.getLocalBounds=function getLocalBounds(rect){var transformRef=this.transform;var parentRef=this.parent;this.parent=null;this.transform=this._tempDisplayObjectParent.transform;if(!rect){if(!this._localBoundsRect){this._localBoundsRect=new _math.Rectangle();}rect=this._localBoundsRect;}var bounds=this.getBounds(false,rect);this.parent=parentRef;this.transform=transformRef;return bounds;};/**
     * Calculates the global position of the display object
     *
     * @param {PIXI.Point} position - The world origin to calculate from
     * @param {PIXI.Point} [point] - A Point object in which to store the value, optional
     *  (otherwise will create a new Point)
     * @param {boolean} [skipUpdate=false] - Should we skip the update transform.
     * @return {PIXI.Point} A point object representing the position of this object
     */DisplayObject.prototype.toGlobal=function toGlobal(position,point){var skipUpdate=arguments.length<=2||arguments[2]===undefined?false:arguments[2];if(!skipUpdate){this._recursivePostUpdateTransform();// this parent check is for just in case the item is a root object.
// If it is we need to give it a temporary parent so that displayObjectUpdateTransform works correctly
// this is mainly to avoid a parent check in the main loop. Every little helps for performance :)
if(!this.parent){this.parent=this._tempDisplayObjectParent;this.displayObjectUpdateTransform();this.parent=null;}else{this.displayObjectUpdateTransform();}}// don't need to update the lot
return this.worldTransform.apply(position,point);};/**
     * Calculates the local position of the display object relative to another point
     *
     * @param {PIXI.Point} position - The world origin to calculate from
     * @param {PIXI.DisplayObject} [from] - The DisplayObject to calculate the global position from
     * @param {PIXI.Point} [point] - A Point object in which to store the value, optional
     *  (otherwise will create a new Point)
     * @param {boolean} [skipUpdate=false] - Should we skip the update transform
     * @return {PIXI.Point} A point object representing the position of this object
     */DisplayObject.prototype.toLocal=function toLocal(position,from,point,skipUpdate){if(from){position=from.toGlobal(position,point,skipUpdate);}if(!skipUpdate){this._recursivePostUpdateTransform();// this parent check is for just in case the item is a root object.
// If it is we need to give it a temporary parent so that displayObjectUpdateTransform works correctly
// this is mainly to avoid a parent check in the main loop. Every little helps for performance :)
if(!this.parent){this.parent=this._tempDisplayObjectParent;this.displayObjectUpdateTransform();this.parent=null;}else{this.displayObjectUpdateTransform();}}// simply apply the matrix..
return this.worldTransform.applyInverse(position,point);};/**
     * Renders the object using the WebGL renderer
     *
     * @param {PIXI.WebGLRenderer} renderer - The renderer
     */DisplayObject.prototype.renderWebGL=function renderWebGL(renderer)// eslint-disable-line no-unused-vars
{}// OVERWRITE;
/**
     * Renders the object using the Canvas renderer
     *
     * @param {PIXI.CanvasRenderer} renderer - The renderer
     */;DisplayObject.prototype.renderCanvas=function renderCanvas(renderer)// eslint-disable-line no-unused-vars
{}// OVERWRITE;
/**
     * Set the parent Container of this DisplayObject
     *
     * @param {PIXI.Container} container - The Container to add this DisplayObject to
     * @return {PIXI.Container} The Container that this DisplayObject was added to
     */;DisplayObject.prototype.setParent=function setParent(container){if(!container||!container.addChild){throw new Error('setParent: Argument must be a Container');}container.addChild(this);return container;};/**
     * Convenience function to set the position, scale, skew and pivot at once.
     *
     * @param {number} [x=0] - The X position
     * @param {number} [y=0] - The Y position
     * @param {number} [scaleX=1] - The X scale value
     * @param {number} [scaleY=1] - The Y scale value
     * @param {number} [rotation=0] - The rotation
     * @param {number} [skewX=0] - The X skew value
     * @param {number} [skewY=0] - The Y skew value
     * @param {number} [pivotX=0] - The X pivot value
     * @param {number} [pivotY=0] - The Y pivot value
     * @return {PIXI.DisplayObject} The DisplayObject instance
     */DisplayObject.prototype.setTransform=function setTransform(){var x=arguments.length<=0||arguments[0]===undefined?0:arguments[0];var y=arguments.length<=1||arguments[1]===undefined?0:arguments[1];var scaleX=arguments.length<=2||arguments[2]===undefined?1:arguments[2];var scaleY=arguments.length<=3||arguments[3]===undefined?1:arguments[3];var rotation=arguments.length<=4||arguments[4]===undefined?0:arguments[4];var skewX=arguments.length<=5||arguments[5]===undefined?0:arguments[5];var skewY=arguments.length<=6||arguments[6]===undefined?0:arguments[6];var pivotX=arguments.length<=7||arguments[7]===undefined?0:arguments[7];var pivotY=arguments.length<=8||arguments[8]===undefined?0:arguments[8];this.position.x=x;this.position.y=y;this.scale.x=!scaleX?1:scaleX;this.scale.y=!scaleY?1:scaleY;this.rotation=rotation;this.skew.x=skewX;this.skew.y=skewY;this.pivot.x=pivotX;this.pivot.y=pivotY;return this;};/**
     * Base destroy method for generic display objects. This will automatically
     * remove the display object from its parent Container as well as remove
     * all current event listeners and internal references. Do not use a DisplayObject
     * after calling `destroy`.
     *
     */DisplayObject.prototype.destroy=function destroy(){this.removeAllListeners();if(this.parent){this.parent.removeChild(this);}this.transform=null;this.parent=null;this._bounds=null;this._currentBounds=null;this._mask=null;this.filterArea=null;this.interactive=false;this.interactiveChildren=false;};/**
     * The position of the displayObject on the x axis relative to the local coordinates of the parent.
     * An alias to position.x
     *
     * @member {number}
     * @memberof PIXI.DisplayObject#
     */_createClass(DisplayObject,[{key:'_tempDisplayObjectParent',get:function get(){if(this.tempDisplayObjectParent===null){this.tempDisplayObjectParent=new DisplayObject();}return this.tempDisplayObjectParent;}},{key:'x',get:function get(){return this.position.x;}/**
         * Sets the X position of the object.
         *
         * @param {number} value - The value to set to.
         */,set:function set(value){this.transform.position.x=value;}/**
         * The position of the displayObject on the y axis relative to the local coordinates of the parent.
         * An alias to position.y
         *
         * @member {number}
         * @memberof PIXI.DisplayObject#
         */},{key:'y',get:function get(){return this.position.y;}/**
         * Sets the Y position of the object.
         *
         * @param {number} value - The value to set to.
         */,set:function set(value){this.transform.position.y=value;}/**
         * Current transform of the object based on world (parent) factors
         *
         * @member {PIXI.Matrix}
         * @memberof PIXI.DisplayObject#
         * @readonly
         */},{key:'worldTransform',get:function get(){return this.transform.worldTransform;}/**
         * Current transform of the object based on local factors: position, scale, other stuff
         *
         * @member {PIXI.Matrix}
         * @memberof PIXI.DisplayObject#
         * @readonly
         */},{key:'localTransform',get:function get(){return this.transform.localTransform;}/**
         * The coordinate of the object relative to the local coordinates of the parent.
         * Assignment by value since pixi-v4.
         *
         * @member {PIXI.Point|PIXI.ObservablePoint}
         * @memberof PIXI.DisplayObject#
         */},{key:'position',get:function get(){return this.transform.position;}/**
         * Copies the point to the position of the object.
         *
         * @param {PIXI.Point} value - The value to set to.
         */,set:function set(value){this.transform.position.copy(value);}/**
         * The scale factor of the object.
         * Assignment by value since pixi-v4.
         *
         * @member {PIXI.Point|PIXI.ObservablePoint}
         * @memberof PIXI.DisplayObject#
         */},{key:'scale',get:function get(){return this.transform.scale;}/**
         * Copies the point to the scale of the object.
         *
         * @param {PIXI.Point} value - The value to set to.
         */,set:function set(value){this.transform.scale.copy(value);}/**
         * The pivot point of the displayObject that it rotates around
         * Assignment by value since pixi-v4.
         *
         * @member {PIXI.Point|PIXI.ObservablePoint}
         * @memberof PIXI.DisplayObject#
         */},{key:'pivot',get:function get(){return this.transform.pivot;}/**
         * Copies the point to the pivot of the object.
         *
         * @param {PIXI.Point} value - The value to set to.
         */,set:function set(value){this.transform.pivot.copy(value);}/**
         * The skew factor for the object in radians.
         * Assignment by value since pixi-v4.
         *
         * @member {PIXI.ObservablePoint}
         * @memberof PIXI.DisplayObject#
         */},{key:'skew',get:function get(){return this.transform.skew;}/**
         * Copies the point to the skew of the object.
         *
         * @param {PIXI.Point} value - The value to set to.
         */,set:function set(value){this.transform.skew.copy(value);}/**
         * The rotation of the object in radians.
         *
         * @member {number}
         * @memberof PIXI.DisplayObject#
         */},{key:'rotation',get:function get(){return this.transform.rotation;}/**
         * Sets the rotation of the object.
         *
         * @param {number} value - The value to set to.
         */,set:function set(value){this.transform.rotation=value;}/**
         * Indicates if the object is globally visible.
         *
         * @member {boolean}
         * @memberof PIXI.DisplayObject#
         * @readonly
         */},{key:'worldVisible',get:function get(){var item=this;do{if(!item.visible){return false;}item=item.parent;}while(item);return true;}/**
         * Sets a mask for the displayObject. A mask is an object that limits the visibility of an
         * object to the shape of the mask applied to it. In PIXI a regular mask must be a
         * PIXI.Graphics or a PIXI.Sprite object. This allows for much faster masking in canvas as it
         * utilises shape clipping. To remove a mask, set this property to null.
         *
         * @todo For the moment, PIXI.CanvasRenderer doesn't support PIXI.Sprite as mask.
         *
         * @member {PIXI.Graphics|PIXI.Sprite}
         * @memberof PIXI.DisplayObject#
         */},{key:'mask',get:function get(){return this._mask;}/**
         * Sets the mask.
         *
         * @param {PIXI.Graphics|PIXI.Sprite} value - The value to set to.
         */,set:function set(value){if(this._mask){this._mask.renderable=true;}this._mask=value;if(this._mask){this._mask.renderable=false;}}/**
         * Sets the filters for the displayObject.
         * * IMPORTANT: This is a webGL only feature and will be ignored by the canvas renderer.
         * To remove filters simply set this property to 'null'
         *
         * @member {PIXI.Filter[]}
         * @memberof PIXI.DisplayObject#
         */},{key:'filters',get:function get(){return this._filters&&this._filters.slice();}/**
         * Shallow copies the array to the filters of the object.
         *
         * @param {PIXI.Filter[]} value - The filters to set.
         */,set:function set(value){this._filters=value&&value.slice();}}]);return DisplayObject;}(_eventemitter2.default);// performance increase to avoid using call.. (10x faster)
exports.default=DisplayObject;DisplayObject.prototype.displayObjectUpdateTransform=DisplayObject.prototype.updateTransform;},{"../const":42,"../math":66,"../settings":97,"./Bounds":43,"./Transform":46,"./TransformStatic":48,"eventemitter3":3}],46:[function(require,module,exports){'use strict';exports.__esModule=true;var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor);}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor;};}();var _math=require('../math');var _TransformBase2=require('./TransformBase');var _TransformBase3=_interopRequireDefault(_TransformBase2);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return call&&((typeof call==="undefined"?"undefined":_typeof2(call))==="object"||typeof call==="function")?call:self;}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof2(superClass)));}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass;}/**
 * Generic class to deal with traditional 2D matrix transforms
 * local transformation is calculated from position,scale,skew and rotation
 *
 * @class
 * @extends PIXI.TransformBase
 * @memberof PIXI
 */var Transform=function(_TransformBase){_inherits(Transform,_TransformBase);/**
   *
   */function Transform(){_classCallCheck(this,Transform);/**
    * The coordinate of the object relative to the local coordinates of the parent.
    *
    * @member {PIXI.Point}
    */var _this=_possibleConstructorReturn(this,_TransformBase.call(this));_this.position=new _math.Point(0,0);/**
     * The scale factor of the object.
     *
     * @member {PIXI.Point}
     */_this.scale=new _math.Point(1,1);/**
     * The skew amount, on the x and y axis.
     *
     * @member {PIXI.ObservablePoint}
     */_this.skew=new _math.ObservablePoint(_this.updateSkew,_this,0,0);/**
     * The pivot point of the displayObject that it rotates around
     *
     * @member {PIXI.Point}
     */_this.pivot=new _math.Point(0,0);/**
     * The rotation value of the object, in radians
     *
     * @member {Number}
     * @private
     */_this._rotation=0;_this._cx=1;// cos rotation + skewY;
_this._sx=0;// sin rotation + skewY;
_this._cy=0;// cos rotation + Math.PI/2 - skewX;
_this._sy=1;// sin rotation + Math.PI/2 - skewX;
return _this;}/**
   * Updates the skew values when the skew or rotation changes.
   *
   * @private
   */Transform.prototype.updateSkew=function updateSkew(){this._cx=Math.cos(this._rotation+this.skew._y);this._sx=Math.sin(this._rotation+this.skew._y);this._cy=-Math.sin(this._rotation-this.skew._x);// cos, added PI/2
this._sy=Math.cos(this._rotation-this.skew._x);// sin, added PI/2
};/**
   * Updates only local matrix
   */Transform.prototype.updateLocalTransform=function updateLocalTransform(){var lt=this.localTransform;lt.a=this._cx*this.scale.x;lt.b=this._sx*this.scale.x;lt.c=this._cy*this.scale.y;lt.d=this._sy*this.scale.y;lt.tx=this.position.x-(this.pivot.x*lt.a+this.pivot.y*lt.c);lt.ty=this.position.y-(this.pivot.x*lt.b+this.pivot.y*lt.d);};/**
   * Updates the values of the object and applies the parent's transform.
   *
   * @param {PIXI.Transform} parentTransform - The transform of the parent of this object
   */Transform.prototype.updateTransform=function updateTransform(parentTransform){var lt=this.localTransform;lt.a=this._cx*this.scale.x;lt.b=this._sx*this.scale.x;lt.c=this._cy*this.scale.y;lt.d=this._sy*this.scale.y;lt.tx=this.position.x-(this.pivot.x*lt.a+this.pivot.y*lt.c);lt.ty=this.position.y-(this.pivot.x*lt.b+this.pivot.y*lt.d);// concat the parent matrix with the objects transform.
var pt=parentTransform.worldTransform;var wt=this.worldTransform;wt.a=lt.a*pt.a+lt.b*pt.c;wt.b=lt.a*pt.b+lt.b*pt.d;wt.c=lt.c*pt.a+lt.d*pt.c;wt.d=lt.c*pt.b+lt.d*pt.d;wt.tx=lt.tx*pt.a+lt.ty*pt.c+pt.tx;wt.ty=lt.tx*pt.b+lt.ty*pt.d+pt.ty;this._worldID++;};/**
   * Decomposes a matrix and sets the transforms properties based on it.
   *
   * @param {PIXI.Matrix} matrix - The matrix to decompose
   */Transform.prototype.setFromMatrix=function setFromMatrix(matrix){matrix.decompose(this);};/**
   * The rotation of the object in radians.
   *
   * @member {number}
   * @memberof PIXI.Transform#
   */_createClass(Transform,[{key:'rotation',get:function get(){return this._rotation;}/**
     * Set the rotation of the transform.
     *
     * @param {number} value - The value to set to.
     */,set:function set(value){this._rotation=value;this.updateSkew();}}]);return Transform;}(_TransformBase3.default);exports.default=Transform;},{"../math":66,"./TransformBase":47}],47:[function(require,module,exports){'use strict';exports.__esModule=true;var _math=require('../math');function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}/**
 * Generic class to deal with traditional 2D matrix transforms
 *
 * @class
 * @memberof PIXI
 */var TransformBase=function(){/**
   *
   */function TransformBase(){_classCallCheck(this,TransformBase);/**
     * The global matrix transform. It can be swapped temporarily by some functions like getLocalBounds()
     *
     * @member {PIXI.Matrix}
     */this.worldTransform=new _math.Matrix();/**
     * The local matrix transform
     *
     * @member {PIXI.Matrix}
     */this.localTransform=new _math.Matrix();this._worldID=0;this._parentID=0;}/**
   * TransformBase does not have decomposition, so this function wont do anything
   */TransformBase.prototype.updateLocalTransform=function updateLocalTransform(){}// empty
/**
   * Updates the values of the object and applies the parent's transform.
   *
   * @param {PIXI.TransformBase} parentTransform - The transform of the parent of this object
   */;TransformBase.prototype.updateTransform=function updateTransform(parentTransform){var pt=parentTransform.worldTransform;var wt=this.worldTransform;var lt=this.localTransform;// concat the parent matrix with the objects transform.
wt.a=lt.a*pt.a+lt.b*pt.c;wt.b=lt.a*pt.b+lt.b*pt.d;wt.c=lt.c*pt.a+lt.d*pt.c;wt.d=lt.c*pt.b+lt.d*pt.d;wt.tx=lt.tx*pt.a+lt.ty*pt.c+pt.tx;wt.ty=lt.tx*pt.b+lt.ty*pt.d+pt.ty;this._worldID++;};return TransformBase;}();/**
 * Updates the values of the object and applies the parent's transform.
 * @param  parentTransform {PIXI.Transform} The transform of the parent of this object
 *
 */exports.default=TransformBase;TransformBase.prototype.updateWorldTransform=TransformBase.prototype.updateTransform;TransformBase.IDENTITY=new TransformBase();},{"../math":66}],48:[function(require,module,exports){'use strict';exports.__esModule=true;var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor);}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor;};}();var _math=require('../math');var _TransformBase2=require('./TransformBase');var _TransformBase3=_interopRequireDefault(_TransformBase2);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return call&&((typeof call==="undefined"?"undefined":_typeof2(call))==="object"||typeof call==="function")?call:self;}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof2(superClass)));}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass;}/**
 * Transform that takes care about its versions
 *
 * @class
 * @extends PIXI.TransformBase
 * @memberof PIXI
 */var TransformStatic=function(_TransformBase){_inherits(TransformStatic,_TransformBase);/**
   *
   */function TransformStatic(){_classCallCheck(this,TransformStatic);/**
    * The coordinate of the object relative to the local coordinates of the parent.
    *
    * @member {PIXI.ObservablePoint}
    */var _this=_possibleConstructorReturn(this,_TransformBase.call(this));_this.position=new _math.ObservablePoint(_this.onChange,_this,0,0);/**
     * The scale factor of the object.
     *
     * @member {PIXI.ObservablePoint}
     */_this.scale=new _math.ObservablePoint(_this.onChange,_this,1,1);/**
     * The pivot point of the displayObject that it rotates around
     *
     * @member {PIXI.ObservablePoint}
     */_this.pivot=new _math.ObservablePoint(_this.onChange,_this,0,0);/**
     * The skew amount, on the x and y axis.
     *
     * @member {PIXI.ObservablePoint}
     */_this.skew=new _math.ObservablePoint(_this.updateSkew,_this,0,0);_this._rotation=0;_this._cx=1;// cos rotation + skewY;
_this._sx=0;// sin rotation + skewY;
_this._cy=0;// cos rotation + Math.PI/2 - skewX;
_this._sy=1;// sin rotation + Math.PI/2 - skewX;
_this._localID=0;_this._currentLocalID=0;return _this;}/**
   * Called when a value changes.
   *
   * @private
   */TransformStatic.prototype.onChange=function onChange(){this._localID++;};/**
   * Called when skew or rotation changes
   *
   * @private
   */TransformStatic.prototype.updateSkew=function updateSkew(){this._cx=Math.cos(this._rotation+this.skew._y);this._sx=Math.sin(this._rotation+this.skew._y);this._cy=-Math.sin(this._rotation-this.skew._x);// cos, added PI/2
this._sy=Math.cos(this._rotation-this.skew._x);// sin, added PI/2
this._localID++;};/**
   * Updates only local matrix
   */TransformStatic.prototype.updateLocalTransform=function updateLocalTransform(){var lt=this.localTransform;if(this._localID!==this._currentLocalID){// get the matrix values of the displayobject based on its transform properties..
lt.a=this._cx*this.scale._x;lt.b=this._sx*this.scale._x;lt.c=this._cy*this.scale._y;lt.d=this._sy*this.scale._y;lt.tx=this.position._x-(this.pivot._x*lt.a+this.pivot._y*lt.c);lt.ty=this.position._y-(this.pivot._x*lt.b+this.pivot._y*lt.d);this._currentLocalID=this._localID;// force an update..
this._parentID=-1;}};/**
   * Updates the values of the object and applies the parent's transform.
   *
   * @param {PIXI.Transform} parentTransform - The transform of the parent of this object
   */TransformStatic.prototype.updateTransform=function updateTransform(parentTransform){var lt=this.localTransform;if(this._localID!==this._currentLocalID){// get the matrix values of the displayobject based on its transform properties..
lt.a=this._cx*this.scale._x;lt.b=this._sx*this.scale._x;lt.c=this._cy*this.scale._y;lt.d=this._sy*this.scale._y;lt.tx=this.position._x-(this.pivot._x*lt.a+this.pivot._y*lt.c);lt.ty=this.position._y-(this.pivot._x*lt.b+this.pivot._y*lt.d);this._currentLocalID=this._localID;// force an update..
this._parentID=-1;}if(this._parentID!==parentTransform._worldID){// concat the parent matrix with the objects transform.
var pt=parentTransform.worldTransform;var wt=this.worldTransform;wt.a=lt.a*pt.a+lt.b*pt.c;wt.b=lt.a*pt.b+lt.b*pt.d;wt.c=lt.c*pt.a+lt.d*pt.c;wt.d=lt.c*pt.b+lt.d*pt.d;wt.tx=lt.tx*pt.a+lt.ty*pt.c+pt.tx;wt.ty=lt.tx*pt.b+lt.ty*pt.d+pt.ty;this._parentID=parentTransform._worldID;// update the id of the transform..
this._worldID++;}};/**
   * Decomposes a matrix and sets the transforms properties based on it.
   *
   * @param {PIXI.Matrix} matrix - The matrix to decompose
   */TransformStatic.prototype.setFromMatrix=function setFromMatrix(matrix){matrix.decompose(this);this._localID++;};/**
   * The rotation of the object in radians.
   *
   * @member {number}
   * @memberof PIXI.TransformStatic#
   */_createClass(TransformStatic,[{key:'rotation',get:function get(){return this._rotation;}/**
     * Sets the rotation of the transform.
     *
     * @param {number} value - The value to set to.
     */,set:function set(value){this._rotation=value;this.updateSkew();}}]);return TransformStatic;}(_TransformBase3.default);exports.default=TransformStatic;},{"../math":66,"./TransformBase":47}],49:[function(require,module,exports){'use strict';exports.__esModule=true;var _Container2=require('../display/Container');var _Container3=_interopRequireDefault(_Container2);var _RenderTexture=require('../textures/RenderTexture');var _RenderTexture2=_interopRequireDefault(_RenderTexture);var _Texture=require('../textures/Texture');var _Texture2=_interopRequireDefault(_Texture);var _GraphicsData=require('./GraphicsData');var _GraphicsData2=_interopRequireDefault(_GraphicsData);var _Sprite=require('../sprites/Sprite');var _Sprite2=_interopRequireDefault(_Sprite);var _math=require('../math');var _utils=require('../utils');var _const=require('../const');var _Bounds=require('../display/Bounds');var _Bounds2=_interopRequireDefault(_Bounds);var _bezierCurveTo2=require('./utils/bezierCurveTo');var _bezierCurveTo3=_interopRequireDefault(_bezierCurveTo2);var _CanvasRenderer=require('../renderers/canvas/CanvasRenderer');var _CanvasRenderer2=_interopRequireDefault(_CanvasRenderer);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return call&&((typeof call==="undefined"?"undefined":_typeof2(call))==="object"||typeof call==="function")?call:self;}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof2(superClass)));}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass;}var canvasRenderer=void 0;var tempMatrix=new _math.Matrix();var tempPoint=new _math.Point();var tempColor1=new Float32Array(4);var tempColor2=new Float32Array(4);/**
 * The Graphics class contains methods used to draw primitive shapes such as lines, circles and
 * rectangles to the display, and to color and fill them.
 *
 * @class
 * @extends PIXI.Container
 * @memberof PIXI
 */var Graphics=function(_Container){_inherits(Graphics,_Container);/**
     *
     */function Graphics(){_classCallCheck(this,Graphics);/**
         * The alpha value used when filling the Graphics object.
         *
         * @member {number}
         * @default 1
         */var _this=_possibleConstructorReturn(this,_Container.call(this));_this.fillAlpha=1;/**
         * The width (thickness) of any lines drawn.
         *
         * @member {number}
         * @default 0
         */_this.lineWidth=0;/**
         * The color of any lines drawn.
         *
         * @member {string}
         * @default 0
         */_this.lineColor=0;/**
         * Graphics data
         *
         * @member {PIXI.GraphicsData[]}
         * @private
         */_this.graphicsData=[];/**
         * The tint applied to the graphic shape. This is a hex value. Apply a value of 0xFFFFFF to
         * reset the tint.
         *
         * @member {number}
         * @default 0xFFFFFF
         */_this.tint=0xFFFFFF;/**
         * The previous tint applied to the graphic shape. Used to compare to the current tint and
         * check if theres change.
         *
         * @member {number}
         * @private
         * @default 0xFFFFFF
         */_this._prevTint=0xFFFFFF;/**
         * The blend mode to be applied to the graphic shape. Apply a value of
         * `PIXI.BLEND_MODES.NORMAL` to reset the blend mode.
         *
         * @member {number}
         * @default PIXI.BLEND_MODES.NORMAL;
         * @see PIXI.BLEND_MODES
         */_this.blendMode=_const.BLEND_MODES.NORMAL;/**
         * Current path
         *
         * @member {PIXI.GraphicsData}
         * @private
         */_this.currentPath=null;/**
         * Array containing some WebGL-related properties used by the WebGL renderer.
         *
         * @member {object<number, object>}
         * @private
         */// TODO - _webgl should use a prototype object, not a random undocumented object...
_this._webGL={};/**
         * Whether this shape is being used as a mask.
         *
         * @member {boolean}
         */_this.isMask=false;/**
         * The bounds' padding used for bounds calculation.
         *
         * @member {number}
         */_this.boundsPadding=0;/**
         * A cache of the local bounds to prevent recalculation.
         *
         * @member {PIXI.Rectangle}
         * @private
         */_this._localBounds=new _Bounds2.default();/**
         * Used to detect if the graphics object has changed. If this is set to true then the graphics
         * object will be recalculated.
         *
         * @member {boolean}
         * @private
         */_this.dirty=0;/**
         * Used to detect if we need to do a fast rect check using the id compare method
         * @type {Number}
         */_this.fastRectDirty=-1;/**
         * Used to detect if we clear the graphics webGL data
         * @type {Number}
         */_this.clearDirty=0;/**
         * Used to detect if we we need to recalculate local bounds
         * @type {Number}
         */_this.boundsDirty=-1;/**
         * Used to detect if the cached sprite object needs to be updated.
         *
         * @member {boolean}
         * @private
         */_this.cachedSpriteDirty=false;_this._spriteRect=null;_this._fastRect=false;/**
         * When cacheAsBitmap is set to true the graphics object will be rendered as if it was a sprite.
         * This is useful if your graphics element does not change often, as it will speed up the rendering
         * of the object in exchange for taking up texture memory. It is also useful if you need the graphics
         * object to be anti-aliased, because it will be rendered using canvas. This is not recommended if
         * you are constantly redrawing the graphics element.
         *
         * @name cacheAsBitmap
         * @member {boolean}
         * @memberof PIXI.Graphics#
         * @default false
         */return _this;}/**
     * Creates a new Graphics object with the same values as this one.
     * Note that the only the properties of the object are cloned, not its transform (position,scale,etc)
     *
     * @return {PIXI.Graphics} A clone of the graphics object
     */Graphics.prototype.clone=function clone(){var clone=new Graphics();clone.renderable=this.renderable;clone.fillAlpha=this.fillAlpha;clone.lineWidth=this.lineWidth;clone.lineColor=this.lineColor;clone.tint=this.tint;clone.blendMode=this.blendMode;clone.isMask=this.isMask;clone.boundsPadding=this.boundsPadding;clone.dirty=0;clone.cachedSpriteDirty=this.cachedSpriteDirty;// copy graphics data
for(var i=0;i<this.graphicsData.length;++i){clone.graphicsData.push(this.graphicsData[i].clone());}clone.currentPath=clone.graphicsData[clone.graphicsData.length-1];clone.updateLocalBounds();return clone;};/**
     * Specifies the line style used for subsequent calls to Graphics methods such as the lineTo()
     * method or the drawCircle() method.
     *
     * @param {number} [lineWidth=0] - width of the line to draw, will update the objects stored style
     * @param {number} [color=0] - color of the line to draw, will update the objects stored style
     * @param {number} [alpha=1] - alpha of the line to draw, will update the objects stored style
     * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls
     */Graphics.prototype.lineStyle=function lineStyle(){var lineWidth=arguments.length<=0||arguments[0]===undefined?0:arguments[0];var color=arguments.length<=1||arguments[1]===undefined?0:arguments[1];var alpha=arguments.length<=2||arguments[2]===undefined?1:arguments[2];this.lineWidth=lineWidth;this.lineColor=color;this.lineAlpha=alpha;if(this.currentPath){if(this.currentPath.shape.points.length){// halfway through a line? start a new one!
var shape=new _math.Polygon(this.currentPath.shape.points.slice(-2));shape.closed=false;this.drawShape(shape);}else{// otherwise its empty so lets just set the line properties
this.currentPath.lineWidth=this.lineWidth;this.currentPath.lineColor=this.lineColor;this.currentPath.lineAlpha=this.lineAlpha;}}return this;};/**
     * Moves the current drawing position to x, y.
     *
     * @param {number} x - the X coordinate to move to
     * @param {number} y - the Y coordinate to move to
     * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls
     */Graphics.prototype.moveTo=function moveTo(x,y){var shape=new _math.Polygon([x,y]);shape.closed=false;this.drawShape(shape);return this;};/**
     * Draws a line using the current line style from the current drawing position to (x, y);
     * The current drawing position is then set to (x, y).
     *
     * @param {number} x - the X coordinate to draw to
     * @param {number} y - the Y coordinate to draw to
     * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls
     */Graphics.prototype.lineTo=function lineTo(x,y){this.currentPath.shape.points.push(x,y);this.dirty++;return this;};/**
     * Calculate the points for a quadratic bezier curve and then draws it.
     * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c
     *
     * @param {number} cpX - Control point x
     * @param {number} cpY - Control point y
     * @param {number} toX - Destination point x
     * @param {number} toY - Destination point y
     * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls
     */Graphics.prototype.quadraticCurveTo=function quadraticCurveTo(cpX,cpY,toX,toY){if(this.currentPath){if(this.currentPath.shape.points.length===0){this.currentPath.shape.points=[0,0];}}else{this.moveTo(0,0);}var n=20;var points=this.currentPath.shape.points;var xa=0;var ya=0;if(points.length===0){this.moveTo(0,0);}var fromX=points[points.length-2];var fromY=points[points.length-1];for(var i=1;i<=n;++i){var j=i/n;xa=fromX+(cpX-fromX)*j;ya=fromY+(cpY-fromY)*j;points.push(xa+(cpX+(toX-cpX)*j-xa)*j,ya+(cpY+(toY-cpY)*j-ya)*j);}this.dirty++;return this;};/**
     * Calculate the points for a bezier curve and then draws it.
     *
     * @param {number} cpX - Control point x
     * @param {number} cpY - Control point y
     * @param {number} cpX2 - Second Control point x
     * @param {number} cpY2 - Second Control point y
     * @param {number} toX - Destination point x
     * @param {number} toY - Destination point y
     * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls
     */Graphics.prototype.bezierCurveTo=function bezierCurveTo(cpX,cpY,cpX2,cpY2,toX,toY){if(this.currentPath){if(this.currentPath.shape.points.length===0){this.currentPath.shape.points=[0,0];}}else{this.moveTo(0,0);}var points=this.currentPath.shape.points;var fromX=points[points.length-2];var fromY=points[points.length-1];points.length-=2;(0,_bezierCurveTo3.default)(fromX,fromY,cpX,cpY,cpX2,cpY2,toX,toY,points);this.dirty++;return this;};/**
     * The arcTo() method creates an arc/curve between two tangents on the canvas.
     *
     * "borrowed" from https://code.google.com/p/fxcanvas/ - thanks google!
     *
     * @param {number} x1 - The x-coordinate of the beginning of the arc
     * @param {number} y1 - The y-coordinate of the beginning of the arc
     * @param {number} x2 - The x-coordinate of the end of the arc
     * @param {number} y2 - The y-coordinate of the end of the arc
     * @param {number} radius - The radius of the arc
     * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls
     */Graphics.prototype.arcTo=function arcTo(x1,y1,x2,y2,radius){if(this.currentPath){if(this.currentPath.shape.points.length===0){this.currentPath.shape.points.push(x1,y1);}}else{this.moveTo(x1,y1);}var points=this.currentPath.shape.points;var fromX=points[points.length-2];var fromY=points[points.length-1];var a1=fromY-y1;var b1=fromX-x1;var a2=y2-y1;var b2=x2-x1;var mm=Math.abs(a1*b2-b1*a2);if(mm<1.0e-8||radius===0){if(points[points.length-2]!==x1||points[points.length-1]!==y1){points.push(x1,y1);}}else{var dd=a1*a1+b1*b1;var cc=a2*a2+b2*b2;var tt=a1*a2+b1*b2;var k1=radius*Math.sqrt(dd)/mm;var k2=radius*Math.sqrt(cc)/mm;var j1=k1*tt/dd;var j2=k2*tt/cc;var cx=k1*b2+k2*b1;var cy=k1*a2+k2*a1;var px=b1*(k2+j1);var py=a1*(k2+j1);var qx=b2*(k1+j2);var qy=a2*(k1+j2);var startAngle=Math.atan2(py-cy,px-cx);var endAngle=Math.atan2(qy-cy,qx-cx);this.arc(cx+x1,cy+y1,radius,startAngle,endAngle,b1*a2>b2*a1);}this.dirty++;return this;};/**
     * The arc method creates an arc/curve (used to create circles, or parts of circles).
     *
     * @param {number} cx - The x-coordinate of the center of the circle
     * @param {number} cy - The y-coordinate of the center of the circle
     * @param {number} radius - The radius of the circle
     * @param {number} startAngle - The starting angle, in radians (0 is at the 3 o'clock position
     *  of the arc's circle)
     * @param {number} endAngle - The ending angle, in radians
     * @param {boolean} [anticlockwise=false] - Specifies whether the drawing should be
     *  counter-clockwise or clockwise. False is default, and indicates clockwise, while true
     *  indicates counter-clockwise.
     * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls
     */Graphics.prototype.arc=function arc(cx,cy,radius,startAngle,endAngle){var anticlockwise=arguments.length<=5||arguments[5]===undefined?false:arguments[5];if(startAngle===endAngle){return this;}if(!anticlockwise&&endAngle<=startAngle){endAngle+=Math.PI*2;}else if(anticlockwise&&startAngle<=endAngle){startAngle+=Math.PI*2;}var sweep=endAngle-startAngle;var segs=Math.ceil(Math.abs(sweep)/(Math.PI*2))*40;if(sweep===0){return this;}var startX=cx+Math.cos(startAngle)*radius;var startY=cy+Math.sin(startAngle)*radius;// If the currentPath exists, take its points. Otherwise call `moveTo` to start a path.
var points=this.currentPath?this.currentPath.shape.points:null;if(points){if(points[points.length-2]!==startX||points[points.length-1]!==startY){points.push(startX,startY);}}else{this.moveTo(startX,startY);points=this.currentPath.shape.points;}var theta=sweep/(segs*2);var theta2=theta*2;var cTheta=Math.cos(theta);var sTheta=Math.sin(theta);var segMinus=segs-1;var remainder=segMinus%1/segMinus;for(var i=0;i<=segMinus;++i){var real=i+remainder*i;var angle=theta+startAngle+theta2*real;var c=Math.cos(angle);var s=-Math.sin(angle);points.push((cTheta*c+sTheta*s)*radius+cx,(cTheta*-s+sTheta*c)*radius+cy);}this.dirty++;return this;};/**
     * Specifies a simple one-color fill that subsequent calls to other Graphics methods
     * (such as lineTo() or drawCircle()) use when drawing.
     *
     * @param {number} [color=0] - the color of the fill
     * @param {number} [alpha=1] - the alpha of the fill
     * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls
     */Graphics.prototype.beginFill=function beginFill(){var color=arguments.length<=0||arguments[0]===undefined?0:arguments[0];var alpha=arguments.length<=1||arguments[1]===undefined?1:arguments[1];this.filling=true;this.fillColor=color;this.fillAlpha=alpha;if(this.currentPath){if(this.currentPath.shape.points.length<=2){this.currentPath.fill=this.filling;this.currentPath.fillColor=this.fillColor;this.currentPath.fillAlpha=this.fillAlpha;}}return this;};/**
     * Applies a fill to the lines and shapes that were added since the last call to the beginFill() method.
     *
     * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls
     */Graphics.prototype.endFill=function endFill(){this.filling=false;this.fillColor=null;this.fillAlpha=1;return this;};/**
     *
     * @param {number} x - The X coord of the top-left of the rectangle
     * @param {number} y - The Y coord of the top-left of the rectangle
     * @param {number} width - The width of the rectangle
     * @param {number} height - The height of the rectangle
     * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls
     */Graphics.prototype.drawRect=function drawRect(x,y,width,height){this.drawShape(new _math.Rectangle(x,y,width,height));return this;};/**
     *
     * @param {number} x - The X coord of the top-left of the rectangle
     * @param {number} y - The Y coord of the top-left of the rectangle
     * @param {number} width - The width of the rectangle
     * @param {number} height - The height of the rectangle
     * @param {number} radius - Radius of the rectangle corners
     * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls
     */Graphics.prototype.drawRoundedRect=function drawRoundedRect(x,y,width,height,radius){this.drawShape(new _math.RoundedRectangle(x,y,width,height,radius));return this;};/**
     * Draws a circle.
     *
     * @param {number} x - The X coordinate of the center of the circle
     * @param {number} y - The Y coordinate of the center of the circle
     * @param {number} radius - The radius of the circle
     * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls
     */Graphics.prototype.drawCircle=function drawCircle(x,y,radius){this.drawShape(new _math.Circle(x,y,radius));return this;};/**
     * Draws an ellipse.
     *
     * @param {number} x - The X coordinate of the center of the ellipse
     * @param {number} y - The Y coordinate of the center of the ellipse
     * @param {number} width - The half width of the ellipse
     * @param {number} height - The half height of the ellipse
     * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls
     */Graphics.prototype.drawEllipse=function drawEllipse(x,y,width,height){this.drawShape(new _math.Ellipse(x,y,width,height));return this;};/**
     * Draws a polygon using the given path.
     *
     * @param {number[]|PIXI.Point[]} path - The path data used to construct the polygon.
     * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls
     */Graphics.prototype.drawPolygon=function drawPolygon(path){// prevents an argument assignment deopt
// see section 3.1: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments
var points=path;var closed=true;if(points instanceof _math.Polygon){closed=points.closed;points=points.points;}if(!Array.isArray(points)){// prevents an argument leak deopt
// see section 3.2: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments
points=new Array(arguments.length);for(var i=0;i<points.length;++i){points[i]=arguments[i];// eslint-disable-line prefer-rest-params
}}var shape=new _math.Polygon(points);shape.closed=closed;this.drawShape(shape);return this;};/**
     * Clears the graphics that were drawn to this Graphics object, and resets fill and line style settings.
     *
     * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls
     */Graphics.prototype.clear=function clear(){if(this.lineWidth||this.filling||this.graphicsData.length>0){this.lineWidth=0;this.filling=false;this.boundsDirty=-1;this.dirty++;this.clearDirty++;this.graphicsData.length=0;}this.currentPath=null;this._spriteRect=null;return this;};/**
     * True if graphics consists of one rectangle, and thus, can be drawn like a Sprite and
     * masked with gl.scissor.
     *
     * @returns {boolean} True if only 1 rect.
     */Graphics.prototype.isFastRect=function isFastRect(){return this.graphicsData.length===1&&this.graphicsData[0].shape.type===_const.SHAPES.RECT&&!this.graphicsData[0].lineWidth;};/**
     * Renders the object using the WebGL renderer
     *
     * @private
     * @param {PIXI.WebGLRenderer} renderer - The renderer
     */Graphics.prototype._renderWebGL=function _renderWebGL(renderer){// if the sprite is not visible or the alpha is 0 then no need to render this element
if(this.dirty!==this.fastRectDirty){this.fastRectDirty=this.dirty;this._fastRect=this.isFastRect();}// TODO this check can be moved to dirty?
if(this._fastRect){this._renderSpriteRect(renderer);}else{renderer.setObjectRenderer(renderer.plugins.graphics);renderer.plugins.graphics.render(this);}};/**
     * Renders a sprite rectangle.
     *
     * @private
     * @param {PIXI.WebGLRenderer} renderer - The renderer
     */Graphics.prototype._renderSpriteRect=function _renderSpriteRect(renderer){var rect=this.graphicsData[0].shape;if(!this._spriteRect){if(!Graphics._SPRITE_TEXTURE){Graphics._SPRITE_TEXTURE=_RenderTexture2.default.create(10,10);var canvas=document.createElement('canvas');canvas.width=10;canvas.height=10;var context=canvas.getContext('2d');context.fillStyle='white';context.fillRect(0,0,10,10);Graphics._SPRITE_TEXTURE=_Texture2.default.fromCanvas(canvas);}this._spriteRect=new _Sprite2.default(Graphics._SPRITE_TEXTURE);}if(this.tint===0xffffff){this._spriteRect.tint=this.graphicsData[0].fillColor;}else{var t1=tempColor1;var t2=tempColor2;(0,_utils.hex2rgb)(this.graphicsData[0].fillColor,t1);(0,_utils.hex2rgb)(this.tint,t2);t1[0]*=t2[0];t1[1]*=t2[1];t1[2]*=t2[2];this._spriteRect.tint=(0,_utils.rgb2hex)(t1);}this._spriteRect.alpha=this.graphicsData[0].fillAlpha;this._spriteRect.worldAlpha=this.worldAlpha*this._spriteRect.alpha;Graphics._SPRITE_TEXTURE._frame.width=rect.width;Graphics._SPRITE_TEXTURE._frame.height=rect.height;this._spriteRect.transform.worldTransform=this.transform.worldTransform;this._spriteRect.anchor.set(-rect.x/rect.width,-rect.y/rect.height);this._spriteRect._onAnchorUpdate();this._spriteRect._renderWebGL(renderer);};/**
     * Renders the object using the Canvas renderer
     *
     * @private
     * @param {PIXI.CanvasRenderer} renderer - The renderer
     */Graphics.prototype._renderCanvas=function _renderCanvas(renderer){if(this.isMask===true){return;}renderer.plugins.graphics.render(this);};/**
     * Retrieves the bounds of the graphic shape as a rectangle object
     *
     * @private
     */Graphics.prototype._calculateBounds=function _calculateBounds(){if(this.boundsDirty!==this.dirty){this.boundsDirty=this.dirty;this.updateLocalBounds();this.cachedSpriteDirty=true;}var lb=this._localBounds;this._bounds.addFrame(this.transform,lb.minX,lb.minY,lb.maxX,lb.maxY);};/**
     * Tests if a point is inside this graphics object
     *
     * @param {PIXI.Point} point - the point to test
     * @return {boolean} the result of the test
     */Graphics.prototype.containsPoint=function containsPoint(point){this.worldTransform.applyInverse(point,tempPoint);var graphicsData=this.graphicsData;for(var i=0;i<graphicsData.length;++i){var data=graphicsData[i];if(!data.fill){continue;}// only deal with fills..
if(data.shape){if(data.shape.contains(tempPoint.x,tempPoint.y)){return true;}}}return false;};/**
     * Update the bounds of the object
     *
     */Graphics.prototype.updateLocalBounds=function updateLocalBounds(){var minX=Infinity;var maxX=-Infinity;var minY=Infinity;var maxY=-Infinity;if(this.graphicsData.length){var shape=0;var x=0;var y=0;var w=0;var h=0;for(var i=0;i<this.graphicsData.length;i++){var data=this.graphicsData[i];var type=data.type;var lineWidth=data.lineWidth;shape=data.shape;if(type===_const.SHAPES.RECT||type===_const.SHAPES.RREC){x=shape.x-lineWidth/2;y=shape.y-lineWidth/2;w=shape.width+lineWidth;h=shape.height+lineWidth;minX=x<minX?x:minX;maxX=x+w>maxX?x+w:maxX;minY=y<minY?y:minY;maxY=y+h>maxY?y+h:maxY;}else if(type===_const.SHAPES.CIRC){x=shape.x;y=shape.y;w=shape.radius+lineWidth/2;h=shape.radius+lineWidth/2;minX=x-w<minX?x-w:minX;maxX=x+w>maxX?x+w:maxX;minY=y-h<minY?y-h:minY;maxY=y+h>maxY?y+h:maxY;}else if(type===_const.SHAPES.ELIP){x=shape.x;y=shape.y;w=shape.width+lineWidth/2;h=shape.height+lineWidth/2;minX=x-w<minX?x-w:minX;maxX=x+w>maxX?x+w:maxX;minY=y-h<minY?y-h:minY;maxY=y+h>maxY?y+h:maxY;}else{// POLY
var points=shape.points;var x2=0;var y2=0;var dx=0;var dy=0;var rw=0;var rh=0;var cx=0;var cy=0;for(var j=0;j+2<points.length;j+=2){x=points[j];y=points[j+1];x2=points[j+2];y2=points[j+3];dx=Math.abs(x2-x);dy=Math.abs(y2-y);h=lineWidth;w=Math.sqrt(dx*dx+dy*dy);if(w<1e-9){continue;}rw=(h/w*dy+dx)/2;rh=(h/w*dx+dy)/2;cx=(x2+x)/2;cy=(y2+y)/2;minX=cx-rw<minX?cx-rw:minX;maxX=cx+rw>maxX?cx+rw:maxX;minY=cy-rh<minY?cy-rh:minY;maxY=cy+rh>maxY?cy+rh:maxY;}}}}else{minX=0;maxX=0;minY=0;maxY=0;}var padding=this.boundsPadding;this._localBounds.minX=minX-padding;this._localBounds.maxX=maxX+padding*2;this._localBounds.minY=minY-padding;this._localBounds.maxY=maxY+padding*2;};/**
     * Draws the given shape to this Graphics object. Can be any of Circle, Rectangle, Ellipse, Line or Polygon.
     *
     * @param {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} shape - The shape object to draw.
     * @return {PIXI.GraphicsData} The generated GraphicsData object.
     */Graphics.prototype.drawShape=function drawShape(shape){if(this.currentPath){// check current path!
if(this.currentPath.shape.points.length<=2){this.graphicsData.pop();}}this.currentPath=null;var data=new _GraphicsData2.default(this.lineWidth,this.lineColor,this.lineAlpha,this.fillColor,this.fillAlpha,this.filling,shape);this.graphicsData.push(data);if(data.type===_const.SHAPES.POLY){data.shape.closed=data.shape.closed||this.filling;this.currentPath=data;}this.dirty++;return data;};/**
     * Generates a canvas texture.
     *
     * @param {number} scaleMode - The scale mode of the texture.
     * @param {number} resolution - The resolution of the texture.
     * @return {PIXI.Texture} The new texture.
     */Graphics.prototype.generateCanvasTexture=function generateCanvasTexture(scaleMode){var resolution=arguments.length<=1||arguments[1]===undefined?1:arguments[1];var bounds=this.getLocalBounds();var canvasBuffer=_RenderTexture2.default.create(bounds.width,bounds.height,scaleMode,resolution);if(!canvasRenderer){canvasRenderer=new _CanvasRenderer2.default();}tempMatrix.tx=-bounds.x;tempMatrix.ty=-bounds.y;canvasRenderer.render(this,canvasBuffer,false,tempMatrix);var texture=_Texture2.default.fromCanvas(canvasBuffer.baseTexture._canvasRenderTarget.canvas,scaleMode);texture.baseTexture.resolution=resolution;texture.baseTexture.update();return texture;};/**
     * Closes the current path.
     *
     * @return {PIXI.Graphics} Returns itself.
     */Graphics.prototype.closePath=function closePath(){// ok so close path assumes next one is a hole!
var currentPath=this.currentPath;if(currentPath&&currentPath.shape){currentPath.shape.close();}return this;};/**
     * Adds a hole in the current path.
     *
     * @return {PIXI.Graphics} Returns itself.
     */Graphics.prototype.addHole=function addHole(){// this is a hole!
var hole=this.graphicsData.pop();this.currentPath=this.graphicsData[this.graphicsData.length-1];this.currentPath.addHole(hole.shape);this.currentPath=null;return this;};/**
     * Destroys the Graphics object.
     *
     * @param {object|boolean} [options] - Options parameter. A boolean will act as if all
     *  options have been set to that value
     * @param {boolean} [options.children=false] - if set to true, all the children will have
     *  their destroy method called as well. 'options' will be passed on to those calls.
     */Graphics.prototype.destroy=function destroy(options){_Container.prototype.destroy.call(this,options);// destroy each of the GraphicsData objects
for(var i=0;i<this.graphicsData.length;++i){this.graphicsData[i].destroy();}// for each webgl data entry, destroy the WebGLGraphicsData
for(var id in this._webgl){for(var j=0;j<this._webgl[id].data.length;++j){this._webgl[id].data[j].destroy();}}if(this._spriteRect){this._spriteRect.destroy();}this.graphicsData=null;this.currentPath=null;this._webgl=null;this._localBounds=null;};return Graphics;}(_Container3.default);exports.default=Graphics;Graphics._SPRITE_TEXTURE=null;},{"../const":42,"../display/Bounds":43,"../display/Container":44,"../math":66,"../renderers/canvas/CanvasRenderer":73,"../sprites/Sprite":98,"../textures/RenderTexture":108,"../textures/Texture":109,"../utils":117,"./GraphicsData":50,"./utils/bezierCurveTo":52}],50:[function(require,module,exports){"use strict";exports.__esModule=true;function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}/**
 * A GraphicsData object.
 *
 * @class
 * @memberof PIXI
 */var GraphicsData=function(){/**
   *
   * @param {number} lineWidth - the width of the line to draw
   * @param {number} lineColor - the color of the line to draw
   * @param {number} lineAlpha - the alpha of the line to draw
   * @param {number} fillColor - the color of the fill
   * @param {number} fillAlpha - the alpha of the fill
   * @param {boolean} fill - whether or not the shape is filled with a colour
   * @param {PIXI.Circle|PIXI.Rectangle|PIXI.Ellipse|PIXI.Polygon} shape - The shape object to draw.
   */function GraphicsData(lineWidth,lineColor,lineAlpha,fillColor,fillAlpha,fill,shape){_classCallCheck(this,GraphicsData);/**
     * @member {number} the width of the line to draw
     */this.lineWidth=lineWidth;/**
     * @member {number} the color of the line to draw
     */this.lineColor=lineColor;/**
     * @member {number} the alpha of the line to draw
     */this.lineAlpha=lineAlpha;/**
     * @member {number} cached tint of the line to draw
     */this._lineTint=lineColor;/**
     * @member {number} the color of the fill
     */this.fillColor=fillColor;/**
     * @member {number} the alpha of the fill
     */this.fillAlpha=fillAlpha;/**
     * @member {number} cached tint of the fill
     */this._fillTint=fillColor;/**
     * @member {boolean} whether or not the shape is filled with a colour
     */this.fill=fill;this.holes=[];/**
     * @member {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} The shape object to draw.
     */this.shape=shape;/**
     * @member {number} The type of the shape, see the Const.Shapes file for all the existing types,
     */this.type=shape.type;}/**
   * Creates a new GraphicsData object with the same values as this one.
   *
   * @return {PIXI.GraphicsData} Cloned GraphicsData object
   */GraphicsData.prototype.clone=function clone(){return new GraphicsData(this.lineWidth,this.lineColor,this.lineAlpha,this.fillColor,this.fillAlpha,this.fill,this.shape);};/**
   * Adds a hole to the shape.
   *
   * @param {PIXI.Rectangle|PIXI.Circle} shape - The shape of the hole.
   */GraphicsData.prototype.addHole=function addHole(shape){this.holes.push(shape);};/**
   * Destroys the Graphics data.
   */GraphicsData.prototype.destroy=function destroy(){this.shape=null;this.holes=null;};return GraphicsData;}();exports.default=GraphicsData;},{}],51:[function(require,module,exports){'use strict';exports.__esModule=true;var _CanvasRenderer=require('../../renderers/canvas/CanvasRenderer');var _CanvasRenderer2=_interopRequireDefault(_CanvasRenderer);var _const=require('../../const');function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}/**
 * @author Mat Groves
 *
 * Big thanks to the very clever Matt DesLauriers <mattdesl> https://github.com/mattdesl/
 * for creating the original pixi version!
 * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they
 * now share 4 bytes on the vertex buffer
 *
 * Heavily inspired by LibGDX's CanvasGraphicsRenderer:
 * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/CanvasGraphicsRenderer.java
 *//**
 * Renderer dedicated to drawing and batching graphics objects.
 *
 * @class
 * @private
 * @memberof PIXI
 */var CanvasGraphicsRenderer=function(){/**
     * @param {PIXI.CanvasRenderer} renderer - The current PIXI renderer.
     */function CanvasGraphicsRenderer(renderer){_classCallCheck(this,CanvasGraphicsRenderer);this.renderer=renderer;}/**
     * Renders a Graphics object to a canvas.
     *
     * @param {PIXI.Graphics} graphics - the actual graphics object to render
     */CanvasGraphicsRenderer.prototype.render=function render(graphics){var renderer=this.renderer;var context=renderer.context;var worldAlpha=graphics.worldAlpha;var transform=graphics.transform.worldTransform;var resolution=renderer.resolution;// if the tint has changed, set the graphics object to dirty.
if(this._prevTint!==this.tint){this.dirty=true;}context.setTransform(transform.a*resolution,transform.b*resolution,transform.c*resolution,transform.d*resolution,transform.tx*resolution,transform.ty*resolution);if(graphics.dirty){this.updateGraphicsTint(graphics);graphics.dirty=false;}renderer.setBlendMode(graphics.blendMode);for(var i=0;i<graphics.graphicsData.length;i++){var data=graphics.graphicsData[i];var shape=data.shape;var fillColor=data._fillTint;var lineColor=data._lineTint;context.lineWidth=data.lineWidth;if(data.type===_const.SHAPES.POLY){context.beginPath();this.renderPolygon(shape.points,shape.closed,context);for(var j=0;j<data.holes.length;j++){this.renderPolygon(data.holes[j].points,true,context);}if(data.fill){context.globalAlpha=data.fillAlpha*worldAlpha;context.fillStyle='#'+('00000'+(fillColor|0).toString(16)).substr(-6);context.fill();}if(data.lineWidth){context.globalAlpha=data.lineAlpha*worldAlpha;context.strokeStyle='#'+('00000'+(lineColor|0).toString(16)).substr(-6);context.stroke();}}else if(data.type===_const.SHAPES.RECT){if(data.fillColor||data.fillColor===0){context.globalAlpha=data.fillAlpha*worldAlpha;context.fillStyle='#'+('00000'+(fillColor|0).toString(16)).substr(-6);context.fillRect(shape.x,shape.y,shape.width,shape.height);}if(data.lineWidth){context.globalAlpha=data.lineAlpha*worldAlpha;context.strokeStyle='#'+('00000'+(lineColor|0).toString(16)).substr(-6);context.strokeRect(shape.x,shape.y,shape.width,shape.height);}}else if(data.type===_const.SHAPES.CIRC){// TODO - need to be Undefined!
context.beginPath();context.arc(shape.x,shape.y,shape.radius,0,2*Math.PI);context.closePath();if(data.fill){context.globalAlpha=data.fillAlpha*worldAlpha;context.fillStyle='#'+('00000'+(fillColor|0).toString(16)).substr(-6);context.fill();}if(data.lineWidth){context.globalAlpha=data.lineAlpha*worldAlpha;context.strokeStyle='#'+('00000'+(lineColor|0).toString(16)).substr(-6);context.stroke();}}else if(data.type===_const.SHAPES.ELIP){// ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
var w=shape.width*2;var h=shape.height*2;var x=shape.x-w/2;var y=shape.y-h/2;context.beginPath();var kappa=0.5522848;var ox=w/2*kappa;// control point offset horizontal
var oy=h/2*kappa;// control point offset vertical
var xe=x+w;// x-end
var ye=y+h;// y-end
var xm=x+w/2;// x-middle
var ym=y+h/2;// y-middle
context.moveTo(x,ym);context.bezierCurveTo(x,ym-oy,xm-ox,y,xm,y);context.bezierCurveTo(xm+ox,y,xe,ym-oy,xe,ym);context.bezierCurveTo(xe,ym+oy,xm+ox,ye,xm,ye);context.bezierCurveTo(xm-ox,ye,x,ym+oy,x,ym);context.closePath();if(data.fill){context.globalAlpha=data.fillAlpha*worldAlpha;context.fillStyle='#'+('00000'+(fillColor|0).toString(16)).substr(-6);context.fill();}if(data.lineWidth){context.globalAlpha=data.lineAlpha*worldAlpha;context.strokeStyle='#'+('00000'+(lineColor|0).toString(16)).substr(-6);context.stroke();}}else if(data.type===_const.SHAPES.RREC){var rx=shape.x;var ry=shape.y;var width=shape.width;var height=shape.height;var radius=shape.radius;var maxRadius=Math.min(width,height)/2|0;radius=radius>maxRadius?maxRadius:radius;context.beginPath();context.moveTo(rx,ry+radius);context.lineTo(rx,ry+height-radius);context.quadraticCurveTo(rx,ry+height,rx+radius,ry+height);context.lineTo(rx+width-radius,ry+height);context.quadraticCurveTo(rx+width,ry+height,rx+width,ry+height-radius);context.lineTo(rx+width,ry+radius);context.quadraticCurveTo(rx+width,ry,rx+width-radius,ry);context.lineTo(rx+radius,ry);context.quadraticCurveTo(rx,ry,rx,ry+radius);context.closePath();if(data.fillColor||data.fillColor===0){context.globalAlpha=data.fillAlpha*worldAlpha;context.fillStyle='#'+('00000'+(fillColor|0).toString(16)).substr(-6);context.fill();}if(data.lineWidth){context.globalAlpha=data.lineAlpha*worldAlpha;context.strokeStyle='#'+('00000'+(lineColor|0).toString(16)).substr(-6);context.stroke();}}}};/**
     * Updates the tint of a graphics object
     *
     * @private
     * @param {PIXI.Graphics} graphics - the graphics that will have its tint updated
     */CanvasGraphicsRenderer.prototype.updateGraphicsTint=function updateGraphicsTint(graphics){graphics._prevTint=graphics.tint;var tintR=(graphics.tint>>16&0xFF)/255;var tintG=(graphics.tint>>8&0xFF)/255;var tintB=(graphics.tint&0xFF)/255;for(var i=0;i<graphics.graphicsData.length;++i){var data=graphics.graphicsData[i];var fillColor=data.fillColor|0;var lineColor=data.lineColor|0;// super inline cos im an optimization NAZI :)
data._fillTint=((fillColor>>16&0xFF)/255*tintR*255<<16)+((fillColor>>8&0xFF)/255*tintG*255<<8)+(fillColor&0xFF)/255*tintB*255;data._lineTint=((lineColor>>16&0xFF)/255*tintR*255<<16)+((lineColor>>8&0xFF)/255*tintG*255<<8)+(lineColor&0xFF)/255*tintB*255;}};/**
     * Renders a polygon.
     *
     * @param {PIXI.Point[]} points - The points to render
     * @param {boolean} close - Should the polygon be closed
     * @param {CanvasRenderingContext2D} context - The rendering context to use
     */CanvasGraphicsRenderer.prototype.renderPolygon=function renderPolygon(points,close,context){context.moveTo(points[0],points[1]);for(var j=1;j<points.length/2;++j){context.lineTo(points[j*2],points[j*2+1]);}if(close){context.closePath();}};/**
     * destroy graphics object
     *
     */CanvasGraphicsRenderer.prototype.destroy=function destroy(){this.renderer=null;};return CanvasGraphicsRenderer;}();exports.default=CanvasGraphicsRenderer;_CanvasRenderer2.default.registerPlugin('graphics',CanvasGraphicsRenderer);},{"../../const":42,"../../renderers/canvas/CanvasRenderer":73}],52:[function(require,module,exports){"use strict";exports.__esModule=true;exports.default=bezierCurveTo;/**
 * Calculate the points for a bezier curve and then draws it.
 *
 * Ignored from docs since it is not directly exposed.
 *
 * @ignore
 * @param {number} fromX - Starting point x
 * @param {number} fromY - Starting point y
 * @param {number} cpX - Control point x
 * @param {number} cpY - Control point y
 * @param {number} cpX2 - Second Control point x
 * @param {number} cpY2 - Second Control point y
 * @param {number} toX - Destination point x
 * @param {number} toY - Destination point y
 * @param {number[]} [path=[]] - Path array to push points into
 * @return {number[]} Array of points of the curve
 */function bezierCurveTo(fromX,fromY,cpX,cpY,cpX2,cpY2,toX,toY){var path=arguments.length<=8||arguments[8]===undefined?[]:arguments[8];var n=20;var dt=0;var dt2=0;var dt3=0;var t2=0;var t3=0;path.push(fromX,fromY);for(var i=1,j=0;i<=n;++i){j=i/n;dt=1-j;dt2=dt*dt;dt3=dt2*dt;t2=j*j;t3=t2*j;path.push(dt3*fromX+3*dt2*j*cpX+3*dt*t2*cpX2+t3*toX,dt3*fromY+3*dt2*j*cpY+3*dt*t2*cpY2+t3*toY);}return path;}},{}],53:[function(require,module,exports){'use strict';exports.__esModule=true;var _utils=require('../../utils');var _const=require('../../const');var _ObjectRenderer2=require('../../renderers/webgl/utils/ObjectRenderer');var _ObjectRenderer3=_interopRequireDefault(_ObjectRenderer2);var _WebGLRenderer=require('../../renderers/webgl/WebGLRenderer');var _WebGLRenderer2=_interopRequireDefault(_WebGLRenderer);var _WebGLGraphicsData=require('./WebGLGraphicsData');var _WebGLGraphicsData2=_interopRequireDefault(_WebGLGraphicsData);var _PrimitiveShader=require('./shaders/PrimitiveShader');var _PrimitiveShader2=_interopRequireDefault(_PrimitiveShader);var _buildPoly=require('./utils/buildPoly');var _buildPoly2=_interopRequireDefault(_buildPoly);var _buildRectangle=require('./utils/buildRectangle');var _buildRectangle2=_interopRequireDefault(_buildRectangle);var _buildRoundedRectangle=require('./utils/buildRoundedRectangle');var _buildRoundedRectangle2=_interopRequireDefault(_buildRoundedRectangle);var _buildCircle=require('./utils/buildCircle');var _buildCircle2=_interopRequireDefault(_buildCircle);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return call&&((typeof call==="undefined"?"undefined":_typeof2(call))==="object"||typeof call==="function")?call:self;}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof2(superClass)));}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass;}/**
 * Renders the graphics object.
 *
 * @class
 * @memberof PIXI
 * @extends PIXI.ObjectRenderer
 */var GraphicsRenderer=function(_ObjectRenderer){_inherits(GraphicsRenderer,_ObjectRenderer);/**
     * @param {PIXI.WebGLRenderer} renderer - The renderer this object renderer works for.
     */function GraphicsRenderer(renderer){_classCallCheck(this,GraphicsRenderer);var _this=_possibleConstructorReturn(this,_ObjectRenderer.call(this,renderer));_this.graphicsDataPool=[];_this.primitiveShader=null;_this.gl=renderer.gl;// easy access!
_this.CONTEXT_UID=0;return _this;}/**
     * Called when there is a WebGL context change
     *
     * @private
     *
     */GraphicsRenderer.prototype.onContextChange=function onContextChange(){this.gl=this.renderer.gl;this.CONTEXT_UID=this.renderer.CONTEXT_UID;this.primitiveShader=new _PrimitiveShader2.default(this.gl);};/**
     * Destroys this renderer.
     *
     */GraphicsRenderer.prototype.destroy=function destroy(){_ObjectRenderer3.default.prototype.destroy.call(this);for(var i=0;i<this.graphicsDataPool.length;++i){this.graphicsDataPool[i].destroy();}this.graphicsDataPool=null;};/**
     * Renders a graphics object.
     *
     * @param {PIXI.Graphics} graphics - The graphics object to render.
     */GraphicsRenderer.prototype.render=function render(graphics){var renderer=this.renderer;var gl=renderer.gl;var webGLData=void 0;var webGL=graphics._webGL[this.CONTEXT_UID];if(!webGL||graphics.dirty!==webGL.dirty){this.updateGraphics(graphics);webGL=graphics._webGL[this.CONTEXT_UID];}// This  could be speeded up for sure!
var shader=this.primitiveShader;renderer.bindShader(shader);renderer.state.setBlendMode(graphics.blendMode);for(var i=0,n=webGL.data.length;i<n;i++){webGLData=webGL.data[i];var shaderTemp=webGLData.shader;renderer.bindShader(shaderTemp);shaderTemp.uniforms.translationMatrix=graphics.transform.worldTransform.toArray(true);shaderTemp.uniforms.tint=(0,_utils.hex2rgb)(graphics.tint);shaderTemp.uniforms.alpha=graphics.worldAlpha;renderer.bindVao(webGLData.vao);webGLData.vao.draw(gl.TRIANGLE_STRIP,webGLData.indices.length);}};/**
     * Updates the graphics object
     *
     * @private
     * @param {PIXI.Graphics} graphics - The graphics object to update
     */GraphicsRenderer.prototype.updateGraphics=function updateGraphics(graphics){var gl=this.renderer.gl;// get the contexts graphics object
var webGL=graphics._webGL[this.CONTEXT_UID];// if the graphics object does not exist in the webGL context time to create it!
if(!webGL){webGL=graphics._webGL[this.CONTEXT_UID]={lastIndex:0,data:[],gl:gl,clearDirty:-1,dirty:-1};}// flag the graphics as not dirty as we are about to update it...
webGL.dirty=graphics.dirty;// if the user cleared the graphics object we will need to clear every object
if(graphics.clearDirty!==webGL.clearDirty){webGL.clearDirty=graphics.clearDirty;// loop through and return all the webGLDatas to the object pool so than can be reused later on
for(var i=0;i<webGL.data.length;i++){this.graphicsDataPool.push(webGL.data[i]);}// clear the array and reset the index..
webGL.data.length=0;webGL.lastIndex=0;}var webGLData=void 0;// loop through the graphics datas and construct each one..
// if the object is a complex fill then the new stencil buffer technique will be used
// other wise graphics objects will be pushed into a batch..
for(var _i=webGL.lastIndex;_i<graphics.graphicsData.length;_i++){var data=graphics.graphicsData[_i];// TODO - this can be simplified
webGLData=this.getWebGLData(webGL,0);if(data.type===_const.SHAPES.POLY){(0,_buildPoly2.default)(data,webGLData);}if(data.type===_const.SHAPES.RECT){(0,_buildRectangle2.default)(data,webGLData);}else if(data.type===_const.SHAPES.CIRC||data.type===_const.SHAPES.ELIP){(0,_buildCircle2.default)(data,webGLData);}else if(data.type===_const.SHAPES.RREC){(0,_buildRoundedRectangle2.default)(data,webGLData);}webGL.lastIndex++;}this.renderer.bindVao(null);// upload all the dirty data...
for(var _i2=0;_i2<webGL.data.length;_i2++){webGLData=webGL.data[_i2];if(webGLData.dirty){webGLData.upload();}}};/**
     *
     * @private
     * @param {WebGLRenderingContext} gl - the current WebGL drawing context
     * @param {number} type - TODO @Alvin
     * @return {*} TODO
     */GraphicsRenderer.prototype.getWebGLData=function getWebGLData(gl,type){var webGLData=gl.data[gl.data.length-1];if(!webGLData||webGLData.points.length>320000){webGLData=this.graphicsDataPool.pop()||new _WebGLGraphicsData2.default(this.renderer.gl,this.primitiveShader,this.renderer.state.attribsState);webGLData.reset(type);gl.data.push(webGLData);}webGLData.dirty=true;return webGLData;};return GraphicsRenderer;}(_ObjectRenderer3.default);exports.default=GraphicsRenderer;_WebGLRenderer2.default.registerPlugin('graphics',GraphicsRenderer);},{"../../const":42,"../../renderers/webgl/WebGLRenderer":80,"../../renderers/webgl/utils/ObjectRenderer":90,"../../utils":117,"./WebGLGraphicsData":54,"./shaders/PrimitiveShader":55,"./utils/buildCircle":56,"./utils/buildPoly":58,"./utils/buildRectangle":59,"./utils/buildRoundedRectangle":60}],54:[function(require,module,exports){'use strict';exports.__esModule=true;var _pixiGlCore=require('pixi-gl-core');var _pixiGlCore2=_interopRequireDefault(_pixiGlCore);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}/**
 * An object containing WebGL specific properties to be used by the WebGL renderer
 *
 * @class
 * @private
 * @memberof PIXI
 */var WebGLGraphicsData=function(){/**
   * @param {WebGLRenderingContext} gl - The current WebGL drawing context
   * @param {PIXI.Shader} shader - The shader
   * @param {object} attribsState - The state for the VAO
   */function WebGLGraphicsData(gl,shader,attribsState){_classCallCheck(this,WebGLGraphicsData);/**
     * The current WebGL drawing context
     *
     * @member {WebGLRenderingContext}
     */this.gl=gl;// TODO does this need to be split before uploading??
/**
     * An array of color components (r,g,b)
     * @member {number[]}
     */this.color=[0,0,0];// color split!
/**
     * An array of points to draw
     * @member {PIXI.Point[]}
     */this.points=[];/**
     * The indices of the vertices
     * @member {number[]}
     */this.indices=[];/**
     * The main buffer
     * @member {WebGLBuffer}
     */this.buffer=_pixiGlCore2.default.GLBuffer.createVertexBuffer(gl);/**
     * The index buffer
     * @member {WebGLBuffer}
     */this.indexBuffer=_pixiGlCore2.default.GLBuffer.createIndexBuffer(gl);/**
     * Whether this graphics is dirty or not
     * @member {boolean}
     */this.dirty=true;this.glPoints=null;this.glIndices=null;/**
     *
     * @member {PIXI.Shader}
     */this.shader=shader;this.vao=new _pixiGlCore2.default.VertexArrayObject(gl,attribsState).addIndex(this.indexBuffer).addAttribute(this.buffer,shader.attributes.aVertexPosition,gl.FLOAT,false,4*6,0).addAttribute(this.buffer,shader.attributes.aColor,gl.FLOAT,false,4*6,2*4);}/**
   * Resets the vertices and the indices
   */WebGLGraphicsData.prototype.reset=function reset(){this.points.length=0;this.indices.length=0;};/**
   * Binds the buffers and uploads the data
   */WebGLGraphicsData.prototype.upload=function upload(){this.glPoints=new Float32Array(this.points);this.buffer.upload(this.glPoints);this.glIndices=new Uint16Array(this.indices);this.indexBuffer.upload(this.glIndices);this.dirty=false;};/**
   * Empties all the data
   */WebGLGraphicsData.prototype.destroy=function destroy(){this.color=null;this.points=null;this.indices=null;this.vao.destroy();this.buffer.destroy();this.indexBuffer.destroy();this.gl=null;this.buffer=null;this.indexBuffer=null;this.glPoints=null;this.glIndices=null;};return WebGLGraphicsData;}();exports.default=WebGLGraphicsData;},{"pixi-gl-core":12}],55:[function(require,module,exports){'use strict';exports.__esModule=true;var _Shader2=require('../../../Shader');var _Shader3=_interopRequireDefault(_Shader2);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return call&&((typeof call==="undefined"?"undefined":_typeof2(call))==="object"||typeof call==="function")?call:self;}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof2(superClass)));}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass;}/**
 * This shader is used to draw simple primitive shapes for {@link PIXI.Graphics}.
 *
 * @class
 * @memberof PIXI
 * @extends PIXI.Shader
 */var PrimitiveShader=function(_Shader){_inherits(PrimitiveShader,_Shader);/**
     * @param {WebGLRenderingContext} gl - The webgl shader manager this shader works for.
     */function PrimitiveShader(gl){_classCallCheck(this,PrimitiveShader);return _possibleConstructorReturn(this,_Shader.call(this,gl,// vertex shader
['attribute vec2 aVertexPosition;','attribute vec4 aColor;','uniform mat3 translationMatrix;','uniform mat3 projectionMatrix;','uniform float alpha;','uniform vec3 tint;','varying vec4 vColor;','void main(void){','   gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);','   vColor = aColor * vec4(tint * alpha, alpha);','}'].join('\n'),// fragment shader
['varying vec4 vColor;','void main(void){','   gl_FragColor = vColor;','}'].join('\n')));}return PrimitiveShader;}(_Shader3.default);exports.default=PrimitiveShader;},{"../../../Shader":41}],56:[function(require,module,exports){'use strict';exports.__esModule=true;exports.default=buildCircle;var _buildLine=require('./buildLine');var _buildLine2=_interopRequireDefault(_buildLine);var _const=require('../../../const');var _utils=require('../../../utils');function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}/**
 * Builds a circle to draw
 *
 * Ignored from docs since it is not directly exposed.
 *
 * @ignore
 * @private
 * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object to draw
 * @param {object} webGLData - an object containing all the webGL-specific information to create this shape
 */function buildCircle(graphicsData,webGLData){// need to convert points to a nice regular data
var circleData=graphicsData.shape;var x=circleData.x;var y=circleData.y;var width=void 0;var height=void 0;// TODO - bit hacky??
if(graphicsData.type===_const.SHAPES.CIRC){width=circleData.radius;height=circleData.radius;}else{width=circleData.width;height=circleData.height;}var totalSegs=Math.floor(30*Math.sqrt(circleData.radius))||Math.floor(15*Math.sqrt(circleData.width+circleData.height));var seg=Math.PI*2/totalSegs;if(graphicsData.fill){var color=(0,_utils.hex2rgb)(graphicsData.fillColor);var alpha=graphicsData.fillAlpha;var r=color[0]*alpha;var g=color[1]*alpha;var b=color[2]*alpha;var verts=webGLData.points;var indices=webGLData.indices;var vecPos=verts.length/6;indices.push(vecPos);for(var i=0;i<totalSegs+1;i++){verts.push(x,y,r,g,b,alpha);verts.push(x+Math.sin(seg*i)*width,y+Math.cos(seg*i)*height,r,g,b,alpha);indices.push(vecPos++,vecPos++);}indices.push(vecPos-1);}if(graphicsData.lineWidth){var tempPoints=graphicsData.points;graphicsData.points=[];for(var _i=0;_i<totalSegs+1;_i++){graphicsData.points.push(x+Math.sin(seg*_i)*width,y+Math.cos(seg*_i)*height);}(0,_buildLine2.default)(graphicsData,webGLData);graphicsData.points=tempPoints;}}},{"../../../const":42,"../../../utils":117,"./buildLine":57}],57:[function(require,module,exports){'use strict';exports.__esModule=true;exports.default=buildLine;var _math=require('../../../math');var _utils=require('../../../utils');/**
 * Builds a line to draw
 *
 * Ignored from docs since it is not directly exposed.
 *
 * @ignore
 * @private
 * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties
 * @param {object} webGLData - an object containing all the webGL-specific information to create this shape
 */function buildLine(graphicsData,webGLData){// TODO OPTIMISE!
var points=graphicsData.points;if(points.length===0){return;}// if the line width is an odd number add 0.5 to align to a whole pixel
// commenting this out fixes #711 and #1620
// if (graphicsData.lineWidth%2)
// {
//     for (i = 0; i < points.length; i++)
//     {
//         points[i] += 0.5;
//     }
// }
// get first and last point.. figure out the middle!
var firstPoint=new _math.Point(points[0],points[1]);var lastPoint=new _math.Point(points[points.length-2],points[points.length-1]);// if the first point is the last point - gonna have issues :)
if(firstPoint.x===lastPoint.x&&firstPoint.y===lastPoint.y){// need to clone as we are going to slightly modify the shape..
points=points.slice();points.pop();points.pop();lastPoint=new _math.Point(points[points.length-2],points[points.length-1]);var midPointX=lastPoint.x+(firstPoint.x-lastPoint.x)*0.5;var midPointY=lastPoint.y+(firstPoint.y-lastPoint.y)*0.5;points.unshift(midPointX,midPointY);points.push(midPointX,midPointY);}var verts=webGLData.points;var indices=webGLData.indices;var length=points.length/2;var indexCount=points.length;var indexStart=verts.length/6;// DRAW the Line
var width=graphicsData.lineWidth/2;// sort color
var color=(0,_utils.hex2rgb)(graphicsData.lineColor);var alpha=graphicsData.lineAlpha;var r=color[0]*alpha;var g=color[1]*alpha;var b=color[2]*alpha;var p1x=points[0];var p1y=points[1];var p2x=points[2];var p2y=points[3];var p3x=0;var p3y=0;var perpx=-(p1y-p2y);var perpy=p1x-p2x;var perp2x=0;var perp2y=0;var perp3x=0;var perp3y=0;var dist=Math.sqrt(perpx*perpx+perpy*perpy);perpx/=dist;perpy/=dist;perpx*=width;perpy*=width;// start
verts.push(p1x-perpx,p1y-perpy,r,g,b,alpha);verts.push(p1x+perpx,p1y+perpy,r,g,b,alpha);for(var i=1;i<length-1;++i){p1x=points[(i-1)*2];p1y=points[(i-1)*2+1];p2x=points[i*2];p2y=points[i*2+1];p3x=points[(i+1)*2];p3y=points[(i+1)*2+1];perpx=-(p1y-p2y);perpy=p1x-p2x;dist=Math.sqrt(perpx*perpx+perpy*perpy);perpx/=dist;perpy/=dist;perpx*=width;perpy*=width;perp2x=-(p2y-p3y);perp2y=p2x-p3x;dist=Math.sqrt(perp2x*perp2x+perp2y*perp2y);perp2x/=dist;perp2y/=dist;perp2x*=width;perp2y*=width;var a1=-perpy+p1y-(-perpy+p2y);var b1=-perpx+p2x-(-perpx+p1x);var c1=(-perpx+p1x)*(-perpy+p2y)-(-perpx+p2x)*(-perpy+p1y);var a2=-perp2y+p3y-(-perp2y+p2y);var b2=-perp2x+p2x-(-perp2x+p3x);var c2=(-perp2x+p3x)*(-perp2y+p2y)-(-perp2x+p2x)*(-perp2y+p3y);var denom=a1*b2-a2*b1;if(Math.abs(denom)<0.1){denom+=10.1;verts.push(p2x-perpx,p2y-perpy,r,g,b,alpha);verts.push(p2x+perpx,p2y+perpy,r,g,b,alpha);continue;}var px=(b1*c2-b2*c1)/denom;var py=(a2*c1-a1*c2)/denom;var pdist=(px-p2x)*(px-p2x)+(py-p2y)*(py-p2y);if(pdist>196*width*width){perp3x=perpx-perp2x;perp3y=perpy-perp2y;dist=Math.sqrt(perp3x*perp3x+perp3y*perp3y);perp3x/=dist;perp3y/=dist;perp3x*=width;perp3y*=width;verts.push(p2x-perp3x,p2y-perp3y);verts.push(r,g,b,alpha);verts.push(p2x+perp3x,p2y+perp3y);verts.push(r,g,b,alpha);verts.push(p2x-perp3x,p2y-perp3y);verts.push(r,g,b,alpha);indexCount++;}else{verts.push(px,py);verts.push(r,g,b,alpha);verts.push(p2x-(px-p2x),p2y-(py-p2y));verts.push(r,g,b,alpha);}}p1x=points[(length-2)*2];p1y=points[(length-2)*2+1];p2x=points[(length-1)*2];p2y=points[(length-1)*2+1];perpx=-(p1y-p2y);perpy=p1x-p2x;dist=Math.sqrt(perpx*perpx+perpy*perpy);perpx/=dist;perpy/=dist;perpx*=width;perpy*=width;verts.push(p2x-perpx,p2y-perpy);verts.push(r,g,b,alpha);verts.push(p2x+perpx,p2y+perpy);verts.push(r,g,b,alpha);indices.push(indexStart);for(var _i=0;_i<indexCount;++_i){indices.push(indexStart++);}indices.push(indexStart-1);}},{"../../../math":66,"../../../utils":117}],58:[function(require,module,exports){'use strict';exports.__esModule=true;exports.default=buildPoly;var _buildLine=require('./buildLine');var _buildLine2=_interopRequireDefault(_buildLine);var _utils=require('../../../utils');var _earcut=require('earcut');var _earcut2=_interopRequireDefault(_earcut);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}/**
 * Builds a polygon to draw
 *
 * Ignored from docs since it is not directly exposed.
 *
 * @ignore
 * @private
 * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties
 * @param {object} webGLData - an object containing all the webGL-specific information to create this shape
 */function buildPoly(graphicsData,webGLData){graphicsData.points=graphicsData.shape.points.slice();var points=graphicsData.points;if(graphicsData.fill&&points.length>=6){var holeArray=[];// Process holes..
var holes=graphicsData.holes;for(var i=0;i<holes.length;i++){var hole=holes[i];holeArray.push(points.length/2);points=points.concat(hole.points);}// get first and last point.. figure out the middle!
var verts=webGLData.points;var indices=webGLData.indices;var length=points.length/2;// sort color
var color=(0,_utils.hex2rgb)(graphicsData.fillColor);var alpha=graphicsData.fillAlpha;var r=color[0]*alpha;var g=color[1]*alpha;var b=color[2]*alpha;var triangles=(0,_earcut2.default)(points,holeArray,2);if(!triangles){return;}var vertPos=verts.length/6;for(var _i=0;_i<triangles.length;_i+=3){indices.push(triangles[_i]+vertPos);indices.push(triangles[_i]+vertPos);indices.push(triangles[_i+1]+vertPos);indices.push(triangles[_i+2]+vertPos);indices.push(triangles[_i+2]+vertPos);}for(var _i2=0;_i2<length;_i2++){verts.push(points[_i2*2],points[_i2*2+1],r,g,b,alpha);}}if(graphicsData.lineWidth>0){(0,_buildLine2.default)(graphicsData,webGLData);}}},{"../../../utils":117,"./buildLine":57,"earcut":2}],59:[function(require,module,exports){'use strict';exports.__esModule=true;exports.default=buildRectangle;var _buildLine=require('./buildLine');var _buildLine2=_interopRequireDefault(_buildLine);var _utils=require('../../../utils');function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}/**
 * Builds a rectangle to draw
 *
 * Ignored from docs since it is not directly exposed.
 *
 * @ignore
 * @private
 * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties
 * @param {object} webGLData - an object containing all the webGL-specific information to create this shape
 */function buildRectangle(graphicsData,webGLData){// --- //
// need to convert points to a nice regular data
//
var rectData=graphicsData.shape;var x=rectData.x;var y=rectData.y;var width=rectData.width;var height=rectData.height;if(graphicsData.fill){var color=(0,_utils.hex2rgb)(graphicsData.fillColor);var alpha=graphicsData.fillAlpha;var r=color[0]*alpha;var g=color[1]*alpha;var b=color[2]*alpha;var verts=webGLData.points;var indices=webGLData.indices;var vertPos=verts.length/6;// start
verts.push(x,y);verts.push(r,g,b,alpha);verts.push(x+width,y);verts.push(r,g,b,alpha);verts.push(x,y+height);verts.push(r,g,b,alpha);verts.push(x+width,y+height);verts.push(r,g,b,alpha);// insert 2 dead triangles..
indices.push(vertPos,vertPos,vertPos+1,vertPos+2,vertPos+3,vertPos+3);}if(graphicsData.lineWidth){var tempPoints=graphicsData.points;graphicsData.points=[x,y,x+width,y,x+width,y+height,x,y+height,x,y];(0,_buildLine2.default)(graphicsData,webGLData);graphicsData.points=tempPoints;}}},{"../../../utils":117,"./buildLine":57}],60:[function(require,module,exports){'use strict';exports.__esModule=true;exports.default=buildRoundedRectangle;var _earcut=require('earcut');var _earcut2=_interopRequireDefault(_earcut);var _buildLine=require('./buildLine');var _buildLine2=_interopRequireDefault(_buildLine);var _utils=require('../../../utils');function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}/**
 * Builds a rounded rectangle to draw
 *
 * Ignored from docs since it is not directly exposed.
 *
 * @ignore
 * @private
 * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties
 * @param {object} webGLData - an object containing all the webGL-specific information to create this shape
 */function buildRoundedRectangle(graphicsData,webGLData){var rrectData=graphicsData.shape;var x=rrectData.x;var y=rrectData.y;var width=rrectData.width;var height=rrectData.height;var radius=rrectData.radius;var recPoints=[];recPoints.push(x,y+radius);quadraticBezierCurve(x,y+height-radius,x,y+height,x+radius,y+height,recPoints);quadraticBezierCurve(x+width-radius,y+height,x+width,y+height,x+width,y+height-radius,recPoints);quadraticBezierCurve(x+width,y+radius,x+width,y,x+width-radius,y,recPoints);quadraticBezierCurve(x+radius,y,x,y,x,y+radius+0.0000000001,recPoints);// this tiny number deals with the issue that occurs when points overlap and earcut fails to triangulate the item.
// TODO - fix this properly, this is not very elegant.. but it works for now.
if(graphicsData.fill){var color=(0,_utils.hex2rgb)(graphicsData.fillColor);var alpha=graphicsData.fillAlpha;var r=color[0]*alpha;var g=color[1]*alpha;var b=color[2]*alpha;var verts=webGLData.points;var indices=webGLData.indices;var vecPos=verts.length/6;var triangles=(0,_earcut2.default)(recPoints,null,2);for(var i=0,j=triangles.length;i<j;i+=3){indices.push(triangles[i]+vecPos);indices.push(triangles[i]+vecPos);indices.push(triangles[i+1]+vecPos);indices.push(triangles[i+2]+vecPos);indices.push(triangles[i+2]+vecPos);}for(var _i=0,_j=recPoints.length;_i<_j;_i++){verts.push(recPoints[_i],recPoints[++_i],r,g,b,alpha);}}if(graphicsData.lineWidth){var tempPoints=graphicsData.points;graphicsData.points=recPoints;(0,_buildLine2.default)(graphicsData,webGLData);graphicsData.points=tempPoints;}}/**
 * Calculate the points for a quadratic bezier curve. (helper function..)
 * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c
 *
 * Ignored from docs since it is not directly exposed.
 *
 * @ignore
 * @private
 * @param {number} fromX - Origin point x
 * @param {number} fromY - Origin point x
 * @param {number} cpX - Control point x
 * @param {number} cpY - Control point y
 * @param {number} toX - Destination point x
 * @param {number} toY - Destination point y
 * @param {number[]} [out=[]] - The output array to add points into. If not passed, a new array is created.
 * @return {number[]} an array of points
 */function quadraticBezierCurve(fromX,fromY,cpX,cpY,toX,toY){var out=arguments.length<=6||arguments[6]===undefined?[]:arguments[6];var n=20;var points=out;var xa=0;var ya=0;var xb=0;var yb=0;var x=0;var y=0;function getPt(n1,n2,perc){var diff=n2-n1;return n1+diff*perc;}for(var i=0,j=0;i<=n;++i){j=i/n;// The Green Line
xa=getPt(fromX,cpX,j);ya=getPt(fromY,cpY,j);xb=getPt(cpX,toX,j);yb=getPt(cpY,toY,j);// The Black Dot
x=getPt(xa,xb,j);y=getPt(ya,yb,j);points.push(x,y);}return points;}},{"../../../utils":117,"./buildLine":57,"earcut":2}],61:[function(require,module,exports){'use strict';exports.__esModule=true;exports.Filter=exports.SpriteMaskFilter=exports.Quad=exports.RenderTarget=exports.ObjectRenderer=exports.WebGLManager=exports.Shader=exports.CanvasRenderTarget=exports.TextureUvs=exports.VideoBaseTexture=exports.BaseRenderTexture=exports.RenderTexture=exports.BaseTexture=exports.Texture=exports.CanvasGraphicsRenderer=exports.GraphicsRenderer=exports.GraphicsData=exports.Graphics=exports.TextStyle=exports.Text=exports.SpriteRenderer=exports.CanvasTinter=exports.CanvasSpriteRenderer=exports.Sprite=exports.TransformBase=exports.TransformStatic=exports.Transform=exports.Container=exports.DisplayObject=exports.Bounds=exports.glCore=exports.WebGLRenderer=exports.CanvasRenderer=exports.ticker=exports.utils=exports.settings=undefined;var _const=require('./const');Object.keys(_const).forEach(function(key){if(key==="default"||key==="__esModule")return;Object.defineProperty(exports,key,{enumerable:true,get:function get(){return _const[key];}});});var _math=require('./math');Object.keys(_math).forEach(function(key){if(key==="default"||key==="__esModule")return;Object.defineProperty(exports,key,{enumerable:true,get:function get(){return _math[key];}});});var _pixiGlCore=require('pixi-gl-core');Object.defineProperty(exports,'glCore',{enumerable:true,get:function get(){return _interopRequireDefault(_pixiGlCore).default;}});var _Bounds=require('./display/Bounds');Object.defineProperty(exports,'Bounds',{enumerable:true,get:function get(){return _interopRequireDefault(_Bounds).default;}});var _DisplayObject=require('./display/DisplayObject');Object.defineProperty(exports,'DisplayObject',{enumerable:true,get:function get(){return _interopRequireDefault(_DisplayObject).default;}});var _Container=require('./display/Container');Object.defineProperty(exports,'Container',{enumerable:true,get:function get(){return _interopRequireDefault(_Container).default;}});var _Transform=require('./display/Transform');Object.defineProperty(exports,'Transform',{enumerable:true,get:function get(){return _interopRequireDefault(_Transform).default;}});var _TransformStatic=require('./display/TransformStatic');Object.defineProperty(exports,'TransformStatic',{enumerable:true,get:function get(){return _interopRequireDefault(_TransformStatic).default;}});var _TransformBase=require('./display/TransformBase');Object.defineProperty(exports,'TransformBase',{enumerable:true,get:function get(){return _interopRequireDefault(_TransformBase).default;}});var _Sprite=require('./sprites/Sprite');Object.defineProperty(exports,'Sprite',{enumerable:true,get:function get(){return _interopRequireDefault(_Sprite).default;}});var _CanvasSpriteRenderer=require('./sprites/canvas/CanvasSpriteRenderer');Object.defineProperty(exports,'CanvasSpriteRenderer',{enumerable:true,get:function get(){return _interopRequireDefault(_CanvasSpriteRenderer).default;}});var _CanvasTinter=require('./sprites/canvas/CanvasTinter');Object.defineProperty(exports,'CanvasTinter',{enumerable:true,get:function get(){return _interopRequireDefault(_CanvasTinter).default;}});var _SpriteRenderer=require('./sprites/webgl/SpriteRenderer');Object.defineProperty(exports,'SpriteRenderer',{enumerable:true,get:function get(){return _interopRequireDefault(_SpriteRenderer).default;}});var _Text=require('./text/Text');Object.defineProperty(exports,'Text',{enumerable:true,get:function get(){return _interopRequireDefault(_Text).default;}});var _TextStyle=require('./text/TextStyle');Object.defineProperty(exports,'TextStyle',{enumerable:true,get:function get(){return _interopRequireDefault(_TextStyle).default;}});var _Graphics=require('./graphics/Graphics');Object.defineProperty(exports,'Graphics',{enumerable:true,get:function get(){return _interopRequireDefault(_Graphics).default;}});var _GraphicsData=require('./graphics/GraphicsData');Object.defineProperty(exports,'GraphicsData',{enumerable:true,get:function get(){return _interopRequireDefault(_GraphicsData).default;}});var _GraphicsRenderer=require('./graphics/webgl/GraphicsRenderer');Object.defineProperty(exports,'GraphicsRenderer',{enumerable:true,get:function get(){return _interopRequireDefault(_GraphicsRenderer).default;}});var _CanvasGraphicsRenderer=require('./graphics/canvas/CanvasGraphicsRenderer');Object.defineProperty(exports,'CanvasGraphicsRenderer',{enumerable:true,get:function get(){return _interopRequireDefault(_CanvasGraphicsRenderer).default;}});var _Texture=require('./textures/Texture');Object.defineProperty(exports,'Texture',{enumerable:true,get:function get(){return _interopRequireDefault(_Texture).default;}});var _BaseTexture=require('./textures/BaseTexture');Object.defineProperty(exports,'BaseTexture',{enumerable:true,get:function get(){return _interopRequireDefault(_BaseTexture).default;}});var _RenderTexture=require('./textures/RenderTexture');Object.defineProperty(exports,'RenderTexture',{enumerable:true,get:function get(){return _interopRequireDefault(_RenderTexture).default;}});var _BaseRenderTexture=require('./textures/BaseRenderTexture');Object.defineProperty(exports,'BaseRenderTexture',{enumerable:true,get:function get(){return _interopRequireDefault(_BaseRenderTexture).default;}});var _VideoBaseTexture=require('./textures/VideoBaseTexture');Object.defineProperty(exports,'VideoBaseTexture',{enumerable:true,get:function get(){return _interopRequireDefault(_VideoBaseTexture).default;}});var _TextureUvs=require('./textures/TextureUvs');Object.defineProperty(exports,'TextureUvs',{enumerable:true,get:function get(){return _interopRequireDefault(_TextureUvs).default;}});var _CanvasRenderTarget=require('./renderers/canvas/utils/CanvasRenderTarget');Object.defineProperty(exports,'CanvasRenderTarget',{enumerable:true,get:function get(){return _interopRequireDefault(_CanvasRenderTarget).default;}});var _Shader=require('./Shader');Object.defineProperty(exports,'Shader',{enumerable:true,get:function get(){return _interopRequireDefault(_Shader).default;}});var _WebGLManager=require('./renderers/webgl/managers/WebGLManager');Object.defineProperty(exports,'WebGLManager',{enumerable:true,get:function get(){return _interopRequireDefault(_WebGLManager).default;}});var _ObjectRenderer=require('./renderers/webgl/utils/ObjectRenderer');Object.defineProperty(exports,'ObjectRenderer',{enumerable:true,get:function get(){return _interopRequireDefault(_ObjectRenderer).default;}});var _RenderTarget=require('./renderers/webgl/utils/RenderTarget');Object.defineProperty(exports,'RenderTarget',{enumerable:true,get:function get(){return _interopRequireDefault(_RenderTarget).default;}});var _Quad=require('./renderers/webgl/utils/Quad');Object.defineProperty(exports,'Quad',{enumerable:true,get:function get(){return _interopRequireDefault(_Quad).default;}});var _SpriteMaskFilter=require('./renderers/webgl/filters/spriteMask/SpriteMaskFilter');Object.defineProperty(exports,'SpriteMaskFilter',{enumerable:true,get:function get(){return _interopRequireDefault(_SpriteMaskFilter).default;}});var _Filter=require('./renderers/webgl/filters/Filter');Object.defineProperty(exports,'Filter',{enumerable:true,get:function get(){return _interopRequireDefault(_Filter).default;}});exports.autoDetectRenderer=autoDetectRenderer;var _utils=require('./utils');var utils=_interopRequireWildcard(_utils);var _ticker=require('./ticker');var ticker=_interopRequireWildcard(_ticker);var _settings=require('./settings');var _settings2=_interopRequireDefault(_settings);var _CanvasRenderer=require('./renderers/canvas/CanvasRenderer');var _CanvasRenderer2=_interopRequireDefault(_CanvasRenderer);var _WebGLRenderer=require('./renderers/webgl/WebGLRenderer');var _WebGLRenderer2=_interopRequireDefault(_WebGLRenderer);function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj;}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key];}}newObj.default=obj;return newObj;}}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}exports.settings=_settings2.default;exports.utils=utils;exports.ticker=ticker;exports.CanvasRenderer=_CanvasRenderer2.default;exports.WebGLRenderer=_WebGLRenderer2.default;/**
                                                  * @namespace PIXI
                                                  *//**
 * This helper function will automatically detect which renderer you should be using.
 * WebGL is the preferred renderer as it is a lot faster. If webGL is not supported by
 * the browser then this function will return a canvas renderer
 *
 * @memberof PIXI
 * @function autoDetectRenderer
 * @param {number} [width=800] - the width of the renderers view
 * @param {number} [height=600] - the height of the renderers view
 * @param {object} [options] - The optional renderer parameters
 * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional
 * @param {boolean} [options.transparent=false] - If the render view is transparent, default false
 * @param {boolean} [options.antialias=false] - sets antialias (only applicable in chrome at the moment)
 * @param {boolean} [options.preserveDrawingBuffer=false] - enables drawing buffer preservation, enable this if you
 *      need to call toDataUrl on the webgl context
 * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer, retina would be 2
 * @param {boolean} [noWebGL=false] - prevents selection of WebGL renderer, even if such is present
 * @return {PIXI.WebGLRenderer|PIXI.CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer
 */function autoDetectRenderer(){var width=arguments.length<=0||arguments[0]===undefined?800:arguments[0];var height=arguments.length<=1||arguments[1]===undefined?600:arguments[1];var options=arguments[2];var noWebGL=arguments[3];if(!noWebGL&&utils.isWebGLSupported()){return new _WebGLRenderer2.default(width,height,options);}return new _CanvasRenderer2.default(width,height,options);}},{"./Shader":41,"./const":42,"./display/Bounds":43,"./display/Container":44,"./display/DisplayObject":45,"./display/Transform":46,"./display/TransformBase":47,"./display/TransformStatic":48,"./graphics/Graphics":49,"./graphics/GraphicsData":50,"./graphics/canvas/CanvasGraphicsRenderer":51,"./graphics/webgl/GraphicsRenderer":53,"./math":66,"./renderers/canvas/CanvasRenderer":73,"./renderers/canvas/utils/CanvasRenderTarget":75,"./renderers/webgl/WebGLRenderer":80,"./renderers/webgl/filters/Filter":82,"./renderers/webgl/filters/spriteMask/SpriteMaskFilter":85,"./renderers/webgl/managers/WebGLManager":89,"./renderers/webgl/utils/ObjectRenderer":90,"./renderers/webgl/utils/Quad":91,"./renderers/webgl/utils/RenderTarget":92,"./settings":97,"./sprites/Sprite":98,"./sprites/canvas/CanvasSpriteRenderer":99,"./sprites/canvas/CanvasTinter":100,"./sprites/webgl/SpriteRenderer":102,"./text/Text":104,"./text/TextStyle":105,"./textures/BaseRenderTexture":106,"./textures/BaseTexture":107,"./textures/RenderTexture":108,"./textures/Texture":109,"./textures/TextureUvs":110,"./textures/VideoBaseTexture":111,"./ticker":113,"./utils":117,"pixi-gl-core":12}],62:[function(require,module,exports){'use strict';exports.__esModule=true;var _Matrix=require('./Matrix');var _Matrix2=_interopRequireDefault(_Matrix);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}var ux=[1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1,0,1];// Your friendly neighbour https://en.wikipedia.org/wiki/Dihedral_group of order 16
var uy=[0,1,1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1];var vx=[0,-1,-1,-1,0,1,1,1,0,1,1,1,0,-1,-1,-1];var vy=[1,1,0,-1,-1,-1,0,1,-1,-1,0,1,1,1,0,-1];var tempMatrices=[];var mul=[];function signum(x){if(x<0){return-1;}if(x>0){return 1;}return 0;}function init(){for(var i=0;i<16;i++){var row=[];mul.push(row);for(var j=0;j<16;j++){var _ux=signum(ux[i]*ux[j]+vx[i]*uy[j]);var _uy=signum(uy[i]*ux[j]+vy[i]*uy[j]);var _vx=signum(ux[i]*vx[j]+vx[i]*vy[j]);var _vy=signum(uy[i]*vx[j]+vy[i]*vy[j]);for(var k=0;k<16;k++){if(ux[k]===_ux&&uy[k]===_uy&&vx[k]===_vx&&vy[k]===_vy){row.push(k);break;}}}}for(var _i=0;_i<16;_i++){var mat=new _Matrix2.default();mat.set(ux[_i],uy[_i],vx[_i],vy[_i],0,0);tempMatrices.push(mat);}}init();/**
 * Implements Dihedral Group D_8, see [group D4]{@link http://mathworld.wolfram.com/DihedralGroupD4.html},
 * D8 is the same but with diagonals. Used for texture rotations.
 *
 * Vector xX(i), xY(i) is U-axis of sprite with rotation i
 * Vector yY(i), yY(i) is V-axis of sprite with rotation i
 * Rotations: 0 grad (0), 90 grad (2), 180 grad (4), 270 grad (6)
 * Mirrors: vertical (8), main diagonal (10), horizontal (12), reverse diagonal (14)
 * This is the small part of gameofbombs.com portal system. It works.
 *
 * @author Ivan @ivanpopelyshev
 *
 * @namespace PIXI.GroupD8
 */var GroupD8={E:0,SE:1,S:2,SW:3,W:4,NW:5,N:6,NE:7,MIRROR_VERTICAL:8,MIRROR_HORIZONTAL:12,uX:function uX(ind){return ux[ind];},uY:function uY(ind){return uy[ind];},vX:function vX(ind){return vx[ind];},vY:function vY(ind){return vy[ind];},inv:function inv(rotation){if(rotation&8){return rotation&15;}return-rotation&7;},add:function add(rotationSecond,rotationFirst){return mul[rotationSecond][rotationFirst];},sub:function sub(rotationSecond,rotationFirst){return mul[rotationSecond][GroupD8.inv(rotationFirst)];},/**
     * Adds 180 degrees to rotation. Commutative operation.
     *
     * @method
     * @param {number} rotation - The number to rotate.
     * @returns {number} rotated number
     */rotate180:function rotate180(rotation){return rotation^4;},/**
     * I dont know why sometimes width and heights needs to be swapped. We'll fix it later.
     *
     * @param {number} rotation - The number to check.
     * @returns {boolean} Whether or not the width/height should be swapped.
     */isSwapWidthHeight:function isSwapWidthHeight(rotation){return(rotation&3)===2;},/**
     * @param {number} dx - TODO
     * @param {number} dy - TODO
     *
     * @return {number} TODO
     */byDirection:function byDirection(dx,dy){if(Math.abs(dx)*2<=Math.abs(dy)){if(dy>=0){return GroupD8.S;}return GroupD8.N;}else if(Math.abs(dy)*2<=Math.abs(dx)){if(dx>0){return GroupD8.E;}return GroupD8.W;}else if(dy>0){if(dx>0){return GroupD8.SE;}return GroupD8.SW;}else if(dx>0){return GroupD8.NE;}return GroupD8.NW;},/**
     * Helps sprite to compensate texture packer rotation.
     *
     * @param {PIXI.Matrix} matrix - sprite world matrix
     * @param {number} rotation - The rotation factor to use.
     * @param {number} tx - sprite anchoring
     * @param {number} ty - sprite anchoring
     */matrixAppendRotationInv:function matrixAppendRotationInv(matrix,rotation){var tx=arguments.length<=2||arguments[2]===undefined?0:arguments[2];var ty=arguments.length<=3||arguments[3]===undefined?0:arguments[3];// Packer used "rotation", we use "inv(rotation)"
var mat=tempMatrices[GroupD8.inv(rotation)];mat.tx=tx;mat.ty=ty;matrix.append(mat);}};exports.default=GroupD8;},{"./Matrix":63}],63:[function(require,module,exports){'use strict';exports.__esModule=true;var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor);}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor;};}();var _Point=require('./Point');var _Point2=_interopRequireDefault(_Point);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}/**
 * The pixi Matrix class as an object, which makes it a lot faster,
 * here is a representation of it :
 * | a | b | tx|
 * | c | d | ty|
 * | 0 | 0 | 1 |
 *
 * @class
 * @memberof PIXI
 */var Matrix=function(){/**
     *
     */function Matrix(){_classCallCheck(this,Matrix);/**
         * @member {number}
         * @default 1
         */this.a=1;/**
         * @member {number}
         * @default 0
         */this.b=0;/**
         * @member {number}
         * @default 0
         */this.c=0;/**
         * @member {number}
         * @default 1
         */this.d=1;/**
         * @member {number}
         * @default 0
         */this.tx=0;/**
         * @member {number}
         * @default 0
         */this.ty=0;this.array=null;}/**
     * Creates a Matrix object based on the given array. The Element to Matrix mapping order is as follows:
     *
     * a = array[0]
     * b = array[1]
     * c = array[3]
     * d = array[4]
     * tx = array[2]
     * ty = array[5]
     *
     * @param {number[]} array - The array that the matrix will be populated from.
     */Matrix.prototype.fromArray=function fromArray(array){this.a=array[0];this.b=array[1];this.c=array[3];this.d=array[4];this.tx=array[2];this.ty=array[5];};/**
     * sets the matrix properties
     *
     * @param {number} a - Matrix component
     * @param {number} b - Matrix component
     * @param {number} c - Matrix component
     * @param {number} d - Matrix component
     * @param {number} tx - Matrix component
     * @param {number} ty - Matrix component
     *
     * @return {PIXI.Matrix} This matrix. Good for chaining method calls.
     */Matrix.prototype.set=function set(a,b,c,d,tx,ty){this.a=a;this.b=b;this.c=c;this.d=d;this.tx=tx;this.ty=ty;return this;};/**
     * Creates an array from the current Matrix object.
     *
     * @param {boolean} transpose - Whether we need to transpose the matrix or not
     * @param {Float32Array} [out=new Float32Array(9)] - If provided the array will be assigned to out
     * @return {number[]} the newly created array which contains the matrix
     */Matrix.prototype.toArray=function toArray(transpose,out){if(!this.array){this.array=new Float32Array(9);}var array=out||this.array;if(transpose){array[0]=this.a;array[1]=this.b;array[2]=0;array[3]=this.c;array[4]=this.d;array[5]=0;array[6]=this.tx;array[7]=this.ty;array[8]=1;}else{array[0]=this.a;array[1]=this.c;array[2]=this.tx;array[3]=this.b;array[4]=this.d;array[5]=this.ty;array[6]=0;array[7]=0;array[8]=1;}return array;};/**
     * Get a new position with the current transformation applied.
     * Can be used to go from a child's coordinate space to the world coordinate space. (e.g. rendering)
     *
     * @param {PIXI.Point} pos - The origin
     * @param {PIXI.Point} [newPos] - The point that the new position is assigned to (allowed to be same as input)
     * @return {PIXI.Point} The new point, transformed through this matrix
     */Matrix.prototype.apply=function apply(pos,newPos){newPos=newPos||new _Point2.default();var x=pos.x;var y=pos.y;newPos.x=this.a*x+this.c*y+this.tx;newPos.y=this.b*x+this.d*y+this.ty;return newPos;};/**
     * Get a new position with the inverse of the current transformation applied.
     * Can be used to go from the world coordinate space to a child's coordinate space. (e.g. input)
     *
     * @param {PIXI.Point} pos - The origin
     * @param {PIXI.Point} [newPos] - The point that the new position is assigned to (allowed to be same as input)
     * @return {PIXI.Point} The new point, inverse-transformed through this matrix
     */Matrix.prototype.applyInverse=function applyInverse(pos,newPos){newPos=newPos||new _Point2.default();var id=1/(this.a*this.d+this.c*-this.b);var x=pos.x;var y=pos.y;newPos.x=this.d*id*x+-this.c*id*y+(this.ty*this.c-this.tx*this.d)*id;newPos.y=this.a*id*y+-this.b*id*x+(-this.ty*this.a+this.tx*this.b)*id;return newPos;};/**
     * Translates the matrix on the x and y.
     *
     * @param {number} x How much to translate x by
     * @param {number} y How much to translate y by
     * @return {PIXI.Matrix} This matrix. Good for chaining method calls.
     */Matrix.prototype.translate=function translate(x,y){this.tx+=x;this.ty+=y;return this;};/**
     * Applies a scale transformation to the matrix.
     *
     * @param {number} x The amount to scale horizontally
     * @param {number} y The amount to scale vertically
     * @return {PIXI.Matrix} This matrix. Good for chaining method calls.
     */Matrix.prototype.scale=function scale(x,y){this.a*=x;this.d*=y;this.c*=x;this.b*=y;this.tx*=x;this.ty*=y;return this;};/**
     * Applies a rotation transformation to the matrix.
     *
     * @param {number} angle - The angle in radians.
     * @return {PIXI.Matrix} This matrix. Good for chaining method calls.
     */Matrix.prototype.rotate=function rotate(angle){var cos=Math.cos(angle);var sin=Math.sin(angle);var a1=this.a;var c1=this.c;var tx1=this.tx;this.a=a1*cos-this.b*sin;this.b=a1*sin+this.b*cos;this.c=c1*cos-this.d*sin;this.d=c1*sin+this.d*cos;this.tx=tx1*cos-this.ty*sin;this.ty=tx1*sin+this.ty*cos;return this;};/**
     * Appends the given Matrix to this Matrix.
     *
     * @param {PIXI.Matrix} matrix - The matrix to append.
     * @return {PIXI.Matrix} This matrix. Good for chaining method calls.
     */Matrix.prototype.append=function append(matrix){var a1=this.a;var b1=this.b;var c1=this.c;var d1=this.d;this.a=matrix.a*a1+matrix.b*c1;this.b=matrix.a*b1+matrix.b*d1;this.c=matrix.c*a1+matrix.d*c1;this.d=matrix.c*b1+matrix.d*d1;this.tx=matrix.tx*a1+matrix.ty*c1+this.tx;this.ty=matrix.tx*b1+matrix.ty*d1+this.ty;return this;};/**
     * Sets the matrix based on all the available properties
     *
     * @param {number} x - Position on the x axis
     * @param {number} y - Position on the y axis
     * @param {number} pivotX - Pivot on the x axis
     * @param {number} pivotY - Pivot on the y axis
     * @param {number} scaleX - Scale on the x axis
     * @param {number} scaleY - Scale on the y axis
     * @param {number} rotation - Rotation in radians
     * @param {number} skewX - Skew on the x axis
     * @param {number} skewY - Skew on the y axis
     * @return {PIXI.Matrix} This matrix. Good for chaining method calls.
     */Matrix.prototype.setTransform=function setTransform(x,y,pivotX,pivotY,scaleX,scaleY,rotation,skewX,skewY){var sr=Math.sin(rotation);var cr=Math.cos(rotation);var cy=Math.cos(skewY);var sy=Math.sin(skewY);var nsx=-Math.sin(skewX);var cx=Math.cos(skewX);var a=cr*scaleX;var b=sr*scaleX;var c=-sr*scaleY;var d=cr*scaleY;this.a=cy*a+sy*c;this.b=cy*b+sy*d;this.c=nsx*a+cx*c;this.d=nsx*b+cx*d;this.tx=x+(pivotX*a+pivotY*c);this.ty=y+(pivotX*b+pivotY*d);return this;};/**
     * Prepends the given Matrix to this Matrix.
     *
     * @param {PIXI.Matrix} matrix - The matrix to prepend
     * @return {PIXI.Matrix} This matrix. Good for chaining method calls.
     */Matrix.prototype.prepend=function prepend(matrix){var tx1=this.tx;if(matrix.a!==1||matrix.b!==0||matrix.c!==0||matrix.d!==1){var a1=this.a;var c1=this.c;this.a=a1*matrix.a+this.b*matrix.c;this.b=a1*matrix.b+this.b*matrix.d;this.c=c1*matrix.a+this.d*matrix.c;this.d=c1*matrix.b+this.d*matrix.d;}this.tx=tx1*matrix.a+this.ty*matrix.c+matrix.tx;this.ty=tx1*matrix.b+this.ty*matrix.d+matrix.ty;return this;};/**
     * Decomposes the matrix (x, y, scaleX, scaleY, and rotation) and sets the properties on to a transform.
     *
     * @param {PIXI.Transform|PIXI.TransformStatic} transform - The transform to apply the properties to.
     * @return {PIXI.Transform|PIXI.TransformStatic} The transform with the newly applied properties
     */Matrix.prototype.decompose=function decompose(transform){// sort out rotation / skew..
var a=this.a;var b=this.b;var c=this.c;var d=this.d;var skewX=-Math.atan2(-c,d);var skewY=Math.atan2(b,a);var delta=Math.abs(skewX+skewY);if(delta<0.00001){transform.rotation=skewY;if(a<0&&d>=0){transform.rotation+=transform.rotation<=0?Math.PI:-Math.PI;}transform.skew.x=transform.skew.y=0;}else{transform.skew.x=skewX;transform.skew.y=skewY;}// next set scale
transform.scale.x=Math.sqrt(a*a+b*b);transform.scale.y=Math.sqrt(c*c+d*d);// next set position
transform.position.x=this.tx;transform.position.y=this.ty;return transform;};/**
     * Inverts this matrix
     *
     * @return {PIXI.Matrix} This matrix. Good for chaining method calls.
     */Matrix.prototype.invert=function invert(){var a1=this.a;var b1=this.b;var c1=this.c;var d1=this.d;var tx1=this.tx;var n=a1*d1-b1*c1;this.a=d1/n;this.b=-b1/n;this.c=-c1/n;this.d=a1/n;this.tx=(c1*this.ty-d1*tx1)/n;this.ty=-(a1*this.ty-b1*tx1)/n;return this;};/**
     * Resets this Matix to an identity (default) matrix.
     *
     * @return {PIXI.Matrix} This matrix. Good for chaining method calls.
     */Matrix.prototype.identity=function identity(){this.a=1;this.b=0;this.c=0;this.d=1;this.tx=0;this.ty=0;return this;};/**
     * Creates a new Matrix object with the same values as this one.
     *
     * @return {PIXI.Matrix} A copy of this matrix. Good for chaining method calls.
     */Matrix.prototype.clone=function clone(){var matrix=new Matrix();matrix.a=this.a;matrix.b=this.b;matrix.c=this.c;matrix.d=this.d;matrix.tx=this.tx;matrix.ty=this.ty;return matrix;};/**
     * Changes the values of the given matrix to be the same as the ones in this matrix
     *
     * @param {PIXI.Matrix} matrix - The matrix to copy from.
     * @return {PIXI.Matrix} The matrix given in parameter with its values updated.
     */Matrix.prototype.copy=function copy(matrix){matrix.a=this.a;matrix.b=this.b;matrix.c=this.c;matrix.d=this.d;matrix.tx=this.tx;matrix.ty=this.ty;return matrix;};/**
     * A default (identity) matrix
     *
     * @static
     * @const
     */_createClass(Matrix,null,[{key:'IDENTITY',get:function get(){return new Matrix();}/**
         * A temp matrix
         *
         * @static
         * @const
         */},{key:'TEMP_MATRIX',get:function get(){return new Matrix();}}]);return Matrix;}();exports.default=Matrix;},{"./Point":65}],64:[function(require,module,exports){"use strict";exports.__esModule=true;var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor);}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor;};}();function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}/**
 * The Point object represents a location in a two-dimensional coordinate system, where x represents
 * the horizontal axis and y represents the vertical axis.
 * An observable point is a point that triggers a callback when the point's position is changed.
 *
 * @class
 * @memberof PIXI
 */var ObservablePoint=function(){/**
     * @param {Function} cb - callback when changed
     * @param {object} scope - owner of callback
     * @param {number} [x=0] - position of the point on the x axis
     * @param {number} [y=0] - position of the point on the y axis
     */function ObservablePoint(cb,scope){var x=arguments.length<=2||arguments[2]===undefined?0:arguments[2];var y=arguments.length<=3||arguments[3]===undefined?0:arguments[3];_classCallCheck(this,ObservablePoint);this._x=x;this._y=y;this.cb=cb;this.scope=scope;}/**
     * Sets the point to a new x and y position.
     * If y is omitted, both x and y will be set to x.
     *
     * @param {number} [x=0] - position of the point on the x axis
     * @param {number} [y=0] - position of the point on the y axis
     */ObservablePoint.prototype.set=function set(x,y){var _x=x||0;var _y=y||(y!==0?_x:0);if(this._x!==_x||this._y!==_y){this._x=_x;this._y=_y;this.cb.call(this.scope);}};/**
     * Copies the data from another point
     *
     * @param {PIXI.Point|PIXI.ObservablePoint} point - point to copy from
     */ObservablePoint.prototype.copy=function copy(point){if(this._x!==point.x||this._y!==point.y){this._x=point.x;this._y=point.y;this.cb.call(this.scope);}};/**
     * The position of the displayObject on the x axis relative to the local coordinates of the parent.
     *
     * @member {number}
     * @memberof PIXI.ObservablePoint#
     */_createClass(ObservablePoint,[{key:"x",get:function get(){return this._x;}/**
         * Sets the X component.
         *
         * @param {number} value - The value to set to.
         */,set:function set(value){if(this._x!==value){this._x=value;this.cb.call(this.scope);}}/**
         * The position of the displayObject on the x axis relative to the local coordinates of the parent.
         *
         * @member {number}
         * @memberof PIXI.ObservablePoint#
         */},{key:"y",get:function get(){return this._y;}/**
         * Sets the Y component.
         *
         * @param {number} value - The value to set to.
         */,set:function set(value){if(this._y!==value){this._y=value;this.cb.call(this.scope);}}}]);return ObservablePoint;}();exports.default=ObservablePoint;},{}],65:[function(require,module,exports){"use strict";exports.__esModule=true;function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}/**
 * The Point object represents a location in a two-dimensional coordinate system, where x represents
 * the horizontal axis and y represents the vertical axis.
 *
 * @class
 * @memberof PIXI
 */var Point=function(){/**
   * @param {number} [x=0] - position of the point on the x axis
   * @param {number} [y=0] - position of the point on the y axis
   */function Point(){var x=arguments.length<=0||arguments[0]===undefined?0:arguments[0];var y=arguments.length<=1||arguments[1]===undefined?0:arguments[1];_classCallCheck(this,Point);/**
     * @member {number}
     * @default 0
     */this.x=x;/**
     * @member {number}
     * @default 0
     */this.y=y;}/**
   * Creates a clone of this point
   *
   * @return {PIXI.Point} a copy of the point
   */Point.prototype.clone=function clone(){return new Point(this.x,this.y);};/**
   * Copies x and y from the given point
   *
   * @param {PIXI.Point} p - The point to copy.
   */Point.prototype.copy=function copy(p){this.set(p.x,p.y);};/**
   * Returns true if the given point is equal to this point
   *
   * @param {PIXI.Point} p - The point to check
   * @returns {boolean} Whether the given point equal to this point
   */Point.prototype.equals=function equals(p){return p.x===this.x&&p.y===this.y;};/**
   * Sets the point to a new x and y position.
   * If y is omitted, both x and y will be set to x.
   *
   * @param {number} [x=0] - position of the point on the x axis
   * @param {number} [y=0] - position of the point on the y axis
   */Point.prototype.set=function set(x,y){this.x=x||0;this.y=y||(y!==0?this.x:0);};return Point;}();exports.default=Point;},{}],66:[function(require,module,exports){'use strict';exports.__esModule=true;var _Point=require('./Point');Object.defineProperty(exports,'Point',{enumerable:true,get:function get(){return _interopRequireDefault(_Point).default;}});var _ObservablePoint=require('./ObservablePoint');Object.defineProperty(exports,'ObservablePoint',{enumerable:true,get:function get(){return _interopRequireDefault(_ObservablePoint).default;}});var _Matrix=require('./Matrix');Object.defineProperty(exports,'Matrix',{enumerable:true,get:function get(){return _interopRequireDefault(_Matrix).default;}});var _GroupD=require('./GroupD8');Object.defineProperty(exports,'GroupD8',{enumerable:true,get:function get(){return _interopRequireDefault(_GroupD).default;}});var _Circle=require('./shapes/Circle');Object.defineProperty(exports,'Circle',{enumerable:true,get:function get(){return _interopRequireDefault(_Circle).default;}});var _Ellipse=require('./shapes/Ellipse');Object.defineProperty(exports,'Ellipse',{enumerable:true,get:function get(){return _interopRequireDefault(_Ellipse).default;}});var _Polygon=require('./shapes/Polygon');Object.defineProperty(exports,'Polygon',{enumerable:true,get:function get(){return _interopRequireDefault(_Polygon).default;}});var _Rectangle=require('./shapes/Rectangle');Object.defineProperty(exports,'Rectangle',{enumerable:true,get:function get(){return _interopRequireDefault(_Rectangle).default;}});var _RoundedRectangle=require('./shapes/RoundedRectangle');Object.defineProperty(exports,'RoundedRectangle',{enumerable:true,get:function get(){return _interopRequireDefault(_RoundedRectangle).default;}});function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}},{"./GroupD8":62,"./Matrix":63,"./ObservablePoint":64,"./Point":65,"./shapes/Circle":67,"./shapes/Ellipse":68,"./shapes/Polygon":69,"./shapes/Rectangle":70,"./shapes/RoundedRectangle":71}],67:[function(require,module,exports){'use strict';exports.__esModule=true;var _Rectangle=require('./Rectangle');var _Rectangle2=_interopRequireDefault(_Rectangle);var _const=require('../../const');function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}/**
 * The Circle object can be used to specify a hit area for displayObjects
 *
 * @class
 * @memberof PIXI
 */var Circle=function(){/**
   * @param {number} [x=0] - The X coordinate of the center of this circle
   * @param {number} [y=0] - The Y coordinate of the center of this circle
   * @param {number} [radius=0] - The radius of the circle
   */function Circle(){var x=arguments.length<=0||arguments[0]===undefined?0:arguments[0];var y=arguments.length<=1||arguments[1]===undefined?0:arguments[1];var radius=arguments.length<=2||arguments[2]===undefined?0:arguments[2];_classCallCheck(this,Circle);/**
     * @member {number}
     * @default 0
     */this.x=x;/**
     * @member {number}
     * @default 0
     */this.y=y;/**
     * @member {number}
     * @default 0
     */this.radius=radius;/**
     * The type of the object, mainly used to avoid `instanceof` checks
     *
     * @member {number}
     * @readOnly
     * @default PIXI.SHAPES.CIRC
     * @see PIXI.SHAPES
     */this.type=_const.SHAPES.CIRC;}/**
   * Creates a clone of this Circle instance
   *
   * @return {PIXI.Circle} a copy of the Circle
   */Circle.prototype.clone=function clone(){return new Circle(this.x,this.y,this.radius);};/**
   * Checks whether the x and y coordinates given are contained within this circle
   *
   * @param {number} x - The X coordinate of the point to test
   * @param {number} y - The Y coordinate of the point to test
   * @return {boolean} Whether the x/y coordinates are within this Circle
   */Circle.prototype.contains=function contains(x,y){if(this.radius<=0){return false;}var r2=this.radius*this.radius;var dx=this.x-x;var dy=this.y-y;dx*=dx;dy*=dy;return dx+dy<=r2;};/**
  * Returns the framing rectangle of the circle as a Rectangle object
  *
  * @return {PIXI.Rectangle} the framing rectangle
  */Circle.prototype.getBounds=function getBounds(){return new _Rectangle2.default(this.x-this.radius,this.y-this.radius,this.radius*2,this.radius*2);};return Circle;}();exports.default=Circle;},{"../../const":42,"./Rectangle":70}],68:[function(require,module,exports){'use strict';exports.__esModule=true;var _Rectangle=require('./Rectangle');var _Rectangle2=_interopRequireDefault(_Rectangle);var _const=require('../../const');function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}/**
 * The Ellipse object can be used to specify a hit area for displayObjects
 *
 * @class
 * @memberof PIXI
 */var Ellipse=function(){/**
   * @param {number} [x=0] - The X coordinate of the center of this circle
   * @param {number} [y=0] - The Y coordinate of the center of this circle
   * @param {number} [width=0] - The half width of this ellipse
   * @param {number} [height=0] - The half height of this ellipse
   */function Ellipse(){var x=arguments.length<=0||arguments[0]===undefined?0:arguments[0];var y=arguments.length<=1||arguments[1]===undefined?0:arguments[1];var width=arguments.length<=2||arguments[2]===undefined?0:arguments[2];var height=arguments.length<=3||arguments[3]===undefined?0:arguments[3];_classCallCheck(this,Ellipse);/**
     * @member {number}
     * @default 0
     */this.x=x;/**
     * @member {number}
     * @default 0
     */this.y=y;/**
     * @member {number}
     * @default 0
     */this.width=width;/**
     * @member {number}
     * @default 0
     */this.height=height;/**
     * The type of the object, mainly used to avoid `instanceof` checks
     *
     * @member {number}
     * @readOnly
     * @default PIXI.SHAPES.ELIP
     * @see PIXI.SHAPES
     */this.type=_const.SHAPES.ELIP;}/**
   * Creates a clone of this Ellipse instance
   *
   * @return {PIXI.Ellipse} a copy of the ellipse
   */Ellipse.prototype.clone=function clone(){return new Ellipse(this.x,this.y,this.width,this.height);};/**
   * Checks whether the x and y coordinates given are contained within this ellipse
   *
   * @param {number} x - The X coordinate of the point to test
   * @param {number} y - The Y coordinate of the point to test
   * @return {boolean} Whether the x/y coords are within this ellipse
   */Ellipse.prototype.contains=function contains(x,y){if(this.width<=0||this.height<=0){return false;}// normalize the coords to an ellipse with center 0,0
var normx=(x-this.x)/this.width;var normy=(y-this.y)/this.height;normx*=normx;normy*=normy;return normx+normy<=1;};/**
   * Returns the framing rectangle of the ellipse as a Rectangle object
   *
   * @return {PIXI.Rectangle} the framing rectangle
   */Ellipse.prototype.getBounds=function getBounds(){return new _Rectangle2.default(this.x-this.width,this.y-this.height,this.width,this.height);};return Ellipse;}();exports.default=Ellipse;},{"../../const":42,"./Rectangle":70}],69:[function(require,module,exports){'use strict';exports.__esModule=true;var _Point=require('../Point');var _Point2=_interopRequireDefault(_Point);var _const=require('../../const');function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}/**
 * @class
 * @memberof PIXI
 */var Polygon=function(){/**
     * @param {PIXI.Point[]|number[]} points - This can be an array of Points
     *  that form the polygon, a flat array of numbers that will be interpreted as [x,y, x,y, ...], or
     *  the arguments passed can be all the points of the polygon e.g.
     *  `new PIXI.Polygon(new PIXI.Point(), new PIXI.Point(), ...)`, or the arguments passed can be flat
     *  x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are Numbers.
     */function Polygon(){for(var _len=arguments.length,points=Array(_len),_key=0;_key<_len;_key++){points[_key]=arguments[_key];}_classCallCheck(this,Polygon);if(Array.isArray(points[0])){points=points[0];}// if this is an array of points, convert it to a flat array of numbers
if(points[0]instanceof _Point2.default){var p=[];for(var i=0,il=points.length;i<il;i++){p.push(points[i].x,points[i].y);}points=p;}this.closed=true;/**
         * An array of the points of this polygon
         *
         * @member {number[]}
         */this.points=points;/**
         * The type of the object, mainly used to avoid `instanceof` checks
         *
         * @member {number}
         * @readOnly
         * @default PIXI.SHAPES.POLY
         * @see PIXI.SHAPES
         */this.type=_const.SHAPES.POLY;}/**
     * Creates a clone of this polygon
     *
     * @return {PIXI.Polygon} a copy of the polygon
     */Polygon.prototype.clone=function clone(){return new Polygon(this.points.slice());};/**
     * Closes the polygon, adding points if necessary.
     *
     */Polygon.prototype.close=function close(){var points=this.points;// close the poly if the value is true!
if(points[0]!==points[points.length-2]||points[1]!==points[points.length-1]){points.push(points[0],points[1]);}};/**
     * Checks whether the x and y coordinates passed to this function are contained within this polygon
     *
     * @param {number} x - The X coordinate of the point to test
     * @param {number} y - The Y coordinate of the point to test
     * @return {boolean} Whether the x/y coordinates are within this polygon
     */Polygon.prototype.contains=function contains(x,y){var inside=false;// use some raycasting to test hits
// https://github.com/substack/point-in-polygon/blob/master/index.js
var length=this.points.length/2;for(var i=0,j=length-1;i<length;j=i++){var xi=this.points[i*2];var yi=this.points[i*2+1];var xj=this.points[j*2];var yj=this.points[j*2+1];var intersect=yi>y!==yj>y&&x<(xj-xi)*((y-yi)/(yj-yi))+xi;if(intersect){inside=!inside;}}return inside;};return Polygon;}();exports.default=Polygon;},{"../../const":42,"../Point":65}],70:[function(require,module,exports){'use strict';exports.__esModule=true;var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor);}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor;};}();var _const=require('../../const');function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}/**
 * Rectangle object is an area defined by its position, as indicated by its top-left corner
 * point (x, y) and by its width and its height.
 *
 * @class
 * @memberof PIXI
 */var Rectangle=function(){/**
     * @param {number} [x=0] - The X coordinate of the upper-left corner of the rectangle
     * @param {number} [y=0] - The Y coordinate of the upper-left corner of the rectangle
     * @param {number} [width=0] - The overall width of this rectangle
     * @param {number} [height=0] - The overall height of this rectangle
     */function Rectangle(){var x=arguments.length<=0||arguments[0]===undefined?0:arguments[0];var y=arguments.length<=1||arguments[1]===undefined?0:arguments[1];var width=arguments.length<=2||arguments[2]===undefined?0:arguments[2];var height=arguments.length<=3||arguments[3]===undefined?0:arguments[3];_classCallCheck(this,Rectangle);/**
         * @member {number}
         * @default 0
         */this.x=x;/**
         * @member {number}
         * @default 0
         */this.y=y;/**
         * @member {number}
         * @default 0
         */this.width=width;/**
         * @member {number}
         * @default 0
         */this.height=height;/**
         * The type of the object, mainly used to avoid `instanceof` checks
         *
         * @member {number}
         * @readOnly
         * @default PIXI.SHAPES.RECT
         * @see PIXI.SHAPES
         */this.type=_const.SHAPES.RECT;}/**
     * returns the left edge of the rectangle
     *
     * @member {number}
     * @memberof PIXI.Rectangle#
     *//**
     * Creates a clone of this Rectangle
     *
     * @return {PIXI.Rectangle} a copy of the rectangle
     */Rectangle.prototype.clone=function clone(){return new Rectangle(this.x,this.y,this.width,this.height);};/**
     * Copies another rectangle to this one.
     *
     * @param {PIXI.Rectangle} rectangle - The rectangle to copy.
     * @return {PIXI.Rectangle} Returns itself.
     */Rectangle.prototype.copy=function copy(rectangle){this.x=rectangle.x;this.y=rectangle.y;this.width=rectangle.width;this.height=rectangle.height;return this;};/**
     * Checks whether the x and y coordinates given are contained within this Rectangle
     *
     * @param {number} x - The X coordinate of the point to test
     * @param {number} y - The Y coordinate of the point to test
     * @return {boolean} Whether the x/y coordinates are within this Rectangle
     */Rectangle.prototype.contains=function contains(x,y){if(this.width<=0||this.height<=0){return false;}if(x>=this.x&&x<this.x+this.width){if(y>=this.y&&y<this.y+this.height){return true;}}return false;};/**
     * Pads the rectangle making it grow in all directions.
     *
     * @param {number} paddingX - The horizontal padding amount.
     * @param {number} paddingY - The vertical padding amount.
     */Rectangle.prototype.pad=function pad(paddingX,paddingY){paddingX=paddingX||0;paddingY=paddingY||(paddingY!==0?paddingX:0);this.x-=paddingX;this.y-=paddingY;this.width+=paddingX*2;this.height+=paddingY*2;};/**
     * Fits this rectangle around the passed one.
     *
     * @param {PIXI.Rectangle} rectangle - The rectangle to fit.
     */Rectangle.prototype.fit=function fit(rectangle){if(this.x<rectangle.x){this.width+=this.x;if(this.width<0){this.width=0;}this.x=rectangle.x;}if(this.y<rectangle.y){this.height+=this.y;if(this.height<0){this.height=0;}this.y=rectangle.y;}if(this.x+this.width>rectangle.x+rectangle.width){this.width=rectangle.width-this.x;if(this.width<0){this.width=0;}}if(this.y+this.height>rectangle.y+rectangle.height){this.height=rectangle.height-this.y;if(this.height<0){this.height=0;}}};/**
     * Enlarges this rectangle to include the passed rectangle.
     *
     * @param {PIXI.Rectangle} rect - The rectangle to include.
     */Rectangle.prototype.enlarge=function enlarge(rect){if(rect===Rectangle.EMPTY){return;}var x1=Math.min(this.x,rect.x);var x2=Math.max(this.x+this.width,rect.x+rect.width);var y1=Math.min(this.y,rect.y);var y2=Math.max(this.y+this.height,rect.y+rect.height);this.x=x1;this.width=x2-x1;this.y=y1;this.height=y2-y1;};_createClass(Rectangle,[{key:'left',get:function get(){return this.x;}/**
         * returns the right edge of the rectangle
         *
         * @member {number}
         * @memberof PIXI.Rectangle
         */},{key:'right',get:function get(){return this.x+this.width;}/**
         * returns the top edge of the rectangle
         *
         * @member {number}
         * @memberof PIXI.Rectangle
         */},{key:'top',get:function get(){return this.y;}/**
         * returns the bottom edge of the rectangle
         *
         * @member {number}
         * @memberof PIXI.Rectangle
         */},{key:'bottom',get:function get(){return this.y+this.height;}/**
         * A constant empty rectangle.
         *
         * @static
         * @constant
         */}],[{key:'EMPTY',get:function get(){return new Rectangle(0,0,0,0);}}]);return Rectangle;}();exports.default=Rectangle;},{"../../const":42}],71:[function(require,module,exports){'use strict';exports.__esModule=true;var _const=require('../../const');function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}/**
 * The Rounded Rectangle object is an area that has nice rounded corners, as indicated by its
 * top-left corner point (x, y) and by its width and its height and its radius.
 *
 * @class
 * @memberof PIXI
 */var RoundedRectangle=function(){/**
     * @param {number} [x=0] - The X coordinate of the upper-left corner of the rounded rectangle
     * @param {number} [y=0] - The Y coordinate of the upper-left corner of the rounded rectangle
     * @param {number} [width=0] - The overall width of this rounded rectangle
     * @param {number} [height=0] - The overall height of this rounded rectangle
     * @param {number} [radius=20] - Controls the radius of the rounded corners
     */function RoundedRectangle(){var x=arguments.length<=0||arguments[0]===undefined?0:arguments[0];var y=arguments.length<=1||arguments[1]===undefined?0:arguments[1];var width=arguments.length<=2||arguments[2]===undefined?0:arguments[2];var height=arguments.length<=3||arguments[3]===undefined?0:arguments[3];var radius=arguments.length<=4||arguments[4]===undefined?20:arguments[4];_classCallCheck(this,RoundedRectangle);/**
         * @member {number}
         * @default 0
         */this.x=x;/**
         * @member {number}
         * @default 0
         */this.y=y;/**
         * @member {number}
         * @default 0
         */this.width=width;/**
         * @member {number}
         * @default 0
         */this.height=height;/**
         * @member {number}
         * @default 20
         */this.radius=radius;/**
         * The type of the object, mainly used to avoid `instanceof` checks
         *
         * @member {number}
         * @readonly
         * @default PIXI.SHAPES.RREC
         * @see PIXI.SHAPES
         */this.type=_const.SHAPES.RREC;}/**
     * Creates a clone of this Rounded Rectangle
     *
     * @return {PIXI.RoundedRectangle} a copy of the rounded rectangle
     */RoundedRectangle.prototype.clone=function clone(){return new RoundedRectangle(this.x,this.y,this.width,this.height,this.radius);};/**
     * Checks whether the x and y coordinates given are contained within this Rounded Rectangle
     *
     * @param {number} x - The X coordinate of the point to test
     * @param {number} y - The Y coordinate of the point to test
     * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle
     */RoundedRectangle.prototype.contains=function contains(x,y){if(this.width<=0||this.height<=0){return false;}if(x>=this.x&&x<=this.x+this.width){if(y>=this.y&&y<=this.y+this.height){if(y>=this.y+this.radius&&y<=this.y+this.height-this.radius||x>=this.x+this.radius&&x<=this.x+this.width-this.radius){return true;}var dx=x-(this.x+this.radius);var dy=y-(this.y+this.radius);var radius2=this.radius*this.radius;if(dx*dx+dy*dy<=radius2){return true;}dx=x-(this.x+this.width-this.radius);if(dx*dx+dy*dy<=radius2){return true;}dy=y-(this.y+this.height-this.radius);if(dx*dx+dy*dy<=radius2){return true;}dx=x-(this.x+this.radius);if(dx*dx+dy*dy<=radius2){return true;}}}return false;};return RoundedRectangle;}();exports.default=RoundedRectangle;},{"../../const":42}],72:[function(require,module,exports){'use strict';exports.__esModule=true;var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor);}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor;};}();var _utils=require('../utils');var _math=require('../math');var _const=require('../const');var _settings=require('../settings');var _settings2=_interopRequireDefault(_settings);var _Container=require('../display/Container');var _Container2=_interopRequireDefault(_Container);var _RenderTexture=require('../textures/RenderTexture');var _RenderTexture2=_interopRequireDefault(_RenderTexture);var _eventemitter=require('eventemitter3');var _eventemitter2=_interopRequireDefault(_eventemitter);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return call&&((typeof call==="undefined"?"undefined":_typeof2(call))==="object"||typeof call==="function")?call:self;}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof2(superClass)));}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass;}var tempMatrix=new _math.Matrix();/**
 * The SystemRenderer is the base for a Pixi Renderer. It is extended by the {@link PIXI.CanvasRenderer}
 * and {@link PIXI.WebGLRenderer} which can be used for rendering a Pixi scene.
 *
 * @abstract
 * @class
 * @extends EventEmitter
 * @memberof PIXI
 */var SystemRenderer=function(_EventEmitter){_inherits(SystemRenderer,_EventEmitter);/**
   * @param {string} system - The name of the system this renderer is for.
   * @param {number} [width=800] - the width of the canvas view
   * @param {number} [height=600] - the height of the canvas view
   * @param {object} [options] - The optional renderer parameters
   * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional
   * @param {boolean} [options.transparent=false] - If the render view is transparent, default false
   * @param {boolean} [options.autoResize=false] - If the render view is automatically resized, default false
   * @param {boolean} [options.antialias=false] - sets antialias (only applicable in chrome at the moment)
   * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer. The
   *  resolution of the renderer retina would be 2.
   * @param {boolean} [options.clearBeforeRender=true] - This sets if the CanvasRenderer will clear the canvas or
   *      not before the new render pass.
   * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area
   *  (shown if not transparent).
   * @param {boolean} [options.roundPixels=false] - If true Pixi will Math.floor() x/y values when rendering,
   *  stopping pixel interpolation.
   */function SystemRenderer(system,width,height,options){_classCallCheck(this,SystemRenderer);var _this=_possibleConstructorReturn(this,_EventEmitter.call(this));(0,_utils.sayHello)(system);// prepare options
if(options){for(var i in _settings2.default.RENDER_OPTIONS){if(typeof options[i]==='undefined'){options[i]=_settings2.default.RENDER_OPTIONS[i];}}}else{options=_settings2.default.RENDER_OPTIONS;}/**
     * The type of the renderer.
     *
     * @member {number}
     * @default PIXI.RENDERER_TYPE.UNKNOWN
     * @see PIXI.RENDERER_TYPE
     */_this.type=_const.RENDERER_TYPE.UNKNOWN;/**
     * The width of the canvas view
     *
     * @member {number}
     * @default 800
     */_this.width=width||800;/**
     * The height of the canvas view
     *
     * @member {number}
     * @default 600
     */_this.height=height||600;/**
     * The canvas element that everything is drawn to
     *
     * @member {HTMLCanvasElement}
     */_this.view=options.view||document.createElement('canvas');/**
     * The resolution / device pixel ratio of the renderer
     *
     * @member {number}
     * @default 1
     */_this.resolution=options.resolution||_settings2.default.RESOLUTION;/**
     * Whether the render view is transparent
     *
     * @member {boolean}
     */_this.transparent=options.transparent;/**
     * Whether the render view should be resized automatically
     *
     * @member {boolean}
     */_this.autoResize=options.autoResize||false;/**
     * Tracks the blend modes useful for this renderer.
     *
     * @member {object<string, mixed>}
     */_this.blendModes=null;/**
     * The value of the preserveDrawingBuffer flag affects whether or not the contents of
     * the stencil buffer is retained after rendering.
     *
     * @member {boolean}
     */_this.preserveDrawingBuffer=options.preserveDrawingBuffer;/**
     * This sets if the CanvasRenderer will clear the canvas or not before the new render pass.
     * If the scene is NOT transparent Pixi will use a canvas sized fillRect operation every
     * frame to set the canvas background color. If the scene is transparent Pixi will use clearRect
     * to clear the canvas every frame. Disable this by setting this to false. For example if
     * your game has a canvas filling background image you often don't need this set.
     *
     * @member {boolean}
     * @default
     */_this.clearBeforeRender=options.clearBeforeRender;/**
     * If true Pixi will Math.floor() x/y values when rendering, stopping pixel interpolation.
     * Handy for crisp pixel art and speed on legacy devices.
     *
     * @member {boolean}
     */_this.roundPixels=options.roundPixels;/**
     * The background color as a number.
     *
     * @member {number}
     * @private
     */_this._backgroundColor=0x000000;/**
     * The background color as an [R, G, B] array.
     *
     * @member {number[]}
     * @private
     */_this._backgroundColorRgba=[0,0,0,0];/**
     * The background color as a string.
     *
     * @member {string}
     * @private
     */_this._backgroundColorString='#000000';_this.backgroundColor=options.backgroundColor||_this._backgroundColor;// run bg color setter
/**
     * This temporary display object used as the parent of the currently being rendered item
     *
     * @member {PIXI.DisplayObject}
     * @private
     */_this._tempDisplayObjectParent=new _Container2.default();/**
     * The last root object that the renderer tried to render.
     *
     * @member {PIXI.DisplayObject}
     * @private
     */_this._lastObjectRendered=_this._tempDisplayObjectParent;return _this;}/**
   * Resizes the canvas view to the specified width and height
   *
   * @param {number} width - the new width of the canvas view
   * @param {number} height - the new height of the canvas view
   */SystemRenderer.prototype.resize=function resize(width,height){this.width=width*this.resolution;this.height=height*this.resolution;this.view.width=this.width;this.view.height=this.height;if(this.autoResize){this.view.style.width=this.width/this.resolution+'px';this.view.style.height=this.height/this.resolution+'px';}};/**
   * Useful function that returns a texture of the display object that can then be used to create sprites
   * This can be quite useful if your displayObject is complicated and needs to be reused multiple times.
   *
   * @param {PIXI.DisplayObject} displayObject - The displayObject the object will be generated from
   * @param {number} scaleMode - Should be one of the scaleMode consts
   * @param {number} resolution - The resolution / device pixel ratio of the texture being generated
   * @return {PIXI.Texture} a texture of the graphics object
   */SystemRenderer.prototype.generateTexture=function generateTexture(displayObject,scaleMode,resolution){var bounds=displayObject.getLocalBounds();var renderTexture=_RenderTexture2.default.create(bounds.width|0,bounds.height|0,scaleMode,resolution);tempMatrix.tx=-bounds.x;tempMatrix.ty=-bounds.y;this.render(displayObject,renderTexture,false,tempMatrix,true);return renderTexture;};/**
   * Removes everything from the renderer and optionally removes the Canvas DOM element.
   *
   * @param {boolean} [removeView=false] - Removes the Canvas element from the DOM.
   */SystemRenderer.prototype.destroy=function destroy(removeView){if(removeView&&this.view.parentNode){this.view.parentNode.removeChild(this.view);}this.type=_const.RENDERER_TYPE.UNKNOWN;this.width=0;this.height=0;this.view=null;this.resolution=0;this.transparent=false;this.autoResize=false;this.blendModes=null;this.preserveDrawingBuffer=false;this.clearBeforeRender=false;this.roundPixels=false;this._backgroundColor=0;this._backgroundColorRgba=null;this._backgroundColorString=null;this.backgroundColor=0;this._tempDisplayObjectParent=null;this._lastObjectRendered=null;};/**
   * The background color to fill if not transparent
   *
   * @member {number}
   * @memberof PIXI.SystemRenderer#
   */_createClass(SystemRenderer,[{key:'backgroundColor',get:function get(){return this._backgroundColor;}/**
     * Sets the background color.
     *
     * @param {number} value - The value to set to.
     */,set:function set(value){this._backgroundColor=value;this._backgroundColorString=(0,_utils.hex2string)(value);(0,_utils.hex2rgb)(value,this._backgroundColorRgba);}}]);return SystemRenderer;}(_eventemitter2.default);exports.default=SystemRenderer;},{"../const":42,"../display/Container":44,"../math":66,"../settings":97,"../textures/RenderTexture":108,"../utils":117,"eventemitter3":3}],73:[function(require,module,exports){'use strict';exports.__esModule=true;var _SystemRenderer2=require('../SystemRenderer');var _SystemRenderer3=_interopRequireDefault(_SystemRenderer2);var _CanvasMaskManager=require('./utils/CanvasMaskManager');var _CanvasMaskManager2=_interopRequireDefault(_CanvasMaskManager);var _CanvasRenderTarget=require('./utils/CanvasRenderTarget');var _CanvasRenderTarget2=_interopRequireDefault(_CanvasRenderTarget);var _mapCanvasBlendModesToPixi=require('./utils/mapCanvasBlendModesToPixi');var _mapCanvasBlendModesToPixi2=_interopRequireDefault(_mapCanvasBlendModesToPixi);var _utils=require('../../utils');var _const=require('../../const');var _settings=require('../../settings');var _settings2=_interopRequireDefault(_settings);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return call&&((typeof call==="undefined"?"undefined":_typeof2(call))==="object"||typeof call==="function")?call:self;}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof2(superClass)));}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass;}/**
 * The CanvasRenderer draws the scene and all its content onto a 2d canvas. This renderer should
 * be used for browsers that do not support WebGL. Don't forget to add the CanvasRenderer.view to
 * your DOM or you will not see anything :)
 *
 * @class
 * @memberof PIXI
 * @extends PIXI.SystemRenderer
 */var CanvasRenderer=function(_SystemRenderer){_inherits(CanvasRenderer,_SystemRenderer);/**
     * @param {number} [width=800] - the width of the canvas view
     * @param {number} [height=600] - the height of the canvas view
     * @param {object} [options] - The optional renderer parameters
     * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional
     * @param {boolean} [options.transparent=false] - If the render view is transparent, default false
     * @param {boolean} [options.autoResize=false] - If the render view is automatically resized, default false
     * @param {boolean} [options.antialias=false] - sets antialias (only applicable in chrome at the moment)
     * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer. The
     *  resolution of the renderer retina would be 2.
     * @param {boolean} [options.clearBeforeRender=true] - This sets if the CanvasRenderer will clear the canvas or
     *      not before the new render pass.
     * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area
     *  (shown if not transparent).
     * @param {boolean} [options.roundPixels=false] - If true Pixi will Math.floor() x/y values when rendering,
     *  stopping pixel interpolation.
     */function CanvasRenderer(width,height){var options=arguments.length<=2||arguments[2]===undefined?{}:arguments[2];_classCallCheck(this,CanvasRenderer);var _this=_possibleConstructorReturn(this,_SystemRenderer.call(this,'Canvas',width,height,options));_this.type=_const.RENDERER_TYPE.CANVAS;/**
         * The canvas 2d context that everything is drawn with.
         *
         * @member {CanvasRenderingContext2D}
         */_this.rootContext=_this.view.getContext('2d',{alpha:_this.transparent});/**
         * Boolean flag controlling canvas refresh.
         *
         * @member {boolean}
         */_this.refresh=true;/**
         * Instance of a CanvasMaskManager, handles masking when using the canvas renderer.
         *
         * @member {PIXI.CanvasMaskManager}
         */_this.maskManager=new _CanvasMaskManager2.default(_this);/**
         * The canvas property used to set the canvas smoothing property.
         *
         * @member {string}
         */_this.smoothProperty='imageSmoothingEnabled';if(!_this.rootContext.imageSmoothingEnabled){if(_this.rootContext.webkitImageSmoothingEnabled){_this.smoothProperty='webkitImageSmoothingEnabled';}else if(_this.rootContext.mozImageSmoothingEnabled){_this.smoothProperty='mozImageSmoothingEnabled';}else if(_this.rootContext.oImageSmoothingEnabled){_this.smoothProperty='oImageSmoothingEnabled';}else if(_this.rootContext.msImageSmoothingEnabled){_this.smoothProperty='msImageSmoothingEnabled';}}_this.initPlugins();_this.blendModes=(0,_mapCanvasBlendModesToPixi2.default)();_this._activeBlendMode=null;_this.context=null;_this.renderingToScreen=false;_this.resize(width,height);return _this;}/**
     * Renders the object to this canvas view
     *
     * @param {PIXI.DisplayObject} displayObject - The object to be rendered
     * @param {PIXI.RenderTexture} [renderTexture] - A render texture to be rendered to.
     *  If unset, it will render to the root context.
     * @param {boolean} [clear=false] - Whether to clear the canvas before drawing
     * @param {PIXI.Transform} [transform] - A transformation to be applied
     * @param {boolean} [skipUpdateTransform=false] - Whether to skip the update transform
     */CanvasRenderer.prototype.render=function render(displayObject,renderTexture,clear,transform,skipUpdateTransform){if(!this.view){return;}// can be handy to know!
this.renderingToScreen=!renderTexture;this.emit('prerender');var rootResolution=this.resolution;if(renderTexture){renderTexture=renderTexture.baseTexture||renderTexture;if(!renderTexture._canvasRenderTarget){renderTexture._canvasRenderTarget=new _CanvasRenderTarget2.default(renderTexture.width,renderTexture.height,renderTexture.resolution);renderTexture.source=renderTexture._canvasRenderTarget.canvas;renderTexture.valid=true;}this.context=renderTexture._canvasRenderTarget.context;this.resolution=renderTexture._canvasRenderTarget.resolution;}else{this.context=this.rootContext;}var context=this.context;if(!renderTexture){this._lastObjectRendered=displayObject;}if(!skipUpdateTransform){// update the scene graph
var cacheParent=displayObject.parent;var tempWt=this._tempDisplayObjectParent.transform.worldTransform;if(transform){transform.copy(tempWt);}else{tempWt.identity();}displayObject.parent=this._tempDisplayObjectParent;displayObject.updateTransform();displayObject.parent=cacheParent;// displayObject.hitArea = //TODO add a temp hit area
}context.setTransform(1,0,0,1,0,0);context.globalAlpha=1;context.globalCompositeOperation=this.blendModes[_const.BLEND_MODES.NORMAL];if(navigator.isCocoonJS&&this.view.screencanvas){context.fillStyle='black';context.clear();}if(clear!==undefined?clear:this.clearBeforeRender){if(this.renderingToScreen){if(this.transparent){context.clearRect(0,0,this.width,this.height);}else{context.fillStyle=this._backgroundColorString;context.fillRect(0,0,this.width,this.height);}}// else {
// TODO: implement background for CanvasRenderTarget or RenderTexture?
// }
}// TODO RENDER TARGET STUFF HERE..
var tempContext=this.context;this.context=context;displayObject.renderCanvas(this);this.context=tempContext;this.resolution=rootResolution;this.emit('postrender');};/**
     * Clear the canvas of renderer.
     *
     * @param {string} [clearColor] - Clear the canvas with this color, except the canvas is transparent.
     */CanvasRenderer.prototype.clear=function clear(clearColor){var context=this.context;clearColor=clearColor||this._backgroundColorString;if(!this.transparent&&clearColor){context.fillStyle=clearColor;context.fillRect(0,0,this.width,this.height);}else{context.clearRect(0,0,this.width,this.height);}};/**
     * Sets the blend mode of the renderer.
     *
     * @param {number} blendMode - See {@link PIXI.BLEND_MODES} for valid values.
     */CanvasRenderer.prototype.setBlendMode=function setBlendMode(blendMode){if(this._activeBlendMode===blendMode){return;}this._activeBlendMode=blendMode;this.context.globalCompositeOperation=this.blendModes[blendMode];};/**
     * Removes everything from the renderer and optionally removes the Canvas DOM element.
     *
     * @param {boolean} [removeView=false] - Removes the Canvas element from the DOM.
     */CanvasRenderer.prototype.destroy=function destroy(removeView){this.destroyPlugins();// call the base destroy
_SystemRenderer.prototype.destroy.call(this,removeView);this.context=null;this.refresh=true;this.maskManager.destroy();this.maskManager=null;this.smoothProperty=null;};/**
     * Resizes the canvas view to the specified width and height.
     *
     * @extends PIXI.SystemRenderer#resize
     *
     * @param {number} width - The new width of the canvas view
     * @param {number} height - The new height of the canvas view
     */CanvasRenderer.prototype.resize=function resize(width,height){_SystemRenderer.prototype.resize.call(this,width,height);// reset the scale mode.. oddly this seems to be reset when the canvas is resized.
// surely a browser bug?? Let pixi fix that for you..
if(this.smoothProperty){this.rootContext[this.smoothProperty]=_settings2.default.SCALE_MODE===_const.SCALE_MODES.LINEAR;}};return CanvasRenderer;}(_SystemRenderer3.default);exports.default=CanvasRenderer;_utils.pluginTarget.mixin(CanvasRenderer);},{"../../const":42,"../../settings":97,"../../utils":117,"../SystemRenderer":72,"./utils/CanvasMaskManager":74,"./utils/CanvasRenderTarget":75,"./utils/mapCanvasBlendModesToPixi":77}],74:[function(require,module,exports){'use strict';exports.__esModule=true;var _const=require('../../../const');function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}/**
 * A set of functions used to handle masking.
 *
 * @class
 * @memberof PIXI
 */var CanvasMaskManager=function(){/**
     * @param {PIXI.CanvasRenderer} renderer - The canvas renderer.
     */function CanvasMaskManager(renderer){_classCallCheck(this,CanvasMaskManager);this.renderer=renderer;}/**
     * This method adds it to the current stack of masks.
     *
     * @param {object} maskData - the maskData that will be pushed
     */CanvasMaskManager.prototype.pushMask=function pushMask(maskData){var renderer=this.renderer;renderer.context.save();var cacheAlpha=maskData.alpha;var transform=maskData.transform.worldTransform;var resolution=renderer.resolution;renderer.context.setTransform(transform.a*resolution,transform.b*resolution,transform.c*resolution,transform.d*resolution,transform.tx*resolution,transform.ty*resolution);// TODO suport sprite alpha masks??
// lots of effort required. If demand is great enough..
if(!maskData._texture){this.renderGraphicsShape(maskData);renderer.context.clip();}maskData.worldAlpha=cacheAlpha;};/**
     * Renders a PIXI.Graphics shape.
     *
     * @param {PIXI.Graphics} graphics - The object to render.
     */CanvasMaskManager.prototype.renderGraphicsShape=function renderGraphicsShape(graphics){var context=this.renderer.context;var len=graphics.graphicsData.length;if(len===0){return;}context.beginPath();for(var i=0;i<len;i++){var data=graphics.graphicsData[i];var shape=data.shape;if(data.type===_const.SHAPES.POLY){var points=shape.points;context.moveTo(points[0],points[1]);for(var j=1;j<points.length/2;j++){context.lineTo(points[j*2],points[j*2+1]);}// if the first and last point are the same close the path - much neater :)
if(points[0]===points[points.length-2]&&points[1]===points[points.length-1]){context.closePath();}}else if(data.type===_const.SHAPES.RECT){context.rect(shape.x,shape.y,shape.width,shape.height);context.closePath();}else if(data.type===_const.SHAPES.CIRC){// TODO - need to be Undefined!
context.arc(shape.x,shape.y,shape.radius,0,2*Math.PI);context.closePath();}else if(data.type===_const.SHAPES.ELIP){// ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
var w=shape.width*2;var h=shape.height*2;var x=shape.x-w/2;var y=shape.y-h/2;var kappa=0.5522848;var ox=w/2*kappa;// control point offset horizontal
var oy=h/2*kappa;// control point offset vertical
var xe=x+w;// x-end
var ye=y+h;// y-end
var xm=x+w/2;// x-middle
var ym=y+h/2;// y-middle
context.moveTo(x,ym);context.bezierCurveTo(x,ym-oy,xm-ox,y,xm,y);context.bezierCurveTo(xm+ox,y,xe,ym-oy,xe,ym);context.bezierCurveTo(xe,ym+oy,xm+ox,ye,xm,ye);context.bezierCurveTo(xm-ox,ye,x,ym+oy,x,ym);context.closePath();}else if(data.type===_const.SHAPES.RREC){var rx=shape.x;var ry=shape.y;var width=shape.width;var height=shape.height;var radius=shape.radius;var maxRadius=Math.min(width,height)/2|0;radius=radius>maxRadius?maxRadius:radius;context.moveTo(rx,ry+radius);context.lineTo(rx,ry+height-radius);context.quadraticCurveTo(rx,ry+height,rx+radius,ry+height);context.lineTo(rx+width-radius,ry+height);context.quadraticCurveTo(rx+width,ry+height,rx+width,ry+height-radius);context.lineTo(rx+width,ry+radius);context.quadraticCurveTo(rx+width,ry,rx+width-radius,ry);context.lineTo(rx+radius,ry);context.quadraticCurveTo(rx,ry,rx,ry+radius);context.closePath();}}};/**
     * Restores the current drawing context to the state it was before the mask was applied.
     *
     * @param {PIXI.CanvasRenderer} renderer - The renderer context to use.
     */CanvasMaskManager.prototype.popMask=function popMask(renderer){renderer.context.restore();};/**
     * Destroys this canvas mask manager.
     *
     */CanvasMaskManager.prototype.destroy=function destroy(){/* empty */};return CanvasMaskManager;}();exports.default=CanvasMaskManager;},{"../../../const":42}],75:[function(require,module,exports){'use strict';exports.__esModule=true;var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor);}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor;};}();var _settings=require('../../../settings');var _settings2=_interopRequireDefault(_settings);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}var RESOLUTION=_settings2.default.RESOLUTION;/**
 * Creates a Canvas element of the given size.
 *
 * @class
 * @memberof PIXI
 */var CanvasRenderTarget=function(){/**
   * @param {number} width - the width for the newly created canvas
   * @param {number} height - the height for the newly created canvas
   * @param {number} [resolution=1] - The resolution / device pixel ratio of the canvas
   */function CanvasRenderTarget(width,height,resolution){_classCallCheck(this,CanvasRenderTarget);/**
     * The Canvas object that belongs to this CanvasRenderTarget.
     *
     * @member {HTMLCanvasElement}
     */this.canvas=document.createElement('canvas');/**
     * A CanvasRenderingContext2D object representing a two-dimensional rendering context.
     *
     * @member {CanvasRenderingContext2D}
     */this.context=this.canvas.getContext('2d');this.resolution=resolution||RESOLUTION;this.resize(width,height);}/**
   * Clears the canvas that was created by the CanvasRenderTarget class.
   *
   * @private
   */CanvasRenderTarget.prototype.clear=function clear(){this.context.setTransform(1,0,0,1,0,0);this.context.clearRect(0,0,this.canvas.width,this.canvas.height);};/**
   * Resizes the canvas to the specified width and height.
   *
   * @param {number} width - the new width of the canvas
   * @param {number} height - the new height of the canvas
   */CanvasRenderTarget.prototype.resize=function resize(width,height){this.canvas.width=width*this.resolution;this.canvas.height=height*this.resolution;};/**
   * Destroys this canvas.
   *
   */CanvasRenderTarget.prototype.destroy=function destroy(){this.context=null;this.canvas=null;};/**
   * The width of the canvas buffer in pixels.
   *
   * @member {number}
   * @memberof PIXI.CanvasRenderTarget#
   */_createClass(CanvasRenderTarget,[{key:'width',get:function get(){return this.canvas.width;}/**
     * Sets the width.
     *
     * @param {number} val - The value to set.
     */,set:function set(val){this.canvas.width=val;}/**
     * The height of the canvas buffer in pixels.
     *
     * @member {number}
     * @memberof PIXI.CanvasRenderTarget#
     */},{key:'height',get:function get(){return this.canvas.height;}/**
     * Sets the height.
     *
     * @param {number} val - The value to set.
     */,set:function set(val){this.canvas.height=val;}}]);return CanvasRenderTarget;}();exports.default=CanvasRenderTarget;},{"../../../settings":97}],76:[function(require,module,exports){'use strict';exports.__esModule=true;exports.default=canUseNewCanvasBlendModes;/**
 * Creates a little colored canvas
 *
 * @ignore
 * @param {string} color - The color to make the canvas
 * @return {canvas} a small canvas element
 */function createColoredCanvas(color){var canvas=document.createElement('canvas');canvas.width=6;canvas.height=1;var context=canvas.getContext('2d');context.fillStyle=color;context.fillRect(0,0,6,1);return canvas;}/**
 * Checks whether the Canvas BlendModes are supported by the current browser
 *
 * @return {boolean} whether they are supported
 */function canUseNewCanvasBlendModes(){if(typeof document==='undefined'){return false;}var magenta=createColoredCanvas('#ff00ff');var yellow=createColoredCanvas('#ffff00');var canvas=document.createElement('canvas');canvas.width=6;canvas.height=1;var context=canvas.getContext('2d');context.globalCompositeOperation='multiply';context.drawImage(magenta,0,0);context.drawImage(yellow,2,0);var imageData=context.getImageData(2,0,1,1);if(!imageData){return false;}var data=imageData.data;return data[0]===255&&data[1]===0&&data[2]===0;}},{}],77:[function(require,module,exports){'use strict';exports.__esModule=true;exports.default=mapCanvasBlendModesToPixi;var _const=require('../../../const');var _canUseNewCanvasBlendModes=require('./canUseNewCanvasBlendModes');var _canUseNewCanvasBlendModes2=_interopRequireDefault(_canUseNewCanvasBlendModes);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}/**
 * Maps blend combinations to Canvas.
 *
 * @memberof PIXI
 * @function mapCanvasBlendModesToPixi
 * @private
 * @param {string[]} [array=[]] - The array to output into.
 * @return {string[]} Mapped modes.
 */function mapCanvasBlendModesToPixi(){var array=arguments.length<=0||arguments[0]===undefined?[]:arguments[0];if((0,_canUseNewCanvasBlendModes2.default)()){array[_const.BLEND_MODES.NORMAL]='source-over';array[_const.BLEND_MODES.ADD]='lighter';// IS THIS OK???
array[_const.BLEND_MODES.MULTIPLY]='multiply';array[_const.BLEND_MODES.SCREEN]='screen';array[_const.BLEND_MODES.OVERLAY]='overlay';array[_const.BLEND_MODES.DARKEN]='darken';array[_const.BLEND_MODES.LIGHTEN]='lighten';array[_const.BLEND_MODES.COLOR_DODGE]='color-dodge';array[_const.BLEND_MODES.COLOR_BURN]='color-burn';array[_const.BLEND_MODES.HARD_LIGHT]='hard-light';array[_const.BLEND_MODES.SOFT_LIGHT]='soft-light';array[_const.BLEND_MODES.DIFFERENCE]='difference';array[_const.BLEND_MODES.EXCLUSION]='exclusion';array[_const.BLEND_MODES.HUE]='hue';array[_const.BLEND_MODES.SATURATION]='saturate';array[_const.BLEND_MODES.COLOR]='color';array[_const.BLEND_MODES.LUMINOSITY]='luminosity';}else{// this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough'
array[_const.BLEND_MODES.NORMAL]='source-over';array[_const.BLEND_MODES.ADD]='lighter';// IS THIS OK???
array[_const.BLEND_MODES.MULTIPLY]='source-over';array[_const.BLEND_MODES.SCREEN]='source-over';array[_const.BLEND_MODES.OVERLAY]='source-over';array[_const.BLEND_MODES.DARKEN]='source-over';array[_const.BLEND_MODES.LIGHTEN]='source-over';array[_const.BLEND_MODES.COLOR_DODGE]='source-over';array[_const.BLEND_MODES.COLOR_BURN]='source-over';array[_const.BLEND_MODES.HARD_LIGHT]='source-over';array[_const.BLEND_MODES.SOFT_LIGHT]='source-over';array[_const.BLEND_MODES.DIFFERENCE]='source-over';array[_const.BLEND_MODES.EXCLUSION]='source-over';array[_const.BLEND_MODES.HUE]='source-over';array[_const.BLEND_MODES.SATURATION]='source-over';array[_const.BLEND_MODES.COLOR]='source-over';array[_const.BLEND_MODES.LUMINOSITY]='source-over';}return array;}},{"../../../const":42,"./canUseNewCanvasBlendModes":76}],78:[function(require,module,exports){'use strict';exports.__esModule=true;var _const=require('../../const');var _settings=require('../../settings');var _settings2=_interopRequireDefault(_settings);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}/**
 * TextureGarbageCollector. This class manages the GPU and ensures that it does not get clogged
 * up with textures that are no longer being used.
 *
 * @class
 * @memberof PIXI
 */var TextureGarbageCollector=function(){/**
     * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for.
     */function TextureGarbageCollector(renderer){_classCallCheck(this,TextureGarbageCollector);this.renderer=renderer;this.count=0;this.checkCount=0;this.maxIdle=_settings2.default.GC_MAX_IDLE;this.checkCountMax=_settings2.default.GC_MAX_CHECK_COUNT;this.mode=_settings2.default.GC_MODE;}/**
     * Checks to see when the last time a texture was used
     * if the texture has not been used for a specified amount of time it will be removed from the GPU
     */TextureGarbageCollector.prototype.update=function update(){this.count++;if(this.mode===_const.GC_MODES.MANUAL){return;}this.checkCount++;if(this.checkCount>this.checkCountMax){this.checkCount=0;this.run();}};/**
     * Checks to see when the last time a texture was used
     * if the texture has not been used for a specified amount of time it will be removed from the GPU
     */TextureGarbageCollector.prototype.run=function run(){var tm=this.renderer.textureManager;var managedTextures=tm._managedTextures;var wasRemoved=false;for(var i=0;i<managedTextures.length;i++){var texture=managedTextures[i];// only supports non generated textures at the moment!
if(!texture._glRenderTargets&&this.count-texture.touched>this.maxIdle){tm.destroyTexture(texture,true);managedTextures[i]=null;wasRemoved=true;}}if(wasRemoved){var j=0;for(var _i=0;_i<managedTextures.length;_i++){if(managedTextures[_i]!==null){managedTextures[j++]=managedTextures[_i];}}managedTextures.length=j;}};/**
     * Removes all the textures within the specified displayObject and its children from the GPU
     *
     * @param {PIXI.DisplayObject} displayObject - the displayObject to remove the textures from.
     */TextureGarbageCollector.prototype.unload=function unload(displayObject){var tm=this.renderer.textureManager;// only destroy non generated textures
if(displayObject._texture&&displayObject._texture._glRenderTargets){tm.destroyTexture(displayObject._texture,true);}for(var i=displayObject.children.length-1;i>=0;i--){this.unload(displayObject.children[i]);}};return TextureGarbageCollector;}();exports.default=TextureGarbageCollector;},{"../../const":42,"../../settings":97}],79:[function(require,module,exports){'use strict';exports.__esModule=true;var _pixiGlCore=require('pixi-gl-core');var _const=require('../../const');var _RenderTarget=require('./utils/RenderTarget');var _RenderTarget2=_interopRequireDefault(_RenderTarget);var _utils=require('../../utils');function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}/**
 * Helper class to create a webGL Texture
 *
 * @class
 * @memberof PIXI
 */var TextureManager=function(){/**
     * @param {PIXI.WebGLRenderer} renderer - A reference to the current renderer
     */function TextureManager(renderer){_classCallCheck(this,TextureManager);/**
         * A reference to the current renderer
         *
         * @member {PIXI.WebGLRenderer}
         */this.renderer=renderer;/**
         * The current WebGL rendering context
         *
         * @member {WebGLRenderingContext}
         */this.gl=renderer.gl;/**
         * Track textures in the renderer so we can no longer listen to them on destruction.
         *
         * @member {Array<*>}
         * @private
         */this._managedTextures=[];}/**
     * Binds a texture.
     *
     */TextureManager.prototype.bindTexture=function bindTexture(){}// empty
/**
     * Gets a texture.
     *
     */;TextureManager.prototype.getTexture=function getTexture(){}// empty
/**
     * Updates and/or Creates a WebGL texture for the renderer's context.
     *
     * @param {PIXI.BaseTexture|PIXI.Texture} texture - the texture to update
     * @param {Number} location - the location the texture will be bound to.
     * @return {GLTexture} The gl texture.
     */;TextureManager.prototype.updateTexture=function updateTexture(texture,location){// assume it good!
// texture = texture.baseTexture || texture;
var gl=this.gl;var isRenderTexture=!!texture._glRenderTargets;if(!texture.hasLoaded){return null;}var boundTextures=this.renderer.boundTextures;// if the location is undefined then this may have been called by n event.
// this being the case the texture may already be bound to a slot. As a texture can only be bound once
// we need to find its current location if it exists.
if(location===undefined){location=0;// TODO maybe we can use texture bound ids later on...
// check if texture is already bound..
for(var i=0;i<boundTextures.length;++i){if(boundTextures[i]===texture){location=i;break;}}}boundTextures[location]=texture;gl.activeTexture(gl.TEXTURE0+location);var glTexture=texture._glTextures[this.renderer.CONTEXT_UID];if(!glTexture){if(isRenderTexture){var renderTarget=new _RenderTarget2.default(this.gl,texture.width,texture.height,texture.scaleMode,texture.resolution);renderTarget.resize(texture.width,texture.height);texture._glRenderTargets[this.renderer.CONTEXT_UID]=renderTarget;glTexture=renderTarget.texture;}else{glTexture=new _pixiGlCore.GLTexture(this.gl,null,null,null,null);glTexture.bind(location);glTexture.premultiplyAlpha=true;glTexture.upload(texture.source);}texture._glTextures[this.renderer.CONTEXT_UID]=glTexture;texture.on('update',this.updateTexture,this);texture.on('dispose',this.destroyTexture,this);this._managedTextures.push(texture);if(texture.isPowerOfTwo){if(texture.mipmap){glTexture.enableMipmap();}if(texture.wrapMode===_const.WRAP_MODES.CLAMP){glTexture.enableWrapClamp();}else if(texture.wrapMode===_const.WRAP_MODES.REPEAT){glTexture.enableWrapRepeat();}else{glTexture.enableWrapMirrorRepeat();}}else{glTexture.enableWrapClamp();}if(texture.scaleMode===_const.SCALE_MODES.NEAREST){glTexture.enableNearestScaling();}else{glTexture.enableLinearScaling();}}// the texture already exists so we only need to update it..
else if(isRenderTexture){texture._glRenderTargets[this.renderer.CONTEXT_UID].resize(texture.width,texture.height);}else{glTexture.upload(texture.source);}return glTexture;};/**
     * Deletes the texture from WebGL
     *
     * @param {PIXI.BaseTexture|PIXI.Texture} texture - the texture to destroy
     * @param {boolean} [skipRemove=false] - Whether to skip removing the texture from the TextureManager.
     */TextureManager.prototype.destroyTexture=function destroyTexture(texture,skipRemove){texture=texture.baseTexture||texture;if(!texture.hasLoaded){return;}if(texture._glTextures[this.renderer.CONTEXT_UID]){this.renderer.unbindTexture(texture);texture._glTextures[this.renderer.CONTEXT_UID].destroy();texture.off('update',this.updateTexture,this);texture.off('dispose',this.destroyTexture,this);delete texture._glTextures[this.renderer.CONTEXT_UID];if(!skipRemove){var i=this._managedTextures.indexOf(texture);if(i!==-1){(0,_utils.removeItems)(this._managedTextures,i,1);}}}};/**
     * Deletes all the textures from WebGL
     */TextureManager.prototype.removeAll=function removeAll(){// empty all the old gl textures as they are useless now
for(var i=0;i<this._managedTextures.length;++i){var texture=this._managedTextures[i];if(texture._glTextures[this.renderer.CONTEXT_UID]){delete texture._glTextures[this.renderer.CONTEXT_UID];}}};/**
     * Destroys this manager and removes all its textures
     */TextureManager.prototype.destroy=function destroy(){// destroy managed textures
for(var i=0;i<this._managedTextures.length;++i){var texture=this._managedTextures[i];this.destroyTexture(texture,true);texture.off('update',this.updateTexture,this);texture.off('dispose',this.destroyTexture,this);}this._managedTextures=null;};return TextureManager;}();exports.default=TextureManager;},{"../../const":42,"../../utils":117,"./utils/RenderTarget":92,"pixi-gl-core":12}],80:[function(require,module,exports){'use strict';exports.__esModule=true;var _SystemRenderer2=require('../SystemRenderer');var _SystemRenderer3=_interopRequireDefault(_SystemRenderer2);var _MaskManager=require('./managers/MaskManager');var _MaskManager2=_interopRequireDefault(_MaskManager);var _StencilManager=require('./managers/StencilManager');var _StencilManager2=_interopRequireDefault(_StencilManager);var _FilterManager=require('./managers/FilterManager');var _FilterManager2=_interopRequireDefault(_FilterManager);var _RenderTarget=require('./utils/RenderTarget');var _RenderTarget2=_interopRequireDefault(_RenderTarget);var _ObjectRenderer=require('./utils/ObjectRenderer');var _ObjectRenderer2=_interopRequireDefault(_ObjectRenderer);var _TextureManager=require('./TextureManager');var _TextureManager2=_interopRequireDefault(_TextureManager);var _BaseTexture=require('../../textures/BaseTexture');var _BaseTexture2=_interopRequireDefault(_BaseTexture);var _TextureGarbageCollector=require('./TextureGarbageCollector');var _TextureGarbageCollector2=_interopRequireDefault(_TextureGarbageCollector);var _WebGLState=require('./WebGLState');var _WebGLState2=_interopRequireDefault(_WebGLState);var _mapWebGLDrawModesToPixi=require('./utils/mapWebGLDrawModesToPixi');var _mapWebGLDrawModesToPixi2=_interopRequireDefault(_mapWebGLDrawModesToPixi);var _validateContext=require('./utils/validateContext');var _validateContext2=_interopRequireDefault(_validateContext);var _utils=require('../../utils');var _pixiGlCore=require('pixi-gl-core');var _pixiGlCore2=_interopRequireDefault(_pixiGlCore);var _const=require('../../const');function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return call&&((typeof call==="undefined"?"undefined":_typeof2(call))==="object"||typeof call==="function")?call:self;}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof2(superClass)));}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass;}var CONTEXT_UID=0;/**
 * The WebGLRenderer draws the scene and all its content onto a webGL enabled canvas. This renderer
 * should be used for browsers that support webGL. This Render works by automatically managing webGLBatchs.
 * So no need for Sprite Batches or Sprite Clouds.
 * Don't forget to add the view to your DOM or you will not see anything :)
 *
 * @class
 * @memberof PIXI
 * @extends PIXI.SystemRenderer
 */var WebGLRenderer=function(_SystemRenderer){_inherits(WebGLRenderer,_SystemRenderer);/**
     *
     * @param {number} [width=0] - the width of the canvas view
     * @param {number} [height=0] - the height of the canvas view
     * @param {object} [options] - The optional renderer parameters
     * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional
     * @param {boolean} [options.transparent=false] - If the render view is transparent, default false
     * @param {boolean} [options.autoResize=false] - If the render view is automatically resized, default false
     * @param {boolean} [options.antialias=false] - sets antialias. If not available natively then FXAA
     *  antialiasing is used
     * @param {boolean} [options.forceFXAA=false] - forces FXAA antialiasing to be used over native.
     *  FXAA is faster, but may not always look as great
     * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer.
     *  The resolution of the renderer retina would be 2.
     * @param {boolean} [options.clearBeforeRender=true] - This sets if the CanvasRenderer will clear
     *  the canvas or not before the new render pass. If you wish to set this to false, you *must* set
     *  preserveDrawingBuffer to `true`.
     * @param {boolean} [options.preserveDrawingBuffer=false] - enables drawing buffer preservation,
     *  enable this if you need to call toDataUrl on the webgl context.
     * @param {boolean} [options.roundPixels=false] - If true Pixi will Math.floor() x/y values when
     *  rendering, stopping pixel interpolation.
     */function WebGLRenderer(width,height){var options=arguments.length<=2||arguments[2]===undefined?{}:arguments[2];_classCallCheck(this,WebGLRenderer);/**
         * The type of this renderer as a standardised const
         *
         * @member {number}
         * @see PIXI.RENDERER_TYPE
         */var _this=_possibleConstructorReturn(this,_SystemRenderer.call(this,'WebGL',width,height,options));_this.type=_const.RENDERER_TYPE.WEBGL;_this.handleContextLost=_this.handleContextLost.bind(_this);_this.handleContextRestored=_this.handleContextRestored.bind(_this);_this.view.addEventListener('webglcontextlost',_this.handleContextLost,false);_this.view.addEventListener('webglcontextrestored',_this.handleContextRestored,false);/**
         * The options passed in to create a new webgl context.
         *
         * @member {object}
         * @private
         */_this._contextOptions={alpha:_this.transparent,antialias:options.antialias,premultipliedAlpha:_this.transparent&&_this.transparent!=='notMultiplied',stencil:true,preserveDrawingBuffer:options.preserveDrawingBuffer};_this._backgroundColorRgba[3]=_this.transparent?0:1;/**
         * Manages the masks using the stencil buffer.
         *
         * @member {PIXI.MaskManager}
         */_this.maskManager=new _MaskManager2.default(_this);/**
         * Manages the stencil buffer.
         *
         * @member {PIXI.StencilManager}
         */_this.stencilManager=new _StencilManager2.default(_this);/**
         * An empty renderer.
         *
         * @member {PIXI.ObjectRenderer}
         */_this.emptyRenderer=new _ObjectRenderer2.default(_this);/**
         * The currently active ObjectRenderer.
         *
         * @member {PIXI.ObjectRenderer}
         */_this.currentRenderer=_this.emptyRenderer;_this.initPlugins();/**
         * The current WebGL rendering context, it is created here
         *
         * @member {WebGLRenderingContext}
         */// initialize the context so it is ready for the managers.
if(options.context){// checks to see if a context is valid..
(0,_validateContext2.default)(options.context);}_this.gl=options.context||_pixiGlCore2.default.createContext(_this.view,_this._contextOptions);_this.CONTEXT_UID=CONTEXT_UID++;/**
         * The currently active ObjectRenderer.
         *
         * @member {PIXI.WebGLState}
         */_this.state=new _WebGLState2.default(_this.gl);_this.renderingToScreen=true;/**
         * Holds the current state of textures bound to the GPU.
         * @type {Array}
         */_this.boundTextures=null;/**
         * Holds the current shader
         *
         * @member {PIXI.Shader}
         */_this._activeShader=null;_this._activeVao=null;/**
         * Holds the current render target
         *
         * @member {PIXI.RenderTarget}
         */_this._activeRenderTarget=null;_this._initContext();/**
         * Manages the filters.
         *
         * @member {PIXI.FilterManager}
         */_this.filterManager=new _FilterManager2.default(_this);// map some webGL blend and drawmodes..
_this.drawModes=(0,_mapWebGLDrawModesToPixi2.default)(_this.gl);_this._nextTextureLocation=0;_this.setBlendMode(0);return _this;}/**
     * Creates the WebGL context
     *
     * @private
     */WebGLRenderer.prototype._initContext=function _initContext(){var gl=this.gl;// restore a context if it was previously lost
if(gl.isContextLost()&&gl.getExtension('WEBGL_lose_context')){gl.getExtension('WEBGL_lose_context').restoreContext();}var maxTextures=gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS);this.boundTextures=new Array(maxTextures);this.emptyTextures=new Array(maxTextures);// create a texture manager...
this.textureManager=new _TextureManager2.default(this);this.textureGC=new _TextureGarbageCollector2.default(this);this.state.resetToDefault();this.rootRenderTarget=new _RenderTarget2.default(gl,this.width,this.height,null,this.resolution,true);this.rootRenderTarget.clearColor=this._backgroundColorRgba;this.bindRenderTarget(this.rootRenderTarget);// now lets fill up the textures with empty ones!
var emptyGLTexture=new _pixiGlCore2.default.GLTexture.fromData(gl,null,1,1);var tempObj={_glTextures:{}};tempObj._glTextures[this.CONTEXT_UID]={};for(var i=0;i<maxTextures;i++){var empty=new _BaseTexture2.default();empty._glTextures[this.CONTEXT_UID]=emptyGLTexture;this.boundTextures[i]=tempObj;this.emptyTextures[i]=empty;this.bindTexture(null,i);}this.emit('context',gl);// setup the width/height properties and gl viewport
this.resize(this.width,this.height);};/**
     * Renders the object to its webGL view
     *
     * @param {PIXI.DisplayObject} displayObject - the object to be rendered
     * @param {PIXI.RenderTexture} renderTexture - The render texture to render to.
     * @param {boolean} [clear] - Should the canvas be cleared before the new render
     * @param {PIXI.Transform} [transform] - A transform to apply to the render texture before rendering.
     * @param {boolean} [skipUpdateTransform] - Should we skip the update transform pass?
     */WebGLRenderer.prototype.render=function render(displayObject,renderTexture,clear,transform,skipUpdateTransform){// can be handy to know!
this.renderingToScreen=!renderTexture;this.emit('prerender');// no point rendering if our context has been blown up!
if(!this.gl||this.gl.isContextLost()){return;}this._nextTextureLocation=0;if(!renderTexture){this._lastObjectRendered=displayObject;}if(!skipUpdateTransform){// update the scene graph
var cacheParent=displayObject.parent;displayObject.parent=this._tempDisplayObjectParent;displayObject.updateTransform();displayObject.parent=cacheParent;// displayObject.hitArea = //TODO add a temp hit area
}this.bindRenderTexture(renderTexture,transform);this.currentRenderer.start();if(clear!==undefined?clear:this.clearBeforeRender){this._activeRenderTarget.clear();}displayObject.renderWebGL(this);// apply transform..
this.currentRenderer.flush();// this.setObjectRenderer(this.emptyRenderer);
this.textureGC.update();this.emit('postrender');};/**
     * Changes the current renderer to the one given in parameter
     *
     * @param {PIXI.ObjectRenderer} objectRenderer - The object renderer to use.
     */WebGLRenderer.prototype.setObjectRenderer=function setObjectRenderer(objectRenderer){if(this.currentRenderer===objectRenderer){return;}this.currentRenderer.stop();this.currentRenderer=objectRenderer;this.currentRenderer.start();};/**
     * This should be called if you wish to do some custom rendering
     * It will basically render anything that may be batched up such as sprites
     *
     */WebGLRenderer.prototype.flush=function flush(){this.setObjectRenderer(this.emptyRenderer);};/**
     * Resizes the webGL view to the specified width and height.
     *
     * @param {number} width - the new width of the webGL view
     * @param {number} height - the new height of the webGL view
     */WebGLRenderer.prototype.resize=function resize(width,height){//  if(width * this.resolution === this.width && height * this.resolution === this.height)return;
_SystemRenderer3.default.prototype.resize.call(this,width,height);this.rootRenderTarget.resize(width,height);if(this._activeRenderTarget===this.rootRenderTarget){this.rootRenderTarget.activate();if(this._activeShader){this._activeShader.uniforms.projectionMatrix=this.rootRenderTarget.projectionMatrix.toArray(true);}}};/**
     * Resizes the webGL view to the specified width and height.
     *
     * @param {number} blendMode - the desired blend mode
     */WebGLRenderer.prototype.setBlendMode=function setBlendMode(blendMode){this.state.setBlendMode(blendMode);};/**
     * Erases the active render target and fills the drawing area with a colour
     *
     * @param {number} [clearColor] - The colour
     */WebGLRenderer.prototype.clear=function clear(clearColor){this._activeRenderTarget.clear(clearColor);};/**
     * Sets the transform of the active render target to the given matrix
     *
     * @param {PIXI.Matrix} matrix - The transformation matrix
     */WebGLRenderer.prototype.setTransform=function setTransform(matrix){this._activeRenderTarget.transform=matrix;};/**
     * Binds a render texture for rendering
     *
     * @param {PIXI.RenderTexture} renderTexture - The render texture to render
     * @param {PIXI.Transform} transform - The transform to be applied to the render texture
     * @return {PIXI.WebGLRenderer} Returns itself.
     */WebGLRenderer.prototype.bindRenderTexture=function bindRenderTexture(renderTexture,transform){var renderTarget=void 0;if(renderTexture){var baseTexture=renderTexture.baseTexture;if(!baseTexture._glRenderTargets[this.CONTEXT_UID]){// bind the current texture
this.textureManager.updateTexture(baseTexture,0);}this.unbindTexture(baseTexture);renderTarget=baseTexture._glRenderTargets[this.CONTEXT_UID];renderTarget.setFrame(renderTexture.frame);}else{renderTarget=this.rootRenderTarget;}renderTarget.transform=transform;this.bindRenderTarget(renderTarget);return this;};/**
     * Changes the current render target to the one given in parameter
     *
     * @param {PIXI.RenderTarget} renderTarget - the new render target
     * @return {PIXI.WebGLRenderer} Returns itself.
     */WebGLRenderer.prototype.bindRenderTarget=function bindRenderTarget(renderTarget){if(renderTarget!==this._activeRenderTarget){this._activeRenderTarget=renderTarget;renderTarget.activate();if(this._activeShader){this._activeShader.uniforms.projectionMatrix=renderTarget.projectionMatrix.toArray(true);}this.stencilManager.setMaskStack(renderTarget.stencilMaskStack);}return this;};/**
     * Changes the current shader to the one given in parameter
     *
     * @param {PIXI.Shader} shader - the new shader
     * @return {PIXI.WebGLRenderer} Returns itself.
     */WebGLRenderer.prototype.bindShader=function bindShader(shader){// TODO cache
if(this._activeShader!==shader){this._activeShader=shader;shader.bind();// automatically set the projection matrix
shader.uniforms.projectionMatrix=this._activeRenderTarget.projectionMatrix.toArray(true);}return this;};/**
     * Binds the texture. This will return the location of the bound texture.
     * It may not be the same as the one you pass in. This is due to optimisation that prevents
     * needless binding of textures. For example if the texture is already bound it will return the
     * current location of the texture instead of the one provided. To bypass this use force location
     *
     * @param {PIXI.Texture} texture - the new texture
     * @param {number} location - the suggested texture location
     * @param {boolean} forceLocation - force the location
     * @return {PIXI.WebGLRenderer} Returns itself.
     */WebGLRenderer.prototype.bindTexture=function bindTexture(texture,location,forceLocation){texture=texture||this.emptyTextures[location];texture=texture.baseTexture||texture;texture.touched=this.textureGC.count;if(!forceLocation){// TODO - maybe look into adding boundIds.. save us the loop?
for(var i=0;i<this.boundTextures.length;i++){if(this.boundTextures[i]===texture){return i;}}if(location===undefined){this._nextTextureLocation++;this._nextTextureLocation%=this.boundTextures.length;location=this.boundTextures.length-this._nextTextureLocation-1;}}else{location=location||0;}var gl=this.gl;var glTexture=texture._glTextures[this.CONTEXT_UID];if(!glTexture){// this will also bind the texture..
this.textureManager.updateTexture(texture,location);}else{// bind the current texture
this.boundTextures[location]=texture;gl.activeTexture(gl.TEXTURE0+location);gl.bindTexture(gl.TEXTURE_2D,glTexture.texture);}return location;};/**
    * unbinds the texture ...
    *
    * @param {PIXI.Texture} texture - the texture to unbind
    * @return {PIXI.WebGLRenderer} Returns itself.
    */WebGLRenderer.prototype.unbindTexture=function unbindTexture(texture){var gl=this.gl;texture=texture.baseTexture||texture;for(var i=0;i<this.boundTextures.length;i++){if(this.boundTextures[i]===texture){this.boundTextures[i]=this.emptyTextures[i];gl.activeTexture(gl.TEXTURE0+i);gl.bindTexture(gl.TEXTURE_2D,this.emptyTextures[i]._glTextures[this.CONTEXT_UID].texture);}}return this;};/**
     * Creates a new VAO from this renderer's context and state.
     *
     * @return {VertexArrayObject} The new VAO.
     */WebGLRenderer.prototype.createVao=function createVao(){return new _pixiGlCore2.default.VertexArrayObject(this.gl,this.state.attribState);};/**
     * Changes the current Vao to the one given in parameter
     *
     * @param {PIXI.VertexArrayObject} vao - the new Vao
     * @return {PIXI.WebGLRenderer} Returns itself.
     */WebGLRenderer.prototype.bindVao=function bindVao(vao){if(this._activeVao===vao){return this;}if(vao){vao.bind();}else if(this._activeVao){// TODO this should always be true i think?
this._activeVao.unbind();}this._activeVao=vao;return this;};/**
     * Resets the WebGL state so you can render things however you fancy!
     *
     * @return {PIXI.WebGLRenderer} Returns itself.
     */WebGLRenderer.prototype.reset=function reset(){this.setObjectRenderer(this.emptyRenderer);this._activeShader=null;this._activeRenderTarget=this.rootRenderTarget;// bind the main frame buffer (the screen);
this.rootRenderTarget.activate();this.state.resetToDefault();return this;};/**
     * Handles a lost webgl context
     *
     * @private
     * @param {WebGLContextEvent} event - The context lost event.
     */WebGLRenderer.prototype.handleContextLost=function handleContextLost(event){event.preventDefault();};/**
     * Handles a restored webgl context
     *
     * @private
     */WebGLRenderer.prototype.handleContextRestored=function handleContextRestored(){this._initContext();this.textureManager.removeAll();};/**
     * Removes everything from the renderer (event listeners, spritebatch, etc...)
     *
     * @param {boolean} [removeView=false] - Removes the Canvas element from the DOM.
     *  See: https://github.com/pixijs/pixi.js/issues/2233
     */WebGLRenderer.prototype.destroy=function destroy(removeView){this.destroyPlugins();// remove listeners
this.view.removeEventListener('webglcontextlost',this.handleContextLost);this.view.removeEventListener('webglcontextrestored',this.handleContextRestored);this.textureManager.destroy();// call base destroy
_SystemRenderer.prototype.destroy.call(this,removeView);this.uid=0;// destroy the managers
this.maskManager.destroy();this.stencilManager.destroy();this.filterManager.destroy();this.maskManager=null;this.filterManager=null;this.textureManager=null;this.currentRenderer=null;this.handleContextLost=null;this.handleContextRestored=null;this._contextOptions=null;this.gl.useProgram(null);if(this.gl.getExtension('WEBGL_lose_context')){this.gl.getExtension('WEBGL_lose_context').loseContext();}this.gl=null;// this = null;
};return WebGLRenderer;}(_SystemRenderer3.default);exports.default=WebGLRenderer;_utils.pluginTarget.mixin(WebGLRenderer);},{"../../const":42,"../../textures/BaseTexture":107,"../../utils":117,"../SystemRenderer":72,"./TextureGarbageCollector":78,"./TextureManager":79,"./WebGLState":81,"./managers/FilterManager":86,"./managers/MaskManager":87,"./managers/StencilManager":88,"./utils/ObjectRenderer":90,"./utils/RenderTarget":92,"./utils/mapWebGLDrawModesToPixi":95,"./utils/validateContext":96,"pixi-gl-core":12}],81:[function(require,module,exports){'use strict';exports.__esModule=true;var _mapWebGLBlendModesToPixi=require('./utils/mapWebGLBlendModesToPixi');var _mapWebGLBlendModesToPixi2=_interopRequireDefault(_mapWebGLBlendModesToPixi);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}var BLEND=0;var DEPTH_TEST=1;var FRONT_FACE=2;var CULL_FACE=3;var BLEND_FUNC=4;/**
 * A WebGL state machines
 *
 * @memberof PIXI
 * @class
 */var WebGLState=function(){/**
     * @param {WebGLRenderingContext} gl - The current WebGL rendering context
     */function WebGLState(gl){_classCallCheck(this,WebGLState);/**
         * The current active state
         *
         * @member {Uint8Array}
         */this.activeState=new Uint8Array(16);/**
         * The default state
         *
         * @member {Uint8Array}
         */this.defaultState=new Uint8Array(16);// default blend mode..
this.defaultState[0]=1;/**
         * The current state index in the stack
         *
         * @member {number}
         * @private
         */this.stackIndex=0;/**
         * The stack holding all the different states
         *
         * @member {Array<*>}
         * @private
         */this.stack=[];/**
         * The current WebGL rendering context
         *
         * @member {WebGLRenderingContext}
         */this.gl=gl;this.maxAttribs=gl.getParameter(gl.MAX_VERTEX_ATTRIBS);this.attribState={tempAttribState:new Array(this.maxAttribs),attribState:new Array(this.maxAttribs)};this.blendModes=(0,_mapWebGLBlendModesToPixi2.default)(gl);// check we have vao..
this.nativeVaoExtension=gl.getExtension('OES_vertex_array_object')||gl.getExtension('MOZ_OES_vertex_array_object')||gl.getExtension('WEBKIT_OES_vertex_array_object');}/**
     * Pushes a new active state
     */WebGLState.prototype.push=function push(){// next state..
var state=this.stack[++this.stackIndex];if(!state){state=this.stack[this.stackIndex]=new Uint8Array(16);}// copy state..
// set active state so we can force overrides of gl state
for(var i=0;i<this.activeState.length;i++){this.activeState[i]=state[i];}};/**
     * Pops a state out
     */WebGLState.prototype.pop=function pop(){var state=this.stack[--this.stackIndex];this.setState(state);};/**
     * Sets the current state
     *
     * @param {*} state - The state to set.
     */WebGLState.prototype.setState=function setState(state){this.setBlend(state[BLEND]);this.setDepthTest(state[DEPTH_TEST]);this.setFrontFace(state[FRONT_FACE]);this.setCullFace(state[CULL_FACE]);this.setBlendMode(state[BLEND_FUNC]);};/**
     * Enables or disabled blending.
     *
     * @param {boolean} value - Turn on or off webgl blending.
     */WebGLState.prototype.setBlend=function setBlend(value){value=value?1:0;if(this.activeState[BLEND]===value){return;}this.activeState[BLEND]=value;this.gl[value?'enable':'disable'](this.gl.BLEND);};/**
     * Sets the blend mode.
     *
     * @param {number} value - The blend mode to set to.
     */WebGLState.prototype.setBlendMode=function setBlendMode(value){if(value===this.activeState[BLEND_FUNC]){return;}this.activeState[BLEND_FUNC]=value;this.gl.blendFunc(this.blendModes[value][0],this.blendModes[value][1]);};/**
     * Sets whether to enable or disable depth test.
     *
     * @param {boolean} value - Turn on or off webgl depth testing.
     */WebGLState.prototype.setDepthTest=function setDepthTest(value){value=value?1:0;if(this.activeState[DEPTH_TEST]===value){return;}this.activeState[DEPTH_TEST]=value;this.gl[value?'enable':'disable'](this.gl.DEPTH_TEST);};/**
     * Sets whether to enable or disable cull face.
     *
     * @param {boolean} value - Turn on or off webgl cull face.
     */WebGLState.prototype.setCullFace=function setCullFace(value){value=value?1:0;if(this.activeState[CULL_FACE]===value){return;}this.activeState[CULL_FACE]=value;this.gl[value?'enable':'disable'](this.gl.CULL_FACE);};/**
     * Sets the gl front face.
     *
     * @param {boolean} value - true is clockwise and false is counter-clockwise
     */WebGLState.prototype.setFrontFace=function setFrontFace(value){value=value?1:0;if(this.activeState[FRONT_FACE]===value){return;}this.activeState[FRONT_FACE]=value;this.gl.frontFace(this.gl[value?'CW':'CCW']);};/**
     * Disables all the vaos in use
     *
     */WebGLState.prototype.resetAttributes=function resetAttributes(){for(var i=0;i<this.attribState.tempAttribState.length;i++){this.attribState.tempAttribState[i]=0;}for(var _i=0;_i<this.attribState.attribState.length;_i++){this.attribState.attribState[_i]=0;}// im going to assume one is always active for performance reasons.
for(var _i2=1;_i2<this.maxAttribs;_i2++){this.gl.disableVertexAttribArray(_i2);}};// used
/**
     * Resets all the logic and disables the vaos
     */WebGLState.prototype.resetToDefault=function resetToDefault(){// unbind any VAO if they exist..
if(this.nativeVaoExtension){this.nativeVaoExtension.bindVertexArrayOES(null);}// reset all attributes..
this.resetAttributes();// set active state so we can force overrides of gl state
for(var i=0;i<this.activeState.length;++i){this.activeState[i]=32;}this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,false);this.setState(this.defaultState);};return WebGLState;}();exports.default=WebGLState;},{"./utils/mapWebGLBlendModesToPixi":94}],82:[function(require,module,exports){'use strict';exports.__esModule=true;var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor);}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor;};}();var _extractUniformsFromSrc=require('./extractUniformsFromSrc');var _extractUniformsFromSrc2=_interopRequireDefault(_extractUniformsFromSrc);var _utils=require('../../../utils');var _const=require('../../../const');function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}var SOURCE_KEY_MAP={};// let math = require('../../../math');
/**
 * @class
 * @memberof PIXI
 * @extends PIXI.Shader
 */var Filter=function(){/**
   * @param {string} [vertexSrc] - The source of the vertex shader.
   * @param {string} [fragmentSrc] - The source of the fragment shader.
   * @param {object} [uniforms] - Custom uniforms to use to augment the built-in ones.
   */function Filter(vertexSrc,fragmentSrc,uniforms){_classCallCheck(this,Filter);/**
     * The vertex shader.
     *
     * @member {string}
     */this.vertexSrc=vertexSrc||Filter.defaultVertexSrc;/**
     * The fragment shader.
     *
     * @member {string}
     */this.fragmentSrc=fragmentSrc||Filter.defaultFragmentSrc;this.blendMode=_const.BLEND_MODES.NORMAL;// pull out the vertex and shader uniforms if they are not specified..
// currently this does not extract structs only default types
this.uniformData=uniforms||(0,_extractUniformsFromSrc2.default)(this.vertexSrc,this.fragmentSrc,'projectionMatrix|uSampler');/**
     * An object containing the current values of custom uniforms.
     * @example <caption>Updating the value of a custom uniform</caption>
     * filter.uniforms.time = performance.now();
     *
     * @member {object}
     */this.uniforms={};for(var i in this.uniformData){this.uniforms[i]=this.uniformData[i].value;}// this is where we store shader references..
// TODO we could cache this!
this.glShaders={};// used for cacheing.. sure there is a better way!
if(!SOURCE_KEY_MAP[this.vertexSrc+this.fragmentSrc]){SOURCE_KEY_MAP[this.vertexSrc+this.fragmentSrc]=(0,_utils.uid)();}this.glShaderKey=SOURCE_KEY_MAP[this.vertexSrc+this.fragmentSrc];/**
     * The padding of the filter. Some filters require extra space to breath such as a blur.
     * Increasing this will add extra width and height to the bounds of the object that the
     * filter is applied to.
     *
     * @member {number}
     */this.padding=4;/**
     * The resolution of the filter. Setting this to be lower will lower the quality but
     * increase the performance of the filter.
     *
     * @member {number}
     */this.resolution=1;/**
     * If enabled is true the filter is applied, if false it will not.
     *
     * @member {boolean}
     */this.enabled=true;}/**
   * Applies the filter
   *
   * @param {PIXI.FilterManager} filterManager - The renderer to retrieve the filter from
   * @param {PIXI.RenderTarget} input - The input render target.
   * @param {PIXI.RenderTarget} output - The target to output to.
   * @param {boolean} clear - Should the output be cleared before rendering to it
   */Filter.prototype.apply=function apply(filterManager,input,output,clear){// --- //
//  this.uniforms.filterMatrix = filterManager.calculateSpriteMatrix(tempMatrix, window.panda );
// do as you please!
filterManager.applyFilter(this,input,output,clear);// or just do a regular render..
};/**
   * The default vertex shader source
   *
   * @static
   * @constant
   */_createClass(Filter,null,[{key:'defaultVertexSrc',get:function get(){return['attribute vec2 aVertexPosition;','attribute vec2 aTextureCoord;','uniform mat3 projectionMatrix;','uniform mat3 filterMatrix;','varying vec2 vTextureCoord;','varying vec2 vFilterCoord;','void main(void){','   gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);','   vFilterCoord = ( filterMatrix * vec3( aTextureCoord, 1.0)  ).xy;','   vTextureCoord = aTextureCoord ;','}'].join('\n');}/**
     * The default fragment shader source
     *
     * @static
     * @constant
     */},{key:'defaultFragmentSrc',get:function get(){return['varying vec2 vTextureCoord;','varying vec2 vFilterCoord;','uniform sampler2D uSampler;','uniform sampler2D filterSampler;','void main(void){','   vec4 masky = texture2D(filterSampler, vFilterCoord);','   vec4 sample = texture2D(uSampler, vTextureCoord);','   vec4 color;','   if(mod(vFilterCoord.x, 1.0) > 0.5)','   {','     color = vec4(1.0, 0.0, 0.0, 1.0);','   }','   else','   {','     color = vec4(0.0, 1.0, 0.0, 1.0);','   }',// '   gl_FragColor = vec4(mod(vFilterCoord.x, 1.5), vFilterCoord.y,0.0,1.0);',
'   gl_FragColor = mix(sample, masky, 0.5);','   gl_FragColor *= sample.a;','}'].join('\n');}}]);return Filter;}();exports.default=Filter;},{"../../../const":42,"../../../utils":117,"./extractUniformsFromSrc":83}],83:[function(require,module,exports){'use strict';exports.__esModule=true;exports.default=extractUniformsFromSrc;var _pixiGlCore=require('pixi-gl-core');var _pixiGlCore2=_interopRequireDefault(_pixiGlCore);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}var defaultValue=_pixiGlCore2.default.shader.defaultValue;function extractUniformsFromSrc(vertexSrc,fragmentSrc,mask){var vertUniforms=extractUniformsFromString(vertexSrc,mask);var fragUniforms=extractUniformsFromString(fragmentSrc,mask);return Object.assign(vertUniforms,fragUniforms);}function extractUniformsFromString(string){var maskRegex=new RegExp('^(projectionMatrix|uSampler|filterArea)$');var uniforms={};var nameSplit=void 0;// clean the lines a little - remove extra spaces / tabs etc
// then split along ';'
var lines=string.replace(/\s+/g,' ').split(/\s*;\s*/);// loop through..
for(var i=0;i<lines.length;i++){var line=lines[i].trim();if(line.indexOf('uniform')>-1){var splitLine=line.split(' ');var type=splitLine[1];var name=splitLine[2];var size=1;if(name.indexOf('[')>-1){// array!
nameSplit=name.split(/\[|]/);name=nameSplit[0];size*=Number(nameSplit[1]);}if(!name.match(maskRegex)){uniforms[name]={value:defaultValue(type,size),name:name,type:type};}}}return uniforms;}},{"pixi-gl-core":12}],84:[function(require,module,exports){'use strict';exports.__esModule=true;exports.calculateScreenSpaceMatrix=calculateScreenSpaceMatrix;exports.calculateNormalizedScreenSpaceMatrix=calculateNormalizedScreenSpaceMatrix;exports.calculateSpriteMatrix=calculateSpriteMatrix;var _math=require('../../../math');/*
 * Calculates the mapped matrix
 * @param filterArea {Rectangle} The filter area
 * @param sprite {Sprite} the target sprite
 * @param outputMatrix {Matrix} @alvin
 */// TODO playing around here.. this is temporary - (will end up in the shader)
// this returns a matrix that will normalise map filter cords in the filter to screen space
function calculateScreenSpaceMatrix(outputMatrix,filterArea,textureSize){// let worldTransform = sprite.worldTransform.copy(Matrix.TEMP_MATRIX),
// let texture = {width:1136, height:700};//sprite._texture.baseTexture;
// TODO unwrap?
var mappedMatrix=outputMatrix.identity();mappedMatrix.translate(filterArea.x/textureSize.width,filterArea.y/textureSize.height);mappedMatrix.scale(textureSize.width,textureSize.height);return mappedMatrix;}function calculateNormalizedScreenSpaceMatrix(outputMatrix,filterArea,textureSize){var mappedMatrix=outputMatrix.identity();mappedMatrix.translate(filterArea.x/textureSize.width,filterArea.y/textureSize.height);var translateScaleX=textureSize.width/filterArea.width;var translateScaleY=textureSize.height/filterArea.height;mappedMatrix.scale(translateScaleX,translateScaleY);return mappedMatrix;}// this will map the filter coord so that a texture can be used based on the transform of a sprite
function calculateSpriteMatrix(outputMatrix,filterArea,textureSize,sprite){var worldTransform=sprite.worldTransform.copy(_math.Matrix.TEMP_MATRIX);var texture=sprite._texture.baseTexture;// TODO unwrap?
var mappedMatrix=outputMatrix.identity();// scale..
var ratio=textureSize.height/textureSize.width;mappedMatrix.translate(filterArea.x/textureSize.width,filterArea.y/textureSize.height);mappedMatrix.scale(1,ratio);var translateScaleX=textureSize.width/texture.width;var translateScaleY=textureSize.height/texture.height;worldTransform.tx/=texture.width*translateScaleX;// this...?  free beer for anyone who can explain why this makes sense!
worldTransform.ty/=texture.width*translateScaleX;// worldTransform.ty /= texture.height * translateScaleY;
worldTransform.invert();mappedMatrix.prepend(worldTransform);// apply inverse scale..
mappedMatrix.scale(1,1/ratio);mappedMatrix.scale(translateScaleX,translateScaleY);mappedMatrix.translate(sprite.anchor.x,sprite.anchor.y);return mappedMatrix;}},{"../../../math":66}],85:[function(require,module,exports){'use strict';exports.__esModule=true;var _Filter2=require('../Filter');var _Filter3=_interopRequireDefault(_Filter2);var _math=require('../../../../math');var _path=require('path');function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return call&&((typeof call==="undefined"?"undefined":_typeof2(call))==="object"||typeof call==="function")?call:self;}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof2(superClass)));}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass;}/**
 * The SpriteMaskFilter class
 *
 * @class
 * @extends PIXI.Filter
 * @memberof PIXI
 */var SpriteMaskFilter=function(_Filter){_inherits(SpriteMaskFilter,_Filter);/**
     * @param {PIXI.Sprite} sprite - the target sprite
     */function SpriteMaskFilter(sprite){_classCallCheck(this,SpriteMaskFilter);var maskMatrix=new _math.Matrix();var _this=_possibleConstructorReturn(this,_Filter.call(this,'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 otherMatrix;\n\nvarying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n    gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n    vTextureCoord = aTextureCoord;\n    vMaskCoord = ( otherMatrix * vec3( aTextureCoord, 1.0)  ).xy;\n}\n','varying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform float alpha;\nuniform sampler2D mask;\n\nvoid main(void)\n{\n    // check clip! this will stop the mask bleeding out from the edges\n    vec2 text = abs( vMaskCoord - 0.5 );\n    text = step(0.5, text);\n\n    float clip = 1.0 - max(text.y, text.x);\n    vec4 original = texture2D(uSampler, vTextureCoord);\n    vec4 masky = texture2D(mask, vMaskCoord);\n\n    original *= (masky.r * masky.a * alpha * clip);\n\n    gl_FragColor = original;\n}\n'));sprite.renderable=false;_this.maskSprite=sprite;_this.maskMatrix=maskMatrix;return _this;}/**
     * Applies the filter
     *
     * @param {PIXI.FilterManager} filterManager - The renderer to retrieve the filter from
     * @param {PIXI.RenderTarget} input - The input render target.
     * @param {PIXI.RenderTarget} output - The target to output to.
     */SpriteMaskFilter.prototype.apply=function apply(filterManager,input,output){var maskSprite=this.maskSprite;this.uniforms.mask=maskSprite._texture;this.uniforms.otherMatrix=filterManager.calculateSpriteMatrix(this.maskMatrix,maskSprite);this.uniforms.alpha=maskSprite.worldAlpha;filterManager.applyFilter(this,input,output);};return SpriteMaskFilter;}(_Filter3.default);exports.default=SpriteMaskFilter;},{"../../../../math":66,"../Filter":82,"path":22}],86:[function(require,module,exports){'use strict';exports.__esModule=true;var _WebGLManager2=require('./WebGLManager');var _WebGLManager3=_interopRequireDefault(_WebGLManager2);var _RenderTarget=require('../utils/RenderTarget');var _RenderTarget2=_interopRequireDefault(_RenderTarget);var _Quad=require('../utils/Quad');var _Quad2=_interopRequireDefault(_Quad);var _math=require('../../../math');var _Shader=require('../../../Shader');var _Shader2=_interopRequireDefault(_Shader);var _filterTransforms=require('../filters/filterTransforms');var filterTransforms=_interopRequireWildcard(_filterTransforms);var _bitTwiddle=require('bit-twiddle');var _bitTwiddle2=_interopRequireDefault(_bitTwiddle);function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj;}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key];}}newObj.default=obj;return newObj;}}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return call&&((typeof call==="undefined"?"undefined":_typeof2(call))==="object"||typeof call==="function")?call:self;}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof2(superClass)));}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass;}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}/**
 * @ignore
 * @class
 */var FilterState=/**
 *
 */function FilterState(){_classCallCheck(this,FilterState);this.renderTarget=null;this.sourceFrame=new _math.Rectangle();this.destinationFrame=new _math.Rectangle();this.filters=[];this.target=null;this.resolution=1;};/**
 * @class
 * @memberof PIXI
 * @extends PIXI.WebGLManager
 */var FilterManager=function(_WebGLManager){_inherits(FilterManager,_WebGLManager);/**
     * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for.
     */function FilterManager(renderer){_classCallCheck(this,FilterManager);var _this=_possibleConstructorReturn(this,_WebGLManager.call(this,renderer));_this.gl=_this.renderer.gl;// know about sprites!
_this.quad=new _Quad2.default(_this.gl,renderer.state.attribState);_this.shaderCache={};// todo add default!
_this.pool={};_this.filterData=null;return _this;}/**
     * Adds a new filter to the manager.
     *
     * @param {PIXI.DisplayObject} target - The target of the filter to render.
     * @param {PIXI.Filter[]} filters - The filters to apply.
     */FilterManager.prototype.pushFilter=function pushFilter(target,filters){var renderer=this.renderer;var filterData=this.filterData;if(!filterData){filterData=this.renderer._activeRenderTarget.filterStack;// add new stack
var filterState=new FilterState();filterState.sourceFrame=filterState.destinationFrame=this.renderer._activeRenderTarget.size;filterState.renderTarget=renderer._activeRenderTarget;this.renderer._activeRenderTarget.filterData=filterData={index:0,stack:[filterState]};this.filterData=filterData;}// get the current filter state..
var currentState=filterData.stack[++filterData.index];if(!currentState){currentState=filterData.stack[filterData.index]=new FilterState();}// for now we go off the filter of the first resolution..
var resolution=filters[0].resolution;var padding=filters[0].padding|0;var targetBounds=target.filterArea||target.getBounds(true);var sourceFrame=currentState.sourceFrame;var destinationFrame=currentState.destinationFrame;sourceFrame.x=(targetBounds.x*resolution|0)/resolution;sourceFrame.y=(targetBounds.y*resolution|0)/resolution;sourceFrame.width=(targetBounds.width*resolution|0)/resolution;sourceFrame.height=(targetBounds.height*resolution|0)/resolution;if(filterData.stack[0].renderTarget.transform){//
// TODO we should fit the rect around the transform..
}else{sourceFrame.fit(filterData.stack[0].destinationFrame);}// lets apply the padding After we fit the element to the screen.
// this should stop the strange side effects that can occur when cropping to the edges
sourceFrame.pad(padding);destinationFrame.width=sourceFrame.width;destinationFrame.height=sourceFrame.height;// lets play the padding after we fit the element to the screen.
// this should stop the strange side effects that can occur when cropping to the edges
var renderTarget=this.getPotRenderTarget(renderer.gl,sourceFrame.width,sourceFrame.height,resolution);currentState.target=target;currentState.filters=filters;currentState.resolution=resolution;currentState.renderTarget=renderTarget;// bind the render target to draw the shape in the top corner..
renderTarget.setFrame(destinationFrame,sourceFrame);// bind the render target
renderer.bindRenderTarget(renderTarget);renderTarget.clear();};/**
     * Pops off the filter and applies it.
     *
     */FilterManager.prototype.popFilter=function popFilter(){var filterData=this.filterData;var lastState=filterData.stack[filterData.index-1];var currentState=filterData.stack[filterData.index];this.quad.map(currentState.renderTarget.size,currentState.sourceFrame).upload();var filters=currentState.filters;if(filters.length===1){filters[0].apply(this,currentState.renderTarget,lastState.renderTarget,false);this.freePotRenderTarget(currentState.renderTarget);}else{var flip=currentState.renderTarget;var flop=this.getPotRenderTarget(this.renderer.gl,currentState.sourceFrame.width,currentState.sourceFrame.height,currentState.resolution);flop.setFrame(currentState.destinationFrame,currentState.sourceFrame);// finally lets clear the render target before drawing to it..
flop.clear();var i=0;for(i=0;i<filters.length-1;++i){filters[i].apply(this,flip,flop,true);var t=flip;flip=flop;flop=t;}filters[i].apply(this,flip,lastState.renderTarget,true);this.freePotRenderTarget(flip);this.freePotRenderTarget(flop);}filterData.index--;if(filterData.index===0){this.filterData=null;}};/**
     * Draws a filter.
     *
     * @param {PIXI.Filter} filter - The filter to draw.
     * @param {PIXI.RenderTarget} input - The input render target.
     * @param {PIXI.RenderTarget} output - The target to output to.
     * @param {boolean} clear - Should the output be cleared before rendering to it
     */FilterManager.prototype.applyFilter=function applyFilter(filter,input,output,clear){var renderer=this.renderer;var gl=renderer.gl;var shader=filter.glShaders[renderer.CONTEXT_UID];// cacheing..
if(!shader){if(filter.glShaderKey){shader=this.shaderCache[filter.glShaderKey];if(!shader){shader=new _Shader2.default(this.gl,filter.vertexSrc,filter.fragmentSrc);filter.glShaders[renderer.CONTEXT_UID]=this.shaderCache[filter.glShaderKey]=shader;}}else{shader=filter.glShaders[renderer.CONTEXT_UID]=new _Shader2.default(this.gl,filter.vertexSrc,filter.fragmentSrc);}// TODO - this only needs to be done once?
renderer.bindVao(null);this.quad.initVao(shader);}renderer.bindVao(this.quad.vao);renderer.bindRenderTarget(output);if(clear){gl.disable(gl.SCISSOR_TEST);renderer.clear();// [1, 1, 1, 1]);
gl.enable(gl.SCISSOR_TEST);}// in case the render target is being masked using a scissor rect
if(output===renderer.maskManager.scissorRenderTarget){renderer.maskManager.pushScissorMask(null,renderer.maskManager.scissorData);}renderer.bindShader(shader);// this syncs the pixi filters  uniforms with glsl uniforms
this.syncUniforms(shader,filter);renderer.state.setBlendMode(filter.blendMode);// temporary bypass cache..
var tex=this.renderer.boundTextures[0];gl.activeTexture(gl.TEXTURE0);gl.bindTexture(gl.TEXTURE_2D,input.texture.texture);this.quad.vao.draw(this.renderer.gl.TRIANGLES,6,0);// restore cache.
gl.bindTexture(gl.TEXTURE_2D,tex._glTextures[this.renderer.CONTEXT_UID].texture);};/**
     * Uploads the uniforms of the filter.
     *
     * @param {GLShader} shader - The underlying gl shader.
     * @param {PIXI.Filter} filter - The filter we are synchronizing.
     */FilterManager.prototype.syncUniforms=function syncUniforms(shader,filter){var uniformData=filter.uniformData;var uniforms=filter.uniforms;// 0 is reserved for the pixi texture so we start at 1!
var textureCount=1;var currentState=void 0;if(shader.uniforms.data.filterArea){currentState=this.filterData.stack[this.filterData.index];var filterArea=shader.uniforms.filterArea;filterArea[0]=currentState.renderTarget.size.width;filterArea[1]=currentState.renderTarget.size.height;filterArea[2]=currentState.sourceFrame.x;filterArea[3]=currentState.sourceFrame.y;shader.uniforms.filterArea=filterArea;}// use this to clamp displaced texture coords so they belong to filterArea
// see displacementFilter fragment shader for an example
if(shader.uniforms.data.filterClamp){currentState=this.filterData.stack[this.filterData.index];var filterClamp=shader.uniforms.filterClamp;filterClamp[0]=0;filterClamp[1]=0;filterClamp[2]=(currentState.sourceFrame.width-1)/currentState.renderTarget.size.width;filterClamp[3]=(currentState.sourceFrame.height-1)/currentState.renderTarget.size.height;shader.uniforms.filterClamp=filterClamp;}// TODO Cacheing layer..
for(var i in uniformData){if(uniformData[i].type==='sampler2D'&&uniforms[i]!==0){if(uniforms[i].baseTexture){shader.uniforms[i]=this.renderer.bindTexture(uniforms[i].baseTexture,textureCount);}else{shader.uniforms[i]=textureCount;// TODO
// this is helpful as renderTargets can also be set.
// Although thinking about it, we could probably
// make the filter texture cache return a RenderTexture
// rather than a renderTarget
var gl=this.renderer.gl;this.renderer.boundTextures[textureCount]=this.renderer.emptyTextures[textureCount];gl.activeTexture(gl.TEXTURE0+textureCount);uniforms[i].texture.bind();}textureCount++;}else if(uniformData[i].type==='mat3'){// check if its pixi matrix..
if(uniforms[i].a!==undefined){shader.uniforms[i]=uniforms[i].toArray(true);}else{shader.uniforms[i]=uniforms[i];}}else if(uniformData[i].type==='vec2'){// check if its a point..
if(uniforms[i].x!==undefined){var val=shader.uniforms[i]||new Float32Array(2);val[0]=uniforms[i].x;val[1]=uniforms[i].y;shader.uniforms[i]=val;}else{shader.uniforms[i]=uniforms[i];}}else if(uniformData[i].type==='float'){if(shader.uniforms.data[i].value!==uniformData[i]){shader.uniforms[i]=uniforms[i];}}else{shader.uniforms[i]=uniforms[i];}}};/**
     * Gets a render target from the pool, or creates a new one.
     *
     * @param {boolean} clear - Should we clear the render texture when we get it?
     * @param {number} resolution - The resolution of the target.
     * @return {PIXI.RenderTarget} The new render target
     */FilterManager.prototype.getRenderTarget=function getRenderTarget(clear,resolution){var currentState=this.filterData.stack[this.filterData.index];var renderTarget=this.getPotRenderTarget(this.renderer.gl,currentState.sourceFrame.width,currentState.sourceFrame.height,resolution||currentState.resolution);renderTarget.setFrame(currentState.destinationFrame,currentState.sourceFrame);return renderTarget;};/**
     * Returns a render target to the pool.
     *
     * @param {PIXI.RenderTarget} renderTarget - The render target to return.
     */FilterManager.prototype.returnRenderTarget=function returnRenderTarget(renderTarget){this.freePotRenderTarget(renderTarget);};/**
     * Calculates the mapped matrix.
     *
     * TODO playing around here.. this is temporary - (will end up in the shader)
     * this returns a matrix that will normalise map filter cords in the filter to screen space
     *
     * @param {PIXI.Matrix} outputMatrix - the matrix to output to.
     * @return {PIXI.Matrix} The mapped matrix.
     */FilterManager.prototype.calculateScreenSpaceMatrix=function calculateScreenSpaceMatrix(outputMatrix){var currentState=this.filterData.stack[this.filterData.index];return filterTransforms.calculateScreenSpaceMatrix(outputMatrix,currentState.sourceFrame,currentState.renderTarget.size);};/**
     * Multiply vTextureCoord to this matrix to achieve (0,0,1,1) for filterArea
     *
     * @param {PIXI.Matrix} outputMatrix - The matrix to output to.
     * @return {PIXI.Matrix} The mapped matrix.
     */FilterManager.prototype.calculateNormalizedScreenSpaceMatrix=function calculateNormalizedScreenSpaceMatrix(outputMatrix){var currentState=this.filterData.stack[this.filterData.index];return filterTransforms.calculateNormalizedScreenSpaceMatrix(outputMatrix,currentState.sourceFrame,currentState.renderTarget.size,currentState.destinationFrame);};/**
     * This will map the filter coord so that a texture can be used based on the transform of a sprite
     *
     * @param {PIXI.Matrix} outputMatrix - The matrix to output to.
     * @param {PIXI.Sprite} sprite - The sprite to map to.
     * @return {PIXI.Matrix} The mapped matrix.
     */FilterManager.prototype.calculateSpriteMatrix=function calculateSpriteMatrix(outputMatrix,sprite){var currentState=this.filterData.stack[this.filterData.index];return filterTransforms.calculateSpriteMatrix(outputMatrix,currentState.sourceFrame,currentState.renderTarget.size,sprite);};/**
     * Destroys this Filter Manager.
     *
     */FilterManager.prototype.destroy=function destroy(){this.shaderCache=[];this.emptyPool();};/**
     * Gets a Power-of-Two render texture.
     *
     * TODO move to a seperate class could be on renderer?
     * also - could cause issue with multiple contexts?
     *
     * @private
     * @param {WebGLRenderingContext} gl - The webgl rendering context
     * @param {number} minWidth - The minimum width of the render target.
     * @param {number} minHeight - The minimum height of the render target.
     * @param {number} resolution - The resolution of the render target.
     * @return {PIXI.RenderTarget} The new render target.
     */FilterManager.prototype.getPotRenderTarget=function getPotRenderTarget(gl,minWidth,minHeight,resolution){// TODO you could return a bigger texture if there is not one in the pool?
minWidth=_bitTwiddle2.default.nextPow2(minWidth*resolution);minHeight=_bitTwiddle2.default.nextPow2(minHeight*resolution);var key=(minWidth&0xFFFF)<<16|minHeight&0xFFFF;if(!this.pool[key]){this.pool[key]=[];}var renderTarget=this.pool[key].pop();// creating render target will cause texture to be bound!
if(!renderTarget){// temporary bypass cache..
var tex=this.renderer.boundTextures[0];gl.activeTexture(gl.TEXTURE0);// internally - this will cause a texture to be bound..
renderTarget=new _RenderTarget2.default(gl,minWidth,minHeight,null,1);// set the current one back
gl.bindTexture(gl.TEXTURE_2D,tex._glTextures[this.renderer.CONTEXT_UID].texture);}// manually tweak the resolution...
// this will not modify the size of the frame buffer, just its resolution.
renderTarget.resolution=resolution;renderTarget.defaultFrame.width=renderTarget.size.width=minWidth/resolution;renderTarget.defaultFrame.height=renderTarget.size.height=minHeight/resolution;return renderTarget;};/**
     * Empties the texture pool.
     *
     */FilterManager.prototype.emptyPool=function emptyPool(){for(var i in this.pool){var textures=this.pool[i];if(textures){for(var j=0;j<textures.length;j++){textures[j].destroy(true);}}}this.pool={};};/**
     * Frees a render target back into the pool.
     *
     * @param {PIXI.RenderTarget} renderTarget - The renderTarget to free
     */FilterManager.prototype.freePotRenderTarget=function freePotRenderTarget(renderTarget){var minWidth=renderTarget.size.width*renderTarget.resolution;var minHeight=renderTarget.size.height*renderTarget.resolution;var key=(minWidth&0xFFFF)<<16|minHeight&0xFFFF;this.pool[key].push(renderTarget);};return FilterManager;}(_WebGLManager3.default);exports.default=FilterManager;},{"../../../Shader":41,"../../../math":66,"../filters/filterTransforms":84,"../utils/Quad":91,"../utils/RenderTarget":92,"./WebGLManager":89,"bit-twiddle":1}],87:[function(require,module,exports){'use strict';exports.__esModule=true;var _WebGLManager2=require('./WebGLManager');var _WebGLManager3=_interopRequireDefault(_WebGLManager2);var _SpriteMaskFilter=require('../filters/spriteMask/SpriteMaskFilter');var _SpriteMaskFilter2=_interopRequireDefault(_SpriteMaskFilter);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return call&&((typeof call==="undefined"?"undefined":_typeof2(call))==="object"||typeof call==="function")?call:self;}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof2(superClass)));}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass;}/**
 * @class
 * @extends PIXI.WebGLManager
 * @memberof PIXI
 */var MaskManager=function(_WebGLManager){_inherits(MaskManager,_WebGLManager);/**
     * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for.
     */function MaskManager(renderer){_classCallCheck(this,MaskManager);// TODO - we don't need both!
var _this=_possibleConstructorReturn(this,_WebGLManager.call(this,renderer));_this.scissor=false;_this.scissorData=null;_this.scissorRenderTarget=null;_this.enableScissor=true;_this.alphaMaskPool=[];_this.alphaMaskIndex=0;return _this;}/**
     * Applies the Mask and adds it to the current filter stack.
     *
     * @param {PIXI.DisplayObject} target - Display Object to push the mask to
     * @param {PIXI.Sprite|PIXI.Graphics} maskData - The masking data.
     */MaskManager.prototype.pushMask=function pushMask(target,maskData){if(maskData.texture){this.pushSpriteMask(target,maskData);}else if(this.enableScissor&&!this.scissor&&!this.renderer.stencilManager.stencilMaskStack.length&&maskData.isFastRect()){var matrix=maskData.worldTransform;var rot=Math.atan2(matrix.b,matrix.a);// use the nearest degree!
rot=Math.round(rot*(180/Math.PI));if(rot%90){this.pushStencilMask(maskData);}else{this.pushScissorMask(target,maskData);}}else{this.pushStencilMask(maskData);}};/**
     * Removes the last mask from the mask stack and doesn't return it.
     *
     * @param {PIXI.DisplayObject} target - Display Object to pop the mask from
     * @param {PIXI.Sprite|PIXI.Graphics} maskData - The masking data.
     */MaskManager.prototype.popMask=function popMask(target,maskData){if(maskData.texture){this.popSpriteMask(target,maskData);}else if(this.enableScissor&&!this.renderer.stencilManager.stencilMaskStack.length){this.popScissorMask(target,maskData);}else{this.popStencilMask(target,maskData);}};/**
     * Applies the Mask and adds it to the current filter stack.
     *
     * @param {PIXI.RenderTarget} target - Display Object to push the sprite mask to
     * @param {PIXI.Sprite} maskData - Sprite to be used as the mask
     */MaskManager.prototype.pushSpriteMask=function pushSpriteMask(target,maskData){var alphaMaskFilter=this.alphaMaskPool[this.alphaMaskIndex];if(!alphaMaskFilter){alphaMaskFilter=this.alphaMaskPool[this.alphaMaskIndex]=[new _SpriteMaskFilter2.default(maskData)];}alphaMaskFilter[0].resolution=this.renderer.resolution;alphaMaskFilter[0].maskSprite=maskData;// TODO - may cause issues!
target.filterArea=maskData.getBounds(true);this.renderer.filterManager.pushFilter(target,alphaMaskFilter);this.alphaMaskIndex++;};/**
     * Removes the last filter from the filter stack and doesn't return it.
     *
     */MaskManager.prototype.popSpriteMask=function popSpriteMask(){this.renderer.filterManager.popFilter();this.alphaMaskIndex--;};/**
     * Applies the Mask and adds it to the current filter stack.
     *
     * @param {PIXI.Sprite|PIXI.Graphics} maskData - The masking data.
     */MaskManager.prototype.pushStencilMask=function pushStencilMask(maskData){this.renderer.currentRenderer.stop();this.renderer.stencilManager.pushStencil(maskData);};/**
     * Removes the last filter from the filter stack and doesn't return it.
     *
     */MaskManager.prototype.popStencilMask=function popStencilMask(){this.renderer.currentRenderer.stop();this.renderer.stencilManager.popStencil();};/**
     *
     * @param {PIXI.DisplayObject} target - Display Object to push the mask to
     * @param {PIXI.Graphics} maskData - The masking data.
     */MaskManager.prototype.pushScissorMask=function pushScissorMask(target,maskData){maskData.renderable=true;var renderTarget=this.renderer._activeRenderTarget;var bounds=maskData.getBounds();bounds.fit(renderTarget.size);maskData.renderable=false;this.renderer.gl.enable(this.renderer.gl.SCISSOR_TEST);var resolution=this.renderer.resolution;this.renderer.gl.scissor(bounds.x*resolution,(renderTarget.root?renderTarget.size.height-bounds.y-bounds.height:bounds.y)*resolution,bounds.width*resolution,bounds.height*resolution);this.scissorRenderTarget=renderTarget;this.scissorData=maskData;this.scissor=true;};/**
     *
     *
     */MaskManager.prototype.popScissorMask=function popScissorMask(){this.scissorRenderTarget=null;this.scissorData=null;this.scissor=false;// must be scissor!
var gl=this.renderer.gl;gl.disable(gl.SCISSOR_TEST);};return MaskManager;}(_WebGLManager3.default);exports.default=MaskManager;},{"../filters/spriteMask/SpriteMaskFilter":85,"./WebGLManager":89}],88:[function(require,module,exports){'use strict';exports.__esModule=true;var _WebGLManager2=require('./WebGLManager');var _WebGLManager3=_interopRequireDefault(_WebGLManager2);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return call&&((typeof call==="undefined"?"undefined":_typeof2(call))==="object"||typeof call==="function")?call:self;}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof2(superClass)));}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass;}/**
 * @class
 * @extends PIXI.WebGLManager
 * @memberof PIXI
 */var StencilManager=function(_WebGLManager){_inherits(StencilManager,_WebGLManager);/**
     * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for.
     */function StencilManager(renderer){_classCallCheck(this,StencilManager);var _this=_possibleConstructorReturn(this,_WebGLManager.call(this,renderer));_this.stencilMaskStack=null;return _this;}/**
     * Changes the mask stack that is used by this manager.
     *
     * @param {PIXI.Graphics[]} stencilMaskStack - The mask stack
     */StencilManager.prototype.setMaskStack=function setMaskStack(stencilMaskStack){this.stencilMaskStack=stencilMaskStack;var gl=this.renderer.gl;if(stencilMaskStack.length===0){gl.disable(gl.STENCIL_TEST);}else{gl.enable(gl.STENCIL_TEST);}};/**
     * Applies the Mask and adds it to the current filter stack. @alvin
     *
     * @param {PIXI.Graphics} graphics - The mask
     */StencilManager.prototype.pushStencil=function pushStencil(graphics){this.renderer.setObjectRenderer(this.renderer.plugins.graphics);this.renderer._activeRenderTarget.attachStencilBuffer();var gl=this.renderer.gl;var sms=this.stencilMaskStack;if(sms.length===0){gl.enable(gl.STENCIL_TEST);gl.clear(gl.STENCIL_BUFFER_BIT);gl.stencilFunc(gl.ALWAYS,1,1);}sms.push(graphics);gl.colorMask(false,false,false,false);gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR);this.renderer.plugins.graphics.render(graphics);gl.colorMask(true,true,true,true);gl.stencilFunc(gl.NOTEQUAL,0,sms.length);gl.stencilOp(gl.KEEP,gl.KEEP,gl.KEEP);};/**
     * TODO @alvin
     */StencilManager.prototype.popStencil=function popStencil(){this.renderer.setObjectRenderer(this.renderer.plugins.graphics);var gl=this.renderer.gl;var sms=this.stencilMaskStack;var graphics=sms.pop();if(sms.length===0){// the stack is empty!
gl.disable(gl.STENCIL_TEST);}else{gl.colorMask(false,false,false,false);gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR);this.renderer.plugins.graphics.render(graphics);gl.colorMask(true,true,true,true);gl.stencilFunc(gl.NOTEQUAL,0,sms.length);gl.stencilOp(gl.KEEP,gl.KEEP,gl.KEEP);}};/**
     * Destroys the mask stack.
     *
     */StencilManager.prototype.destroy=function destroy(){_WebGLManager3.default.prototype.destroy.call(this);this.stencilMaskStack.stencilStack=null;};return StencilManager;}(_WebGLManager3.default);exports.default=StencilManager;},{"./WebGLManager":89}],89:[function(require,module,exports){'use strict';exports.__esModule=true;function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}/**
 * @class
 * @memberof PIXI
 */var WebGLManager=function(){/**
   * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for.
   */function WebGLManager(renderer){_classCallCheck(this,WebGLManager);/**
     * The renderer this manager works for.
     *
     * @member {PIXI.WebGLRenderer}
     */this.renderer=renderer;this.renderer.on('context',this.onContextChange,this);}/**
   * Generic method called when there is a WebGL context change.
   *
   */WebGLManager.prototype.onContextChange=function onContextChange(){}// do some codes init!
/**
   * Generic destroy methods to be overridden by the subclass
   *
   */;WebGLManager.prototype.destroy=function destroy(){this.renderer.off('context',this.onContextChange,this);this.renderer=null;};return WebGLManager;}();exports.default=WebGLManager;},{}],90:[function(require,module,exports){'use strict';exports.__esModule=true;var _WebGLManager2=require('../managers/WebGLManager');var _WebGLManager3=_interopRequireDefault(_WebGLManager2);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return call&&((typeof call==="undefined"?"undefined":_typeof2(call))==="object"||typeof call==="function")?call:self;}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof2(superClass)));}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass;}/**
 * Base for a common object renderer that can be used as a system renderer plugin.
 *
 * @class
 * @extends PIXI.WebGLManager
 * @memberof PIXI
 */var ObjectRenderer=function(_WebGLManager){_inherits(ObjectRenderer,_WebGLManager);function ObjectRenderer(){_classCallCheck(this,ObjectRenderer);return _possibleConstructorReturn(this,_WebGLManager.apply(this,arguments));}/**
   * Starts the renderer and sets the shader
   *
   */ObjectRenderer.prototype.start=function start(){}// set the shader..
/**
   * Stops the renderer
   *
   */;ObjectRenderer.prototype.stop=function stop(){this.flush();};/**
   * Stub method for rendering content and emptying the current batch.
   *
   */ObjectRenderer.prototype.flush=function flush(){}// flush!
/**
   * Renders an object
   *
   * @param {PIXI.DisplayObject} object - The object to render.
   */;ObjectRenderer.prototype.render=function render(object)// eslint-disable-line no-unused-vars
{// render the object
};return ObjectRenderer;}(_WebGLManager3.default);exports.default=ObjectRenderer;},{"../managers/WebGLManager":89}],91:[function(require,module,exports){'use strict';exports.__esModule=true;var _pixiGlCore=require('pixi-gl-core');var _pixiGlCore2=_interopRequireDefault(_pixiGlCore);var _createIndicesForQuads=require('../../../utils/createIndicesForQuads');var _createIndicesForQuads2=_interopRequireDefault(_createIndicesForQuads);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}/**
 * Helper class to create a quad
 *
 * @class
 * @memberof PIXI
 */var Quad=function(){/**
   * @param {WebGLRenderingContext} gl - The gl context for this quad to use.
   * @param {object} state - TODO: Description
   */function Quad(gl,state){_classCallCheck(this,Quad);/*
     * the current WebGL drawing context
     *
     * @member {WebGLRenderingContext}
     */this.gl=gl;/**
     * An array of vertices
     *
     * @member {Float32Array}
     */this.vertices=new Float32Array([-1,-1,1,-1,1,1,-1,1]);/**
     * The Uvs of the quad
     *
     * @member {Float32Array}
     */this.uvs=new Float32Array([0,0,1,0,1,1,0,1]);this.interleaved=new Float32Array(8*2);for(var i=0;i<4;i++){this.interleaved[i*4]=this.vertices[i*2];this.interleaved[i*4+1]=this.vertices[i*2+1];this.interleaved[i*4+2]=this.uvs[i*2];this.interleaved[i*4+3]=this.uvs[i*2+1];}/*
     * @member {Uint16Array} An array containing the indices of the vertices
     */this.indices=(0,_createIndicesForQuads2.default)(1);/*
     * @member {glCore.GLBuffer} The vertex buffer
     */this.vertexBuffer=_pixiGlCore2.default.GLBuffer.createVertexBuffer(gl,this.interleaved,gl.STATIC_DRAW);/*
     * @member {glCore.GLBuffer} The index buffer
     */this.indexBuffer=_pixiGlCore2.default.GLBuffer.createIndexBuffer(gl,this.indices,gl.STATIC_DRAW);/*
     * @member {glCore.VertexArrayObject} The index buffer
     */this.vao=new _pixiGlCore2.default.VertexArrayObject(gl,state);}/**
   * Initialises the vaos and uses the shader.
   *
   * @param {PIXI.Shader} shader - the shader to use
   */Quad.prototype.initVao=function initVao(shader){this.vao.clear().addIndex(this.indexBuffer).addAttribute(this.vertexBuffer,shader.attributes.aVertexPosition,this.gl.FLOAT,false,4*4,0).addAttribute(this.vertexBuffer,shader.attributes.aTextureCoord,this.gl.FLOAT,false,4*4,2*4);};/**
   * Maps two Rectangle to the quad.
   *
   * @param {PIXI.Rectangle} targetTextureFrame - the first rectangle
   * @param {PIXI.Rectangle} destinationFrame - the second rectangle
   * @return {PIXI.Quad} Returns itself.
   */Quad.prototype.map=function map(targetTextureFrame,destinationFrame){var x=0;// destinationFrame.x / targetTextureFrame.width;
var y=0;// destinationFrame.y / targetTextureFrame.height;
this.uvs[0]=x;this.uvs[1]=y;this.uvs[2]=x+destinationFrame.width/targetTextureFrame.width;this.uvs[3]=y;this.uvs[4]=x+destinationFrame.width/targetTextureFrame.width;this.uvs[5]=y+destinationFrame.height/targetTextureFrame.height;this.uvs[6]=x;this.uvs[7]=y+destinationFrame.height/targetTextureFrame.height;x=destinationFrame.x;y=destinationFrame.y;this.vertices[0]=x;this.vertices[1]=y;this.vertices[2]=x+destinationFrame.width;this.vertices[3]=y;this.vertices[4]=x+destinationFrame.width;this.vertices[5]=y+destinationFrame.height;this.vertices[6]=x;this.vertices[7]=y+destinationFrame.height;return this;};/**
   * Binds the buffer and uploads the data
   *
   * @return {PIXI.Quad} Returns itself.
   */Quad.prototype.upload=function upload(){for(var i=0;i<4;i++){this.interleaved[i*4]=this.vertices[i*2];this.interleaved[i*4+1]=this.vertices[i*2+1];this.interleaved[i*4+2]=this.uvs[i*2];this.interleaved[i*4+3]=this.uvs[i*2+1];}this.vertexBuffer.upload(this.interleaved);return this;};/**
   * Removes this quad from WebGL
   */Quad.prototype.destroy=function destroy(){var gl=this.gl;gl.deleteBuffer(this.vertexBuffer);gl.deleteBuffer(this.indexBuffer);};return Quad;}();exports.default=Quad;},{"../../../utils/createIndicesForQuads":115,"pixi-gl-core":12}],92:[function(require,module,exports){'use strict';exports.__esModule=true;var _math=require('../../../math');var _const=require('../../../const');var _settings=require('../../../settings');var _settings2=_interopRequireDefault(_settings);var _pixiGlCore=require('pixi-gl-core');function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}/**
 * @class
 * @memberof PIXI
 */var RenderTarget=function(){/**
   * @param {WebGLRenderingContext} gl - The current WebGL drawing context
   * @param {number} [width=0] - the horizontal range of the filter
   * @param {number} [height=0] - the vertical range of the filter
   * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values
   * @param {number} [resolution=1] - The current resolution / device pixel ratio
   * @param {boolean} [root=false] - Whether this object is the root element or not
   */function RenderTarget(gl,width,height,scaleMode,resolution,root){_classCallCheck(this,RenderTarget);// TODO Resolution could go here ( eg low res blurs )
/**
     * The current WebGL drawing context.
     *
     * @member {WebGLRenderingContext}
     */this.gl=gl;// next time to create a frame buffer and texture
/**
     * A frame buffer
     *
     * @member {PIXI.glCore.GLFramebuffer}
     */this.frameBuffer=null;/**
     * The texture
     *
     * @member {PIXI.glCore.GLTexture}
     */this.texture=null;/**
     * The background colour of this render target, as an array of [r,g,b,a] values
     *
     * @member {number[]}
     */this.clearColor=[0,0,0,0];/**
     * The size of the object as a rectangle
     *
     * @member {PIXI.Rectangle}
     */this.size=new _math.Rectangle(0,0,1,1);/**
     * The current resolution / device pixel ratio
     *
     * @member {number}
     * @default 1
     */this.resolution=resolution||_settings2.default.RESOLUTION;/**
     * The projection matrix
     *
     * @member {PIXI.Matrix}
     */this.projectionMatrix=new _math.Matrix();/**
     * The object's transform
     *
     * @member {PIXI.Matrix}
     */this.transform=null;/**
     * The frame.
     *
     * @member {PIXI.Rectangle}
     */this.frame=null;/**
     * The stencil buffer stores masking data for the render target
     *
     * @member {glCore.GLBuffer}
     */this.defaultFrame=new _math.Rectangle();this.destinationFrame=null;this.sourceFrame=null;/**
     * The stencil buffer stores masking data for the render target
     *
     * @member {glCore.GLBuffer}
     */this.stencilBuffer=null;/**
     * The data structure for the stencil masks
     *
     * @member {PIXI.Graphics[]}
     */this.stencilMaskStack=[];/**
     * Stores filter data for the render target
     *
     * @member {object[]}
     */this.filterData=null;/**
     * The scale mode.
     *
     * @member {number}
     * @default PIXI.settings.SCALE_MODE
     * @see PIXI.SCALE_MODES
     */this.scaleMode=scaleMode||_settings2.default.SCALE_MODE;/**
     * Whether this object is the root element or not
     *
     * @member {boolean}
     */this.root=root;if(!this.root){this.frameBuffer=_pixiGlCore.GLFramebuffer.createRGBA(gl,100,100);if(this.scaleMode===_const.SCALE_MODES.NEAREST){this.frameBuffer.texture.enableNearestScaling();}else{this.frameBuffer.texture.enableLinearScaling();}/*
          A frame buffer needs a target to render to..
          create a texture and bind it attach it to the framebuffer..
       */// this is used by the base texture
this.texture=this.frameBuffer.texture;}else{// make it a null framebuffer..
this.frameBuffer=new _pixiGlCore.GLFramebuffer(gl,100,100);this.frameBuffer.framebuffer=null;}this.setFrame();this.resize(width,height);}/**
   * Clears the filter texture.
   *
   * @param {number[]} [clearColor=this.clearColor] - Array of [r,g,b,a] to clear the framebuffer
   */RenderTarget.prototype.clear=function clear(clearColor){var cc=clearColor||this.clearColor;this.frameBuffer.clear(cc[0],cc[1],cc[2],cc[3]);// r,g,b,a);
};/**
   * Binds the stencil buffer.
   *
   */RenderTarget.prototype.attachStencilBuffer=function attachStencilBuffer(){// TODO check if stencil is done?
/**
     * The stencil buffer is used for masking in pixi
     * lets create one and then add attach it to the framebuffer..
     */if(!this.root){this.frameBuffer.enableStencil();}};/**
   * Sets the frame of the render target.
   *
   * @param {Rectangle} destinationFrame - The destination frame.
   * @param {Rectangle} sourceFrame - The source frame.
   */RenderTarget.prototype.setFrame=function setFrame(destinationFrame,sourceFrame){this.destinationFrame=destinationFrame||this.destinationFrame||this.defaultFrame;this.sourceFrame=sourceFrame||this.sourceFrame||destinationFrame;};/**
   * Binds the buffers and initialises the viewport.
   *
   */RenderTarget.prototype.activate=function activate(){// TOOD refactor usage of frame..
var gl=this.gl;// make sure the texture is unbound!
this.frameBuffer.bind();this.calculateProjection(this.destinationFrame,this.sourceFrame);if(this.transform){this.projectionMatrix.append(this.transform);}// TODO add a check as them may be the same!
if(this.destinationFrame!==this.sourceFrame){gl.enable(gl.SCISSOR_TEST);gl.scissor(this.destinationFrame.x|0,this.destinationFrame.y|0,this.destinationFrame.width*this.resolution|0,this.destinationFrame.height*this.resolution|0);}else{gl.disable(gl.SCISSOR_TEST);}// TODO - does not need to be updated all the time??
gl.viewport(this.destinationFrame.x|0,this.destinationFrame.y|0,this.destinationFrame.width*this.resolution|0,this.destinationFrame.height*this.resolution|0);};/**
   * Updates the projection matrix based on a projection frame (which is a rectangle)
   *
   * @param {Rectangle} destinationFrame - The destination frame.
   * @param {Rectangle} sourceFrame - The source frame.
   */RenderTarget.prototype.calculateProjection=function calculateProjection(destinationFrame,sourceFrame){var pm=this.projectionMatrix;sourceFrame=sourceFrame||destinationFrame;pm.identity();// TODO: make dest scale source
if(!this.root){pm.a=1/destinationFrame.width*2;pm.d=1/destinationFrame.height*2;pm.tx=-1-sourceFrame.x*pm.a;pm.ty=-1-sourceFrame.y*pm.d;}else{pm.a=1/destinationFrame.width*2;pm.d=-1/destinationFrame.height*2;pm.tx=-1-sourceFrame.x*pm.a;pm.ty=1-sourceFrame.y*pm.d;}};/**
   * Resizes the texture to the specified width and height
   *
   * @param {number} width - the new width of the texture
   * @param {number} height - the new height of the texture
   */RenderTarget.prototype.resize=function resize(width,height){width=width|0;height=height|0;if(this.size.width===width&&this.size.height===height){return;}this.size.width=width;this.size.height=height;this.defaultFrame.width=width;this.defaultFrame.height=height;this.frameBuffer.resize(width*this.resolution,height*this.resolution);var projectionFrame=this.frame||this.size;this.calculateProjection(projectionFrame);};/**
   * Destroys the render target.
   *
   */RenderTarget.prototype.destroy=function destroy(){this.frameBuffer.destroy();this.frameBuffer=null;this.texture=null;};return RenderTarget;}();exports.default=RenderTarget;},{"../../../const":42,"../../../math":66,"../../../settings":97,"pixi-gl-core":12}],93:[function(require,module,exports){'use strict';exports.__esModule=true;exports.default=checkMaxIfStatmentsInShader;var _pixiGlCore=require('pixi-gl-core');var _pixiGlCore2=_interopRequireDefault(_pixiGlCore);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}var fragTemplate=['precision mediump float;','void main(void){','float test = 0.1;','%forloop%','gl_FragColor = vec4(0.0);','}'].join('\n');function checkMaxIfStatmentsInShader(maxIfs,gl){var createTempContext=!gl;if(maxIfs===0){throw new Error('Invalid value of `0` passed to `checkMaxIfStatementsInShader`');}if(createTempContext){var tinyCanvas=document.createElement('canvas');tinyCanvas.width=1;tinyCanvas.height=1;gl=_pixiGlCore2.default.createContext(tinyCanvas);}var shader=gl.createShader(gl.FRAGMENT_SHADER);while(true)// eslint-disable-line no-constant-condition
{var fragmentSrc=fragTemplate.replace(/%forloop%/gi,generateIfTestSrc(maxIfs));gl.shaderSource(shader,fragmentSrc);gl.compileShader(shader);if(!gl.getShaderParameter(shader,gl.COMPILE_STATUS)){maxIfs=maxIfs/2|0;}else{// valid!
break;}}if(createTempContext){// get rid of context
if(gl.getExtension('WEBGL_lose_context')){gl.getExtension('WEBGL_lose_context').loseContext();}}return maxIfs;}function generateIfTestSrc(maxIfs){var src='';for(var i=0;i<maxIfs;++i){if(i>0){src+='\nelse ';}if(i<maxIfs-1){src+='if(test == '+i+'.0){}';}}return src;}},{"pixi-gl-core":12}],94:[function(require,module,exports){'use strict';exports.__esModule=true;exports.default=mapWebGLBlendModesToPixi;var _const=require('../../../const');/**
 * Maps gl blend combinations to WebGL.
 *
 * @memberof PIXI
 * @function mapWebGLBlendModesToPixi
 * @private
 * @param {WebGLRenderingContext} gl - The rendering context.
 * @param {string[]} [array=[]] - The array to output into.
 * @return {string[]} Mapped modes.
 */function mapWebGLBlendModesToPixi(gl){var array=arguments.length<=1||arguments[1]===undefined?[]:arguments[1];// TODO - premultiply alpha would be different.
// add a boolean for that!
array[_const.BLEND_MODES.NORMAL]=[gl.ONE,gl.ONE_MINUS_SRC_ALPHA];array[_const.BLEND_MODES.ADD]=[gl.ONE,gl.DST_ALPHA];array[_const.BLEND_MODES.MULTIPLY]=[gl.DST_COLOR,gl.ONE_MINUS_SRC_ALPHA];array[_const.BLEND_MODES.SCREEN]=[gl.ONE,gl.ONE_MINUS_SRC_COLOR];array[_const.BLEND_MODES.OVERLAY]=[gl.ONE,gl.ONE_MINUS_SRC_ALPHA];array[_const.BLEND_MODES.DARKEN]=[gl.ONE,gl.ONE_MINUS_SRC_ALPHA];array[_const.BLEND_MODES.LIGHTEN]=[gl.ONE,gl.ONE_MINUS_SRC_ALPHA];array[_const.BLEND_MODES.COLOR_DODGE]=[gl.ONE,gl.ONE_MINUS_SRC_ALPHA];array[_const.BLEND_MODES.COLOR_BURN]=[gl.ONE,gl.ONE_MINUS_SRC_ALPHA];array[_const.BLEND_MODES.HARD_LIGHT]=[gl.ONE,gl.ONE_MINUS_SRC_ALPHA];array[_const.BLEND_MODES.SOFT_LIGHT]=[gl.ONE,gl.ONE_MINUS_SRC_ALPHA];array[_const.BLEND_MODES.DIFFERENCE]=[gl.ONE,gl.ONE_MINUS_SRC_ALPHA];array[_const.BLEND_MODES.EXCLUSION]=[gl.ONE,gl.ONE_MINUS_SRC_ALPHA];array[_const.BLEND_MODES.HUE]=[gl.ONE,gl.ONE_MINUS_SRC_ALPHA];array[_const.BLEND_MODES.SATURATION]=[gl.ONE,gl.ONE_MINUS_SRC_ALPHA];array[_const.BLEND_MODES.COLOR]=[gl.ONE,gl.ONE_MINUS_SRC_ALPHA];array[_const.BLEND_MODES.LUMINOSITY]=[gl.ONE,gl.ONE_MINUS_SRC_ALPHA];return array;}},{"../../../const":42}],95:[function(require,module,exports){'use strict';exports.__esModule=true;exports.default=mapWebGLDrawModesToPixi;var _const=require('../../../const');/**
 * Generic Mask Stack data structure.
 *
 * @memberof PIXI
 * @function mapWebGLDrawModesToPixi
 * @private
 * @param {WebGLRenderingContext} gl - The current WebGL drawing context
 * @param {object} [object={}] - The object to map into
 * @return {object} The mapped draw modes.
 */function mapWebGLDrawModesToPixi(gl){var object=arguments.length<=1||arguments[1]===undefined?{}:arguments[1];object[_const.DRAW_MODES.POINTS]=gl.POINTS;object[_const.DRAW_MODES.LINES]=gl.LINES;object[_const.DRAW_MODES.LINE_LOOP]=gl.LINE_LOOP;object[_const.DRAW_MODES.LINE_STRIP]=gl.LINE_STRIP;object[_const.DRAW_MODES.TRIANGLES]=gl.TRIANGLES;object[_const.DRAW_MODES.TRIANGLE_STRIP]=gl.TRIANGLE_STRIP;object[_const.DRAW_MODES.TRIANGLE_FAN]=gl.TRIANGLE_FAN;return object;}},{"../../../const":42}],96:[function(require,module,exports){'use strict';exports.__esModule=true;exports.default=validateContext;function validateContext(gl){var attributes=gl.getContextAttributes();// this is going to be fairly simple for now.. but at least we have room to grow!
if(!attributes.stencil){/* eslint-disable no-console */console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly');/* eslint-enable no-console */}}},{}],97:[function(require,module,exports){'use strict';exports.__esModule=true;var _maxRecommendedTextures=require('./utils/maxRecommendedTextures');var _maxRecommendedTextures2=_interopRequireDefault(_maxRecommendedTextures);var _canUploadSameBuffer=require('./utils/canUploadSameBuffer');var _canUploadSameBuffer2=_interopRequireDefault(_canUploadSameBuffer);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}/**
 * @namespace PIXI.settings
 */exports.default={/**
   * Target frames per millisecond.
   *
   * @static
   * @memberof PIXI.settings
   * @type {number}
   * @default 0.06
   */TARGET_FPMS:0.06,/**
   * If set to true WebGL will attempt make textures mimpaped by default.
   * Mipmapping will only succeed if the base texture uploaded has power of two dimensions.
   *
   * @static
   * @memberof PIXI.settings
   * @type {boolean}
   * @default true
   */MIPMAP_TEXTURES:true,/**
   * Default resolution / device pixel ratio of the renderer.
   *
   * @static
   * @memberof PIXI.settings
   * @type {number}
   * @default 1
   */RESOLUTION:1,/**
   * Default filter resolution.
   *
   * @static
   * @memberof PIXI.settings
   * @type {number}
   * @default 1
   */FILTER_RESOLUTION:1,/**
   * The maximum textures that this device supports.
   *
   * @static
   * @memberof PIXI.settings
   * @type {number}
   * @default 32
   */SPRITE_MAX_TEXTURES:(0,_maxRecommendedTextures2.default)(32),// TODO: maybe change to SPRITE.BATCH_SIZE: 2000
// TODO: maybe add PARTICLE.BATCH_SIZE: 15000
/**
   * The default sprite batch size.
   *
   * The default aims to balance desktop and mobile devices.
   *
   * @static
   * @memberof PIXI.settings
   * @type {number}
   * @default 4096
   */SPRITE_BATCH_SIZE:4096,/**
   * The prefix that denotes a URL is for a retina asset.
   *
   * @static
   * @memberof PIXI.settings
   * @type {RegExp|string}
   * @example `@2x`
   * @default /@(.+)x/
   */RETINA_PREFIX:/@(.+)x/,/**
   * The default render options if none are supplied to {@link PIXI.WebGLRenderer}
   * or {@link PIXI.CanvasRenderer}.
   *
   * @static
   * @constant
   * @memberof PIXI.settings
   * @type {object}
   * @property {HTMLCanvasElement} view=null
   * @property {number} resolution=1
   * @property {boolean} antialias=false
   * @property {boolean} forceFXAA=false
   * @property {boolean} autoResize=false
   * @property {boolean} transparent=false
   * @property {number} backgroundColor=0x000000
   * @property {boolean} clearBeforeRender=true
   * @property {boolean} preserveDrawingBuffer=false
   * @property {boolean} roundPixels=false
   */RENDER_OPTIONS:{view:null,antialias:false,forceFXAA:false,autoResize:false,transparent:false,backgroundColor:0x000000,clearBeforeRender:true,preserveDrawingBuffer:false,roundPixels:false},/**
   * Default transform type.
   *
   * @static
   * @memberof PIXI.settings
   * @type {PIXI.TRANSFORM_MODE}
   * @default PIXI.TRANSFORM_MODE.STATIC
   */TRANSFORM_MODE:0,/**
   * Default Garbage Collection mode.
   *
   * @static
   * @memberof PIXI.settings
   * @type {PIXI.GC_MODES}
   * @default PIXI.GC_MODES.AUTO
   */GC_MODE:0,/**
   * Default Garbage Collection max idle.
   *
   * @static
   * @memberof PIXI.settings
   * @type {number}
   * @default 3600
   */GC_MAX_IDLE:60*60,/**
   * Default Garbage Collection maximum check count.
   *
   * @static
   * @memberof PIXI.settings
   * @type {number}
   * @default 600
   */GC_MAX_CHECK_COUNT:60*10,/**
   * Default wrap modes that are supported by pixi.
   *
   * @static
   * @memberof PIXI.settings
   * @type {PIXI.WRAP_MODES}
   * @default PIXI.WRAP_MODES.CLAMP
   */WRAP_MODE:0,/**
   * The scale modes that are supported by pixi.
   *
   * @static
   * @memberof PIXI.settings
   * @type {PIXI.SCALE_MODES}
   * @default PIXI.SCALE_MODES.LINEAR
   */SCALE_MODE:0,/**
   * Default specify float precision in shaders.
   *
   * @static
   * @memberof PIXI.settings
   * @type {PIXI.PRECISION}
   * @default PIXI.PRECISION.MEDIUM
   */PRECISION:'mediump',/**
   * Can we upload the same buffer in a single frame?
   *
   * @static
   * @constant
   * @memberof PIXI
   * @type {boolean}
   */CAN_UPLOAD_SAME_BUFFER:(0,_canUploadSameBuffer2.default)()};},{"./utils/canUploadSameBuffer":114,"./utils/maxRecommendedTextures":118}],98:[function(require,module,exports){'use strict';exports.__esModule=true;var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor);}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor;};}();var _math=require('../math');var _utils=require('../utils');var _const=require('../const');var _Texture=require('../textures/Texture');var _Texture2=_interopRequireDefault(_Texture);var _Container2=require('../display/Container');var _Container3=_interopRequireDefault(_Container2);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return call&&((typeof call==="undefined"?"undefined":_typeof2(call))==="object"||typeof call==="function")?call:self;}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof2(superClass)));}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass;}var tempPoint=new _math.Point();/**
 * The Sprite object is the base for all textured objects that are rendered to the screen
 *
 * A sprite can be created directly from an image like this:
 *
 * ```js
 * let sprite = new PIXI.Sprite.fromImage('assets/image.png');
 * ```
 *
 * @class
 * @extends PIXI.Container
 * @memberof PIXI
 */var Sprite=function(_Container){_inherits(Sprite,_Container);/**
     * @param {PIXI.Texture} texture - The texture for this sprite
     */function Sprite(texture){_classCallCheck(this,Sprite);/**
         * The anchor sets the origin point of the texture.
         * The default is 0,0 this means the texture's origin is the top left
         * Setting the anchor to 0.5,0.5 means the texture's origin is centered
         * Setting the anchor to 1,1 would mean the texture's origin point will be the bottom right corner
         *
         * @member {PIXI.ObservablePoint}
         * @private
         */var _this=_possibleConstructorReturn(this,_Container.call(this));_this._anchor=new _math.ObservablePoint(_this._onAnchorUpdate,_this);/**
         * The texture that the sprite is using
         *
         * @private
         * @member {PIXI.Texture}
         */_this._texture=null;/**
         * The width of the sprite (this is initially set by the texture)
         *
         * @private
         * @member {number}
         */_this._width=0;/**
         * The height of the sprite (this is initially set by the texture)
         *
         * @private
         * @member {number}
         */_this._height=0;/**
         * The tint applied to the sprite. This is a hex value. A value of 0xFFFFFF will remove any tint effect.
         *
         * @private
         * @member {number}
         * @default 0xFFFFFF
         */_this._tint=null;_this._tintRGB=null;_this.tint=0xFFFFFF;/**
         * The blend mode to be applied to the sprite. Apply a value of `PIXI.BLEND_MODES.NORMAL` to reset the blend mode.
         *
         * @member {number}
         * @default PIXI.BLEND_MODES.NORMAL
         * @see PIXI.BLEND_MODES
         */_this.blendMode=_const.BLEND_MODES.NORMAL;/**
         * The shader that will be used to render the sprite. Set to null to remove a current shader.
         *
         * @member {PIXI.Filter|PIXI.Shader}
         */_this.shader=null;/**
         * An internal cached value of the tint.
         *
         * @private
         * @member {number}
         * @default 0xFFFFFF
         */_this.cachedTint=0xFFFFFF;// call texture setter
_this.texture=texture||_Texture2.default.EMPTY;/**
         * this is used to store the vertex data of the sprite (basically a quad)
         *
         * @private
         * @member {Float32Array}
         */_this.vertexData=new Float32Array(8);/**
         * This is used to calculate the bounds of the object IF it is a trimmed sprite
         *
         * @private
         * @member {Float32Array}
         */_this.vertexTrimmedData=null;_this._transformID=-1;_this._textureID=-1;/**
         * Plugin that is responsible for rendering this element.
         * Allows to customize the rendering process without overriding '_renderWebGL' & '_renderCanvas' methods.
         *
         * @member {string}
         * @default 'sprite'
         */_this.pluginName='sprite';return _this;}/**
     * When the texture is updated, this event will fire to update the scale and frame
     *
     * @private
     */Sprite.prototype._onTextureUpdate=function _onTextureUpdate(){this._textureID=-1;// so if _width is 0 then width was not set..
if(this._width){this.scale.x=(0,_utils.sign)(this.scale.x)*this._width/this.texture.orig.width;}if(this._height){this.scale.y=(0,_utils.sign)(this.scale.y)*this._height/this.texture.orig.height;}};/**
     * Called when the anchor position updates.
     *
     * @private
     */Sprite.prototype._onAnchorUpdate=function _onAnchorUpdate(){this._transformID=-1;};/**
     * calculates worldTransform * vertices, store it in vertexData
     */Sprite.prototype.calculateVertices=function calculateVertices(){if(this._transformID===this.transform._worldID&&this._textureID===this._texture._updateID){return;}this._transformID=this.transform._worldID;this._textureID=this._texture._updateID;// set the vertex data
var texture=this._texture;var wt=this.transform.worldTransform;var a=wt.a;var b=wt.b;var c=wt.c;var d=wt.d;var tx=wt.tx;var ty=wt.ty;var vertexData=this.vertexData;var trim=texture.trim;var orig=texture.orig;var anchor=this._anchor;var w0=0;var w1=0;var h0=0;var h1=0;if(trim){// if the sprite is trimmed and is not a tilingsprite then we need to add the extra
// space before transforming the sprite coords.
w1=trim.x-anchor._x*orig.width;w0=w1+trim.width;h1=trim.y-anchor._y*orig.height;h0=h1+trim.height;}else{w0=orig.width*(1-anchor._x);w1=orig.width*-anchor._x;h0=orig.height*(1-anchor._y);h1=orig.height*-anchor._y;}// xy
vertexData[0]=a*w1+c*h1+tx;vertexData[1]=d*h1+b*w1+ty;// xy
vertexData[2]=a*w0+c*h1+tx;vertexData[3]=d*h1+b*w0+ty;// xy
vertexData[4]=a*w0+c*h0+tx;vertexData[5]=d*h0+b*w0+ty;// xy
vertexData[6]=a*w1+c*h0+tx;vertexData[7]=d*h0+b*w1+ty;};/**
     * calculates worldTransform * vertices for a non texture with a trim. store it in vertexTrimmedData
     * This is used to ensure that the true width and height of a trimmed texture is respected
     */Sprite.prototype.calculateTrimmedVertices=function calculateTrimmedVertices(){if(!this.vertexTrimmedData){this.vertexTrimmedData=new Float32Array(8);}// lets do some special trim code!
var texture=this._texture;var vertexData=this.vertexTrimmedData;var orig=texture.orig;var anchor=this._anchor;// lets calculate the new untrimmed bounds..
var wt=this.transform.worldTransform;var a=wt.a;var b=wt.b;var c=wt.c;var d=wt.d;var tx=wt.tx;var ty=wt.ty;var w0=orig.width*(1-anchor._x);var w1=orig.width*-anchor._x;var h0=orig.height*(1-anchor._y);var h1=orig.height*-anchor._y;// xy
vertexData[0]=a*w1+c*h1+tx;vertexData[1]=d*h1+b*w1+ty;// xy
vertexData[2]=a*w0+c*h1+tx;vertexData[3]=d*h1+b*w0+ty;// xy
vertexData[4]=a*w0+c*h0+tx;vertexData[5]=d*h0+b*w0+ty;// xy
vertexData[6]=a*w1+c*h0+tx;vertexData[7]=d*h0+b*w1+ty;};/**
    *
    * Renders the object using the WebGL renderer
    *
    * @private
    * @param {PIXI.WebGLRenderer} renderer - The webgl renderer to use.
    */Sprite.prototype._renderWebGL=function _renderWebGL(renderer){this.calculateVertices();renderer.setObjectRenderer(renderer.plugins[this.pluginName]);renderer.plugins[this.pluginName].render(this);};/**
    * Renders the object using the Canvas renderer
    *
    * @private
    * @param {PIXI.CanvasRenderer} renderer - The renderer
    */Sprite.prototype._renderCanvas=function _renderCanvas(renderer){renderer.plugins[this.pluginName].render(this);};/**
     * Updates the bounds of the sprite.
     *
     * @private
     */Sprite.prototype._calculateBounds=function _calculateBounds(){var trim=this._texture.trim;var orig=this._texture.orig;// First lets check to see if the current texture has a trim..
if(!trim||trim.width===orig.width&&trim.height===orig.height){// no trim! lets use the usual calculations..
this.calculateVertices();this._bounds.addQuad(this.vertexData);}else{// lets calculate a special trimmed bounds...
this.calculateTrimmedVertices();this._bounds.addQuad(this.vertexTrimmedData);}};/**
     * Gets the local bounds of the sprite object.
     *
     * @param {Rectangle} rect - The output rectangle.
     * @return {Rectangle} The bounds.
     */Sprite.prototype.getLocalBounds=function getLocalBounds(rect){// we can do a fast local bounds if the sprite has no children!
if(this.children.length===0){this._bounds.minX=this._texture.orig.width*-this._anchor._x;this._bounds.minY=this._texture.orig.height*-this._anchor._y;this._bounds.maxX=this._texture.orig.width*(1-this._anchor._x);this._bounds.maxY=this._texture.orig.height*(1-this._anchor._x);if(!rect){if(!this._localBoundsRect){this._localBoundsRect=new _math.Rectangle();}rect=this._localBoundsRect;}return this._bounds.getRectangle(rect);}return _Container.prototype.getLocalBounds.call(this,rect);};/**
     * Tests if a point is inside this sprite
     *
     * @param {PIXI.Point} point - the point to test
     * @return {boolean} the result of the test
     */Sprite.prototype.containsPoint=function containsPoint(point){this.worldTransform.applyInverse(point,tempPoint);var width=this._texture.orig.width;var height=this._texture.orig.height;var x1=-width*this.anchor.x;var y1=0;if(tempPoint.x>x1&&tempPoint.x<x1+width){y1=-height*this.anchor.y;if(tempPoint.y>y1&&tempPoint.y<y1+height){return true;}}return false;};/**
     * Destroys this sprite and optionally its texture and children
     *
     * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options
     *  have been set to that value
     * @param {boolean} [options.children=false] - if set to true, all the children will have their destroy
     *      method called as well. 'options' will be passed on to those calls.
     * @param {boolean} [options.texture=false] - Should it destroy the current texture of the sprite as well
     * @param {boolean} [options.baseTexture=false] - Should it destroy the base texture of the sprite as well
     */Sprite.prototype.destroy=function destroy(options){_Container.prototype.destroy.call(this,options);this._anchor=null;var destroyTexture=typeof options==='boolean'?options:options&&options.texture;if(destroyTexture){var destroyBaseTexture=typeof options==='boolean'?options:options&&options.baseTexture;this._texture.destroy(!!destroyBaseTexture);}this._texture=null;this.shader=null;};// some helper functions..
/**
     * Helper function that creates a new sprite based on the source you provide.
     * The source can be - frame id, image url, video url, canvas element, video element, base texture
     *
     * @static
     * @param {number|string|PIXI.BaseTexture|HTMLCanvasElement|HTMLVideoElement} source Source to create texture from
     * @return {PIXI.Texture} The newly created texture
     */Sprite.from=function from(source){return new Sprite(_Texture2.default.from(source));};/**
     * Helper function that creates a sprite that will contain a texture from the TextureCache based on the frameId
     * The frame ids are created when a Texture packer file has been loaded
     *
     * @static
     * @param {string} frameId - The frame Id of the texture in the cache
     * @return {PIXI.Sprite} A new Sprite using a texture from the texture cache matching the frameId
     */Sprite.fromFrame=function fromFrame(frameId){var texture=_utils.TextureCache[frameId];if(!texture){throw new Error('The frameId "'+frameId+'" does not exist in the texture cache');}return new Sprite(texture);};/**
     * Helper function that creates a sprite that will contain a texture based on an image url
     * If the image is not in the texture cache it will be loaded
     *
     * @static
     * @param {string} imageId - The image url of the texture
     * @param {boolean} [crossorigin=(auto)] - if you want to specify the cross-origin parameter
     * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - if you want to specify the scale mode,
     *  see {@link PIXI.SCALE_MODES} for possible values
     * @return {PIXI.Sprite} A new Sprite using a texture from the texture cache matching the image id
     */Sprite.fromImage=function fromImage(imageId,crossorigin,scaleMode){return new Sprite(_Texture2.default.fromImage(imageId,crossorigin,scaleMode));};/**
     * The width of the sprite, setting this will actually modify the scale to achieve the value set
     *
     * @member {number}
     * @memberof PIXI.Sprite#
     */_createClass(Sprite,[{key:'width',get:function get(){return Math.abs(this.scale.x)*this._texture.orig.width;}/**
         * Sets the width of the sprite by modifying the scale.
         *
         * @param {number} value - The value to set to.
         */,set:function set(value){var s=(0,_utils.sign)(this.scale.x)||1;this.scale.x=s*value/this._texture.orig.width;this._width=value;}/**
         * The height of the sprite, setting this will actually modify the scale to achieve the value set
         *
         * @member {number}
         * @memberof PIXI.Sprite#
         */},{key:'height',get:function get(){return Math.abs(this.scale.y)*this._texture.orig.height;}/**
         * Sets the height of the sprite by modifying the scale.
         *
         * @param {number} value - The value to set to.
         */,set:function set(value){var s=(0,_utils.sign)(this.scale.y)||1;this.scale.y=s*value/this._texture.orig.height;this._height=value;}/**
         * The anchor sets the origin point of the texture.
         * The default is 0,0 this means the texture's origin is the top left
         * Setting the anchor to 0.5,0.5 means the texture's origin is centered
         * Setting the anchor to 1,1 would mean the texture's origin point will be the bottom right corner
         *
         * @member {PIXI.ObservablePoint}
         * @memberof PIXI.Sprite#
         */},{key:'anchor',get:function get(){return this._anchor;}/**
         * Copies the anchor to the sprite.
         *
         * @param {number} value - The value to set to.
         */,set:function set(value){this._anchor.copy(value);}/**
         * The tint applied to the sprite. This is a hex value. A value of
         * 0xFFFFFF will remove any tint effect.
         *
         * @member {number}
         * @memberof PIXI.Sprite#
         * @default 0xFFFFFF
         */},{key:'tint',get:function get(){return this._tint;}/**
         * Sets the tint of the sprite.
         *
         * @param {number} value - The value to set to.
         */,set:function set(value){this._tint=value;this._tintRGB=(value>>16)+(value&0xff00)+((value&0xff)<<16);}/**
         * The texture that the sprite is using
         *
         * @member {PIXI.Texture}
         * @memberof PIXI.Sprite#
         */},{key:'texture',get:function get(){return this._texture;}/**
         * Sets the texture of the sprite.
         *
         * @param {PIXI.Texture} value - The value to set to.
         */,set:function set(value){if(this._texture===value){return;}this._texture=value;this.cachedTint=0xFFFFFF;this._textureID=-1;if(value){// wait for the texture to load
if(value.baseTexture.hasLoaded){this._onTextureUpdate();}else{value.once('update',this._onTextureUpdate,this);}}}}]);return Sprite;}(_Container3.default);exports.default=Sprite;},{"../const":42,"../display/Container":44,"../math":66,"../textures/Texture":109,"../utils":117}],99:[function(require,module,exports){'use strict';exports.__esModule=true;var _CanvasRenderer=require('../../renderers/canvas/CanvasRenderer');var _CanvasRenderer2=_interopRequireDefault(_CanvasRenderer);var _const=require('../../const');var _math=require('../../math');var _CanvasTinter=require('./CanvasTinter');var _CanvasTinter2=_interopRequireDefault(_CanvasTinter);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}var canvasRenderWorldTransform=new _math.Matrix();/**
 * @author Mat Groves
 *
 * Big thanks to the very clever Matt DesLauriers <mattdesl> https://github.com/mattdesl/
 * for creating the original pixi version!
 * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they now
 * share 4 bytes on the vertex buffer
 *
 * Heavily inspired by LibGDX's CanvasSpriteRenderer:
 * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/CanvasSpriteRenderer.java
 *//**
 * Renderer dedicated to drawing and batching sprites.
 *
 * @class
 * @private
 * @memberof PIXI
 */var CanvasSpriteRenderer=function(){/**
     * @param {PIXI.WebGLRenderer} renderer -The renderer sprite this batch works for.
     */function CanvasSpriteRenderer(renderer){_classCallCheck(this,CanvasSpriteRenderer);this.renderer=renderer;}/**
     * Renders the sprite object.
     *
     * @param {PIXI.Sprite} sprite - the sprite to render when using this spritebatch
     */CanvasSpriteRenderer.prototype.render=function render(sprite){var texture=sprite._texture;var renderer=this.renderer;var width=texture._frame.width;var height=texture._frame.height;var wt=sprite.transform.worldTransform;var dx=0;var dy=0;if(texture.orig.width<=0||texture.orig.height<=0||!texture.baseTexture.source){return;}renderer.setBlendMode(sprite.blendMode);//  Ignore null sources
if(texture.valid){renderer.context.globalAlpha=sprite.worldAlpha;// If smoothingEnabled is supported and we need to change the smoothing property for sprite texture
var smoothingEnabled=texture.baseTexture.scaleMode===_const.SCALE_MODES.LINEAR;if(renderer.smoothProperty&&renderer.context[renderer.smoothProperty]!==smoothingEnabled){renderer.context[renderer.smoothProperty]=smoothingEnabled;}if(texture.trim){dx=texture.trim.width/2+texture.trim.x-sprite.anchor.x*texture.orig.width;dy=texture.trim.height/2+texture.trim.y-sprite.anchor.y*texture.orig.height;}else{dx=(0.5-sprite.anchor.x)*texture.orig.width;dy=(0.5-sprite.anchor.y)*texture.orig.height;}if(texture.rotate){wt.copy(canvasRenderWorldTransform);wt=canvasRenderWorldTransform;_math.GroupD8.matrixAppendRotationInv(wt,texture.rotate,dx,dy);// the anchor has already been applied above, so lets set it to zero
dx=0;dy=0;}dx-=width/2;dy-=height/2;// Allow for pixel rounding
if(renderer.roundPixels){renderer.context.setTransform(wt.a,wt.b,wt.c,wt.d,wt.tx*renderer.resolution|0,wt.ty*renderer.resolution|0);dx=dx|0;dy=dy|0;}else{renderer.context.setTransform(wt.a,wt.b,wt.c,wt.d,wt.tx*renderer.resolution,wt.ty*renderer.resolution);}var resolution=texture.baseTexture.resolution;if(sprite.tint!==0xFFFFFF){if(sprite.cachedTint!==sprite.tint){sprite.cachedTint=sprite.tint;// TODO clean up caching - how to clean up the caches?
sprite.tintedTexture=_CanvasTinter2.default.getTintedTexture(sprite,sprite.tint);}renderer.context.drawImage(sprite.tintedTexture,0,0,width*resolution,height*resolution,dx*renderer.resolution,dy*renderer.resolution,width*renderer.resolution,height*renderer.resolution);}else{renderer.context.drawImage(texture.baseTexture.source,texture._frame.x*resolution,texture._frame.y*resolution,width*resolution,height*resolution,dx*renderer.resolution,dy*renderer.resolution,width*renderer.resolution,height*renderer.resolution);}}};/**
     * destroy the sprite object.
     *
     */CanvasSpriteRenderer.prototype.destroy=function destroy(){this.renderer=null;};return CanvasSpriteRenderer;}();exports.default=CanvasSpriteRenderer;_CanvasRenderer2.default.registerPlugin('sprite',CanvasSpriteRenderer);},{"../../const":42,"../../math":66,"../../renderers/canvas/CanvasRenderer":73,"./CanvasTinter":100}],100:[function(require,module,exports){'use strict';exports.__esModule=true;var _utils=require('../../utils');var _canUseNewCanvasBlendModes=require('../../renderers/canvas/utils/canUseNewCanvasBlendModes');var _canUseNewCanvasBlendModes2=_interopRequireDefault(_canUseNewCanvasBlendModes);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}/**
 * Utility methods for Sprite/Texture tinting.
 *
 * @namespace PIXI.CanvasTinter
 */var CanvasTinter={/**
     * Basically this method just needs a sprite and a color and tints the sprite with the given color.
     *
     * @memberof PIXI.CanvasTinter
     * @param {PIXI.Sprite} sprite - the sprite to tint
     * @param {number} color - the color to use to tint the sprite with
     * @return {HTMLCanvasElement} The tinted canvas
     */getTintedTexture:function getTintedTexture(sprite,color){var texture=sprite.texture;color=CanvasTinter.roundColor(color);var stringColor='#'+('00000'+(color|0).toString(16)).substr(-6);texture.tintCache=texture.tintCache||{};if(texture.tintCache[stringColor]){return texture.tintCache[stringColor];}// clone texture..
var canvas=CanvasTinter.canvas||document.createElement('canvas');// CanvasTinter.tintWithPerPixel(texture, stringColor, canvas);
CanvasTinter.tintMethod(texture,color,canvas);if(CanvasTinter.convertTintToImage){// is this better?
var tintImage=new Image();tintImage.src=canvas.toDataURL();texture.tintCache[stringColor]=tintImage;}else{texture.tintCache[stringColor]=canvas;// if we are not converting the texture to an image then we need to lose the reference to the canvas
CanvasTinter.canvas=null;}return canvas;},/**
     * Tint a texture using the 'multiply' operation.
     *
     * @memberof PIXI.CanvasTinter
     * @param {PIXI.Texture} texture - the texture to tint
     * @param {number} color - the color to use to tint the sprite with
     * @param {HTMLCanvasElement} canvas - the current canvas
     */tintWithMultiply:function tintWithMultiply(texture,color,canvas){var context=canvas.getContext('2d');var crop=texture._frame.clone();var resolution=texture.baseTexture.resolution;crop.x*=resolution;crop.y*=resolution;crop.width*=resolution;crop.height*=resolution;canvas.width=crop.width;canvas.height=crop.height;context.fillStyle='#'+('00000'+(color|0).toString(16)).substr(-6);context.fillRect(0,0,crop.width,crop.height);context.globalCompositeOperation='multiply';context.drawImage(texture.baseTexture.source,crop.x,crop.y,crop.width,crop.height,0,0,crop.width,crop.height);context.globalCompositeOperation='destination-atop';context.drawImage(texture.baseTexture.source,crop.x,crop.y,crop.width,crop.height,0,0,crop.width,crop.height);},/**
     * Tint a texture using the 'overlay' operation.
     *
     * @memberof PIXI.CanvasTinter
     * @param {PIXI.Texture} texture - the texture to tint
     * @param {number} color - the color to use to tint the sprite with
     * @param {HTMLCanvasElement} canvas - the current canvas
     */tintWithOverlay:function tintWithOverlay(texture,color,canvas){var context=canvas.getContext('2d');var crop=texture._frame.clone();var resolution=texture.baseTexture.resolution;crop.x*=resolution;crop.y*=resolution;crop.width*=resolution;crop.height*=resolution;canvas.width=crop.width;canvas.height=crop.height;context.globalCompositeOperation='copy';context.fillStyle='#'+('00000'+(color|0).toString(16)).substr(-6);context.fillRect(0,0,crop.width,crop.height);context.globalCompositeOperation='destination-atop';context.drawImage(texture.baseTexture.source,crop.x,crop.y,crop.width,crop.height,0,0,crop.width,crop.height);// context.globalCompositeOperation = 'copy';
},/**
     * Tint a texture pixel per pixel.
     *
     * @memberof PIXI.CanvasTinter
     * @param {PIXI.Texture} texture - the texture to tint
     * @param {number} color - the color to use to tint the sprite with
     * @param {HTMLCanvasElement} canvas - the current canvas
     */tintWithPerPixel:function tintWithPerPixel(texture,color,canvas){var context=canvas.getContext('2d');var crop=texture._frame.clone();var resolution=texture.baseTexture.resolution;crop.x*=resolution;crop.y*=resolution;crop.width*=resolution;crop.height*=resolution;canvas.width=crop.width;canvas.height=crop.height;context.globalCompositeOperation='copy';context.drawImage(texture.baseTexture.source,crop.x,crop.y,crop.width,crop.height,0,0,crop.width,crop.height);var rgbValues=(0,_utils.hex2rgb)(color);var r=rgbValues[0];var g=rgbValues[1];var b=rgbValues[2];var pixelData=context.getImageData(0,0,crop.width,crop.height);var pixels=pixelData.data;for(var i=0;i<pixels.length;i+=4){pixels[i+0]*=r;pixels[i+1]*=g;pixels[i+2]*=b;}context.putImageData(pixelData,0,0);},/**
     * Rounds the specified color according to the CanvasTinter.cacheStepsPerColorChannel.
     *
     * @memberof PIXI.CanvasTinter
     * @param {number} color - the color to round, should be a hex color
     * @return {number} The rounded color.
     */roundColor:function roundColor(color){var step=CanvasTinter.cacheStepsPerColorChannel;var rgbValues=(0,_utils.hex2rgb)(color);rgbValues[0]=Math.min(255,rgbValues[0]/step*step);rgbValues[1]=Math.min(255,rgbValues[1]/step*step);rgbValues[2]=Math.min(255,rgbValues[2]/step*step);return(0,_utils.rgb2hex)(rgbValues);},/**
     * Number of steps which will be used as a cap when rounding colors.
     *
     * @memberof PIXI.CanvasTinter
     * @type {number}
     */cacheStepsPerColorChannel:8,/**
     * Tint cache boolean flag.
     *
     * @memberof PIXI.CanvasTinter
     * @type {boolean}
     */convertTintToImage:false,/**
     * Whether or not the Canvas BlendModes are supported, consequently the ability to tint using the multiply method.
     *
     * @memberof PIXI.CanvasTinter
     * @type {boolean}
     */canUseMultiply:(0,_canUseNewCanvasBlendModes2.default)(),/**
     * The tinting method that will be used.
     *
     * @memberof PIXI.CanvasTinter
     * @type {tintMethodFunctionType}
     */tintMethod:0};CanvasTinter.tintMethod=CanvasTinter.canUseMultiply?CanvasTinter.tintWithMultiply:CanvasTinter.tintWithPerPixel;/**
 * The tintMethod type.
 *
 * @memberof PIXI.CanvasTinter
 * @callback tintMethodFunctionType
 * @param texture {PIXI.Texture} the texture to tint
 * @param color {number} the color to use to tint the sprite with
 * @param canvas {HTMLCanvasElement} the current canvas
 */exports.default=CanvasTinter;},{"../../renderers/canvas/utils/canUseNewCanvasBlendModes":76,"../../utils":117}],101:[function(require,module,exports){"use strict";exports.__esModule=true;function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}/**
 * @class
 */var Buffer=function(){/**
   * @param {number} size - The size of the buffer in bytes.
   */function Buffer(size){_classCallCheck(this,Buffer);this.vertices=new ArrayBuffer(size);/**
     * View on the vertices as a Float32Array for positions
     *
     * @member {Float32Array}
     */this.float32View=new Float32Array(this.vertices);/**
     * View on the vertices as a Uint32Array for uvs
     *
     * @member {Float32Array}
     */this.uint32View=new Uint32Array(this.vertices);}/**
   * Destroys the buffer.
   *
   */Buffer.prototype.destroy=function destroy(){this.vertices=null;this.positions=null;this.uvs=null;this.colors=null;};return Buffer;}();exports.default=Buffer;},{}],102:[function(require,module,exports){'use strict';exports.__esModule=true;var _ObjectRenderer2=require('../../renderers/webgl/utils/ObjectRenderer');var _ObjectRenderer3=_interopRequireDefault(_ObjectRenderer2);var _WebGLRenderer=require('../../renderers/webgl/WebGLRenderer');var _WebGLRenderer2=_interopRequireDefault(_WebGLRenderer);var _createIndicesForQuads=require('../../utils/createIndicesForQuads');var _createIndicesForQuads2=_interopRequireDefault(_createIndicesForQuads);var _generateMultiTextureShader=require('./generateMultiTextureShader');var _generateMultiTextureShader2=_interopRequireDefault(_generateMultiTextureShader);var _checkMaxIfStatmentsInShader=require('../../renderers/webgl/utils/checkMaxIfStatmentsInShader');var _checkMaxIfStatmentsInShader2=_interopRequireDefault(_checkMaxIfStatmentsInShader);var _BatchBuffer=require('./BatchBuffer');var _BatchBuffer2=_interopRequireDefault(_BatchBuffer);var _settings=require('../../settings');var _settings2=_interopRequireDefault(_settings);var _pixiGlCore=require('pixi-gl-core');var _pixiGlCore2=_interopRequireDefault(_pixiGlCore);var _bitTwiddle=require('bit-twiddle');var _bitTwiddle2=_interopRequireDefault(_bitTwiddle);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return call&&((typeof call==="undefined"?"undefined":_typeof2(call))==="object"||typeof call==="function")?call:self;}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof2(superClass)));}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass;}var TICK=0;var TEXTURE_TICK=0;/**
 * Renderer dedicated to drawing and batching sprites.
 *
 * @class
 * @private
 * @memberof PIXI
 * @extends PIXI.ObjectRenderer
 */var SpriteRenderer=function(_ObjectRenderer){_inherits(SpriteRenderer,_ObjectRenderer);/**
     * @param {PIXI.WebGLRenderer} renderer - The renderer this sprite batch works for.
     */function SpriteRenderer(renderer){_classCallCheck(this,SpriteRenderer);/**
         * Number of values sent in the vertex buffer.
         * positionX, positionY, colorR, colorG, colorB = 5
         *
         * @member {number}
         */var _this=_possibleConstructorReturn(this,_ObjectRenderer.call(this,renderer));_this.vertSize=5;/**
         * The size of the vertex information in bytes.
         *
         * @member {number}
         */_this.vertByteSize=_this.vertSize*4;/**
         * The number of images in the SpriteRenderer before it flushes.
         *
         * @member {number}
         */_this.size=_settings2.default.SPRITE_BATCH_SIZE;// 2000 is a nice balance between mobile / desktop
// the total number of bytes in our batch
// let numVerts = this.size * 4 * this.vertByteSize;
_this.buffers=[];for(var i=1;i<=_bitTwiddle2.default.nextPow2(_this.size);i*=2){_this.buffers.push(new _BatchBuffer2.default(i*4*_this.vertByteSize));}/**
         * Holds the indices of the geometry (quads) to draw
         *
         * @member {Uint16Array}
         */_this.indices=(0,_createIndicesForQuads2.default)(_this.size);/**
         * The default shaders that is used if a sprite doesn't have a more specific one.
         * there is a shader for each number of textures that can be rendererd.
         * These shaders will also be generated on the fly as required.
         * @member {PIXI.Shader[]}
         */_this.shader=null;_this.currentIndex=0;TICK=0;_this.groups=[];for(var k=0;k<_this.size;k++){_this.groups[k]={textures:[],textureCount:0,ids:[],size:0,start:0,blend:0};}_this.sprites=[];_this.vertexBuffers=[];_this.vaos=[];_this.vaoMax=2;_this.vertexCount=0;_this.renderer.on('prerender',_this.onPrerender,_this);return _this;}/**
     * Sets up the renderer context and necessary buffers.
     *
     * @private
     */SpriteRenderer.prototype.onContextChange=function onContextChange(){var gl=this.renderer.gl;// step 1: first check max textures the GPU can handle.
this.MAX_TEXTURES=Math.min(gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS),_settings2.default.SPRITE_MAX_TEXTURES);// step 2: check the maximum number of if statements the shader can have too..
this.MAX_TEXTURES=(0,_checkMaxIfStatmentsInShader2.default)(this.MAX_TEXTURES,gl);var shader=this.shader=(0,_generateMultiTextureShader2.default)(gl,this.MAX_TEXTURES);// create a couple of buffers
this.indexBuffer=_pixiGlCore2.default.GLBuffer.createIndexBuffer(gl,this.indices,gl.STATIC_DRAW);// we use the second shader as the first one depending on your browser may omit aTextureId
// as it is not used by the shader so is optimized out.
this.renderer.bindVao(null);for(var i=0;i<this.vaoMax;i++){this.vertexBuffers[i]=_pixiGlCore2.default.GLBuffer.createVertexBuffer(gl,null,gl.STREAM_DRAW);/* eslint-disable max-len */// build the vao object that will render..
this.vaos[i]=this.renderer.createVao().addIndex(this.indexBuffer).addAttribute(this.vertexBuffers[i],shader.attributes.aVertexPosition,gl.FLOAT,false,this.vertByteSize,0).addAttribute(this.vertexBuffers[i],shader.attributes.aTextureCoord,gl.UNSIGNED_SHORT,true,this.vertByteSize,2*4).addAttribute(this.vertexBuffers[i],shader.attributes.aColor,gl.UNSIGNED_BYTE,true,this.vertByteSize,3*4).addAttribute(this.vertexBuffers[i],shader.attributes.aTextureId,gl.FLOAT,false,this.vertByteSize,4*4);/* eslint-disable max-len */}this.vao=this.vaos[0];this.currentBlendMode=99999;this.boundTextures=new Array(this.MAX_TEXTURES);};/**
     * Called before the renderer starts rendering.
     *
     */SpriteRenderer.prototype.onPrerender=function onPrerender(){this.vertexCount=0;};/**
     * Renders the sprite object.
     *
     * @param {PIXI.Sprite} sprite - the sprite to render when using this spritebatch
     */SpriteRenderer.prototype.render=function render(sprite){// TODO set blend modes..
// check texture..
if(this.currentIndex>=this.size){this.flush();}// get the uvs for the texture
// if the uvs have not updated then no point rendering just yet!
if(!sprite._texture._uvs){return;}// push a texture.
// increment the batchsize
this.sprites[this.currentIndex++]=sprite;};/**
     * Renders the content and empties the current batch.
     *
     */SpriteRenderer.prototype.flush=function flush(){if(this.currentIndex===0){return;}var gl=this.renderer.gl;var MAX_TEXTURES=this.MAX_TEXTURES;var np2=_bitTwiddle2.default.nextPow2(this.currentIndex);var log2=_bitTwiddle2.default.log2(np2);var buffer=this.buffers[log2];var sprites=this.sprites;var groups=this.groups;var float32View=buffer.float32View;var uint32View=buffer.uint32View;var boundTextures=this.boundTextures;var rendererBoundTextures=this.renderer.boundTextures;var touch=this.renderer.textureGC.count;var index=0;var nextTexture=void 0;var currentTexture=void 0;var groupCount=1;var textureCount=0;var currentGroup=groups[0];var vertexData=void 0;var uvs=void 0;var blendMode=sprites[0].blendMode;currentGroup.textureCount=0;currentGroup.start=0;currentGroup.blend=blendMode;TICK++;var i=void 0;// copy textures..
for(i=0;i<MAX_TEXTURES;++i){boundTextures[i]=rendererBoundTextures[i];boundTextures[i]._virtalBoundId=i;}for(i=0;i<this.currentIndex;++i){// upload the sprite elemetns...
// they have all ready been calculated so we just need to push them into the buffer.
var sprite=sprites[i];nextTexture=sprite._texture.baseTexture;if(blendMode!==sprite.blendMode){// finish a group..
blendMode=sprite.blendMode;// force the batch to break!
currentTexture=null;textureCount=MAX_TEXTURES;TICK++;}if(currentTexture!==nextTexture){currentTexture=nextTexture;if(nextTexture._enabled!==TICK){if(textureCount===MAX_TEXTURES){TICK++;currentGroup.size=i-currentGroup.start;textureCount=0;currentGroup=groups[groupCount++];currentGroup.blend=blendMode;currentGroup.textureCount=0;currentGroup.start=i;}nextTexture.touched=touch;if(nextTexture._virtalBoundId===-1){for(var j=0;j<MAX_TEXTURES;++j){var tIndex=(j+TEXTURE_TICK)%MAX_TEXTURES;var t=boundTextures[tIndex];if(t._enabled!==TICK){TEXTURE_TICK++;t._virtalBoundId=-1;nextTexture._virtalBoundId=tIndex;boundTextures[tIndex]=nextTexture;break;}}}nextTexture._enabled=TICK;currentGroup.textureCount++;currentGroup.ids[textureCount]=nextTexture._virtalBoundId;currentGroup.textures[textureCount++]=nextTexture;}}vertexData=sprite.vertexData;// TODO this sum does not need to be set each frame..
uvs=sprite._texture._uvs.uvsUint32;if(this.renderer.roundPixels){var resolution=this.renderer.resolution;// xy
float32View[index]=(vertexData[0]*resolution|0)/resolution;float32View[index+1]=(vertexData[1]*resolution|0)/resolution;// xy
float32View[index+5]=(vertexData[2]*resolution|0)/resolution;float32View[index+6]=(vertexData[3]*resolution|0)/resolution;// xy
float32View[index+10]=(vertexData[4]*resolution|0)/resolution;float32View[index+11]=(vertexData[5]*resolution|0)/resolution;// xy
float32View[index+15]=(vertexData[6]*resolution|0)/resolution;float32View[index+16]=(vertexData[7]*resolution|0)/resolution;}else{// xy
float32View[index]=vertexData[0];float32View[index+1]=vertexData[1];// xy
float32View[index+5]=vertexData[2];float32View[index+6]=vertexData[3];// xy
float32View[index+10]=vertexData[4];float32View[index+11]=vertexData[5];// xy
float32View[index+15]=vertexData[6];float32View[index+16]=vertexData[7];}uint32View[index+2]=uvs[0];uint32View[index+7]=uvs[1];uint32View[index+12]=uvs[2];uint32View[index+17]=uvs[3];uint32View[index+3]=uint32View[index+8]=uint32View[index+13]=uint32View[index+18]=sprite._tintRGB+(Math.min(sprite.worldAlpha,1)*255<<24);float32View[index+4]=float32View[index+9]=float32View[index+14]=float32View[index+19]=nextTexture._virtalBoundId;index+=20;}currentGroup.size=i-currentGroup.start;if(!_settings2.default.CAN_UPLOAD_SAME_BUFFER){// this is still needed for IOS performance..
// it really does not like uploading to the same buffer in a single frame!
if(this.vaoMax<=this.vertexCount){this.vaoMax++;this.vertexBuffers[this.vertexCount]=_pixiGlCore2.default.GLBuffer.createVertexBuffer(gl,null,gl.STREAM_DRAW);// build the vao object that will render..
this.vaos[this.vertexCount]=this.renderer.createVao().addIndex(this.indexBuffer).addAttribute(this.vertexBuffers[this.vertexCount],this.shader.attributes.aVertexPosition,gl.FLOAT,false,this.vertByteSize,0).addAttribute(this.vertexBuffers[this.vertexCount],this.shader.attributes.aTextureCoord,gl.UNSIGNED_SHORT,true,this.vertByteSize,2*4).addAttribute(this.vertexBuffers[this.vertexCount],this.shader.attributes.aColor,gl.UNSIGNED_BYTE,true,this.vertByteSize,3*4).addAttribute(this.vertexBuffers[this.vertexCount],this.shader.attributes.aTextureId,gl.FLOAT,false,this.vertByteSize,4*4);}this.renderer.bindVao(this.vaos[this.vertexCount]);this.vertexBuffers[this.vertexCount].upload(buffer.vertices,0,false);this.vertexCount++;}else{// lets use the faster option, always use buffer number 0
this.vertexBuffers[this.vertexCount].upload(buffer.vertices,0,true);}for(i=0;i<MAX_TEXTURES;++i){rendererBoundTextures[i]._virtalBoundId=-1;}// render the groups..
for(i=0;i<groupCount;++i){var group=groups[i];var groupTextureCount=group.textureCount;for(var _j=0;_j<groupTextureCount;_j++){currentTexture=group.textures[_j];// reset virtual ids..
// lets do a quick check..
if(rendererBoundTextures[group.ids[_j]]!==currentTexture){this.renderer.bindTexture(currentTexture,group.ids[_j],true);}// reset the virtualId..
currentTexture._virtalBoundId=-1;}// set the blend mode..
this.renderer.state.setBlendMode(group.blend);gl.drawElements(gl.TRIANGLES,group.size*6,gl.UNSIGNED_SHORT,group.start*6*2);}// reset elements for the next flush
this.currentIndex=0;};/**
     * Starts a new sprite batch.
     */SpriteRenderer.prototype.start=function start(){this.renderer.bindShader(this.shader);if(_settings2.default.CAN_UPLOAD_SAME_BUFFER){// bind buffer #0, we don't need others
this.renderer.bindVao(this.vaos[this.vertexCount]);this.vertexBuffers[this.vertexCount].bind();}};/**
     * Stops and flushes the current batch.
     *
     */SpriteRenderer.prototype.stop=function stop(){this.flush();};/**
     * Destroys the SpriteRenderer.
     *
     */SpriteRenderer.prototype.destroy=function destroy(){for(var i=0;i<this.vaoMax;i++){if(this.vertexBuffers[i]){this.vertexBuffers[i].destroy();}if(this.vaos[i]){this.vaos[i].destroy();}}if(this.indexBuffer){this.indexBuffer.destroy();}this.renderer.off('prerender',this.onPrerender,this);_ObjectRenderer.prototype.destroy.call(this);if(this.shader){this.shader.destroy();this.shader=null;}this.vertexBuffers=null;this.vaos=null;this.indexBuffer=null;this.indices=null;this.sprites=null;for(var _i=0;_i<this.buffers.length;++_i){this.buffers[_i].destroy();}};return SpriteRenderer;}(_ObjectRenderer3.default);exports.default=SpriteRenderer;_WebGLRenderer2.default.registerPlugin('sprite',SpriteRenderer);},{"../../renderers/webgl/WebGLRenderer":80,"../../renderers/webgl/utils/ObjectRenderer":90,"../../renderers/webgl/utils/checkMaxIfStatmentsInShader":93,"../../settings":97,"../../utils/createIndicesForQuads":115,"./BatchBuffer":101,"./generateMultiTextureShader":103,"bit-twiddle":1,"pixi-gl-core":12}],103:[function(require,module,exports){'use strict';exports.__esModule=true;exports.default=generateMultiTextureShader;var _Shader=require('../../Shader');var _Shader2=_interopRequireDefault(_Shader);var _path=require('path');function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}var fragTemplate=['varying vec2 vTextureCoord;','varying vec4 vColor;','varying float vTextureId;','uniform sampler2D uSamplers[%count%];','void main(void){','vec4 color;','float textureId = floor(vTextureId+0.5);','%forloop%','gl_FragColor = color * vColor;','}'].join('\n');function generateMultiTextureShader(gl,maxTextures){var vertexSrc='attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\nattribute vec4 aColor;\nattribute float aTextureId;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\nvarying float vTextureId;\n\nvoid main(void){\n    gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n    vTextureCoord = aTextureCoord;\n    vTextureId = aTextureId;\n    vColor = vec4(aColor.rgb * aColor.a, aColor.a);\n}\n';var fragmentSrc=fragTemplate;fragmentSrc=fragmentSrc.replace(/%count%/gi,maxTextures);fragmentSrc=fragmentSrc.replace(/%forloop%/gi,generateSampleSrc(maxTextures));var shader=new _Shader2.default(gl,vertexSrc,fragmentSrc);var sampleValues=[];for(var i=0;i<maxTextures;i++){sampleValues[i]=i;}shader.bind();shader.uniforms.uSamplers=sampleValues;return shader;}function generateSampleSrc(maxTextures){var src='';src+='\n';src+='\n';for(var i=0;i<maxTextures;i++){if(i>0){src+='\nelse ';}if(i<maxTextures-1){src+='if(textureId == '+i+'.0)';}src+='\n{';src+='\n\tcolor = texture2D(uSamplers['+i+'], vTextureCoord);';src+='\n}';}src+='\n';src+='\n';return src;}},{"../../Shader":41,"path":22}],104:[function(require,module,exports){'use strict';exports.__esModule=true;var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor);}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor;};}();var _Sprite2=require('../sprites/Sprite');var _Sprite3=_interopRequireDefault(_Sprite2);var _Texture=require('../textures/Texture');var _Texture2=_interopRequireDefault(_Texture);var _math=require('../math');var _utils=require('../utils');var _const=require('../const');var _settings=require('../settings');var _settings2=_interopRequireDefault(_settings);var _TextStyle=require('./TextStyle');var _TextStyle2=_interopRequireDefault(_TextStyle);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return call&&((typeof call==="undefined"?"undefined":_typeof2(call))==="object"||typeof call==="function")?call:self;}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof2(superClass)));}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass;}/* eslint max-depth: [2, 8] */var defaultDestroyOptions={texture:true,children:false,baseTexture:true};/**
 * A Text Object will create a line or multiple lines of text. To split a line you can use '\n' in your text string,
 * or add a wordWrap property set to true and and wordWrapWidth property with a value in the style object.
 *
 * A Text can be created directly from a string and a style object
 *
 * ```js
 * let text = new PIXI.Text('This is a pixi text',{fontFamily : 'Arial', fontSize: 24, fill : 0xff1010, align : 'center'});
 * ```
 *
 * @class
 * @extends PIXI.Sprite
 * @memberof PIXI
 */var Text=function(_Sprite){_inherits(Text,_Sprite);/**
     * @param {string} text - The string that you would like the text to display
     * @param {object|PIXI.TextStyle} [style] - The style parameters
     * @param {HTMLCanvasElement} [canvas] - The canvas element for drawing text
     */function Text(text,style,canvas){_classCallCheck(this,Text);canvas=canvas||document.createElement('canvas');canvas.width=3;canvas.height=3;var texture=_Texture2.default.fromCanvas(canvas);texture.orig=new _math.Rectangle();texture.trim=new _math.Rectangle();/**
         * The canvas element that everything is drawn to
         *
         * @member {HTMLCanvasElement}
         */var _this=_possibleConstructorReturn(this,_Sprite.call(this,texture));_this.canvas=canvas;/**
         * The canvas 2d context that everything is drawn with
         * @member {HTMLCanvasElement}
         */_this.context=_this.canvas.getContext('2d');/**
         * The resolution / device pixel ratio of the canvas. This is set automatically by the renderer.
         * @member {number}
         * @default 1
         */_this.resolution=_settings2.default.RESOLUTION;/**
         * Private tracker for the current text.
         *
         * @member {string}
         * @private
         */_this._text=null;/**
         * Private tracker for the current style.
         *
         * @member {object}
         * @private
         */_this._style=null;/**
         * Private listener to track style changes.
         *
         * @member {Function}
         * @private
         */_this._styleListener=null;/**
         * Private tracker for the current font.
         *
         * @member {string}
         * @private
         */_this._font='';_this.text=text;_this.style=style;_this.localStyleID=-1;return _this;}/**
     * Renders text and updates it when needed.
     *
     * @private
     * @param {boolean} respectDirty - Whether to abort updating the text if the Text isn't dirty and the function is called.
     */Text.prototype.updateText=function updateText(respectDirty){var style=this._style;// check if style has changed..
if(this.localStyleID!==style.styleID){this.dirty=true;this.localStyleID=style.styleID;}if(!this.dirty&&respectDirty){return;}this._font=Text.getFontStyle(style);this.context.font=this._font;// word wrap
// preserve original text
var outputText=style.wordWrap?this.wordWrap(this._text):this._text;// split text into lines
var lines=outputText.split(/(?:\r\n|\r|\n)/);// calculate text width
var lineWidths=new Array(lines.length);var maxLineWidth=0;var fontProperties=Text.calculateFontProperties(this._font);for(var i=0;i<lines.length;i++){var lineWidth=this.context.measureText(lines[i]).width+(lines[i].length-1)*style.letterSpacing;lineWidths[i]=lineWidth;maxLineWidth=Math.max(maxLineWidth,lineWidth);}var width=maxLineWidth+style.strokeThickness;if(style.dropShadow){width+=style.dropShadowDistance;}width+=style.padding*2;this.canvas.width=Math.ceil((width+this.context.lineWidth)*this.resolution);// calculate text height
var lineHeight=this.style.lineHeight||fontProperties.fontSize+style.strokeThickness;var height=Math.max(lineHeight,fontProperties.fontSize+style.strokeThickness)+(lines.length-1)*lineHeight;if(style.dropShadow){height+=style.dropShadowDistance;}this.canvas.height=Math.ceil((height+this._style.padding*2)*this.resolution);this.context.scale(this.resolution,this.resolution);this.context.clearRect(0,0,this.canvas.width,this.canvas.height);this.context.font=this._font;this.context.strokeStyle=style.stroke;this.context.lineWidth=style.strokeThickness;this.context.textBaseline=style.textBaseline;this.context.lineJoin=style.lineJoin;this.context.miterLimit=style.miterLimit;var linePositionX=void 0;var linePositionY=void 0;if(style.dropShadow){if(style.dropShadowBlur>0){this.context.shadowColor=style.dropShadowColor;this.context.shadowBlur=style.dropShadowBlur;}else{this.context.fillStyle=style.dropShadowColor;}var xShadowOffset=Math.cos(style.dropShadowAngle)*style.dropShadowDistance;var yShadowOffset=Math.sin(style.dropShadowAngle)*style.dropShadowDistance;for(var _i=0;_i<lines.length;_i++){linePositionX=style.strokeThickness/2;linePositionY=style.strokeThickness/2+_i*lineHeight+fontProperties.ascent;if(style.align==='right'){linePositionX+=maxLineWidth-lineWidths[_i];}else if(style.align==='center'){linePositionX+=(maxLineWidth-lineWidths[_i])/2;}if(style.fill){this.drawLetterSpacing(lines[_i],linePositionX+xShadowOffset+style.padding,linePositionY+yShadowOffset+style.padding);if(style.stroke&&style.strokeThickness){this.context.strokeStyle=style.dropShadowColor;this.drawLetterSpacing(lines[_i],linePositionX+xShadowOffset+style.padding,linePositionY+yShadowOffset+style.padding,true);this.context.strokeStyle=style.stroke;}}}}// set canvas text styles
this.context.fillStyle=this._generateFillStyle(style,lines);// draw lines line by line
for(var _i2=0;_i2<lines.length;_i2++){linePositionX=style.strokeThickness/2;linePositionY=style.strokeThickness/2+_i2*lineHeight+fontProperties.ascent;if(style.align==='right'){linePositionX+=maxLineWidth-lineWidths[_i2];}else if(style.align==='center'){linePositionX+=(maxLineWidth-lineWidths[_i2])/2;}if(style.stroke&&style.strokeThickness){this.drawLetterSpacing(lines[_i2],linePositionX+style.padding,linePositionY+style.padding,true);}if(style.fill){this.drawLetterSpacing(lines[_i2],linePositionX+style.padding,linePositionY+style.padding);}}this.updateTexture();};/**
     * Render the text with letter-spacing.
     * @param {string} text - The text to draw
     * @param {number} x - Horizontal position to draw the text
     * @param {number} y - Vertical position to draw the text
     * @param {boolean} [isStroke=false] - Is this drawing for the outside stroke of the
     *  text? If not, it's for the inside fill
     * @private
     */Text.prototype.drawLetterSpacing=function drawLetterSpacing(text,x,y){var isStroke=arguments.length<=3||arguments[3]===undefined?false:arguments[3];var style=this._style;// letterSpacing of 0 means normal
var letterSpacing=style.letterSpacing;if(letterSpacing===0){if(isStroke){this.context.strokeText(text,x,y);}else{this.context.fillText(text,x,y);}return;}var characters=String.prototype.split.call(text,'');var currentPosition=x;var index=0;var current='';while(index<text.length){current=characters[index++];if(isStroke){this.context.strokeText(current,currentPosition,y);}else{this.context.fillText(current,currentPosition,y);}currentPosition+=this.context.measureText(current).width+letterSpacing;}};/**
     * Updates texture size based on canvas size
     *
     * @private
     */Text.prototype.updateTexture=function updateTexture(){var texture=this._texture;var style=this._style;texture.baseTexture.hasLoaded=true;texture.baseTexture.resolution=this.resolution;texture.baseTexture.realWidth=this.canvas.width;texture.baseTexture.realHeight=this.canvas.height;texture.baseTexture.width=this.canvas.width/this.resolution;texture.baseTexture.height=this.canvas.height/this.resolution;texture.trim.width=texture._frame.width=this.canvas.width/this.resolution;texture.trim.height=texture._frame.height=this.canvas.height/this.resolution;texture.trim.x=-style.padding;texture.trim.y=-style.padding;texture.orig.width=texture._frame.width-style.padding*2;texture.orig.height=texture._frame.height-style.padding*2;// call sprite onTextureUpdate to update scale if _width or _height were set
this._onTextureUpdate();texture.baseTexture.emit('update',texture.baseTexture);this.dirty=false;};/**
     * Renders the object using the WebGL renderer
     *
     * @param {PIXI.WebGLRenderer} renderer - The renderer
     */Text.prototype.renderWebGL=function renderWebGL(renderer){if(this.resolution!==renderer.resolution){this.resolution=renderer.resolution;this.dirty=true;}this.updateText(true);_Sprite.prototype.renderWebGL.call(this,renderer);};/**
     * Renders the object using the Canvas renderer
     *
     * @private
     * @param {PIXI.CanvasRenderer} renderer - The renderer
     */Text.prototype._renderCanvas=function _renderCanvas(renderer){if(this.resolution!==renderer.resolution){this.resolution=renderer.resolution;this.dirty=true;}this.updateText(true);_Sprite.prototype._renderCanvas.call(this,renderer);};/**
     * Applies newlines to a string to have it optimally fit into the horizontal
     * bounds set by the Text object's wordWrapWidth property.
     *
     * @private
     * @param {string} text - String to apply word wrapping to
     * @return {string} New string with new lines applied where required
     */Text.prototype.wordWrap=function wordWrap(text){// Greedy wrapping algorithm that will wrap words as the line grows longer
// than its horizontal bounds.
var result='';var lines=text.split('\n');var wordWrapWidth=this._style.wordWrapWidth;for(var i=0;i<lines.length;i++){var spaceLeft=wordWrapWidth;var words=lines[i].split(' ');for(var j=0;j<words.length;j++){var wordWidth=this.context.measureText(words[j]).width;if(this._style.breakWords&&wordWidth>wordWrapWidth){// Word should be split in the middle
var characters=words[j].split('');for(var c=0;c<characters.length;c++){var characterWidth=this.context.measureText(characters[c]).width;if(characterWidth>spaceLeft){result+='\n'+characters[c];spaceLeft=wordWrapWidth-characterWidth;}else{if(c===0){result+=' ';}result+=characters[c];spaceLeft-=characterWidth;}}}else{var wordWidthWithSpace=wordWidth+this.context.measureText(' ').width;if(j===0||wordWidthWithSpace>spaceLeft){// Skip printing the newline if it's the first word of the line that is
// greater than the word wrap width.
if(j>0){result+='\n';}result+=words[j];spaceLeft=wordWrapWidth-wordWidth;}else{spaceLeft-=wordWidthWithSpace;result+=' '+words[j];}}}if(i<lines.length-1){result+='\n';}}return result;};/**
     * calculates the bounds of the Text as a rectangle. The bounds calculation takes the worldTransform into account.
     */Text.prototype._calculateBounds=function _calculateBounds(){this.updateText(true);this.calculateVertices();// if we have already done this on THIS frame.
this._bounds.addQuad(this.vertexData);};/**
     * Method to be called upon a TextStyle change.
     * @private
     */Text.prototype._onStyleChange=function _onStyleChange(){this.dirty=true;};/**
     * Generates the fill style. Can automatically generate a gradient based on the fill style being an array
     *
     * @private
     * @param {object} style - The style.
     * @param {string[]} lines - The lines of text.
     * @return {string|number|CanvasGradient} The fill style
     */Text.prototype._generateFillStyle=function _generateFillStyle(style,lines){if(!Array.isArray(style.fill)){return style.fill;}// cocoon on canvas+ cannot generate textures, so use the first colour instead
if(navigator.isCocoonJS){return style.fill[0];}// the gradient will be evenly spaced out according to how large the array is.
// ['#FF0000', '#00FF00', '#0000FF'] would created stops at 0.25, 0.5 and 0.75
var gradient=void 0;var totalIterations=void 0;var currentIteration=void 0;var stop=void 0;var width=this.canvas.width/this.resolution;var height=this.canvas.height/this.resolution;if(style.fillGradientType===_const.TEXT_GRADIENT.LINEAR_VERTICAL){// start the gradient at the top center of the canvas, and end at the bottom middle of the canvas
gradient=this.context.createLinearGradient(width/2,0,width/2,height);// we need to repeat the gradient so that each individual line of text has the same vertical gradient effect
// ['#FF0000', '#00FF00', '#0000FF'] over 2 lines would create stops at 0.125, 0.25, 0.375, 0.625, 0.75, 0.875
totalIterations=(style.fill.length+1)*lines.length;currentIteration=0;for(var i=0;i<lines.length;i++){currentIteration+=1;for(var j=0;j<style.fill.length;j++){stop=currentIteration/totalIterations;gradient.addColorStop(stop,style.fill[j]);currentIteration++;}}}else{// start the gradient at the center left of the canvas, and end at the center right of the canvas
gradient=this.context.createLinearGradient(0,height/2,width,height/2);// can just evenly space out the gradients in this case, as multiple lines makes no difference
// to an even left to right gradient
totalIterations=style.fill.length+1;currentIteration=1;for(var _i3=0;_i3<style.fill.length;_i3++){stop=currentIteration/totalIterations;gradient.addColorStop(stop,style.fill[_i3]);currentIteration++;}}return gradient;};/**
     * Destroys this text object.
     * Note* Unlike a Sprite, a Text object will automatically destroy its baseTexture and texture as
     * the majorety of the time the texture will not be shared with any other Sprites.
     *
     * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options
     *  have been set to that value
     * @param {boolean} [options.children=false] - if set to true, all the children will have their
     *  destroy method called as well. 'options' will be passed on to those calls.
     * @param {boolean} [options.texture=true] - Should it destroy the current texture of the sprite as well
     * @param {boolean} [options.baseTexture=true] - Should it destroy the base texture of the sprite as well
     */Text.prototype.destroy=function destroy(options){if(typeof options==='boolean'){options={children:options};}options=Object.assign({},defaultDestroyOptions,options);_Sprite.prototype.destroy.call(this,options);// make sure to reset the the context and canvas.. dont want this hanging around in memory!
this.context=null;this.canvas=null;this._style=null;};/**
     * The width of the Text, setting this will actually modify the scale to achieve the value set
     *
     * @member {number}
     * @memberof PIXI.Text#
     *//**
     * Generates a font style string to use for Text.calculateFontProperties(). Takes the same parameter
     * as Text.style.
     *
     * @static
     * @param {object|TextStyle} style - String representing the style of the font
     * @return {string} Font style string, for passing to Text.calculateFontProperties()
     */Text.getFontStyle=function getFontStyle(style){style=style||{};if(!(style instanceof _TextStyle2.default)){style=new _TextStyle2.default(style);}// build canvas api font setting from individual components. Convert a numeric style.fontSize to px
var fontSizeString=typeof style.fontSize==='number'?style.fontSize+'px':style.fontSize;// Clean-up fontFamily property by quoting each font name
// this will support font names with spaces
var fontFamilies=style.fontFamily;if(!Array.isArray(style.fontFamily)){fontFamilies=style.fontFamily.split(',');}for(var i=fontFamilies.length-1;i>=0;i--){// Trim any extra white-space
var fontFamily=fontFamilies[i].trim();// Check if font already contains strings
if(!/([\"\'])[^\'\"]+\1/.test(fontFamily)){fontFamily='"'+fontFamily+'"';}fontFamilies[i]=fontFamily;}return style.fontStyle+' '+style.fontVariant+' '+style.fontWeight+' '+fontSizeString+' '+fontFamilies.join(',');};/**
     * Calculates the ascent, descent and fontSize of a given fontStyle
     *
     * @static
     * @param {string} fontStyle - String representing the style of the font
     * @return {Object} Font properties object
     */Text.calculateFontProperties=function calculateFontProperties(fontStyle){// as this method is used for preparing assets, don't recalculate things if we don't need to
if(Text.fontPropertiesCache[fontStyle]){return Text.fontPropertiesCache[fontStyle];}var properties={};var canvas=Text.fontPropertiesCanvas;var context=Text.fontPropertiesContext;context.font=fontStyle;var width=Math.ceil(context.measureText('|MÉq').width);var baseline=Math.ceil(context.measureText('M').width);var height=2*baseline;baseline=baseline*1.4|0;canvas.width=width;canvas.height=height;context.fillStyle='#f00';context.fillRect(0,0,width,height);context.font=fontStyle;context.textBaseline='alphabetic';context.fillStyle='#000';context.fillText('|MÉq',0,baseline);var imagedata=context.getImageData(0,0,width,height).data;var pixels=imagedata.length;var line=width*4;var i=0;var idx=0;var stop=false;// ascent. scan from top to bottom until we find a non red pixel
for(i=0;i<baseline;++i){for(var j=0;j<line;j+=4){if(imagedata[idx+j]!==255){stop=true;break;}}if(!stop){idx+=line;}else{break;}}properties.ascent=baseline-i;idx=pixels-line;stop=false;// descent. scan from bottom to top until we find a non red pixel
for(i=height;i>baseline;--i){for(var _j=0;_j<line;_j+=4){if(imagedata[idx+_j]!==255){stop=true;break;}}if(!stop){idx-=line;}else{break;}}properties.descent=i-baseline;properties.fontSize=properties.ascent+properties.descent;Text.fontPropertiesCache[fontStyle]=properties;return properties;};_createClass(Text,[{key:'width',get:function get(){this.updateText(true);return Math.abs(this.scale.x)*this._texture.orig.width;}/**
         * Sets the width of the text.
         *
         * @param {number} value - The value to set to.
         */,set:function set(value){this.updateText(true);var s=(0,_utils.sign)(this.scale.x)||1;this.scale.x=s*value/this._texture.orig.width;this._width=value;}/**
         * The height of the Text, setting this will actually modify the scale to achieve the value set
         *
         * @member {number}
         * @memberof PIXI.Text#
         */},{key:'height',get:function get(){this.updateText(true);return Math.abs(this.scale.y)*this._texture.orig.height;}/**
         * Sets the height of the text.
         *
         * @param {number} value - The value to set to.
         */,set:function set(value){this.updateText(true);var s=(0,_utils.sign)(this.scale.y)||1;this.scale.y=s*value/this._texture.orig.height;this._height=value;}/**
         * Set the style of the text. Set up an event listener to listen for changes on the style
         * object and mark the text as dirty.
         *
         * @member {object|PIXI.TextStyle}
         * @memberof PIXI.Text#
         */},{key:'style',get:function get(){return this._style;}/**
         * Sets the style of the text.
         *
         * @param {object} style - The value to set to.
         */,set:function set(style){style=style||{};if(style instanceof _TextStyle2.default){this._style=style;}else{this._style=new _TextStyle2.default(style);}this.localStyleID=-1;this.dirty=true;}/**
         * Set the copy for the text object. To split a line you can use '\n'.
         *
         * @member {string}
         * @memberof PIXI.Text#
         */},{key:'text',get:function get(){return this._text;}/**
         * Sets the text.
         *
         * @param {string} text - The value to set to.
         */,set:function set(text){text=String(text||' ');if(this._text===text){return;}this._text=text;this.dirty=true;}}]);return Text;}(_Sprite3.default);exports.default=Text;Text.fontPropertiesCache={};Text.fontPropertiesCanvas=document.createElement('canvas');Text.fontPropertiesContext=Text.fontPropertiesCanvas.getContext('2d');},{"../const":42,"../math":66,"../settings":97,"../sprites/Sprite":98,"../textures/Texture":109,"../utils":117,"./TextStyle":105}],105:[function(require,module,exports){'use strict';exports.__esModule=true;var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor);}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor;};}();// disabling eslint for now, going to rewrite this in v5
/* eslint-disable */var _const=require('../const');var _utils=require('../utils');function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}var defaultStyle={align:'left',breakWords:false,dropShadow:false,dropShadowAngle:Math.PI/6,dropShadowBlur:0,dropShadowColor:'#000000',dropShadowDistance:5,fill:'black',fillGradientType:_const.TEXT_GRADIENT.LINEAR_VERTICAL,fontFamily:'Arial',fontSize:26,fontStyle:'normal',fontVariant:'normal',fontWeight:'normal',letterSpacing:0,lineHeight:0,lineJoin:'miter',miterLimit:10,padding:0,stroke:'black',strokeThickness:0,textBaseline:'alphabetic',wordWrap:false,wordWrapWidth:100};/**
 * A TextStyle Object decorates a Text Object. It can be shared between
 * multiple Text objects. Changing the style will update all text objects using it.
 *
 * @class
 * @memberof PIXI
 */var TextStyle=function(){/**
     * @param {object} [style] - The style parameters
     * @param {string} [style.align='left'] - Alignment for multiline text ('left', 'center' or 'right'),
     *  does not affect single line text
     * @param {boolean} [style.breakWords=false] - Indicates if lines can be wrapped within words, it
     *  needs wordWrap to be set to true
     * @param {boolean} [style.dropShadow=false] - Set a drop shadow for the text
     * @param {number} [style.dropShadowAngle=Math.PI/6] - Set a angle of the drop shadow
     * @param {number} [style.dropShadowBlur=0] - Set a shadow blur radius
     * @param {string} [style.dropShadowColor='#000000'] - A fill style to be used on the dropshadow e.g 'red', '#00FF00'
     * @param {number} [style.dropShadowDistance=5] - Set a distance of the drop shadow
     * @param {string|string[]|number|number[]|CanvasGradient|CanvasPattern} [style.fill='black'] - A canvas
     *  fillstyle that will be used on the text e.g 'red', '#00FF00'. Can be an array to create a gradient
     *  eg ['#000000','#FFFFFF']
     * {@link https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/fillStyle|MDN}
     * @param {number} [style.fillGradientType=PIXI.TEXT_GRADIENT.LINEAR_VERTICAL] - If fills styles are
     *  supplied, this can change the type/direction of the gradient. See {@link PIXI.TEXT_GRADIENT} for possible values
     * @param {string|string[]} [style.fontFamily='Arial'] - The font family
     * @param {number|string} [style.fontSize=26] - The font size (as a number it converts to px, but as a string,
     *  equivalents are '26px','20pt','160%' or '1.6em')
     * @param {string} [style.fontStyle='normal'] - The font style ('normal', 'italic' or 'oblique')
     * @param {string} [style.fontVariant='normal'] - The font variant ('normal' or 'small-caps')
     * @param {string} [style.fontWeight='normal'] - The font weight ('normal', 'bold', 'bolder', 'lighter' and '100',
     *  '200', '300', '400', '500', '600', '700', 800' or '900')
     * @param {number} [style.letterSpacing=0] - The amount of spacing between letters, default is 0
     * @param {number} [style.lineHeight] - The line height, a number that represents the vertical space that a letter uses
     * @param {string} [style.lineJoin='miter'] - The lineJoin property sets the type of corner created, it can resolve
     *      spiked text issues. Default is 'miter' (creates a sharp corner).
     * @param {number} [style.miterLimit=10] - The miter limit to use when using the 'miter' lineJoin mode. This can reduce
     *      or increase the spikiness of rendered text.
     * @param {number} [style.padding=0] - Occasionally some fonts are cropped. Adding some padding will prevent this from
     *     happening by adding padding to all sides of the text.
     * @param {string|number} [style.stroke='black'] - A canvas fillstyle that will be used on the text stroke
     *  e.g 'blue', '#FCFF00'
     * @param {number} [style.strokeThickness=0] - A number that represents the thickness of the stroke.
     *  Default is 0 (no stroke)
     * @param {string} [style.textBaseline='alphabetic'] - The baseline of the text that is rendered.
     * @param {boolean} [style.wordWrap=false] - Indicates if word wrap should be used
     * @param {number} [style.wordWrapWidth=100] - The width at which text will wrap, it needs wordWrap to be set to true
     */function TextStyle(style){_classCallCheck(this,TextStyle);this.styleID=0;Object.assign(this,defaultStyle,style);}/**
     * Creates a new TextStyle object with the same values as this one.
     * Note that the only the properties of the object are cloned.
     *
     * @return {PIXI.TextStyle} New cloned TextStyle object
     */TextStyle.prototype.clone=function clone(){var clonedProperties={};for(var key in defaultStyle){clonedProperties[key]=this[key];}return new TextStyle(clonedProperties);};/**
     * Resets all properties to the defaults specified in TextStyle.prototype._default
     */TextStyle.prototype.reset=function reset(){Object.assign(this,defaultStyle);};_createClass(TextStyle,[{key:'align',get:function get(){return this._align;},set:function set(align){if(this._align!==align){this._align=align;this.styleID++;}}},{key:'breakWords',get:function get(){return this._breakWords;},set:function set(breakWords){if(this._breakWords!==breakWords){this._breakWords=breakWords;this.styleID++;}}},{key:'dropShadow',get:function get(){return this._dropShadow;},set:function set(dropShadow){if(this._dropShadow!==dropShadow){this._dropShadow=dropShadow;this.styleID++;}}},{key:'dropShadowAngle',get:function get(){return this._dropShadowAngle;},set:function set(dropShadowAngle){if(this._dropShadowAngle!==dropShadowAngle){this._dropShadowAngle=dropShadowAngle;this.styleID++;}}},{key:'dropShadowBlur',get:function get(){return this._dropShadowBlur;},set:function set(dropShadowBlur){if(this._dropShadowBlur!==dropShadowBlur){this._dropShadowBlur=dropShadowBlur;this.styleID++;}}},{key:'dropShadowColor',get:function get(){return this._dropShadowColor;},set:function set(dropShadowColor){var outputColor=getColor(dropShadowColor);if(this._dropShadowColor!==outputColor){this._dropShadowColor=outputColor;this.styleID++;}}},{key:'dropShadowDistance',get:function get(){return this._dropShadowDistance;},set:function set(dropShadowDistance){if(this._dropShadowDistance!==dropShadowDistance){this._dropShadowDistance=dropShadowDistance;this.styleID++;}}},{key:'fill',get:function get(){return this._fill;},set:function set(fill){var outputColor=getColor(fill);if(this._fill!==outputColor){this._fill=outputColor;this.styleID++;}}},{key:'fillGradientType',get:function get(){return this._fillGradientType;},set:function set(fillGradientType){if(this._fillGradientType!==fillGradientType){this._fillGradientType=fillGradientType;this.styleID++;}}},{key:'fontFamily',get:function get(){return this._fontFamily;},set:function set(fontFamily){if(this.fontFamily!==fontFamily){this._fontFamily=fontFamily;this.styleID++;}}},{key:'fontSize',get:function get(){return this._fontSize;},set:function set(fontSize){if(this._fontSize!==fontSize){this._fontSize=fontSize;this.styleID++;}}},{key:'fontStyle',get:function get(){return this._fontStyle;},set:function set(fontStyle){if(this._fontStyle!==fontStyle){this._fontStyle=fontStyle;this.styleID++;}}},{key:'fontVariant',get:function get(){return this._fontVariant;},set:function set(fontVariant){if(this._fontVariant!==fontVariant){this._fontVariant=fontVariant;this.styleID++;}}},{key:'fontWeight',get:function get(){return this._fontWeight;},set:function set(fontWeight){if(this._fontWeight!==fontWeight){this._fontWeight=fontWeight;this.styleID++;}}},{key:'letterSpacing',get:function get(){return this._letterSpacing;},set:function set(letterSpacing){if(this._letterSpacing!==letterSpacing){this._letterSpacing=letterSpacing;this.styleID++;}}},{key:'lineHeight',get:function get(){return this._lineHeight;},set:function set(lineHeight){if(this._lineHeight!==lineHeight){this._lineHeight=lineHeight;this.styleID++;}}},{key:'lineJoin',get:function get(){return this._lineJoin;},set:function set(lineJoin){if(this._lineJoin!==lineJoin){this._lineJoin=lineJoin;this.styleID++;}}},{key:'miterLimit',get:function get(){return this._miterLimit;},set:function set(miterLimit){if(this._miterLimit!==miterLimit){this._miterLimit=miterLimit;this.styleID++;}}},{key:'padding',get:function get(){return this._padding;},set:function set(padding){if(this._padding!==padding){this._padding=padding;this.styleID++;}}},{key:'stroke',get:function get(){return this._stroke;},set:function set(stroke){var outputColor=getColor(stroke);if(this._stroke!==outputColor){this._stroke=outputColor;this.styleID++;}}},{key:'strokeThickness',get:function get(){return this._strokeThickness;},set:function set(strokeThickness){if(this._strokeThickness!==strokeThickness){this._strokeThickness=strokeThickness;this.styleID++;}}},{key:'textBaseline',get:function get(){return this._textBaseline;},set:function set(textBaseline){if(this._textBaseline!==textBaseline){this._textBaseline=textBaseline;this.styleID++;}}},{key:'wordWrap',get:function get(){return this._wordWrap;},set:function set(wordWrap){if(this._wordWrap!==wordWrap){this._wordWrap=wordWrap;this.styleID++;}}},{key:'wordWrapWidth',get:function get(){return this._wordWrapWidth;},set:function set(wordWrapWidth){if(this._wordWrapWidth!==wordWrapWidth){this._wordWrapWidth=wordWrapWidth;this.styleID++;}}}]);return TextStyle;}();/**
 * Utility function to convert hexadecimal colors to strings, and simply return the color if it's a string.
 *
 * @param {number|number[]} color
 * @return {string} The color as a string.
 */exports.default=TextStyle;function getSingleColor(color){if(typeof color==='number'){return(0,_utils.hex2string)(color);}else if(typeof color==='string'){if(color.indexOf('0x')===0){color=color.replace('0x','#');}}return color;}/**
 * Utility function to convert hexadecimal colors to strings, and simply return the color if it's a string.
 * This version can also convert array of colors
 *
 * @param {number|number[]} color
 * @return {string} The color as a string.
 */function getColor(color){if(!Array.isArray(color)){return getSingleColor(color);}else{for(var i=0;i<color.length;++i){color[i]=getSingleColor(color[i]);}return color;}}},{"../const":42,"../utils":117}],106:[function(require,module,exports){'use strict';exports.__esModule=true;var _BaseTexture2=require('./BaseTexture');var _BaseTexture3=_interopRequireDefault(_BaseTexture2);var _settings=require('../settings');var _settings2=_interopRequireDefault(_settings);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return call&&((typeof call==="undefined"?"undefined":_typeof2(call))==="object"||typeof call==="function")?call:self;}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof2(superClass)));}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass;}var RESOLUTION=_settings2.default.RESOLUTION;var SCALE_MODE=_settings2.default.SCALE_MODE;/**
 * A BaseRenderTexture is a special texture that allows any Pixi display object to be rendered to it.
 *
 * __Hint__: All DisplayObjects (i.e. Sprites) that render to a BaseRenderTexture should be preloaded
 * otherwise black rectangles will be drawn instead.
 *
 * A BaseRenderTexture takes a snapshot of any Display Object given to its render method. The position
 * and rotation of the given Display Objects is ignored. For example:
 *
 * ```js
 * let renderer = PIXI.autoDetectRenderer(1024, 1024, { view: canvas, ratio: 1 });
 * let baseRenderTexture = new PIXI.BaseRenderTexture(renderer, 800, 600);
 * let sprite = PIXI.Sprite.fromImage("spinObj_01.png");
 *
 * sprite.position.x = 800/2;
 * sprite.position.y = 600/2;
 * sprite.anchor.x = 0.5;
 * sprite.anchor.y = 0.5;
 *
 * baseRenderTexture.render(sprite);
 * ```
 *
 * The Sprite in this case will be rendered to a position of 0,0. To render this sprite at its actual
 * position a Container should be used:
 *
 * ```js
 * let doc = new PIXI.Container();
 *
 * doc.addChild(sprite);
 *
 * let baseRenderTexture = new PIXI.BaseRenderTexture(100, 100);
 * let renderTexture = new PIXI.RenderTexture(baseRenderTexture);
 *
 * renderer.render(doc, renderTexture);  // Renders to center of RenderTexture
 * ```
 *
 * @class
 * @extends PIXI.BaseTexture
 * @memberof PIXI
 */var BaseRenderTexture=function(_BaseTexture){_inherits(BaseRenderTexture,_BaseTexture);/**
   * @param {number} [width=100] - The width of the base render texture
   * @param {number} [height=100] - The height of the base render texture
   * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values
   * @param {number} [resolution=1] - The resolution / device pixel ratio of the texture being generated
   */function BaseRenderTexture(){var width=arguments.length<=0||arguments[0]===undefined?100:arguments[0];var height=arguments.length<=1||arguments[1]===undefined?100:arguments[1];var scaleMode=arguments[2];var resolution=arguments[3];_classCallCheck(this,BaseRenderTexture);var _this=_possibleConstructorReturn(this,_BaseTexture.call(this,null,scaleMode));_this.resolution=resolution||RESOLUTION;_this.width=width;_this.height=height;_this.realWidth=_this.width*_this.resolution;_this.realHeight=_this.height*_this.resolution;_this.scaleMode=scaleMode||SCALE_MODE;_this.hasLoaded=true;/**
     * A map of renderer IDs to webgl renderTargets
     *
     * @private
     * @member {object<number, WebGLTexture>}
     */_this._glRenderTargets={};/**
     * A reference to the canvas render target (we only need one as this can be shared across renderers)
     *
     * @private
     * @member {object<number, WebGLTexture>}
     */_this._canvasRenderTarget=null;/**
     * This will let the renderer know if the texture is valid. If it's not then it cannot be rendered.
     *
     * @member {boolean}
     */_this.valid=false;return _this;}/**
   * Resizes the BaseRenderTexture.
   *
   * @param {number} width - The width to resize to.
   * @param {number} height - The height to resize to.
   */BaseRenderTexture.prototype.resize=function resize(width,height){if(width===this.width&&height===this.height){return;}this.valid=width>0&&height>0;this.width=width;this.height=height;this.realWidth=this.width*this.resolution;this.realHeight=this.height*this.resolution;if(!this.valid){return;}this.emit('update',this);};/**
   * Destroys this texture
   *
   */BaseRenderTexture.prototype.destroy=function destroy(){_BaseTexture.prototype.destroy.call(this,true);this.renderer=null;};return BaseRenderTexture;}(_BaseTexture3.default);exports.default=BaseRenderTexture;},{"../settings":97,"./BaseTexture":107}],107:[function(require,module,exports){'use strict';exports.__esModule=true;var _typeof=typeof Symbol==="function"&&_typeof2(Symbol.iterator)==="symbol"?function(obj){return typeof obj==="undefined"?"undefined":_typeof2(obj);}:function(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol?"symbol":typeof obj==="undefined"?"undefined":_typeof2(obj);};var _utils=require('../utils');var _settings=require('../settings');var _settings2=_interopRequireDefault(_settings);var _eventemitter=require('eventemitter3');var _eventemitter2=_interopRequireDefault(_eventemitter);var _determineCrossOrigin=require('../utils/determineCrossOrigin');var _determineCrossOrigin2=_interopRequireDefault(_determineCrossOrigin);var _bitTwiddle=require('bit-twiddle');var _bitTwiddle2=_interopRequireDefault(_bitTwiddle);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return call&&((typeof call==="undefined"?"undefined":_typeof2(call))==="object"||typeof call==="function")?call:self;}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof2(superClass)));}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass;}/**
 * A texture stores the information that represents an image. All textures have a base texture.
 *
 * @class
 * @extends EventEmitter
 * @memberof PIXI
 */var BaseTexture=function(_EventEmitter){_inherits(BaseTexture,_EventEmitter);/**
     * @param {HTMLImageElement|HTMLCanvasElement} [source] - the source object of the texture.
     * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values
     * @param {number} [resolution=1] - The resolution / device pixel ratio of the texture
     */function BaseTexture(source,scaleMode,resolution){_classCallCheck(this,BaseTexture);var _this=_possibleConstructorReturn(this,_EventEmitter.call(this));_this.uid=(0,_utils.uid)();_this.touched=0;/**
         * The resolution / device pixel ratio of the texture
         *
         * @member {number}
         * @default 1
         */_this.resolution=resolution||_settings2.default.RESOLUTION;/**
         * The width of the base texture set when the image has loaded
         *
         * @readonly
         * @member {number}
         */_this.width=100;/**
         * The height of the base texture set when the image has loaded
         *
         * @readonly
         * @member {number}
         */_this.height=100;// TODO docs
// used to store the actual dimensions of the source
/**
         * Used to store the actual width of the source of this texture
         *
         * @readonly
         * @member {number}
         */_this.realWidth=100;/**
         * Used to store the actual height of the source of this texture
         *
         * @readonly
         * @member {number}
         */_this.realHeight=100;/**
         * The scale mode to apply when scaling this texture
         *
         * @member {number}
         * @default PIXI.settings.SCALE_MODE
         * @see PIXI.SCALE_MODES
         */_this.scaleMode=scaleMode||_settings2.default.SCALE_MODE;/**
         * Set to true once the base texture has successfully loaded.
         *
         * This is never true if the underlying source fails to load or has no texture data.
         *
         * @readonly
         * @member {boolean}
         */_this.hasLoaded=false;/**
         * Set to true if the source is currently loading.
         *
         * If an Image source is loading the 'loaded' or 'error' event will be
         * dispatched when the operation ends. An underyling source that is
         * immediately-available bypasses loading entirely.
         *
         * @readonly
         * @member {boolean}
         */_this.isLoading=false;/**
         * The image source that is used to create the texture.
         *
         * TODO: Make this a setter that calls loadSource();
         *
         * @readonly
         * @member {HTMLImageElement|HTMLCanvasElement}
         */_this.source=null;// set in loadSource, if at all
/**
         * The image source that is used to create the texture. This is used to
         * store the original Svg source when it is replaced with a canvas element.
         *
         * TODO: Currently not in use but could be used when re-scaling svg.
         *
         * @readonly
         * @member {Image}
         */_this.origSource=null;// set in loadSvg, if at all
/**
         * Type of image defined in source, eg. `png` or `svg`
         *
         * @readonly
         * @member {string}
         */_this.imageType=null;// set in updateImageType
/**
         * Scale for source image. Used with Svg images to scale them before rasterization.
         *
         * @readonly
         * @member {number}
         */_this.sourceScale=1.0;/**
         * Controls if RGB channels should be pre-multiplied by Alpha  (WebGL only)
         * All blend modes, and shaders written for default value. Change it on your own risk.
         *
         * @member {boolean}
         * @default true
         */_this.premultipliedAlpha=true;/**
         * The image url of the texture
         *
         * @member {string}
         */_this.imageUrl=null;/**
         * Whether or not the texture is a power of two, try to use power of two textures as much
         * as you can
         *
         * @private
         * @member {boolean}
         */_this.isPowerOfTwo=false;// used for webGL
/**
         *
         * Set this to true if a mipmap of this texture needs to be generated. This value needs
         * to be set before the texture is used
         * Also the texture must be a power of two size to work
         *
         * @member {boolean}
         * @see PIXI.MIPMAP_TEXTURES
         */_this.mipmap=_settings2.default.MIPMAP_TEXTURES;/**
         *
         * WebGL Texture wrap mode
         *
         * @member {number}
         * @see PIXI.WRAP_MODES
         */_this.wrapMode=_settings2.default.WRAP_MODE;/**
         * A map of renderer IDs to webgl textures
         *
         * @private
         * @member {object<number, WebGLTexture>}
         */_this._glTextures={};_this._enabled=0;_this._virtalBoundId=-1;// if no source passed don't try to load
if(source){_this.loadSource(source);}/**
         * Fired when a not-immediately-available source finishes loading.
         *
         * @protected
         * @event loaded
         * @memberof PIXI.BaseTexture#
         *//**
         * Fired when a not-immediately-available source fails to load.
         *
         * @protected
         * @event error
         * @memberof PIXI.BaseTexture#
         */return _this;}/**
     * Updates the texture on all the webgl renderers, this also assumes the src has changed.
     *
     * @fires update
     */BaseTexture.prototype.update=function update(){// Svg size is handled during load
if(this.imageType!=='svg'){this.realWidth=this.source.naturalWidth||this.source.videoWidth||this.source.width;this.realHeight=this.source.naturalHeight||this.source.videoHeight||this.source.height;this.width=this.realWidth/this.resolution;this.height=this.realHeight/this.resolution;this.isPowerOfTwo=_bitTwiddle2.default.isPow2(this.realWidth)&&_bitTwiddle2.default.isPow2(this.realHeight);}this.emit('update',this);};/**
     * Load a source.
     *
     * If the source is not-immediately-available, such as an image that needs to be
     * downloaded, then the 'loaded' or 'error' event will be dispatched in the future
     * and `hasLoaded` will remain false after this call.
     *
     * The logic state after calling `loadSource` directly or indirectly (eg. `fromImage`, `new BaseTexture`) is:
     *
     *     if (texture.hasLoaded) {
     *        // texture ready for use
     *     } else if (texture.isLoading) {
     *        // listen to 'loaded' and/or 'error' events on texture
     *     } else {
     *        // not loading, not going to load UNLESS the source is reloaded
     *        // (it may still make sense to listen to the events)
     *     }
     *
     * @protected
     * @param {HTMLImageElement|HTMLCanvasElement} source - the source object of the texture.
     */BaseTexture.prototype.loadSource=function loadSource(source){var _this2=this;var wasLoading=this.isLoading;this.hasLoaded=false;this.isLoading=false;if(wasLoading&&this.source){this.source.onload=null;this.source.onerror=null;}var firstSourceLoaded=!this.source;this.source=source;// Apply source if loaded. Otherwise setup appropriate loading monitors.
if((source.src&&source.complete||source.getContext)&&source.width&&source.height){this._updateImageType();if(this.imageType==='svg'){this._loadSvgSource();}else{this._sourceLoaded();}if(firstSourceLoaded){// send loaded event if previous source was null and we have been passed a pre-loaded IMG element
this.emit('loaded',this);}}else if(!source.getContext){var _ret=function(){// Image fail / not ready
_this2.isLoading=true;var scope=_this2;source.onload=function(){scope._updateImageType();source.onload=null;source.onerror=null;if(!scope.isLoading){return;}scope.isLoading=false;scope._sourceLoaded();if(scope.imageType==='svg'){scope._loadSvgSource();return;}scope.emit('loaded',scope);};source.onerror=function(){source.onload=null;source.onerror=null;if(!scope.isLoading){return;}scope.isLoading=false;scope.emit('error',scope);};// Per http://www.w3.org/TR/html5/embedded-content-0.html#the-img-element
//   "The value of `complete` can thus change while a script is executing."
// So complete needs to be re-checked after the callbacks have been added..
// NOTE: complete will be true if the image has no src so best to check if the src is set.
if(source.complete&&source.src){// ..and if we're complete now, no need for callbacks
source.onload=null;source.onerror=null;if(scope.imageType==='svg'){scope._loadSvgSource();return{v:void 0};}_this2.isLoading=false;if(source.width&&source.height){_this2._sourceLoaded();// If any previous subscribers possible
if(wasLoading){_this2.emit('loaded',_this2);}}// If any previous subscribers possible
else if(wasLoading){_this2.emit('error',_this2);}}}();if((typeof _ret==='undefined'?'undefined':_typeof(_ret))==="object")return _ret.v;}};/**
     * Updates type of the source image.
     */BaseTexture.prototype._updateImageType=function _updateImageType(){if(!this.imageUrl){return;}var dataUri=(0,_utils.decomposeDataUri)(this.imageUrl);var imageType=void 0;if(dataUri&&dataUri.mediaType==='image'){// Check for subType validity
var firstSubType=dataUri.subType.split('+')[0];imageType=(0,_utils.getUrlFileExtension)('.'+firstSubType);if(!imageType){throw new Error('Invalid image type in data URI.');}}else{imageType=(0,_utils.getUrlFileExtension)(this.imageUrl);if(!imageType){imageType='png';}}this.imageType=imageType;};/**
     * Checks if `source` is an SVG image and whether it's loaded via a URL or a data URI. Then calls
     * `_loadSvgSourceUsingDataUri` or `_loadSvgSourceUsingXhr`.
     */BaseTexture.prototype._loadSvgSource=function _loadSvgSource(){if(this.imageType!=='svg'){// Do nothing if source is not svg
return;}var dataUri=(0,_utils.decomposeDataUri)(this.imageUrl);if(dataUri){this._loadSvgSourceUsingDataUri(dataUri);}else{// We got an URL, so we need to do an XHR to check the svg size
this._loadSvgSourceUsingXhr();}};/**
     * Reads an SVG string from data URI and then calls `_loadSvgSourceUsingString`.
     *
     * @param {string} dataUri - The data uri to load from.
     */BaseTexture.prototype._loadSvgSourceUsingDataUri=function _loadSvgSourceUsingDataUri(dataUri){var svgString=void 0;if(dataUri.encoding==='base64'){if(!atob){throw new Error('Your browser doesn\'t support base64 conversions.');}svgString=atob(dataUri.data);}else{svgString=dataUri.data;}this._loadSvgSourceUsingString(svgString);};/**
     * Loads an SVG string from `imageUrl` using XHR and then calls `_loadSvgSourceUsingString`.
     */BaseTexture.prototype._loadSvgSourceUsingXhr=function _loadSvgSourceUsingXhr(){var _this3=this;var svgXhr=new XMLHttpRequest();// This throws error on IE, so SVG Document can't be used
// svgXhr.responseType = 'document';
// This is not needed since we load the svg as string (breaks IE too)
// but overrideMimeType() can be used to force the response to be parsed as XML
// svgXhr.overrideMimeType('image/svg+xml');
svgXhr.onload=function(){if(svgXhr.readyState!==svgXhr.DONE||svgXhr.status!==200){throw new Error('Failed to load SVG using XHR.');}_this3._loadSvgSourceUsingString(svgXhr.response);};svgXhr.onerror=function(){return _this3.emit('error',_this3);};svgXhr.open('GET',this.imageUrl,true);svgXhr.send();};/**
     * Loads texture using an SVG string. The original SVG Image is stored as `origSource` and the
     * created canvas is the new `source`. The SVG is scaled using `sourceScale`. Called by
     * `_loadSvgSourceUsingXhr` or `_loadSvgSourceUsingDataUri`.
     *
     * @param  {string} svgString SVG source as string
     *
     * @fires loaded
     */BaseTexture.prototype._loadSvgSourceUsingString=function _loadSvgSourceUsingString(svgString){var svgSize=(0,_utils.getSvgSize)(svgString);var svgWidth=svgSize.width;var svgHeight=svgSize.height;if(!svgWidth||!svgHeight){throw new Error('The SVG image must have width and height defined (in pixels), canvas API needs them.');}// Scale realWidth and realHeight
this.realWidth=Math.round(svgWidth*this.sourceScale);this.realHeight=Math.round(svgHeight*this.sourceScale);this.width=this.realWidth/this.resolution;this.height=this.realHeight/this.resolution;// Check pow2 after scale
this.isPowerOfTwo=_bitTwiddle2.default.isPow2(this.realWidth)&&_bitTwiddle2.default.isPow2(this.realHeight);// Create a canvas element
var canvas=document.createElement('canvas');canvas.width=this.realWidth;canvas.height=this.realHeight;canvas._pixiId='canvas_'+(0,_utils.uid)();// Draw the Svg to the canvas
canvas.getContext('2d').drawImage(this.source,0,0,svgWidth,svgHeight,0,0,this.realWidth,this.realHeight);// Replace the original source image with the canvas
this.origSource=this.source;this.source=canvas;// Add also the canvas in cache (destroy clears by `imageUrl` and `source._pixiId`)
_utils.BaseTextureCache[canvas._pixiId]=this;this.isLoading=false;this._sourceLoaded();this.emit('loaded',this);};/**
     * Used internally to update the width, height, and some other tracking vars once
     * a source has successfully loaded.
     *
     * @private
     */BaseTexture.prototype._sourceLoaded=function _sourceLoaded(){this.hasLoaded=true;this.update();};/**
     * Destroys this base texture
     *
     */BaseTexture.prototype.destroy=function destroy(){if(this.imageUrl){delete _utils.BaseTextureCache[this.imageUrl];delete _utils.TextureCache[this.imageUrl];this.imageUrl=null;if(!navigator.isCocoonJS){this.source.src='';}}// An svg source has both `imageUrl` and `__pixiId`, so no `else if` here
if(this.source&&this.source._pixiId){delete _utils.BaseTextureCache[this.source._pixiId];}this.source=null;this.dispose();};/**
     * Frees the texture from WebGL memory without destroying this texture object.
     * This means you can still use the texture later which will upload it to GPU
     * memory again.
     *
     */BaseTexture.prototype.dispose=function dispose(){this.emit('dispose',this);};/**
     * Changes the source image of the texture.
     * The original source must be an Image element.
     *
     * @param {string} newSrc - the path of the image
     */BaseTexture.prototype.updateSourceImage=function updateSourceImage(newSrc){this.source.src=newSrc;this.loadSource(this.source);};/**
     * Helper function that creates a base texture from the given image url.
     * If the image is not in the base texture cache it will be created and loaded.
     *
     * @static
     * @param {string} imageUrl - The image url of the texture
     * @param {boolean} [crossorigin=(auto)] - Should use anonymous CORS? Defaults to true if the URL is not a data-URI.
     * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values
     * @param {number} [sourceScale=(auto)] - Scale for the original image, used with Svg images.
     * @return {PIXI.BaseTexture} The new base texture.
     */BaseTexture.fromImage=function fromImage(imageUrl,crossorigin,scaleMode,sourceScale){var baseTexture=_utils.BaseTextureCache[imageUrl];if(!baseTexture){// new Image() breaks tex loading in some versions of Chrome.
// See https://code.google.com/p/chromium/issues/detail?id=238071
var image=new Image();// document.createElement('img');
if(crossorigin===undefined&&imageUrl.indexOf('data:')!==0){image.crossOrigin=(0,_determineCrossOrigin2.default)(imageUrl);}baseTexture=new BaseTexture(image,scaleMode);baseTexture.imageUrl=imageUrl;if(sourceScale){baseTexture.sourceScale=sourceScale;}// if there is an @2x at the end of the url we are going to assume its a highres image
baseTexture.resolution=(0,_utils.getResolutionOfUrl)(imageUrl);image.src=imageUrl;// Setting this triggers load
_utils.BaseTextureCache[imageUrl]=baseTexture;}return baseTexture;};/**
     * Helper function that creates a base texture from the given canvas element.
     *
     * @static
     * @param {HTMLCanvasElement} canvas - The canvas element source of the texture
     * @param {number} scaleMode - See {@link PIXI.SCALE_MODES} for possible values
     * @return {PIXI.BaseTexture} The new base texture.
     */BaseTexture.fromCanvas=function fromCanvas(canvas,scaleMode){if(!canvas._pixiId){canvas._pixiId='canvas_'+(0,_utils.uid)();}var baseTexture=_utils.BaseTextureCache[canvas._pixiId];if(!baseTexture){baseTexture=new BaseTexture(canvas,scaleMode);_utils.BaseTextureCache[canvas._pixiId]=baseTexture;}return baseTexture;};return BaseTexture;}(_eventemitter2.default);exports.default=BaseTexture;},{"../settings":97,"../utils":117,"../utils/determineCrossOrigin":116,"bit-twiddle":1,"eventemitter3":3}],108:[function(require,module,exports){'use strict';exports.__esModule=true;var _BaseRenderTexture=require('./BaseRenderTexture');var _BaseRenderTexture2=_interopRequireDefault(_BaseRenderTexture);var _Texture2=require('./Texture');var _Texture3=_interopRequireDefault(_Texture2);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return call&&((typeof call==="undefined"?"undefined":_typeof2(call))==="object"||typeof call==="function")?call:self;}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof2(superClass)));}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass;}/**
 * A RenderTexture is a special texture that allows any Pixi display object to be rendered to it.
 *
 * __Hint__: All DisplayObjects (i.e. Sprites) that render to a RenderTexture should be preloaded
 * otherwise black rectangles will be drawn instead.
 *
 * A RenderTexture takes a snapshot of any Display Object given to its render method. The position
 * and rotation of the given Display Objects is ignored. For example:
 *
 * ```js
 * let renderer = PIXI.autoDetectRenderer(1024, 1024, { view: canvas, ratio: 1 });
 * let renderTexture = PIXI.RenderTexture.create(800, 600);
 * let sprite = PIXI.Sprite.fromImage("spinObj_01.png");
 *
 * sprite.position.x = 800/2;
 * sprite.position.y = 600/2;
 * sprite.anchor.x = 0.5;
 * sprite.anchor.y = 0.5;
 *
 * renderer.render(sprite, renderTexture);
 * ```
 *
 * The Sprite in this case will be rendered to a position of 0,0. To render this sprite at its actual
 * position a Container should be used:
 *
 * ```js
 * let doc = new PIXI.Container();
 *
 * doc.addChild(sprite);
 *
 * renderer.render(doc, renderTexture);  // Renders to center of renderTexture
 * ```
 *
 * @class
 * @extends PIXI.Texture
 * @memberof PIXI
 */var RenderTexture=function(_Texture){_inherits(RenderTexture,_Texture);/**
     * @param {PIXI.BaseRenderTexture} baseRenderTexture - The renderer used for this RenderTexture
     * @param {PIXI.Rectangle} [frame] - The rectangle frame of the texture to show
     */function RenderTexture(baseRenderTexture,frame){_classCallCheck(this,RenderTexture);// support for legacy..
var _legacyRenderer=null;if(!(baseRenderTexture instanceof _BaseRenderTexture2.default)){/* eslint-disable prefer-rest-params, no-console */var width=arguments[1];var height=arguments[2];var scaleMode=arguments[3]||0;var resolution=arguments[4]||1;// we have an old render texture..
console.warn('Please use RenderTexture.create('+width+', '+height+') instead of the ctor directly.');_legacyRenderer=arguments[0];/* eslint-enable prefer-rest-params, no-console */frame=null;baseRenderTexture=new _BaseRenderTexture2.default(width,height,scaleMode,resolution);}/**
         * The base texture object that this texture uses
         *
         * @member {BaseTexture}
         */var _this=_possibleConstructorReturn(this,_Texture.call(this,baseRenderTexture,frame));_this.legacyRenderer=_legacyRenderer;/**
         * This will let the renderer know if the texture is valid. If it's not then it cannot be rendered.
         *
         * @member {boolean}
         */_this.valid=true;_this._updateUvs();return _this;}/**
     * Resizes the RenderTexture.
     *
     * @param {number} width - The width to resize to.
     * @param {number} height - The height to resize to.
     * @param {boolean} doNotResizeBaseTexture - Should the baseTexture.width and height values be resized as well?
     */RenderTexture.prototype.resize=function resize(width,height,doNotResizeBaseTexture){// TODO - could be not required..
this.valid=width>0&&height>0;this._frame.width=this.orig.width=width;this._frame.height=this.orig.height=height;if(!doNotResizeBaseTexture){this.baseTexture.resize(width,height);}this._updateUvs();};/**
     * A short hand way of creating a render texture.
     *
     * @param {number} [width=100] - The width of the render texture
     * @param {number} [height=100] - The height of the render texture
     * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values
     * @param {number} [resolution=1] - The resolution / device pixel ratio of the texture being generated
     * @return {PIXI.RenderTexture} The new render texture
     */RenderTexture.create=function create(width,height,scaleMode,resolution){return new RenderTexture(new _BaseRenderTexture2.default(width,height,scaleMode,resolution));};return RenderTexture;}(_Texture3.default);exports.default=RenderTexture;},{"./BaseRenderTexture":106,"./Texture":109}],109:[function(require,module,exports){'use strict';exports.__esModule=true;var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor);}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor;};}();var _BaseTexture=require('./BaseTexture');var _BaseTexture2=_interopRequireDefault(_BaseTexture);var _VideoBaseTexture=require('./VideoBaseTexture');var _VideoBaseTexture2=_interopRequireDefault(_VideoBaseTexture);var _TextureUvs=require('./TextureUvs');var _TextureUvs2=_interopRequireDefault(_TextureUvs);var _eventemitter=require('eventemitter3');var _eventemitter2=_interopRequireDefault(_eventemitter);var _math=require('../math');var _utils=require('../utils');function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return call&&((typeof call==="undefined"?"undefined":_typeof2(call))==="object"||typeof call==="function")?call:self;}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof2(superClass)));}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass;}/**
 * A texture stores the information that represents an image or part of an image. It cannot be added
 * to the display list directly. Instead use it as the texture for a Sprite. If no frame is provided
 * then the whole image is used.
 *
 * You can directly create a texture from an image and then reuse it multiple times like this :
 *
 * ```js
 * let texture = PIXI.Texture.fromImage('assets/image.png');
 * let sprite1 = new PIXI.Sprite(texture);
 * let sprite2 = new PIXI.Sprite(texture);
 * ```
 *
 * Textures made from SVGs, loaded or not, cannot be used before the file finishes processing.
 * You can check for this by checking the sprite's _textureID property.
 * ```js
 * var texture = PIXI.Texture.fromImage('assets/image.svg');
 * var sprite1 = new PIXI.Sprite(texture);
 * //sprite1._textureID should not be undefined if the texture has finished processing the SVG file
 * ```
 * You can use a ticker or rAF to ensure your sprites load the finished textures after processing. See issue #3068.
 *
 * @class
 * @extends EventEmitter
 * @memberof PIXI
 */var Texture=function(_EventEmitter){_inherits(Texture,_EventEmitter);/**
     * @param {PIXI.BaseTexture} baseTexture - The base texture source to create the texture from
     * @param {PIXI.Rectangle} [frame] - The rectangle frame of the texture to show
     * @param {PIXI.Rectangle} [orig] - The area of original texture
     * @param {PIXI.Rectangle} [trim] - Trimmed rectangle of original texture
     * @param {number} [rotate] - indicates how the texture was rotated by texture packer. See {@link PIXI.GroupD8}
     */function Texture(baseTexture,frame,orig,trim,rotate){_classCallCheck(this,Texture);/**
         * Does this Texture have any frame data assigned to it?
         *
         * @member {boolean}
         */var _this=_possibleConstructorReturn(this,_EventEmitter.call(this));_this.noFrame=false;if(!frame){_this.noFrame=true;frame=new _math.Rectangle(0,0,1,1);}if(baseTexture instanceof Texture){baseTexture=baseTexture.baseTexture;}/**
         * The base texture that this texture uses.
         *
         * @member {PIXI.BaseTexture}
         */_this.baseTexture=baseTexture;/**
         * This is the area of the BaseTexture image to actually copy to the Canvas / WebGL when rendering,
         * irrespective of the actual frame size or placement (which can be influenced by trimmed texture atlases)
         *
         * @member {PIXI.Rectangle}
         */_this._frame=frame;/**
         * This is the trimmed area of original texture, before it was put in atlas
         *
         * @member {PIXI.Rectangle}
         */_this.trim=trim;/**
         * This will let the renderer know if the texture is valid. If it's not then it cannot be rendered.
         *
         * @member {boolean}
         */_this.valid=false;/**
         * This will let a renderer know that a texture has been updated (used mainly for webGL uv updates)
         *
         * @member {boolean}
         */_this.requiresUpdate=false;/**
         * The WebGL UV data cache.
         *
         * @member {PIXI.TextureUvs}
         * @private
         */_this._uvs=null;/**
         * This is the area of original texture, before it was put in atlas
         *
         * @member {PIXI.Rectangle}
         */_this.orig=orig||frame;// new Rectangle(0, 0, 1, 1);
_this._rotate=Number(rotate||0);if(rotate===true){// this is old texturepacker legacy, some games/libraries are passing "true" for rotated textures
_this._rotate=2;}else if(_this._rotate%2!==0){throw new Error('attempt to use diamond-shaped UVs. If you are sure, set rotation manually');}if(baseTexture.hasLoaded){if(_this.noFrame){frame=new _math.Rectangle(0,0,baseTexture.width,baseTexture.height);// if there is no frame we should monitor for any base texture changes..
baseTexture.on('update',_this.onBaseTextureUpdated,_this);}_this.frame=frame;}else{baseTexture.once('loaded',_this.onBaseTextureLoaded,_this);}/**
         * Fired when the texture is updated. This happens if the frame or the baseTexture is updated.
         *
         * @event update
         * @memberof PIXI.Texture#
         * @protected
         */_this._updateID=0;/**
         * Extra field for extra plugins. May contain clamp settings and some matrices
         * @type {Object}
         */_this.transform=null;return _this;}/**
     * Updates this texture on the gpu.
     *
     */Texture.prototype.update=function update(){this.baseTexture.update();};/**
     * Called when the base texture is loaded
     *
     * @private
     * @param {PIXI.BaseTexture} baseTexture - The base texture.
     */Texture.prototype.onBaseTextureLoaded=function onBaseTextureLoaded(baseTexture){this._updateID++;// TODO this code looks confusing.. boo to abusing getters and setters!
if(this.noFrame){this.frame=new _math.Rectangle(0,0,baseTexture.width,baseTexture.height);}else{this.frame=this._frame;}this.baseTexture.on('update',this.onBaseTextureUpdated,this);this.emit('update',this);};/**
     * Called when the base texture is updated
     *
     * @private
     * @param {PIXI.BaseTexture} baseTexture - The base texture.
     */Texture.prototype.onBaseTextureUpdated=function onBaseTextureUpdated(baseTexture){this._updateID++;this._frame.width=baseTexture.width;this._frame.height=baseTexture.height;this.emit('update',this);};/**
     * Destroys this texture
     *
     * @param {boolean} [destroyBase=false] Whether to destroy the base texture as well
     */Texture.prototype.destroy=function destroy(destroyBase){if(this.baseTexture){if(destroyBase){// delete the texture if it exists in the texture cache..
// this only needs to be removed if the base texture is actually destroyed too..
if(_utils.TextureCache[this.baseTexture.imageUrl]){delete _utils.TextureCache[this.baseTexture.imageUrl];}this.baseTexture.destroy();}this.baseTexture.off('update',this.onBaseTextureUpdated,this);this.baseTexture.off('loaded',this.onBaseTextureLoaded,this);this.baseTexture=null;}this._frame=null;this._uvs=null;this.trim=null;this.orig=null;this.valid=false;this.off('dispose',this.dispose,this);this.off('update',this.update,this);};/**
     * Creates a new texture object that acts the same as this one.
     *
     * @return {PIXI.Texture} The new texture
     */Texture.prototype.clone=function clone(){return new Texture(this.baseTexture,this.frame,this.orig,this.trim,this.rotate);};/**
     * Updates the internal WebGL UV cache.
     *
     * @protected
     */Texture.prototype._updateUvs=function _updateUvs(){if(!this._uvs){this._uvs=new _TextureUvs2.default();}this._uvs.set(this._frame,this.baseTexture,this.rotate);this._updateID++;};/**
     * Helper function that creates a Texture object from the given image url.
     * If the image is not in the texture cache it will be  created and loaded.
     *
     * @static
     * @param {string} imageUrl - The image url of the texture
     * @param {boolean} [crossorigin] - Whether requests should be treated as crossorigin
     * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values
     * @param {number} [sourceScale=(auto)] - Scale for the original image, used with SVG images.
     * @return {PIXI.Texture} The newly created texture
     */Texture.fromImage=function fromImage(imageUrl,crossorigin,scaleMode,sourceScale){var texture=_utils.TextureCache[imageUrl];if(!texture){texture=new Texture(_BaseTexture2.default.fromImage(imageUrl,crossorigin,scaleMode,sourceScale));_utils.TextureCache[imageUrl]=texture;}return texture;};/**
     * Helper function that creates a sprite that will contain a texture from the TextureCache based on the frameId
     * The frame ids are created when a Texture packer file has been loaded
     *
     * @static
     * @param {string} frameId - The frame Id of the texture in the cache
     * @return {PIXI.Texture} The newly created texture
     */Texture.fromFrame=function fromFrame(frameId){var texture=_utils.TextureCache[frameId];if(!texture){throw new Error('The frameId "'+frameId+'" does not exist in the texture cache');}return texture;};/**
     * Helper function that creates a new Texture based on the given canvas element.
     *
     * @static
     * @param {HTMLCanvasElement} canvas - The canvas element source of the texture
     * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values
     * @return {PIXI.Texture} The newly created texture
     */Texture.fromCanvas=function fromCanvas(canvas,scaleMode){return new Texture(_BaseTexture2.default.fromCanvas(canvas,scaleMode));};/**
     * Helper function that creates a new Texture based on the given video element.
     *
     * @static
     * @param {HTMLVideoElement|string} video - The URL or actual element of the video
     * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values
     * @return {PIXI.Texture} The newly created texture
     */Texture.fromVideo=function fromVideo(video,scaleMode){if(typeof video==='string'){return Texture.fromVideoUrl(video,scaleMode);}return new Texture(_VideoBaseTexture2.default.fromVideo(video,scaleMode));};/**
     * Helper function that creates a new Texture based on the video url.
     *
     * @static
     * @param {string} videoUrl - URL of the video
     * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values
     * @return {PIXI.Texture} The newly created texture
     */Texture.fromVideoUrl=function fromVideoUrl(videoUrl,scaleMode){return new Texture(_VideoBaseTexture2.default.fromUrl(videoUrl,scaleMode));};/**
     * Helper function that creates a new Texture based on the source you provide.
     * The source can be - frame id, image url, video url, canvas element, video element, base texture
     *
     * @static
     * @param {number|string|PIXI.BaseTexture|HTMLCanvasElement|HTMLVideoElement} source - Source to create texture from
     * @return {PIXI.Texture} The newly created texture
     */Texture.from=function from(source){// TODO auto detect cross origin..
// TODO pass in scale mode?
if(typeof source==='string'){var texture=_utils.TextureCache[source];if(!texture){// check if its a video..
var isVideo=source.match(/\.(mp4|webm|ogg|h264|avi|mov)$/)!==null;if(isVideo){return Texture.fromVideoUrl(source);}return Texture.fromImage(source);}return texture;}else if(source instanceof HTMLImageElement){return new Texture(new _BaseTexture2.default(source));}else if(source instanceof HTMLCanvasElement){return Texture.fromCanvas(source);}else if(source instanceof HTMLVideoElement){return Texture.fromVideo(source);}else if(source instanceof _BaseTexture2.default){return new Texture(source);}// lets assume its a texture!
return source;};/**
     * Adds a texture to the global TextureCache. This cache is shared across the whole PIXI object.
     *
     * @static
     * @param {PIXI.Texture} texture - The Texture to add to the cache.
     * @param {string} id - The id that the texture will be stored against.
     */Texture.addTextureToCache=function addTextureToCache(texture,id){_utils.TextureCache[id]=texture;};/**
     * Remove a texture from the global TextureCache.
     *
     * @static
     * @param {string} id - The id of the texture to be removed
     * @return {PIXI.Texture} The texture that was removed
     */Texture.removeTextureFromCache=function removeTextureFromCache(id){var texture=_utils.TextureCache[id];delete _utils.TextureCache[id];delete _utils.BaseTextureCache[id];return texture;};/**
     * The frame specifies the region of the base texture that this texture uses.
     *
     * @member {PIXI.Rectangle}
     * @memberof PIXI.Texture#
     */_createClass(Texture,[{key:'frame',get:function get(){return this._frame;}/**
         * Set the frame.
         *
         * @param {Rectangle} frame - The new frame to set.
         */,set:function set(frame){this._frame=frame;this.noFrame=false;if(frame.x+frame.width>this.baseTexture.width||frame.y+frame.height>this.baseTexture.height){throw new Error('Texture Error: frame does not fit inside the base Texture dimensions '+this);}// this.valid = frame && frame.width && frame.height && this.baseTexture.source && this.baseTexture.hasLoaded;
this.valid=frame&&frame.width&&frame.height&&this.baseTexture.hasLoaded;if(!this.trim&&!this.rotate){this.orig=frame;}if(this.valid){this._updateUvs();}}/**
         * Indicates whether the texture is rotated inside the atlas
         * set to 2 to compensate for texture packer rotation
         * set to 6 to compensate for spine packer rotation
         * can be used to rotate or mirror sprites
         * See {@link PIXI.GroupD8} for explanation
         *
         * @member {number}
         */},{key:'rotate',get:function get(){return this._rotate;}/**
         * Set the rotation
         *
         * @param {number} rotate - The new rotation to set.
         */,set:function set(rotate){this._rotate=rotate;if(this.valid){this._updateUvs();}}/**
         * The width of the Texture in pixels.
         *
         * @member {number}
         */},{key:'width',get:function get(){return this.orig.width;}/**
         * The height of the Texture in pixels.
         *
         * @member {number}
         */},{key:'height',get:function get(){return this.orig.height;}}]);return Texture;}(_eventemitter2.default);/**
 * An empty texture, used often to not have to create multiple empty textures.
 * Can not be destroyed.
 *
 * @static
 * @constant
 */exports.default=Texture;Texture.EMPTY=new Texture(new _BaseTexture2.default());Texture.EMPTY.destroy=function _emptyDestroy(){/* empty */};Texture.EMPTY.on=function _emptyOn(){/* empty */};Texture.EMPTY.once=function _emptyOnce(){/* empty */};Texture.EMPTY.emit=function _emptyEmit(){/* empty */};},{"../math":66,"../utils":117,"./BaseTexture":107,"./TextureUvs":110,"./VideoBaseTexture":111,"eventemitter3":3}],110:[function(require,module,exports){'use strict';exports.__esModule=true;var _GroupD=require('../math/GroupD8');var _GroupD2=_interopRequireDefault(_GroupD);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}/**
 * A standard object to store the Uvs of a texture
 *
 * @class
 * @private
 * @memberof PIXI
 */var TextureUvs=function(){/**
     *
     */function TextureUvs(){_classCallCheck(this,TextureUvs);this.x0=0;this.y0=0;this.x1=1;this.y1=0;this.x2=1;this.y2=1;this.x3=0;this.y3=1;this.uvsUint32=new Uint32Array(4);}/**
     * Sets the texture Uvs based on the given frame information.
     *
     * @private
     * @param {PIXI.Rectangle} frame - The frame of the texture
     * @param {PIXI.Rectangle} baseFrame - The base frame of the texture
     * @param {number} rotate - Rotation of frame, see {@link PIXI.GroupD8}
     */TextureUvs.prototype.set=function set(frame,baseFrame,rotate){var tw=baseFrame.width;var th=baseFrame.height;if(rotate){// width and height div 2 div baseFrame size
var w2=frame.width/2/tw;var h2=frame.height/2/th;// coordinates of center
var cX=frame.x/tw+w2;var cY=frame.y/th+h2;rotate=_GroupD2.default.add(rotate,_GroupD2.default.NW);// NW is top-left corner
this.x0=cX+w2*_GroupD2.default.uX(rotate);this.y0=cY+h2*_GroupD2.default.uY(rotate);rotate=_GroupD2.default.add(rotate,2);// rotate 90 degrees clockwise
this.x1=cX+w2*_GroupD2.default.uX(rotate);this.y1=cY+h2*_GroupD2.default.uY(rotate);rotate=_GroupD2.default.add(rotate,2);this.x2=cX+w2*_GroupD2.default.uX(rotate);this.y2=cY+h2*_GroupD2.default.uY(rotate);rotate=_GroupD2.default.add(rotate,2);this.x3=cX+w2*_GroupD2.default.uX(rotate);this.y3=cY+h2*_GroupD2.default.uY(rotate);}else{this.x0=frame.x/tw;this.y0=frame.y/th;this.x1=(frame.x+frame.width)/tw;this.y1=frame.y/th;this.x2=(frame.x+frame.width)/tw;this.y2=(frame.y+frame.height)/th;this.x3=frame.x/tw;this.y3=(frame.y+frame.height)/th;}this.uvsUint32[0]=(this.y0*65535&0xFFFF)<<16|this.x0*65535&0xFFFF;this.uvsUint32[1]=(this.y1*65535&0xFFFF)<<16|this.x1*65535&0xFFFF;this.uvsUint32[2]=(this.y2*65535&0xFFFF)<<16|this.x2*65535&0xFFFF;this.uvsUint32[3]=(this.y3*65535&0xFFFF)<<16|this.x3*65535&0xFFFF;};return TextureUvs;}();exports.default=TextureUvs;},{"../math/GroupD8":62}],111:[function(require,module,exports){'use strict';exports.__esModule=true;var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor);}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor;};}();var _BaseTexture2=require('./BaseTexture');var _BaseTexture3=_interopRequireDefault(_BaseTexture2);var _utils=require('../utils');var _ticker=require('../ticker');var ticker=_interopRequireWildcard(_ticker);function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj;}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key];}}newObj.default=obj;return newObj;}}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return call&&((typeof call==="undefined"?"undefined":_typeof2(call))==="object"||typeof call==="function")?call:self;}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof2(superClass)));}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass;}/**
 * A texture of a [playing] Video.
 *
 * Video base textures mimic Pixi BaseTexture.from.... method in their creation process.
 *
 * This can be used in several ways, such as:
 *
 * ```js
 * let texture = PIXI.VideoBaseTexture.fromUrl('http://mydomain.com/video.mp4');
 *
 * let texture = PIXI.VideoBaseTexture.fromUrl({ src: 'http://mydomain.com/video.mp4', mime: 'video/mp4' });
 *
 * let texture = PIXI.VideoBaseTexture.fromUrls(['/video.webm', '/video.mp4']);
 *
 * let texture = PIXI.VideoBaseTexture.fromUrls([
 *     { src: '/video.webm', mime: 'video/webm' },
 *     { src: '/video.mp4', mime: 'video/mp4' }
 * ]);
 * ```
 *
 * See the ["deus" demo](http://www.goodboydigital.com/pixijs/examples/deus/).
 *
 * @class
 * @extends PIXI.BaseTexture
 * @memberof PIXI
 */var VideoBaseTexture=function(_BaseTexture){_inherits(VideoBaseTexture,_BaseTexture);/**
     * @param {HTMLVideoElement} source - Video source
     * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values
     */function VideoBaseTexture(source,scaleMode){_classCallCheck(this,VideoBaseTexture);if(!source){throw new Error('No video source element specified.');}// hook in here to check if video is already available.
// BaseTexture looks for a source.complete boolean, plus width & height.
if((source.readyState===source.HAVE_ENOUGH_DATA||source.readyState===source.HAVE_FUTURE_DATA)&&source.width&&source.height){source.complete=true;}var _this=_possibleConstructorReturn(this,_BaseTexture.call(this,source,scaleMode));_this.width=source.videoWidth;_this.height=source.videoHeight;_this._autoUpdate=true;_this._isAutoUpdating=false;/**
         * When set to true will automatically play videos used by this texture once
         * they are loaded. If false, it will not modify the playing state.
         *
         * @member {boolean}
         * @default true
         */_this.autoPlay=true;_this.update=_this.update.bind(_this);_this._onCanPlay=_this._onCanPlay.bind(_this);source.addEventListener('play',_this._onPlayStart.bind(_this));source.addEventListener('pause',_this._onPlayStop.bind(_this));_this.hasLoaded=false;_this.__loaded=false;if(!_this._isSourceReady()){source.addEventListener('canplay',_this._onCanPlay);source.addEventListener('canplaythrough',_this._onCanPlay);}else{_this._onCanPlay();}return _this;}/**
     * Returns true if the underlying source is playing.
     *
     * @private
     * @return {boolean} True if playing.
     */VideoBaseTexture.prototype._isSourcePlaying=function _isSourcePlaying(){var source=this.source;return source.currentTime>0&&source.paused===false&&source.ended===false&&source.readyState>2;};/**
     * Returns true if the underlying source is ready for playing.
     *
     * @private
     * @return {boolean} True if ready.
     */VideoBaseTexture.prototype._isSourceReady=function _isSourceReady(){return this.source.readyState===3||this.source.readyState===4;};/**
     * Runs the update loop when the video is ready to play
     *
     * @private
     */VideoBaseTexture.prototype._onPlayStart=function _onPlayStart(){// Just in case the video has not received its can play even yet..
if(!this.hasLoaded){this._onCanPlay();}if(!this._isAutoUpdating&&this.autoUpdate){ticker.shared.add(this.update,this);this._isAutoUpdating=true;}};/**
     * Fired when a pause event is triggered, stops the update loop
     *
     * @private
     */VideoBaseTexture.prototype._onPlayStop=function _onPlayStop(){if(this._isAutoUpdating){ticker.shared.remove(this.update,this);this._isAutoUpdating=false;}};/**
     * Fired when the video is loaded and ready to play
     *
     * @private
     */VideoBaseTexture.prototype._onCanPlay=function _onCanPlay(){this.hasLoaded=true;if(this.source){this.source.removeEventListener('canplay',this._onCanPlay);this.source.removeEventListener('canplaythrough',this._onCanPlay);this.width=this.source.videoWidth;this.height=this.source.videoHeight;// prevent multiple loaded dispatches..
if(!this.__loaded){this.__loaded=true;this.emit('loaded',this);}if(this._isSourcePlaying()){this._onPlayStart();}else if(this.autoPlay){this.source.play();}}};/**
     * Destroys this texture
     *
     */VideoBaseTexture.prototype.destroy=function destroy(){if(this._isAutoUpdating){ticker.shared.remove(this.update,this);}if(this.source&&this.source._pixiId){delete _utils.BaseTextureCache[this.source._pixiId];delete this.source._pixiId;}_BaseTexture.prototype.destroy.call(this);};/**
     * Mimic Pixi BaseTexture.from.... method.
     *
     * @static
     * @param {HTMLVideoElement} video - Video to create texture from
     * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values
     * @return {PIXI.VideoBaseTexture} Newly created VideoBaseTexture
     */VideoBaseTexture.fromVideo=function fromVideo(video,scaleMode){if(!video._pixiId){video._pixiId='video_'+(0,_utils.uid)();}var baseTexture=_utils.BaseTextureCache[video._pixiId];if(!baseTexture){baseTexture=new VideoBaseTexture(video,scaleMode);_utils.BaseTextureCache[video._pixiId]=baseTexture;}return baseTexture;};/**
     * Helper function that creates a new BaseTexture based on the given video element.
     * This BaseTexture can then be used to create a texture
     *
     * @static
     * @param {string|object|string[]|object[]} videoSrc - The URL(s) for the video.
     * @param {string} [videoSrc.src] - One of the source urls for the video
     * @param {string} [videoSrc.mime] - The mimetype of the video (e.g. 'video/mp4'). If not specified
     *  the url's extension will be used as the second part of the mime type.
     * @param {number} scaleMode - See {@link PIXI.SCALE_MODES} for possible values
     * @return {PIXI.VideoBaseTexture} Newly created VideoBaseTexture
     */VideoBaseTexture.fromUrl=function fromUrl(videoSrc,scaleMode){var video=document.createElement('video');video.setAttribute('webkit-playsinline','');video.setAttribute('playsinline','');// array of objects or strings
if(Array.isArray(videoSrc)){for(var i=0;i<videoSrc.length;++i){video.appendChild(createSource(videoSrc[i].src||videoSrc[i],videoSrc[i].mime));}}// single object or string
else{video.appendChild(createSource(videoSrc.src||videoSrc,videoSrc.mime));}video.load();return VideoBaseTexture.fromVideo(video,scaleMode);};/**
     * Should the base texture automatically update itself, set to true by default
     *
     * @member {boolean}
     * @memberof PIXI.VideoBaseTexture#
     */_createClass(VideoBaseTexture,[{key:'autoUpdate',get:function get(){return this._autoUpdate;}/**
         * Sets autoUpdate property.
         *
         * @param {number} value - enable auto update or not
         */,set:function set(value){if(value!==this._autoUpdate){this._autoUpdate=value;if(!this._autoUpdate&&this._isAutoUpdating){ticker.shared.remove(this.update,this);this._isAutoUpdating=false;}else if(this._autoUpdate&&!this._isAutoUpdating){ticker.shared.add(this.update,this);this._isAutoUpdating=true;}}}}]);return VideoBaseTexture;}(_BaseTexture3.default);exports.default=VideoBaseTexture;VideoBaseTexture.fromUrls=VideoBaseTexture.fromUrl;function createSource(path,type){if(!type){type='video/'+path.substr(path.lastIndexOf('.')+1);}var source=document.createElement('source');source.src=path;source.type=type;return source;}},{"../ticker":113,"../utils":117,"./BaseTexture":107}],112:[function(require,module,exports){'use strict';exports.__esModule=true;var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor);}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor;};}();var _settings=require('../settings');var _settings2=_interopRequireDefault(_settings);var _eventemitter=require('eventemitter3');var _eventemitter2=_interopRequireDefault(_eventemitter);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}// Internal event used by composed emitter
var TICK='tick';/**
 * A Ticker class that runs an update loop that other objects listen to.
 * This class is composed around an EventEmitter object to add listeners
 * meant for execution on the next requested animation frame.
 * Animation frames are requested only when necessary,
 * e.g. When the ticker is started and the emitter has listeners.
 *
 * @class
 * @memberof PIXI.ticker
 */var Ticker=function(){/**
     *
     */function Ticker(){var _this=this;_classCallCheck(this,Ticker);/**
         * Internal emitter used to fire 'tick' event
         * @private
         */this._emitter=new _eventemitter2.default();/**
         * Internal current frame request ID
         * @private
         */this._requestId=null;/**
         * Internal value managed by minFPS property setter and getter.
         * This is the maximum allowed milliseconds between updates.
         * @private
         */this._maxElapsedMS=100;/**
         * Whether or not this ticker should invoke the method
         * {@link PIXI.ticker.Ticker#start} automatically
         * when a listener is added.
         *
         * @member {boolean}
         * @default false
         */this.autoStart=false;/**
         * Scalar time value from last frame to this frame.
         * This value is capped by setting {@link PIXI.ticker.Ticker#minFPS}
         * and is scaled with {@link PIXI.ticker.Ticker#speed}.
         * **Note:** The cap may be exceeded by scaling.
         *
         * @member {number}
         * @default 1
         */this.deltaTime=1;/**
         * Time elapsed in milliseconds from last frame to this frame.
         * Opposed to what the scalar {@link PIXI.ticker.Ticker#deltaTime}
         * is based, this value is neither capped nor scaled.
         * If the platform supports DOMHighResTimeStamp,
         * this value will have a precision of 1 µs.
         *
         * @member {number}
         * @default 1 / TARGET_FPMS
         */this.elapsedMS=1/_settings2.default.TARGET_FPMS;// default to target frame time
/**
         * The last time {@link PIXI.ticker.Ticker#update} was invoked.
         * This value is also reset internally outside of invoking
         * update, but only when a new animation frame is requested.
         * If the platform supports DOMHighResTimeStamp,
         * this value will have a precision of 1 µs.
         *
         * @member {number}
         * @default 0
         */this.lastTime=0;/**
         * Factor of current {@link PIXI.ticker.Ticker#deltaTime}.
         * @example
         * // Scales ticker.deltaTime to what would be
         * // the equivalent of approximately 120 FPS
         * ticker.speed = 2;
         *
         * @member {number}
         * @default 1
         */this.speed=1;/**
         * Whether or not this ticker has been started.
         * `true` if {@link PIXI.ticker.Ticker#start} has been called.
         * `false` if {@link PIXI.ticker.Ticker#stop} has been called.
         * While `false`, this value may change to `true` in the
         * event of {@link PIXI.ticker.Ticker#autoStart} being `true`
         * and a listener is added.
         *
         * @member {boolean}
         * @default false
         */this.started=false;/**
         * Internal tick method bound to ticker instance.
         * This is because in early 2015, Function.bind
         * is still 60% slower in high performance scenarios.
         * Also separating frame requests from update method
         * so listeners may be called at any time and with
         * any animation API, just invoke ticker.update(time).
         *
         * @private
         * @param {number} time - Time since last tick.
         */this._tick=function(time){_this._requestId=null;if(_this.started){// Invoke listeners now
_this.update(time);// Listener side effects may have modified ticker state.
if(_this.started&&_this._requestId===null&&_this._emitter.listeners(TICK,true)){_this._requestId=requestAnimationFrame(_this._tick);}}};}/**
     * Conditionally requests a new animation frame.
     * If a frame has not already been requested, and if the internal
     * emitter has listeners, a new frame is requested.
     *
     * @private
     */Ticker.prototype._requestIfNeeded=function _requestIfNeeded(){if(this._requestId===null&&this._emitter.listeners(TICK,true)){// ensure callbacks get correct delta
this.lastTime=performance.now();this._requestId=requestAnimationFrame(this._tick);}};/**
     * Conditionally cancels a pending animation frame.
     *
     * @private
     */Ticker.prototype._cancelIfNeeded=function _cancelIfNeeded(){if(this._requestId!==null){cancelAnimationFrame(this._requestId);this._requestId=null;}};/**
     * Conditionally requests a new animation frame.
     * If the ticker has been started it checks if a frame has not already
     * been requested, and if the internal emitter has listeners. If these
     * conditions are met, a new frame is requested. If the ticker has not
     * been started, but autoStart is `true`, then the ticker starts now,
     * and continues with the previous conditions to request a new frame.
     *
     * @private
     */Ticker.prototype._startIfPossible=function _startIfPossible(){if(this.started){this._requestIfNeeded();}else if(this.autoStart){this.start();}};/**
     * Calls {@link module:eventemitter3.EventEmitter#on} internally for the
     * internal 'tick' event. It checks if the emitter has listeners,
     * and if so it requests a new animation frame at this point.
     *
     * @param {Function} fn - The listener function to be added for updates
     * @param {Function} [context] - The listener context
     * @returns {PIXI.ticker.Ticker} This instance of a ticker
     */Ticker.prototype.add=function add(fn,context){this._emitter.on(TICK,fn,context);this._startIfPossible();return this;};/**
     * Calls {@link module:eventemitter3.EventEmitter#once} internally for the
     * internal 'tick' event. It checks if the emitter has listeners,
     * and if so it requests a new animation frame at this point.
     *
     * @param {Function} fn - The listener function to be added for one update
     * @param {Function} [context] - The listener context
     * @returns {PIXI.ticker.Ticker} This instance of a ticker
     */Ticker.prototype.addOnce=function addOnce(fn,context){this._emitter.once(TICK,fn,context);this._startIfPossible();return this;};/**
     * Calls {@link module:eventemitter3.EventEmitter#off} internally for 'tick' event.
     * It checks if the emitter has listeners for 'tick' event.
     * If it does, then it cancels the animation frame.
     *
     * @param {Function} [fn] - The listener function to be removed
     * @param {Function} [context] - The listener context to be removed
     * @returns {PIXI.ticker.Ticker} This instance of a ticker
     */Ticker.prototype.remove=function remove(fn,context){this._emitter.off(TICK,fn,context);if(!this._emitter.listeners(TICK,true)){this._cancelIfNeeded();}return this;};/**
     * Starts the ticker. If the ticker has listeners
     * a new animation frame is requested at this point.
     */Ticker.prototype.start=function start(){if(!this.started){this.started=true;this._requestIfNeeded();}};/**
     * Stops the ticker. If the ticker has requested
     * an animation frame it is canceled at this point.
     */Ticker.prototype.stop=function stop(){if(this.started){this.started=false;this._cancelIfNeeded();}};/**
     * Triggers an update. An update entails setting the
     * current {@link PIXI.ticker.Ticker#elapsedMS},
     * the current {@link PIXI.ticker.Ticker#deltaTime},
     * invoking all listeners with current deltaTime,
     * and then finally setting {@link PIXI.ticker.Ticker#lastTime}
     * with the value of currentTime that was provided.
     * This method will be called automatically by animation
     * frame callbacks if the ticker instance has been started
     * and listeners are added.
     *
     * @param {number} [currentTime=performance.now()] - the current time of execution
     */Ticker.prototype.update=function update(){var currentTime=arguments.length<=0||arguments[0]===undefined?performance.now():arguments[0];var elapsedMS=void 0;// If the difference in time is zero or negative, we ignore most of the work done here.
// If there is no valid difference, then should be no reason to let anyone know about it.
// A zero delta, is exactly that, nothing should update.
//
// The difference in time can be negative, and no this does not mean time traveling.
// This can be the result of a race condition between when an animation frame is requested
// on the current JavaScript engine event loop, and when the ticker's start method is invoked
// (which invokes the internal _requestIfNeeded method). If a frame is requested before
// _requestIfNeeded is invoked, then the callback for the animation frame the ticker requests,
// can receive a time argument that can be less than the lastTime value that was set within
// _requestIfNeeded. This difference is in microseconds, but this is enough to cause problems.
//
// This check covers this browser engine timing issue, as well as if consumers pass an invalid
// currentTime value. This may happen if consumers opt-out of the autoStart, and update themselves.
if(currentTime>this.lastTime){// Save uncapped elapsedMS for measurement
elapsedMS=this.elapsedMS=currentTime-this.lastTime;// cap the milliseconds elapsed used for deltaTime
if(elapsedMS>this._maxElapsedMS){elapsedMS=this._maxElapsedMS;}this.deltaTime=elapsedMS*_settings2.default.TARGET_FPMS*this.speed;// Invoke listeners added to internal emitter
this._emitter.emit(TICK,this.deltaTime);}else{this.deltaTime=this.elapsedMS=0;}this.lastTime=currentTime;};/**
     * The frames per second at which this ticker is running.
     * The default is approximately 60 in most modern browsers.
     * **Note:** This does not factor in the value of
     * {@link PIXI.ticker.Ticker#speed}, which is specific
     * to scaling {@link PIXI.ticker.Ticker#deltaTime}.
     *
     * @memberof PIXI.ticker.Ticker#
     * @readonly
     */_createClass(Ticker,[{key:'FPS',get:function get(){return 1000/this.elapsedMS;}/**
         * Manages the maximum amount of milliseconds allowed to
         * elapse between invoking {@link PIXI.ticker.Ticker#update}.
         * This value is used to cap {@link PIXI.ticker.Ticker#deltaTime},
         * but does not effect the measured value of {@link PIXI.ticker.Ticker#FPS}.
         * When setting this property it is clamped to a value between
         * `0` and `PIXI.settings.TARGET_FPMS * 1000`.
         *
         * @memberof PIXI.ticker.Ticker#
         * @default 10
         */},{key:'minFPS',get:function get(){return 1000/this._maxElapsedMS;}/**
         * Sets the min fps.
         *
         * @param {number} fps - value to set.
         */,set:function set(fps){// Clamp: 0 to TARGET_FPMS
var minFPMS=Math.min(Math.max(0,fps)/1000,_settings2.default.TARGET_FPMS);this._maxElapsedMS=1/minFPMS;}}]);return Ticker;}();exports.default=Ticker;},{"../settings":97,"eventemitter3":3}],113:[function(require,module,exports){'use strict';exports.__esModule=true;exports.Ticker=exports.shared=undefined;var _Ticker=require('./Ticker');var _Ticker2=_interopRequireDefault(_Ticker);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}/**
 * The shared ticker instance used by {@link PIXI.extras.AnimatedSprite}.
 * and by {@link PIXI.interaction.InteractionManager}.
 * The property {@link PIXI.ticker.Ticker#autoStart} is set to `true`
 * for this instance. Please follow the examples for usage, including
 * how to opt-out of auto-starting the shared ticker.
 *
 * @example
 * let ticker = PIXI.ticker.shared;
 * // Set this to prevent starting this ticker when listeners are added.
 * // By default this is true only for the PIXI.ticker.shared instance.
 * ticker.autoStart = false;
 * // FYI, call this to ensure the ticker is stopped. It should be stopped
 * // if you have not attempted to render anything yet.
 * ticker.stop();
 * // Call this when you are ready for a running shared ticker.
 * ticker.start();
 *
 * @example
 * // You may use the shared ticker to render...
 * let renderer = PIXI.autoDetectRenderer(800, 600);
 * let stage = new PIXI.Container();
 * let interactionManager = PIXI.interaction.InteractionManager(renderer);
 * document.body.appendChild(renderer.view);
 * ticker.add(function (time) {
 *     renderer.render(stage);
 * });
 *
 * @example
 * // Or you can just update it manually.
 * ticker.autoStart = false;
 * ticker.stop();
 * function animate(time) {
 *     ticker.update(time);
 *     renderer.render(stage);
 *     requestAnimationFrame(animate);
 * }
 * animate(performance.now());
 *
 * @type {PIXI.ticker.Ticker}
 * @memberof PIXI.ticker
 */var shared=new _Ticker2.default();shared.autoStart=true;/**
 * @namespace PIXI.ticker
 */exports.shared=shared;exports.Ticker=_Ticker2.default;},{"./Ticker":112}],114:[function(require,module,exports){"use strict";exports.__esModule=true;exports.default=canUploadSameBuffer;function canUploadSameBuffer(){// Uploading the same buffer multiple times in a single frame can cause perf issues.
// Apparent on IOS so only check for that at the moment
// this check may become more complex if this issue pops up elsewhere.
var ios=!!navigator.platform&&/iPad|iPhone|iPod/.test(navigator.platform);return!ios;}},{}],115:[function(require,module,exports){"use strict";exports.__esModule=true;exports.default=createIndicesForQuads;/**
 * Generic Mask Stack data structure
 *
 * @memberof PIXI
 * @function createIndicesForQuads
 * @private
 * @param {number} size - Number of quads
 * @return {Uint16Array} indices
 */function createIndicesForQuads(size){// the total number of indices in our array, there are 6 points per quad.
var totalIndices=size*6;var indices=new Uint16Array(totalIndices);// fill the indices with the quads to draw
for(var i=0,j=0;i<totalIndices;i+=6,j+=4){indices[i+0]=j+0;indices[i+1]=j+1;indices[i+2]=j+2;indices[i+3]=j+0;indices[i+4]=j+2;indices[i+5]=j+3;}return indices;}},{}],116:[function(require,module,exports){'use strict';exports.__esModule=true;exports.default=determineCrossOrigin;var _url2=require('url');var _url3=_interopRequireDefault(_url2);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}var tempAnchor=void 0;/**
 * Sets the `crossOrigin` property for this resource based on if the url
 * for this resource is cross-origin. If crossOrigin was manually set, this
 * function does nothing.
 * Nipped from the resource loader!
 *
 * @ignore
 * @param {string} url - The url to test.
 * @param {object} [loc=window.location] - The location object to test against.
 * @return {string} The crossOrigin value to use (or empty string for none).
 */function determineCrossOrigin(url){var loc=arguments.length<=1||arguments[1]===undefined?window.location:arguments[1];// data: and javascript: urls are considered same-origin
if(url.indexOf('data:')===0){return'';}// default is window.location
loc=loc||window.location;if(!tempAnchor){tempAnchor=document.createElement('a');}// let the browser determine the full href for the url of this resource and then
// parse with the node url lib, we can't use the properties of the anchor element
// because they don't work in IE9 :(
tempAnchor.href=url;url=_url3.default.parse(tempAnchor.href);var samePort=!url.port&&loc.port===''||url.port===loc.port;// if cross origin
if(url.hostname!==loc.hostname||!samePort||url.protocol!==loc.protocol){return'anonymous';}return'';}},{"url":28}],117:[function(require,module,exports){'use strict';exports.__esModule=true;exports.BaseTextureCache=exports.TextureCache=exports.pluginTarget=exports.EventEmitter=exports.isMobile=undefined;exports.uid=uid;exports.hex2rgb=hex2rgb;exports.hex2string=hex2string;exports.rgb2hex=rgb2hex;exports.getResolutionOfUrl=getResolutionOfUrl;exports.decomposeDataUri=decomposeDataUri;exports.getUrlFileExtension=getUrlFileExtension;exports.getSvgSize=getSvgSize;exports.skipHello=skipHello;exports.sayHello=sayHello;exports.isWebGLSupported=isWebGLSupported;exports.sign=sign;exports.removeItems=removeItems;var _const=require('../const');var _settings=require('../settings');var _settings2=_interopRequireDefault(_settings);var _eventemitter=require('eventemitter3');var _eventemitter2=_interopRequireDefault(_eventemitter);var _pluginTarget=require('./pluginTarget');var _pluginTarget2=_interopRequireDefault(_pluginTarget);var _ismobilejs=require('ismobilejs');var isMobile=_interopRequireWildcard(_ismobilejs);function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj;}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key];}}newObj.default=obj;return newObj;}}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}var nextUid=0;var saidHello=false;/**
 * @namespace PIXI.utils
 */exports.isMobile=isMobile;exports.EventEmitter=_eventemitter2.default;exports.pluginTarget=_pluginTarget2.default;/**
 * Gets the next unique identifier
 *
 * @memberof PIXI.utils
 * @function uid
 * @return {number} The next unique identifier to use.
 */function uid(){return++nextUid;}/**
 * Converts a hex color number to an [R, G, B] array
 *
 * @memberof PIXI.utils
 * @function hex2rgb
 * @param {number} hex - The number to convert
 * @param  {number[]} [out=[]] If supplied, this array will be used rather than returning a new one
 * @return {number[]} An array representing the [R, G, B] of the color.
 */function hex2rgb(hex,out){out=out||[];out[0]=(hex>>16&0xFF)/255;out[1]=(hex>>8&0xFF)/255;out[2]=(hex&0xFF)/255;return out;}/**
 * Converts a hex color number to a string.
 *
 * @memberof PIXI.utils
 * @function hex2string
 * @param {number} hex - Number in hex
 * @return {string} The string color.
 */function hex2string(hex){hex=hex.toString(16);hex='000000'.substr(0,6-hex.length)+hex;return'#'+hex;}/**
 * Converts a color as an [R, G, B] array to a hex number
 *
 * @memberof PIXI.utils
 * @function rgb2hex
 * @param {number[]} rgb - rgb array
 * @return {number} The color number
 */function rgb2hex(rgb){return(rgb[0]*255<<16)+(rgb[1]*255<<8)+rgb[2]*255;}/**
 * get the resolution / device pixel ratio of an asset by looking for the prefix
 * used by spritesheets and image urls
 *
 * @memberof PIXI.utils
 * @function getResolutionOfUrl
 * @param {string} url - the image path
 * @param {number} [defaultValue=1] - the defaultValue if no filename prefix is set.
 * @return {number} resolution / device pixel ratio of an asset
 */function getResolutionOfUrl(url,defaultValue){var resolution=_settings2.default.RETINA_PREFIX.exec(url);if(resolution){return parseFloat(resolution[1]);}return defaultValue!==undefined?defaultValue:1;}/**
 * Typedef for decomposeDataUri return object.
 *
 * @typedef {object} DecomposedDataUri
 * @property {mediaType} Media type, eg. `image`
 * @property {subType} Sub type, eg. `png`
 * @property {encoding} Data encoding, eg. `base64`
 * @property {data} The actual data
 *//**
 * Split a data URI into components. Returns undefined if
 * parameter `dataUri` is not a valid data URI.
 *
 * @memberof PIXI.utils
 * @function decomposeDataUri
 * @param {string} dataUri - the data URI to check
 * @return {DecomposedDataUri|undefined} The decomposed data uri or undefined
 */function decomposeDataUri(dataUri){var dataUriMatch=_const.DATA_URI.exec(dataUri);if(dataUriMatch){return{mediaType:dataUriMatch[1]?dataUriMatch[1].toLowerCase():undefined,subType:dataUriMatch[2]?dataUriMatch[2].toLowerCase():undefined,encoding:dataUriMatch[3]?dataUriMatch[3].toLowerCase():undefined,data:dataUriMatch[4]};}return undefined;}/**
 * Get type of the image by regexp for extension. Returns undefined for unknown extensions.
 *
 * @memberof PIXI.utils
 * @function getUrlFileExtension
 * @param {string} url - the image path
 * @return {string|undefined} image extension
 */function getUrlFileExtension(url){var extension=_const.URL_FILE_EXTENSION.exec(url);if(extension){return extension[1].toLowerCase();}return undefined;}/**
 * Typedef for Size object.
 *
 * @typedef {object} Size
 * @property {width} Width component
 * @property {height} Height component
 *//**
 * Get size from an svg string using regexp.
 *
 * @memberof PIXI.utils
 * @function getSvgSize
 * @param {string} svgString - a serialized svg element
 * @return {Size|undefined} image extension
 */function getSvgSize(svgString){var sizeMatch=_const.SVG_SIZE.exec(svgString);var size={};if(sizeMatch){size[sizeMatch[1]]=Math.round(parseFloat(sizeMatch[3]));size[sizeMatch[5]]=Math.round(parseFloat(sizeMatch[7]));}return size;}/**
 * Skips the hello message of renderers that are created after this is run.
 *
 * @function skipHello
 * @memberof PIXI.utils
 */function skipHello(){saidHello=true;}/**
 * Logs out the version and renderer information for this running instance of PIXI.
 * If you don't want to see this message you can run `PIXI.utils.skipHello()` before
 * creating your renderer. Keep in mind that doing that will forever makes you a jerk face.
 *
 * @static
 * @function sayHello
 * @memberof PIXI.utils
 * @param {string} type - The string renderer type to log.
 */function sayHello(type){if(saidHello){return;}if(navigator.userAgent.toLowerCase().indexOf('chrome')>-1){var args=['\n %c %c %c Pixi.js '+_const.VERSION+' - ✰ '+type+' ✰  %c  %c  http://www.pixijs.com/  %c %c ♥%c♥%c♥ \n\n','background: #ff66a5; padding:5px 0;','background: #ff66a5; padding:5px 0;','color: #ff66a5; background: #030307; padding:5px 0;','background: #ff66a5; padding:5px 0;','background: #ffc3dc; padding:5px 0;','background: #ff66a5; padding:5px 0;','color: #ff2424; background: #fff; padding:5px 0;','color: #ff2424; background: #fff; padding:5px 0;','color: #ff2424; background: #fff; padding:5px 0;'];window.console.log.apply(console,args);}else if(window.console){window.console.log('Pixi.js '+_const.VERSION+' - '+type+' - http://www.pixijs.com/');}saidHello=true;}/**
 * Helper for checking for webgl support
 *
 * @memberof PIXI.utils
 * @function isWebGLSupported
 * @return {boolean} is webgl supported
 */function isWebGLSupported(){var contextOptions={stencil:true,failIfMajorPerformanceCaveat:true};try{if(!window.WebGLRenderingContext){return false;}var canvas=document.createElement('canvas');var gl=canvas.getContext('webgl',contextOptions)||canvas.getContext('experimental-webgl',contextOptions);var success=!!(gl&&gl.getContextAttributes().stencil);if(gl){var loseContext=gl.getExtension('WEBGL_lose_context');if(loseContext){loseContext.loseContext();}}gl=null;return success;}catch(e){return false;}}/**
 * Returns sign of number
 *
 * @memberof PIXI.utils
 * @function sign
 * @param {number} n - the number to check the sign of
 * @returns {number} 0 if `n` is 0, -1 if `n` is negative, 1 if `n` is positive
 */function sign(n){if(n===0)return 0;return n<0?-1:1;}/**
 * Remove a range of items from an array
 *
 * @memberof PIXI.utils
 * @function removeItems
 * @param {Array<*>} arr The target array
 * @param {number} startIdx The index to begin removing from (inclusive)
 * @param {number} removeCount How many items to remove
 */function removeItems(arr,startIdx,removeCount){var length=arr.length;if(startIdx>=length||removeCount===0){return;}removeCount=startIdx+removeCount>length?length-startIdx:removeCount;var len=length-removeCount;for(var i=startIdx;i<len;++i){arr[i]=arr[i+removeCount];}arr.length=len;}/**
 * @todo Describe property usage
 *
 * @memberof PIXI.utils
 * @private
 */var TextureCache=exports.TextureCache={};/**
 * @todo Describe property usage
 *
 * @memberof PIXI.utils
 * @private
 */var BaseTextureCache=exports.BaseTextureCache={};},{"../const":42,"../settings":97,"./pluginTarget":119,"eventemitter3":3,"ismobilejs":4}],118:[function(require,module,exports){'use strict';exports.__esModule=true;exports.default=maxRecommendedTextures;var _ismobilejs=require('ismobilejs');var _ismobilejs2=_interopRequireDefault(_ismobilejs);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function maxRecommendedTextures(max){if(_ismobilejs2.default.tablet||_ismobilejs2.default.phone){// check if the res is iphone 6 or higher..
return 4;}// desktop should be ok
return max;}},{"ismobilejs":4}],119:[function(require,module,exports){"use strict";exports.__esModule=true;/**
 * Mixins functionality to make an object have "plugins".
 *
 * @example
 *      function MyObject() {}
 *
 *      pluginTarget.mixin(MyObject);
 *
 * @mixin
 * @memberof PIXI.utils
 * @param {object} obj - The object to mix into.
 */function pluginTarget(obj){obj.__plugins={};/**
     * Adds a plugin to an object
     *
     * @param {string} pluginName - The events that should be listed.
     * @param {Function} ctor - The constructor function for the plugin.
     */obj.registerPlugin=function registerPlugin(pluginName,ctor){obj.__plugins[pluginName]=ctor;};/**
     * Instantiates all the plugins of this object
     *
     */obj.prototype.initPlugins=function initPlugins(){this.plugins=this.plugins||{};for(var o in obj.__plugins){this.plugins[o]=new obj.__plugins[o](this);}};/**
     * Removes all the plugins of this object
     *
     */obj.prototype.destroyPlugins=function destroyPlugins(){for(var o in this.plugins){this.plugins[o].destroy();this.plugins[o]=null;}this.plugins=null;};}exports.default={/**
     * Mixes in the properties of the pluginTarget into another object
     *
     * @param {object} obj - The obj to mix into
     */mixin:function mixin(obj){pluginTarget(obj);}};},{}],120:[function(require,module,exports){'use strict';var _core=require('./core');var core=_interopRequireWildcard(_core);var _mesh=require('./mesh');var mesh=_interopRequireWildcard(_mesh);var _particles=require('./particles');var particles=_interopRequireWildcard(_particles);var _extras=require('./extras');var extras=_interopRequireWildcard(_extras);var _filters=require('./filters');var filters=_interopRequireWildcard(_filters);var _prepare=require('./prepare');var prepare=_interopRequireWildcard(_prepare);var _loaders=require('./loaders');var loaders=_interopRequireWildcard(_loaders);function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj;}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key];}}newObj.default=obj;return newObj;}}// provide method to give a stack track for warnings
// useful for tracking-down where deprecated methods/properties/classes
// are being used within the code
function warn(msg){/* eslint-disable no-console */var stack=new Error().stack;// Handle IE < 10 and Safari < 6
if(typeof stack==='undefined'){console.warn('Deprecation Warning: ',msg);}else{// chop off the stack trace which includes pixi.js internal calls
stack=stack.split('\n').splice(3).join('\n');if(console.groupCollapsed){console.groupCollapsed('%cDeprecation Warning: %c%s','color:#614108;background:#fffbe6','font-weight:normal;color:#614108;background:#fffbe6',msg);console.warn(stack);console.groupEnd();}else{console.warn('Deprecation Warning: ',msg);console.warn(stack);}}/* eslint-enable no-console */}/**
 * @class
 * @private
 * @name SpriteBatch
 * @memberof PIXI
 * @see PIXI.ParticleContainer
 * @throws {ReferenceError} SpriteBatch does not exist any more, please use the new ParticleContainer instead.
 * @deprecated since version 3.0.0
 */core.SpriteBatch=function(){throw new ReferenceError('SpriteBatch does not exist any more, please use the new ParticleContainer instead.');};/**
 * @class
 * @private
 * @name AssetLoader
 * @memberof PIXI
 * @see PIXI.loaders.Loader
 * @throws {ReferenceError} The loader system was overhauled in pixi v3, please see the new PIXI.loaders.Loader class.
 * @deprecated since version 3.0.0
 */core.AssetLoader=function(){throw new ReferenceError('The loader system was overhauled in pixi v3, please see the new PIXI.loaders.Loader class.');};Object.defineProperties(core,{/**
     * @class
     * @private
     * @name Stage
     * @memberof PIXI
     * @see PIXI.Container
     * @deprecated since version 3.0.0
     */Stage:{enumerable:true,get:function get(){warn('You do not need to use a PIXI Stage any more, you can simply render any container.');return core.Container;}},/**
     * @class
     * @private
     * @name DisplayObjectContainer
     * @memberof PIXI
     * @see PIXI.Container
     * @deprecated since version 3.0.0
     */DisplayObjectContainer:{enumerable:true,get:function get(){warn('DisplayObjectContainer has been shortened to Container, please use Container from now on.');return core.Container;}},/**
     * @class
     * @private
     * @name Strip
     * @memberof PIXI
     * @see PIXI.mesh.Mesh
     * @deprecated since version 3.0.0
     */Strip:{enumerable:true,get:function get(){warn('The Strip class has been renamed to Mesh and moved to mesh.Mesh, please use mesh.Mesh from now on.');return mesh.Mesh;}},/**
     * @class
     * @private
     * @name Rope
     * @memberof PIXI
     * @see PIXI.mesh.Rope
     * @deprecated since version 3.0.0
     */Rope:{enumerable:true,get:function get(){warn('The Rope class has been moved to mesh.Rope, please use mesh.Rope from now on.');return mesh.Rope;}},/**
     * @class
     * @private
     * @name ParticleContainer
     * @memberof PIXI
     * @see PIXI.particles.ParticleContainer
     * @deprecated since version 4.0.0
     */ParticleContainer:{enumerable:true,get:function get(){warn('The ParticleContainer class has been moved to particles.ParticleContainer, '+'please use particles.ParticleContainer from now on.');return particles.ParticleContainer;}},/**
     * @class
     * @private
     * @name MovieClip
     * @memberof PIXI
     * @see PIXI.extras.MovieClip
     * @deprecated since version 3.0.0
     */MovieClip:{enumerable:true,get:function get(){warn('The MovieClip class has been moved to extras.AnimatedSprite, please use extras.AnimatedSprite.');return extras.AnimatedSprite;}},/**
     * @class
     * @private
     * @name TilingSprite
     * @memberof PIXI
     * @see PIXI.extras.TilingSprite
     * @deprecated since version 3.0.0
     */TilingSprite:{enumerable:true,get:function get(){warn('The TilingSprite class has been moved to extras.TilingSprite, '+'please use extras.TilingSprite from now on.');return extras.TilingSprite;}},/**
     * @class
     * @private
     * @name BitmapText
     * @memberof PIXI
     * @see PIXI.extras.BitmapText
     * @deprecated since version 3.0.0
     */BitmapText:{enumerable:true,get:function get(){warn('The BitmapText class has been moved to extras.BitmapText, '+'please use extras.BitmapText from now on.');return extras.BitmapText;}},/**
     * @class
     * @private
     * @name blendModes
     * @memberof PIXI
     * @see PIXI.BLEND_MODES
     * @deprecated since version 3.0.0
     */blendModes:{enumerable:true,get:function get(){warn('The blendModes has been moved to BLEND_MODES, please use BLEND_MODES from now on.');return core.BLEND_MODES;}},/**
     * @class
     * @private
     * @name scaleModes
     * @memberof PIXI
     * @see PIXI.SCALE_MODES
     * @deprecated since version 3.0.0
     */scaleModes:{enumerable:true,get:function get(){warn('The scaleModes has been moved to SCALE_MODES, please use SCALE_MODES from now on.');return core.SCALE_MODES;}},/**
     * @class
     * @private
     * @name BaseTextureCache
     * @memberof PIXI
     * @see PIXI.utils.BaseTextureCache
     * @deprecated since version 3.0.0
     */BaseTextureCache:{enumerable:true,get:function get(){warn('The BaseTextureCache class has been moved to utils.BaseTextureCache, '+'please use utils.BaseTextureCache from now on.');return core.utils.BaseTextureCache;}},/**
     * @class
     * @private
     * @name TextureCache
     * @memberof PIXI
     * @see PIXI.utils.TextureCache
     * @deprecated since version 3.0.0
     */TextureCache:{enumerable:true,get:function get(){warn('The TextureCache class has been moved to utils.TextureCache, '+'please use utils.TextureCache from now on.');return core.utils.TextureCache;}},/**
     * @namespace
     * @private
     * @name math
     * @memberof PIXI
     * @see PIXI
     * @deprecated since version 3.0.6
     */math:{enumerable:true,get:function get(){warn('The math namespace is deprecated, please access members already accessible on PIXI.');return core;}},/**
     * @class
     * @private
     * @name PIXI.AbstractFilter
     * @see PIXI.Filter
     * @deprecated since version 3.0.6
     */AbstractFilter:{enumerable:true,get:function get(){warn('AstractFilter has been renamed to Filter, please use PIXI.Filter');return core.Filter;}},/**
     * @class
     * @private
     * @name PIXI.TransformManual
     * @see PIXI.TransformBase
     * @deprecated since version 4.0.0
     */TransformManual:{enumerable:true,get:function get(){warn('TransformManual has been renamed to TransformBase, please update your pixi-spine');return core.TransformBase;}},/**
     * @static
     * @constant
     * @name PIXI.TARGET_FPMS
     * @see PIXI.settings.TARGET_FPMS
     * @deprecated since version 4.2.0
     */TARGET_FPMS:{enumerable:true,get:function get(){warn('PIXI.TARGET_FPMS has been deprecated, please use PIXI.settings.TARGET_FPMS');return core.settings.TARGET_FPMS;},set:function set(value){warn('PIXI.TARGET_FPMS has been deprecated, please use PIXI.settings.TARGET_FPMS');core.settings.TARGET_FPMS=value;}},/**
     * @static
     * @constant
     * @name PIXI.FILTER_RESOLUTION
     * @see PIXI.settings.FILTER_RESOLUTION
     * @deprecated since version 4.2.0
     */FILTER_RESOLUTION:{enumerable:true,get:function get(){warn('PIXI.FILTER_RESOLUTION has been deprecated, please use PIXI.settings.FILTER_RESOLUTION');return core.settings.FILTER_RESOLUTION;},set:function set(value){warn('PIXI.FILTER_RESOLUTION has been deprecated, please use PIXI.settings.FILTER_RESOLUTION');core.settings.FILTER_RESOLUTION=value;}},/**
     * @static
     * @constant
     * @name PIXI.RESOLUTION
     * @see PIXI.settings.RESOLUTION
     * @deprecated since version 4.2.0
     */RESOLUTION:{enumerable:true,get:function get(){warn('PIXI.RESOLUTION has been deprecated, please use PIXI.settings.RESOLUTION');return core.settings.RESOLUTION;},set:function set(value){warn('PIXI.RESOLUTION has been deprecated, please use PIXI.settings.RESOLUTION');core.settings.RESOLUTION=value;}},/**
     * @static
     * @constant
     * @name PIXI.MIPMAP_TEXTURES
     * @see PIXI.settings.MIPMAP_TEXTURES
     * @deprecated since version 4.2.0
     */MIPMAP_TEXTURES:{enumerable:true,get:function get(){warn('PIXI.MIPMAP_TEXTURES has been deprecated, please use PIXI.settings.MIPMAP_TEXTURES');return core.settings.MIPMAP_TEXTURES;},set:function set(value){warn('PIXI.MIPMAP_TEXTURES has been deprecated, please use PIXI.settings.MIPMAP_TEXTURES');core.settings.MIPMAP_TEXTURES=value;}},/**
     * @static
     * @constant
     * @name PIXI.SPRITE_BATCH_SIZE
     * @see PIXI.settings.SPRITE_BATCH_SIZE
     * @deprecated since version 4.2.0
     */SPRITE_BATCH_SIZE:{enumerable:true,get:function get(){warn('PIXI.SPRITE_BATCH_SIZE has been deprecated, please use PIXI.settings.SPRITE_BATCH_SIZE');return core.settings.SPRITE_BATCH_SIZE;},set:function set(value){warn('PIXI.SPRITE_BATCH_SIZE has been deprecated, please use PIXI.settings.SPRITE_BATCH_SIZE');core.settings.SPRITE_BATCH_SIZE=value;}},/**
     * @static
     * @constant
     * @name PIXI.SPRITE_MAX_TEXTURES
     * @see PIXI.settings.SPRITE_MAX_TEXTURES
     * @deprecated since version 4.2.0
     */SPRITE_MAX_TEXTURES:{enumerable:true,get:function get(){warn('PIXI.SPRITE_MAX_TEXTURES has been deprecated, please use PIXI.settings.SPRITE_MAX_TEXTURES');return core.settings.SPRITE_MAX_TEXTURES;},set:function set(value){warn('PIXI.SPRITE_MAX_TEXTURES has been deprecated, please use PIXI.settings.SPRITE_MAX_TEXTURES');core.settings.SPRITE_MAX_TEXTURES=value;}},/**
     * @static
     * @constant
     * @name PIXI.RETINA_PREFIX
     * @see PIXI.settings.RETINA_PREFIX
     * @deprecated since version 4.2.0
     */RETINA_PREFIX:{enumerable:true,get:function get(){warn('PIXI.RETINA_PREFIX has been deprecated, please use PIXI.settings.RETINA_PREFIX');return core.settings.RETINA_PREFIX;},set:function set(value){warn('PIXI.RETINA_PREFIX has been deprecated, please use PIXI.settings.RETINA_PREFIX');core.settings.RETINA_PREFIX=value;}},/**
     * @static
     * @constant
     * @name PIXI.DEFAULT_RENDER_OPTIONS
     * @see PIXI.settings.RENDER_OPTIONS
     * @deprecated since version 4.2.0
     */DEFAULT_RENDER_OPTIONS:{enumerable:true,get:function get(){warn('PIXI.DEFAULT_RENDER_OPTIONS has been deprecated, please use PIXI.settings.DEFAULT_RENDER_OPTIONS');return core.settings.RENDER_OPTIONS;}}});// Move the default properties to settings
var defaults=[{parent:'TRANSFORM_MODE',target:'TRANSFORM_MODE'},{parent:'GC_MODES',target:'GC_MODE'},{parent:'WRAP_MODES',target:'WRAP_MODE'},{parent:'SCALE_MODES',target:'SCALE_MODE'},{parent:'PRECISION',target:'PRECISION'}];var _loop=function _loop(i){var deprecation=defaults[i];Object.defineProperty(core[deprecation.parent],'DEFAULT',{enumerable:true,get:function get(){warn('PIXI.'+deprecation.parent+'.DEFAULT has been deprecated, please use PIXI.settings.'+deprecation.target);return core.settings[deprecation.target];},set:function set(value){warn('PIXI.'+deprecation.parent+'.DEFAULT has been deprecated, please use PIXI.settings.'+deprecation.target);core.settings[deprecation.target]=value;}});};for(var i=0;i<defaults.length;i++){_loop(i);}Object.defineProperties(extras,{/**
     * @class
     * @name MovieClip
     * @memberof PIXI.extras
     * @see PIXI.extras.AnimatedSprite
     * @deprecated since version 4.2.0
     */MovieClip:{enumerable:true,get:function get(){warn('The MovieClip class has been renamed to AnimatedSprite, please use AnimatedSprite from now on.');return extras.AnimatedSprite;}}});core.DisplayObject.prototype.generateTexture=function generateTexture(renderer,scaleMode,resolution){warn('generateTexture has moved to the renderer, please use renderer.generateTexture(displayObject)');return renderer.generateTexture(this,scaleMode,resolution);};core.Graphics.prototype.generateTexture=function generateTexture(scaleMode,resolution){warn('graphics generate texture has moved to the renderer. '+'Or to render a graphics to a texture using canvas please use generateCanvasTexture');return this.generateCanvasTexture(scaleMode,resolution);};core.RenderTexture.prototype.render=function render(displayObject,matrix,clear,updateTransform){this.legacyRenderer.render(displayObject,this,clear,matrix,!updateTransform);warn('RenderTexture.render is now deprecated, please use renderer.render(displayObject, renderTexture)');};core.RenderTexture.prototype.getImage=function getImage(target){warn('RenderTexture.getImage is now deprecated, please use renderer.extract.image(target)');return this.legacyRenderer.extract.image(target);};core.RenderTexture.prototype.getBase64=function getBase64(target){warn('RenderTexture.getBase64 is now deprecated, please use renderer.extract.base64(target)');return this.legacyRenderer.extract.base64(target);};core.RenderTexture.prototype.getCanvas=function getCanvas(target){warn('RenderTexture.getCanvas is now deprecated, please use renderer.extract.canvas(target)');return this.legacyRenderer.extract.canvas(target);};core.RenderTexture.prototype.getPixels=function getPixels(target){warn('RenderTexture.getPixels is now deprecated, please use renderer.extract.pixels(target)');return this.legacyRenderer.pixels(target);};/**
 * @method
 * @private
 * @name PIXI.Sprite#setTexture
 * @see PIXI.Sprite#texture
 * @deprecated since version 3.0.0
 * @param {PIXI.Texture} texture - The texture to set to.
 */core.Sprite.prototype.setTexture=function setTexture(texture){this.texture=texture;warn('setTexture is now deprecated, please use the texture property, e.g : sprite.texture = texture;');};/**
 * @method
 * @name PIXI.extras.BitmapText#setText
 * @see PIXI.extras.BitmapText#text
 * @deprecated since version 3.0.0
 * @param {string} text - The text to set to.
 */extras.BitmapText.prototype.setText=function setText(text){this.text=text;warn('setText is now deprecated, please use the text property, e.g : myBitmapText.text = \'my text\';');};/**
 * @method
 * @name PIXI.Text#setText
 * @see PIXI.Text#text
 * @deprecated since version 3.0.0
 * @param {string} text - The text to set to.
 */core.Text.prototype.setText=function setText(text){this.text=text;warn('setText is now deprecated, please use the text property, e.g : myText.text = \'my text\';');};/**
 * @method
 * @name PIXI.Text#setStyle
 * @see PIXI.Text#style
 * @deprecated since version 3.0.0
 * @param {*} style - The style to set to.
 */core.Text.prototype.setStyle=function setStyle(style){this.style=style;warn('setStyle is now deprecated, please use the style property, e.g : myText.style = style;');};/**
 * @method
 * @name PIXI.Text#determineFontProperties
 * @see PIXI.Text#calculateFontProperties
 * @deprecated since version 4.2.0
 * @private
 * @param {string} fontStyle - String representing the style of the font
 * @return {Object} Font properties object
 */core.Text.prototype.determineFontProperties=function determineFontProperties(fontStyle){warn('determineFontProperties is now deprecated, please use the static calculateFontProperties method, '+'e.g : Text.calculateFontProperties(fontStyle);');return Text.calculateFontProperties(fontStyle);};Object.defineProperties(core.TextStyle.prototype,{/**
     * Set all properties of a font as a single string
     *
     * @name PIXI.TextStyle#font
     * @deprecated since version 4.0.0
     */font:{get:function get(){warn('text style property \'font\' is now deprecated, please use the '+'\'fontFamily\', \'fontSize\', \'fontStyle\', \'fontVariant\' and \'fontWeight\' properties from now on');var fontSizeString=typeof this._fontSize==='number'?this._fontSize+'px':this._fontSize;return this._fontStyle+' '+this._fontVariant+' '+this._fontWeight+' '+fontSizeString+' '+this._fontFamily;},set:function set(font){warn('text style property \'font\' is now deprecated, please use the '+'\'fontFamily\',\'fontSize\',fontStyle\',\'fontVariant\' and \'fontWeight\' properties from now on');// can work out fontStyle from search of whole string
if(font.indexOf('italic')>1){this._fontStyle='italic';}else if(font.indexOf('oblique')>-1){this._fontStyle='oblique';}else{this._fontStyle='normal';}// can work out fontVariant from search of whole string
if(font.indexOf('small-caps')>-1){this._fontVariant='small-caps';}else{this._fontVariant='normal';}// fontWeight and fontFamily are tricker to find, but it's easier to find the fontSize due to it's units
var splits=font.split(' ');var fontSizeIndex=-1;this._fontSize=26;for(var _i=0;_i<splits.length;++_i){if(splits[_i].match(/(px|pt|em|%)/)){fontSizeIndex=_i;this._fontSize=splits[_i];break;}}// we can now search for fontWeight as we know it must occur before the fontSize
this._fontWeight='normal';for(var _i2=0;_i2<fontSizeIndex;++_i2){if(splits[_i2].match(/(bold|bolder|lighter|100|200|300|400|500|600|700|800|900)/)){this._fontWeight=splits[_i2];break;}}// and finally join everything together after the fontSize in case the font family has multiple words
if(fontSizeIndex>-1&&fontSizeIndex<splits.length-1){this._fontFamily='';for(var _i3=fontSizeIndex+1;_i3<splits.length;++_i3){this._fontFamily+=splits[_i3]+' ';}this._fontFamily=this._fontFamily.slice(0,-1);}else{this._fontFamily='Arial';}this.styleID++;}}});/**
 * @method
 * @name PIXI.Texture#setFrame
 * @see PIXI.Texture#setFrame
 * @deprecated since version 3.0.0
 * @param {PIXI.Rectangle} frame - The frame to set.
 */core.Texture.prototype.setFrame=function setFrame(frame){this.frame=frame;warn('setFrame is now deprecated, please use the frame property, e.g: myTexture.frame = frame;');};Object.defineProperties(filters,{/**
     * @class
     * @private
     * @name PIXI.filters.AbstractFilter
     * @see PIXI.AbstractFilter
     * @deprecated since version 3.0.6
     */AbstractFilter:{get:function get(){warn('AstractFilter has been renamed to Filter, please use PIXI.Filter');return core.AbstractFilter;}},/**
     * @class
     * @private
     * @name PIXI.filters.SpriteMaskFilter
     * @see PIXI.SpriteMaskFilter
     * @deprecated since version 3.0.6
     */SpriteMaskFilter:{get:function get(){warn('filters.SpriteMaskFilter is an undocumented alias, please use SpriteMaskFilter from now on.');return core.SpriteMaskFilter;}}});/**
 * @method
 * @name PIXI.utils.uuid
 * @see PIXI.utils.uid
 * @deprecated since version 3.0.6
 * @return {number} The uid
 */core.utils.uuid=function(){warn('utils.uuid() is deprecated, please use utils.uid() from now on.');return core.utils.uid();};/**
 * @method
 * @name PIXI.utils.canUseNewCanvasBlendModes
 * @see PIXI.CanvasTinter
 * @deprecated
 * @return {boolean} Can use blend modes.
 */core.utils.canUseNewCanvasBlendModes=function(){warn('utils.canUseNewCanvasBlendModes() is deprecated, please use CanvasTinter.canUseMultiply from now on');return core.CanvasTinter.canUseMultiply;};var saidHello=true;/**
 * @name PIXI.utils._saidHello
 * @type {boolean}
 * @see PIXI.utils.skipHello
 * @deprecated since 4.1.0
 */Object.defineProperty(core.utils,'_saidHello',{set:function set(bool){if(bool){warn('PIXI.utils._saidHello is deprecated, please use PIXI.utils.skipHello()');this.skipHello();}saidHello=bool;},get:function get(){return saidHello;}});/**
 * The number of graphics or textures to upload to the GPU.
 *
 * @name PIXI.prepare.canvas.UPLOADS_PER_FRAME
 * @static
 * @type {number}
 * @see PIXI.prepare.BasePrepare.limiter
 * @deprecated since 4.2.0
 */Object.defineProperty(prepare.canvas,'UPLOADS_PER_FRAME',{set:function set(){warn('PIXI.CanvasPrepare.UPLOADS_PER_FRAME has been removed. Please set '+'renderer.plugins.prepare.limiter.maxItemsPerFrame on your renderer');// because we don't have a reference to the renderer, we can't actually set
// the uploads per frame, so we'll have to stick with the warning.
},get:function get(){warn('PIXI.CanvasPrepare.UPLOADS_PER_FRAME has been removed. Please use '+'renderer.plugins.prepare.limiter');return NaN;}});/**
 * The number of graphics or textures to upload to the GPU.
 *
 * @name PIXI.prepare.webgl.UPLOADS_PER_FRAME
 * @static
 * @type {number}
 * @see PIXI.prepare.BasePrepare.limiter
 * @deprecated since 4.2.0
 */Object.defineProperty(prepare.webgl,'UPLOADS_PER_FRAME',{set:function set(){warn('PIXI.WebGLPrepare.UPLOADS_PER_FRAME has been removed. Please set '+'renderer.plugins.prepare.limiter.maxItemsPerFrame on your renderer');// because we don't have a reference to the renderer, we can't actually set
// the uploads per frame, so we'll have to stick with the warning.
},get:function get(){warn('PIXI.WebGLPrepare.UPLOADS_PER_FRAME has been removed. Please use '+'renderer.plugins.prepare.limiter');return NaN;}});Object.defineProperties(loaders.Resource.prototype,{isJson:{get:function get(){warn('The isJson property is deprecated, please use `resource.type === Resource.TYPE.JSON`.');return this.type===loaders.Loader.Resource.TYPE.JSON;}},isXml:{get:function get(){warn('The isXml property is deprecated, please use `resource.type === Resource.TYPE.XML`.');return this.type===loaders.Loader.Resource.TYPE.XML;}},isImage:{get:function get(){warn('The isImage property is deprecated, please use `resource.type === Resource.TYPE.IMAGE`.');return this.type===loaders.Loader.Resource.TYPE.IMAGE;}},isAudio:{get:function get(){warn('The isAudio property is deprecated, please use `resource.type === Resource.TYPE.AUDIO`.');return this.type===loaders.Loader.Resource.TYPE.AUDIO;}},isVideo:{get:function get(){warn('The isVideo property is deprecated, please use `resource.type === Resource.TYPE.VIDEO`.');return this.type===loaders.Loader.Resource.TYPE.VIDEO;}}});Object.defineProperties(loaders.Loader.prototype,{before:{get:function get(){warn('The before() method is deprecated, please use pre().');return this.pre;}},after:{get:function get(){warn('The after() method is deprecated, please use use().');return this.use;}}});},{"./core":61,"./extras":131,"./filters":142,"./loaders":151,"./mesh":160,"./particles":163,"./prepare":173}],121:[function(require,module,exports){'use strict';exports.__esModule=true;var _core=require('../../core');var core=_interopRequireWildcard(_core);function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj;}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key];}}newObj.default=obj;return newObj;}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}var TEMP_RECT=new core.Rectangle();/**
 * The extract manager provides functionality to export content from the renderers.
 *
 * @class
 * @memberof PIXI
 */var CanvasExtract=function(){/**
     * @param {PIXI.CanvasRenderer} renderer - A reference to the current renderer
     */function CanvasExtract(renderer){_classCallCheck(this,CanvasExtract);this.renderer=renderer;/**
         * Collection of methods for extracting data (image, pixels, etc.) from a display object or render texture
         *
         * @member {PIXI.CanvasExtract} extract
         * @memberof PIXI.CanvasRenderer#
         * @see PIXI.CanvasExtract
         */renderer.extract=this;}/**
     * Will return a HTML Image of the target
     *
     * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture
     *  to convert. If left empty will use use the main renderer
     * @return {HTMLImageElement} HTML Image of the target
     */CanvasExtract.prototype.image=function image(target){var image=new Image();image.src=this.base64(target);return image;};/**
     * Will return a a base64 encoded string of this target. It works by calling
     *  `CanvasExtract.getCanvas` and then running toDataURL on that.
     *
     * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture
     *  to convert. If left empty will use use the main renderer
     * @return {string} A base64 encoded string of the texture.
     */CanvasExtract.prototype.base64=function base64(target){return this.canvas(target).toDataURL();};/**
     * Creates a Canvas element, renders this target to it and then returns it.
     *
     * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture
     *  to convert. If left empty will use use the main renderer
     * @return {HTMLCanvasElement} A Canvas element with the texture rendered on.
     */CanvasExtract.prototype.canvas=function canvas(target){var renderer=this.renderer;var context=void 0;var resolution=void 0;var frame=void 0;var renderTexture=void 0;if(target){if(target instanceof core.RenderTexture){renderTexture=target;}else{renderTexture=renderer.generateTexture(target);}}if(renderTexture){context=renderTexture.baseTexture._canvasRenderTarget.context;resolution=renderTexture.baseTexture._canvasRenderTarget.resolution;frame=renderTexture.frame;}else{context=renderer.rootContext;frame=TEMP_RECT;frame.width=this.renderer.width;frame.height=this.renderer.height;}var width=frame.width*resolution;var height=frame.height*resolution;var canvasBuffer=new core.CanvasRenderTarget(width,height);var canvasData=context.getImageData(frame.x*resolution,frame.y*resolution,width,height);canvasBuffer.context.putImageData(canvasData,0,0);// send the canvas back..
return canvasBuffer.canvas;};/**
     * Will return a one-dimensional array containing the pixel data of the entire texture in RGBA
     * order, with integer values between 0 and 255 (included).
     *
     * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture
     *  to convert. If left empty will use use the main renderer
     * @return {Uint8ClampedArray} One-dimensional array containing the pixel data of the entire texture
     */CanvasExtract.prototype.pixels=function pixels(target){var renderer=this.renderer;var context=void 0;var resolution=void 0;var frame=void 0;var renderTexture=void 0;if(target){if(target instanceof core.RenderTexture){renderTexture=target;}else{renderTexture=renderer.generateTexture(target);}}if(renderTexture){context=renderTexture.baseTexture._canvasRenderTarget.context;resolution=renderTexture.baseTexture._canvasRenderTarget.resolution;frame=renderTexture.frame;}else{context=renderer.rootContext;frame=TEMP_RECT;frame.width=renderer.width;frame.height=renderer.height;}return context.getImageData(0,0,frame.width*resolution,frame.height*resolution).data;};/**
     * Destroys the extract
     *
     */CanvasExtract.prototype.destroy=function destroy(){this.renderer.extract=null;this.renderer=null;};return CanvasExtract;}();exports.default=CanvasExtract;core.CanvasRenderer.registerPlugin('extract',CanvasExtract);},{"../../core":61}],122:[function(require,module,exports){'use strict';exports.__esModule=true;var _WebGLExtract=require('./webgl/WebGLExtract');Object.defineProperty(exports,'webgl',{enumerable:true,get:function get(){return _interopRequireDefault(_WebGLExtract).default;}});var _CanvasExtract=require('./canvas/CanvasExtract');Object.defineProperty(exports,'canvas',{enumerable:true,get:function get(){return _interopRequireDefault(_CanvasExtract).default;}});function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}},{"./canvas/CanvasExtract":121,"./webgl/WebGLExtract":123}],123:[function(require,module,exports){'use strict';exports.__esModule=true;var _core=require('../../core');var core=_interopRequireWildcard(_core);function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj;}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key];}}newObj.default=obj;return newObj;}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}var TEMP_RECT=new core.Rectangle();var BYTES_PER_PIXEL=4;/**
 * The extract manager provides functionality to export content from the renderers.
 *
 * @class
 * @memberof PIXI
 */var WebGLExtract=function(){/**
     * @param {PIXI.WebGLRenderer} renderer - A reference to the current renderer
     */function WebGLExtract(renderer){_classCallCheck(this,WebGLExtract);this.renderer=renderer;/**
         * Collection of methods for extracting data (image, pixels, etc.) from a display object or render texture
         *
         * @member {PIXI.WebGLExtract} extract
         * @memberof PIXI.WebGLRenderer#
         * @see PIXI.WebGLExtract
         */renderer.extract=this;}/**
     * Will return a HTML Image of the target
     *
     * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture
     *  to convert. If left empty will use use the main renderer
     * @return {HTMLImageElement} HTML Image of the target
     */WebGLExtract.prototype.image=function image(target){var image=new Image();image.src=this.base64(target);return image;};/**
     * Will return a a base64 encoded string of this target. It works by calling
     *  `WebGLExtract.getCanvas` and then running toDataURL on that.
     *
     * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture
     *  to convert. If left empty will use use the main renderer
     * @return {string} A base64 encoded string of the texture.
     */WebGLExtract.prototype.base64=function base64(target){return this.canvas(target).toDataURL();};/**
     * Creates a Canvas element, renders this target to it and then returns it.
     *
     * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture
     *  to convert. If left empty will use use the main renderer
     * @return {HTMLCanvasElement} A Canvas element with the texture rendered on.
     */WebGLExtract.prototype.canvas=function canvas(target){var renderer=this.renderer;var textureBuffer=void 0;var resolution=void 0;var frame=void 0;var flipY=false;var renderTexture=void 0;if(target){if(target instanceof core.RenderTexture){renderTexture=target;}else{renderTexture=this.renderer.generateTexture(target);}}if(renderTexture){textureBuffer=renderTexture.baseTexture._glRenderTargets[this.renderer.CONTEXT_UID];resolution=textureBuffer.resolution;frame=renderTexture.frame;flipY=false;}else{textureBuffer=this.renderer.rootRenderTarget;resolution=textureBuffer.resolution;flipY=true;frame=TEMP_RECT;frame.width=textureBuffer.size.width;frame.height=textureBuffer.size.height;}var width=frame.width*resolution;var height=frame.height*resolution;var canvasBuffer=new core.CanvasRenderTarget(width,height);if(textureBuffer){// bind the buffer
renderer.bindRenderTarget(textureBuffer);// set up an array of pixels
var webglPixels=new Uint8Array(BYTES_PER_PIXEL*width*height);// read pixels to the array
var gl=renderer.gl;gl.readPixels(frame.x*resolution,frame.y*resolution,width,height,gl.RGBA,gl.UNSIGNED_BYTE,webglPixels);// add the pixels to the canvas
var canvasData=canvasBuffer.context.getImageData(0,0,width,height);canvasData.data.set(webglPixels);canvasBuffer.context.putImageData(canvasData,0,0);// pulling pixels
if(flipY){canvasBuffer.context.scale(1,-1);canvasBuffer.context.drawImage(canvasBuffer.canvas,0,-height);}}// send the canvas back..
return canvasBuffer.canvas;};/**
     * Will return a one-dimensional array containing the pixel data of the entire texture in RGBA
     * order, with integer values between 0 and 255 (included).
     *
     * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture
     *  to convert. If left empty will use use the main renderer
     * @return {Uint8ClampedArray} One-dimensional array containing the pixel data of the entire texture
     */WebGLExtract.prototype.pixels=function pixels(target){var renderer=this.renderer;var textureBuffer=void 0;var resolution=void 0;var frame=void 0;var renderTexture=void 0;if(target){if(target instanceof core.RenderTexture){renderTexture=target;}else{renderTexture=this.renderer.generateTexture(target);}}if(renderTexture){textureBuffer=renderTexture.baseTexture._glRenderTargets[this.renderer.CONTEXT_UID];resolution=textureBuffer.resolution;frame=renderTexture.frame;}else{textureBuffer=this.renderer.rootRenderTarget;resolution=textureBuffer.resolution;frame=TEMP_RECT;frame.width=textureBuffer.size.width;frame.height=textureBuffer.size.height;}var width=frame.width*resolution;var height=frame.height*resolution;var webglPixels=new Uint8Array(BYTES_PER_PIXEL*width*height);if(textureBuffer){// bind the buffer
renderer.bindRenderTarget(textureBuffer);// read pixels to the array
var gl=renderer.gl;gl.readPixels(frame.x*resolution,frame.y*resolution,width,height,gl.RGBA,gl.UNSIGNED_BYTE,webglPixels);}return webglPixels;};/**
     * Destroys the extract
     *
     */WebGLExtract.prototype.destroy=function destroy(){this.renderer.extract=null;this.renderer=null;};return WebGLExtract;}();exports.default=WebGLExtract;core.WebGLRenderer.registerPlugin('extract',WebGLExtract);},{"../../core":61}],124:[function(require,module,exports){'use strict';exports.__esModule=true;var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor);}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor;};}();var _core=require('../core');var core=_interopRequireWildcard(_core);function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj;}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key];}}newObj.default=obj;return newObj;}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return call&&((typeof call==="undefined"?"undefined":_typeof2(call))==="object"||typeof call==="function")?call:self;}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof2(superClass)));}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass;}/**
 * @typedef FrameObject
 * @type {object}
 * @property {PIXI.Texture} texture - The {@link PIXI.Texture} of the frame
 * @property {number} time - the duration of the frame in ms
 *//**
 * An AnimatedSprite is a simple way to display an animation depicted by a list of textures.
 *
 * ```js
 * let alienImages = ["image_sequence_01.png","image_sequence_02.png","image_sequence_03.png","image_sequence_04.png"];
 * let textureArray = [];
 *
 * for (let i=0; i < 4; i++)
 * {
 *      let texture = PIXI.Texture.fromImage(alienImages[i]);
 *      textureArray.push(texture);
 * };
 *
 * let mc = new PIXI.AnimatedSprite(textureArray);
 * ```
 *
 * @class
 * @extends PIXI.Sprite
 * @memberof PIXI.extras
 */var AnimatedSprite=function(_core$Sprite){_inherits(AnimatedSprite,_core$Sprite);/**
     * @param {PIXI.Texture[]|FrameObject[]} textures - an array of {@link PIXI.Texture} or frame
     *  objects that make up the animation
     */function AnimatedSprite(textures){_classCallCheck(this,AnimatedSprite);/**
         * @private
         */var _this=_possibleConstructorReturn(this,_core$Sprite.call(this,textures[0]instanceof core.Texture?textures[0]:textures[0].texture));_this._textures=null;/**
         * @private
         */_this._durations=null;_this.textures=textures;/**
         * The speed that the AnimatedSprite will play at. Higher is faster, lower is slower
         *
         * @member {number}
         * @default 1
         */_this.animationSpeed=1;/**
         * Whether or not the animate sprite repeats after playing.
         *
         * @member {boolean}
         * @default true
         */_this.loop=true;/**
         * Function to call when a AnimatedSprite finishes playing
         *
         * @method
         * @memberof PIXI.extras.AnimatedSprite#
         */_this.onComplete=null;/**
         * Function to call when a AnimatedSprite changes which texture is being rendered
         *
         * @method
         * @memberof PIXI.extras.AnimatedSprite#
         */_this.onFrameChange=null;/**
         * Elapsed time since animation has been started, used internally to display current texture
         *
         * @member {number}
         * @private
         */_this._currentTime=0;/**
         * Indicates if the AnimatedSprite is currently playing
         *
         * @member {boolean}
         * @readonly
         */_this.playing=false;return _this;}/**
     * Stops the AnimatedSprite
     *
     */AnimatedSprite.prototype.stop=function stop(){if(!this.playing){return;}this.playing=false;core.ticker.shared.remove(this.update,this);};/**
     * Plays the AnimatedSprite
     *
     */AnimatedSprite.prototype.play=function play(){if(this.playing){return;}this.playing=true;core.ticker.shared.add(this.update,this);};/**
     * Stops the AnimatedSprite and goes to a specific frame
     *
     * @param {number} frameNumber - frame index to stop at
     */AnimatedSprite.prototype.gotoAndStop=function gotoAndStop(frameNumber){this.stop();var previousFrame=this.currentFrame;this._currentTime=frameNumber;if(previousFrame!==this.currentFrame){this.updateTexture();}};/**
     * Goes to a specific frame and begins playing the AnimatedSprite
     *
     * @param {number} frameNumber - frame index to start at
     */AnimatedSprite.prototype.gotoAndPlay=function gotoAndPlay(frameNumber){var previousFrame=this.currentFrame;this._currentTime=frameNumber;if(previousFrame!==this.currentFrame){this.updateTexture();}this.play();};/**
     * Updates the object transform for rendering.
     *
     * @private
     * @param {number} deltaTime - Time since last tick.
     */AnimatedSprite.prototype.update=function update(deltaTime){var elapsed=this.animationSpeed*deltaTime;var previousFrame=this.currentFrame;if(this._durations!==null){var lag=this._currentTime%1*this._durations[this.currentFrame];lag+=elapsed/60*1000;while(lag<0){this._currentTime--;lag+=this._durations[this.currentFrame];}var sign=Math.sign(this.animationSpeed*deltaTime);this._currentTime=Math.floor(this._currentTime);while(lag>=this._durations[this.currentFrame]){lag-=this._durations[this.currentFrame]*sign;this._currentTime+=sign;}this._currentTime+=lag/this._durations[this.currentFrame];}else{this._currentTime+=elapsed;}if(this._currentTime<0&&!this.loop){this.gotoAndStop(0);if(this.onComplete){this.onComplete();}}else if(this._currentTime>=this._textures.length&&!this.loop){this.gotoAndStop(this._textures.length-1);if(this.onComplete){this.onComplete();}}else if(previousFrame!==this.currentFrame){this.updateTexture();}};/**
     * Updates the displayed texture to match the current frame index
     *
     * @private
     */AnimatedSprite.prototype.updateTexture=function updateTexture(){this._texture=this._textures[this.currentFrame];this._textureID=-1;if(this.onFrameChange){this.onFrameChange(this.currentFrame);}};/**
     * Stops the AnimatedSprite and destroys it
     *
     */AnimatedSprite.prototype.destroy=function destroy(){this.stop();_core$Sprite.prototype.destroy.call(this);};/**
     * A short hand way of creating a movieclip from an array of frame ids
     *
     * @static
     * @param {string[]} frames - The array of frames ids the movieclip will use as its texture frames
     * @return {AnimatedSprite} The new animated sprite with the specified frames.
     */AnimatedSprite.fromFrames=function fromFrames(frames){var textures=[];for(var i=0;i<frames.length;++i){textures.push(core.Texture.fromFrame(frames[i]));}return new AnimatedSprite(textures);};/**
     * A short hand way of creating a movieclip from an array of image ids
     *
     * @static
     * @param {string[]} images - the array of image urls the movieclip will use as its texture frames
     * @return {AnimatedSprite} The new animate sprite with the specified images as frames.
     */AnimatedSprite.fromImages=function fromImages(images){var textures=[];for(var i=0;i<images.length;++i){textures.push(core.Texture.fromImage(images[i]));}return new AnimatedSprite(textures);};/**
     * totalFrames is the total number of frames in the AnimatedSprite. This is the same as number of textures
     * assigned to the AnimatedSprite.
     *
     * @readonly
     * @member {number}
     * @memberof PIXI.extras.AnimatedSprite#
     * @default 0
     */_createClass(AnimatedSprite,[{key:'totalFrames',get:function get(){return this._textures.length;}/**
         * The array of textures used for this AnimatedSprite
         *
         * @member {PIXI.Texture[]}
         * @memberof PIXI.extras.AnimatedSprite#
         */},{key:'textures',get:function get(){return this._textures;}/**
         * Sets the textures.
         *
         * @param {PIXI.Texture[]} value - The texture to set.
         */,set:function set(value){if(value[0]instanceof core.Texture){this._textures=value;this._durations=null;}else{this._textures=[];this._durations=[];for(var i=0;i<value.length;i++){this._textures.push(value[i].texture);this._durations.push(value[i].time);}}}/**
        * The AnimatedSprites current frame index
        *
        * @member {number}
        * @memberof PIXI.extras.AnimatedSprite#
        * @readonly
        */},{key:'currentFrame',get:function get(){var currentFrame=Math.floor(this._currentTime)%this._textures.length;if(currentFrame<0){currentFrame+=this._textures.length;}return currentFrame;}}]);return AnimatedSprite;}(core.Sprite);exports.default=AnimatedSprite;},{"../core":61}],125:[function(require,module,exports){'use strict';exports.__esModule=true;var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor);}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor;};}();var _core=require('../core');var core=_interopRequireWildcard(_core);var _ObservablePoint=require('../core/math/ObservablePoint');var _ObservablePoint2=_interopRequireDefault(_ObservablePoint);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj;}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key];}}newObj.default=obj;return newObj;}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return call&&((typeof call==="undefined"?"undefined":_typeof2(call))==="object"||typeof call==="function")?call:self;}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof2(superClass)));}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass;}/**
 * A BitmapText object will create a line or multiple lines of text using bitmap font. To
 * split a line you can use '\n', '\r' or '\r\n' in your string. You can generate the fnt files using:
 *
 * A BitmapText can only be created when the font is loaded
 *
 * ```js
 * // in this case the font is in a file called 'desyrel.fnt'
 * let bitmapText = new PIXI.extras.BitmapText("text using a fancy font!", {font: "35px Desyrel", align: "right"});
 * ```
 *
 * http://www.angelcode.com/products/bmfont/ for windows or
 * http://www.bmglyph.com/ for mac.
 *
 * @class
 * @extends PIXI.Container
 * @memberof PIXI.extras
 */var BitmapText=function(_core$Container){_inherits(BitmapText,_core$Container);/**
     * @param {string} text - The copy that you would like the text to display
     * @param {object} style - The style parameters
     * @param {string|object} style.font - The font descriptor for the object, can be passed as a string of form
     *      "24px FontName" or "FontName" or as an object with explicit name/size properties.
     * @param {string} [style.font.name] - The bitmap font id
     * @param {number} [style.font.size] - The size of the font in pixels, e.g. 24
     * @param {string} [style.align='left'] - Alignment for multiline text ('left', 'center' or 'right'), does not affect
     *      single line text
     * @param {number} [style.tint=0xFFFFFF] - The tint color
     */function BitmapText(text){var style=arguments.length<=1||arguments[1]===undefined?{}:arguments[1];_classCallCheck(this,BitmapText);/**
         * Private tracker for the width of the overall text
         *
         * @member {number}
         * @private
         */var _this=_possibleConstructorReturn(this,_core$Container.call(this));_this._textWidth=0;/**
         * Private tracker for the height of the overall text
         *
         * @member {number}
         * @private
         */_this._textHeight=0;/**
         * Private tracker for the letter sprite pool.
         *
         * @member {PIXI.Sprite[]}
         * @private
         */_this._glyphs=[];/**
         * Private tracker for the current style.
         *
         * @member {object}
         * @private
         */_this._font={tint:style.tint!==undefined?style.tint:0xFFFFFF,align:style.align||'left',name:null,size:0};/**
         * Private tracker for the current font.
         *
         * @member {object}
         * @private
         */_this.font=style.font;// run font setter
/**
         * Private tracker for the current text.
         *
         * @member {string}
         * @private
         */_this._text=text;/**
         * The max width of this bitmap text in pixels. If the text provided is longer than the
         * value provided, line breaks will be automatically inserted in the last whitespace.
         * Disable by setting value to 0
         *
         * @member {number}
         */_this.maxWidth=0;/**
         * The max line height. This is useful when trying to use the total height of the Text,
         * ie: when trying to vertically align.
         *
         * @member {number}
         */_this.maxLineHeight=0;/**
         * Text anchor. read-only
         *
         * @member {PIXI.ObservablePoint}
         * @private
         */_this._anchor=new _ObservablePoint2.default(function(){_this.dirty=true;},_this,0,0);/**
         * The dirty state of this object.
         *
         * @member {boolean}
         */_this.dirty=false;_this.updateText();return _this;}/**
     * Renders text and updates it when needed
     *
     * @private
     */BitmapText.prototype.updateText=function updateText(){var data=BitmapText.fonts[this._font.name];var scale=this._font.size/data.size;var pos=new core.Point();var chars=[];var lineWidths=[];var prevCharCode=null;var lastLineWidth=0;var maxLineWidth=0;var line=0;var lastSpace=-1;var lastSpaceWidth=0;var maxLineHeight=0;for(var i=0;i<this.text.length;i++){var charCode=this.text.charCodeAt(i);if(/(\s)/.test(this.text.charAt(i))){lastSpace=i;lastSpaceWidth=lastLineWidth;}if(/(?:\r\n|\r|\n)/.test(this.text.charAt(i))){lineWidths.push(lastLineWidth);maxLineWidth=Math.max(maxLineWidth,lastLineWidth);line++;pos.x=0;pos.y+=data.lineHeight;prevCharCode=null;continue;}if(lastSpace!==-1&&this.maxWidth>0&&pos.x*scale>this.maxWidth){core.utils.removeItems(chars,lastSpace,i-lastSpace);i=lastSpace;lastSpace=-1;lineWidths.push(lastSpaceWidth);maxLineWidth=Math.max(maxLineWidth,lastSpaceWidth);line++;pos.x=0;pos.y+=data.lineHeight;prevCharCode=null;continue;}var charData=data.chars[charCode];if(!charData){continue;}if(prevCharCode&&charData.kerning[prevCharCode]){pos.x+=charData.kerning[prevCharCode];}chars.push({texture:charData.texture,line:line,charCode:charCode,position:new core.Point(pos.x+charData.xOffset,pos.y+charData.yOffset)});lastLineWidth=pos.x+(charData.texture.width+charData.xOffset);pos.x+=charData.xAdvance;maxLineHeight=Math.max(maxLineHeight,charData.yOffset+charData.texture.height);prevCharCode=charCode;}lineWidths.push(lastLineWidth);maxLineWidth=Math.max(maxLineWidth,lastLineWidth);var lineAlignOffsets=[];for(var _i=0;_i<=line;_i++){var alignOffset=0;if(this._font.align==='right'){alignOffset=maxLineWidth-lineWidths[_i];}else if(this._font.align==='center'){alignOffset=(maxLineWidth-lineWidths[_i])/2;}lineAlignOffsets.push(alignOffset);}var lenChars=chars.length;var tint=this.tint;for(var _i2=0;_i2<lenChars;_i2++){var c=this._glyphs[_i2];// get the next glyph sprite
if(c){c.texture=chars[_i2].texture;}else{c=new core.Sprite(chars[_i2].texture);this._glyphs.push(c);}c.position.x=(chars[_i2].position.x+lineAlignOffsets[chars[_i2].line])*scale;c.position.y=chars[_i2].position.y*scale;c.scale.x=c.scale.y=scale;c.tint=tint;if(!c.parent){this.addChild(c);}}// remove unnecessary children.
for(var _i3=lenChars;_i3<this._glyphs.length;++_i3){this.removeChild(this._glyphs[_i3]);}this._textWidth=maxLineWidth*scale;this._textHeight=(pos.y+data.lineHeight)*scale;// apply anchor
if(this.anchor.x!==0||this.anchor.y!==0){for(var _i4=0;_i4<lenChars;_i4++){this._glyphs[_i4].x-=this._textWidth*this.anchor.x;this._glyphs[_i4].y-=this._textHeight*this.anchor.y;}}this.maxLineHeight=maxLineHeight*scale;};/**
     * Updates the transform of this object
     *
     * @private
     */BitmapText.prototype.updateTransform=function updateTransform(){this.validate();this.containerUpdateTransform();};/**
     * Validates text before calling parent's getLocalBounds
     *
     * @return {PIXI.Rectangle} The rectangular bounding area
     */BitmapText.prototype.getLocalBounds=function getLocalBounds(){this.validate();return _core$Container.prototype.getLocalBounds.call(this);};/**
     * Updates text when needed
     *
     * @private
     */BitmapText.prototype.validate=function validate(){if(this.dirty){this.updateText();this.dirty=false;}};/**
     * The tint of the BitmapText object
     *
     * @member {number}
     * @memberof PIXI.extras.BitmapText#
     */_createClass(BitmapText,[{key:'tint',get:function get(){return this._font.tint;}/**
         * Sets the tint.
         *
         * @param {number} value - The value to set to.
         */,set:function set(value){this._font.tint=typeof value==='number'&&value>=0?value:0xFFFFFF;this.dirty=true;}/**
         * The alignment of the BitmapText object
         *
         * @member {string}
         * @default 'left'
         * @memberof PIXI.extras.BitmapText#
         */},{key:'align',get:function get(){return this._font.align;}/**
         * Sets the alignment
         *
         * @param {string} value - The value to set to.
         */,set:function set(value){this._font.align=value||'left';this.dirty=true;}/**
         * The anchor sets the origin point of the text.
         * The default is 0,0 this means the text's origin is the top left
         * Setting the anchor to 0.5,0.5 means the text's origin is centered
         * Setting the anchor to 1,1 would mean the text's origin point will be the bottom right corner
         *
         * @member {PIXI.Point | number}
         * @memberof PIXI.extras.BitmapText#
         */},{key:'anchor',get:function get(){return this._anchor;}/**
         * Sets the anchor.
         *
         * @param {PIXI.Point|number} value - The value to set to.
         */,set:function set(value){if(typeof value==='number'){this._anchor.set(value);}else{this._anchor.copy(value);}}/**
         * The font descriptor of the BitmapText object
         *
         * @member {string|object}
         * @memberof PIXI.extras.BitmapText#
         */},{key:'font',get:function get(){return this._font;}/**
         * Sets the font.
         *
         * @param {string|object} value - The value to set to.
         */,set:function set(value){if(!value){return;}if(typeof value==='string'){value=value.split(' ');this._font.name=value.length===1?value[0]:value.slice(1).join(' ');this._font.size=value.length>=2?parseInt(value[0],10):BitmapText.fonts[this._font.name].size;}else{this._font.name=value.name;this._font.size=typeof value.size==='number'?value.size:parseInt(value.size,10);}this.dirty=true;}/**
         * The text of the BitmapText object
         *
         * @member {string}
         * @memberof PIXI.extras.BitmapText#
         */},{key:'text',get:function get(){return this._text;}/**
         * Sets the text.
         *
         * @param {string} value - The value to set to.
         */,set:function set(value){value=value.toString()||' ';if(this._text===value){return;}this._text=value;this.dirty=true;}/**
         * The width of the overall text, different from fontSize,
         * which is defined in the style object
         *
         * @member {number}
         * @memberof PIXI.extras.BitmapText#
         * @readonly
         */},{key:'textWidth',get:function get(){this.validate();return this._textWidth;}/**
         * The height of the overall text, different from fontSize,
         * which is defined in the style object
         *
         * @member {number}
         * @memberof PIXI.extras.BitmapText#
         * @readonly
         */},{key:'textHeight',get:function get(){this.validate();return this._textHeight;}}]);return BitmapText;}(core.Container);exports.default=BitmapText;BitmapText.fonts={};},{"../core":61,"../core/math/ObservablePoint":64}],126:[function(require,module,exports){'use strict';exports.__esModule=true;var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor);}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor;};}();var _Matrix=require('../core/math/Matrix');var _Matrix2=_interopRequireDefault(_Matrix);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}var tempMat=new _Matrix2.default();/**
 * class controls uv transform and frame clamp for texture
 *
 * @class
 * @memberof PIXI.extras
 */var TextureTransform=function(){/**
     *
     * @param {PIXI.Texture} texture observed texture
     * @param {number} [clampMargin] Changes frame clamping, 0.5 by default. Use -0.5 for extra border.
     * @constructor
     */function TextureTransform(texture,clampMargin){_classCallCheck(this,TextureTransform);this._texture=texture;this.mapCoord=new _Matrix2.default();this.uClampFrame=new Float32Array(4);this.uClampOffset=new Float32Array(2);this._lastTextureID=-1;/**
         * Changes frame clamping
         * Works with TilingSprite and Mesh
         * Change to 1.5 if you texture has repeated right and bottom lines, that leads to smoother borders
         *
         * @default 0
         * @member {number}
         */this.clampOffset=0;/**
         * Changes frame clamping
         * Works with TilingSprite and Mesh
         * Change to -0.5 to add a pixel to the edge, recommended for transparent trimmed textures in atlas
         *
         * @default 0.5
         * @member {number}
         */this.clampMargin=typeof clampMargin==='undefined'?0.5:clampMargin;}/**
     * texture property
     * @member {PIXI.Texture}
     * @memberof PIXI.TextureTransform
     *//**
     * updates matrices if texture was changed
     * @param {boolean} forceUpdate if true, matrices will be updated any case
     */TextureTransform.prototype.update=function update(forceUpdate){var tex=this._texture;if(!tex||!tex.valid){return;}if(!forceUpdate&&this._lastTextureID===tex._updateID){return;}this._lastTextureID=tex._updateID;var uvs=tex._uvs;this.mapCoord.set(uvs.x1-uvs.x0,uvs.y1-uvs.y0,uvs.x3-uvs.x0,uvs.y3-uvs.y0,uvs.x0,uvs.y0);var orig=tex.orig;var trim=tex.trim;if(trim){tempMat.set(orig.width/trim.width,0,0,orig.height/trim.height,-trim.x/trim.width,-trim.y/trim.height);this.mapCoord.append(tempMat);}var texBase=tex.baseTexture;var frame=this.uClampFrame;var margin=this.clampMargin/texBase.resolution;var offset=this.clampOffset;frame[0]=(tex._frame.x+margin+offset)/texBase.width;frame[1]=(tex._frame.y+margin+offset)/texBase.height;frame[2]=(tex._frame.x+tex._frame.width-margin+offset)/texBase.width;frame[3]=(tex._frame.y+tex._frame.height-margin+offset)/texBase.height;this.uClampOffset[0]=offset/texBase.realWidth;this.uClampOffset[1]=offset/texBase.realHeight;};_createClass(TextureTransform,[{key:'texture',get:function get(){return this._texture;}/**
         * sets texture value
         * @param {PIXI.Texture} value texture to be set
         */,set:function set(value){this._texture=value;this._lastTextureID=-1;}}]);return TextureTransform;}();exports.default=TextureTransform;},{"../core/math/Matrix":63}],127:[function(require,module,exports){'use strict';exports.__esModule=true;var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor);}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor;};}();var _core=require('../core');var core=_interopRequireWildcard(_core);var _CanvasTinter=require('../core/sprites/canvas/CanvasTinter');var _CanvasTinter2=_interopRequireDefault(_CanvasTinter);var _TextureTransform=require('./TextureTransform');var _TextureTransform2=_interopRequireDefault(_TextureTransform);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj;}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key];}}newObj.default=obj;return newObj;}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return call&&((typeof call==="undefined"?"undefined":_typeof2(call))==="object"||typeof call==="function")?call:self;}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof2(superClass)));}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass;}var tempPoint=new core.Point();/**
 * A tiling sprite is a fast way of rendering a tiling image
 *
 * @class
 * @extends PIXI.Sprite
 * @memberof PIXI.extras
 */var TilingSprite=function(_core$Sprite){_inherits(TilingSprite,_core$Sprite);/**
     * @param {PIXI.Texture} texture - the texture of the tiling sprite
     * @param {number} [width=100] - the width of the tiling sprite
     * @param {number} [height=100] - the height of the tiling sprite
     */function TilingSprite(texture){var width=arguments.length<=1||arguments[1]===undefined?100:arguments[1];var height=arguments.length<=2||arguments[2]===undefined?100:arguments[2];_classCallCheck(this,TilingSprite);/**
         * Tile transform
         *
         * @member {PIXI.TransformStatic}
         */var _this=_possibleConstructorReturn(this,_core$Sprite.call(this,texture));_this.tileTransform=new core.TransformStatic();// /// private
/**
         * The with of the tiling sprite
         *
         * @member {number}
         * @private
         */_this._width=width;/**
         * The height of the tiling sprite
         *
         * @member {number}
         * @private
         */_this._height=height;/**
         * Canvas pattern
         *
         * @type {CanvasPattern}
         * @private
         */_this._canvasPattern=null;/**
         * transform that is applied to UV to get the texture coords
         *
         * @member {PIXI.extras.TextureTransform}
         */_this.uvTransform=texture.transform||new _TextureTransform2.default(texture);/**
         * Plugin that is responsible for rendering this element.
         * Allows to customize the rendering process without overriding '_renderWebGL' method.
         *
         * @member {string}
         * @default 'tilingSprite'
         */_this.pluginName='tilingSprite';return _this;}/**
     * Changes frame clamping in corresponding textureTransform, shortcut
     * Change to -0.5 to add a pixel to the edge, recommended for transparent trimmed textures in atlas
     *
     * @default 0.5
     * @member {number}
     * @memberof PIXI.TilingSprite
     *//**
     * @private
     */TilingSprite.prototype._onTextureUpdate=function _onTextureUpdate(){if(this.uvTransform){this.uvTransform.texture=this._texture;}};/**
     * Renders the object using the WebGL renderer
     *
     * @private
     * @param {PIXI.WebGLRenderer} renderer - The renderer
     */TilingSprite.prototype._renderWebGL=function _renderWebGL(renderer){// tweak our texture temporarily..
var texture=this._texture;if(!texture||!texture.valid){return;}this.tileTransform.updateLocalTransform();this.uvTransform.update();renderer.setObjectRenderer(renderer.plugins[this.pluginName]);renderer.plugins[this.pluginName].render(this);};/**
     * Renders the object using the Canvas renderer
     *
     * @private
     * @param {PIXI.CanvasRenderer} renderer - a reference to the canvas renderer
     */TilingSprite.prototype._renderCanvas=function _renderCanvas(renderer){var texture=this._texture;if(!texture.baseTexture.hasLoaded){return;}var context=renderer.context;var transform=this.worldTransform;var resolution=renderer.resolution;var baseTexture=texture.baseTexture;var baseTextureResolution=texture.baseTexture.resolution;var modX=this.tilePosition.x/this.tileScale.x%texture._frame.width;var modY=this.tilePosition.y/this.tileScale.y%texture._frame.height;// create a nice shiny pattern!
// TODO this needs to be refreshed if texture changes..
if(!this._canvasPattern){// cut an object from a spritesheet..
var tempCanvas=new core.CanvasRenderTarget(texture._frame.width,texture._frame.height,baseTextureResolution);// Tint the tiling sprite
if(this.tint!==0xFFFFFF){if(this.cachedTint!==this.tint){this.cachedTint=this.tint;this.tintedTexture=_CanvasTinter2.default.getTintedTexture(this,this.tint);}tempCanvas.context.drawImage(this.tintedTexture,0,0);}else{tempCanvas.context.drawImage(baseTexture.source,-texture._frame.x,-texture._frame.y);}this._canvasPattern=tempCanvas.context.createPattern(tempCanvas.canvas,'repeat');}// set context state..
context.globalAlpha=this.worldAlpha;context.setTransform(transform.a*resolution,transform.b*resolution,transform.c*resolution,transform.d*resolution,transform.tx*resolution,transform.ty*resolution);// TODO - this should be rolled into the setTransform above..
context.scale(this.tileScale.x/baseTextureResolution,this.tileScale.y/baseTextureResolution);context.translate(modX+this.anchor.x*-this._width,modY+this.anchor.y*-this._height);renderer.setBlendMode(this.blendMode);// fill the pattern!
context.fillStyle=this._canvasPattern;context.fillRect(-modX,-modY,this._width/this.tileScale.x*baseTextureResolution,this._height/this.tileScale.y*baseTextureResolution);};/**
     * Updates the bounds of the tiling sprite.
     *
     * @private
     */TilingSprite.prototype._calculateBounds=function _calculateBounds(){var minX=this._width*-this._anchor._x;var minY=this._height*-this._anchor._y;var maxX=this._width*(1-this._anchor._x);var maxY=this._height*(1-this._anchor._y);this._bounds.addFrame(this.transform,minX,minY,maxX,maxY);};/**
     * Gets the local bounds of the sprite object.
     *
     * @param {PIXI.Rectangle} rect - The output rectangle.
     * @return {PIXI.Rectangle} The bounds.
     */TilingSprite.prototype.getLocalBounds=function getLocalBounds(rect){// we can do a fast local bounds if the sprite has no children!
if(this.children.length===0){this._bounds.minX=this._width*-this._anchor._x;this._bounds.minY=this._height*-this._anchor._y;this._bounds.maxX=this._width*(1-this._anchor._x);this._bounds.maxY=this._height*(1-this._anchor._x);if(!rect){if(!this._localBoundsRect){this._localBoundsRect=new core.Rectangle();}rect=this._localBoundsRect;}return this._bounds.getRectangle(rect);}return _core$Sprite.prototype.getLocalBounds.call(this,rect);};/**
     * Checks if a point is inside this tiling sprite.
     *
     * @param {PIXI.Point} point - the point to check
     * @return {boolean} Whether or not the sprite contains the point.
     */TilingSprite.prototype.containsPoint=function containsPoint(point){this.worldTransform.applyInverse(point,tempPoint);var width=this._width;var height=this._height;var x1=-width*this.anchor._x;if(tempPoint.x>x1&&tempPoint.x<x1+width){var y1=-height*this.anchor._y;if(tempPoint.y>y1&&tempPoint.y<y1+height){return true;}}return false;};/**
     * Destroys this tiling sprite
     *
     */TilingSprite.prototype.destroy=function destroy(){_core$Sprite.prototype.destroy.call(this);this.tileTransform=null;this.uvTransform=null;};/**
     * Helper function that creates a new tiling sprite based on the source you provide.
     * The source can be - frame id, image url, video url, canvas element, video element, base texture
     *
     * @static
     * @param {number|string|PIXI.BaseTexture|HTMLCanvasElement|HTMLVideoElement} source - Source to create texture from
     * @param {number} width - the width of the tiling sprite
     * @param {number} height - the height of the tiling sprite
     * @return {PIXI.Texture} The newly created texture
     */TilingSprite.from=function from(source,width,height){return new TilingSprite(core.Texture.from(source),width,height);};/**
     * Helper function that creates a tiling sprite that will use a texture from the TextureCache based on the frameId
     * The frame ids are created when a Texture packer file has been loaded
     *
     * @static
     * @param {string} frameId - The frame Id of the texture in the cache
     * @param {number} width - the width of the tiling sprite
     * @param {number} height - the height of the tiling sprite
     * @return {PIXI.extras.TilingSprite} A new TilingSprite using a texture from the texture cache matching the frameId
     */TilingSprite.fromFrame=function fromFrame(frameId,width,height){var texture=core.utils.TextureCache[frameId];if(!texture){throw new Error('The frameId "'+frameId+'" does not exist in the texture cache '+this);}return new TilingSprite(texture,width,height);};/**
     * Helper function that creates a sprite that will contain a texture based on an image url
     * If the image is not in the texture cache it will be loaded
     *
     * @static
     * @param {string} imageId - The image url of the texture
     * @param {number} width - the width of the tiling sprite
     * @param {number} height - the height of the tiling sprite
     * @param {boolean} [crossorigin] - if you want to specify the cross-origin parameter
     * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - if you want to specify the scale mode,
     *  see {@link PIXI.SCALE_MODES} for possible values
     * @return {PIXI.extras.TilingSprite} A new TilingSprite using a texture from the texture cache matching the image id
     */TilingSprite.fromImage=function fromImage(imageId,width,height,crossorigin,scaleMode){return new TilingSprite(core.Texture.fromImage(imageId,crossorigin,scaleMode),width,height);};/**
     * The width of the sprite, setting this will actually modify the scale to achieve the value set
     *
     * @member {number}
     * @memberof PIXI.extras.TilingSprite#
     */_createClass(TilingSprite,[{key:'clampMargin',get:function get(){return this.uvTransform.clampMargin;}/**
         * setter for clampMargin
         *
         * @param {number} value assigned value
         */,set:function set(value){this.uvTransform.clampMargin=value;this.uvTransform.update(true);}/**
         * The scaling of the image that is being tiled
         *
         * @member {PIXI.ObservablePoint}
         * @memberof PIXI.DisplayObject#
         */},{key:'tileScale',get:function get(){return this.tileTransform.scale;}/**
         * Copies the point to the scale of the tiled image.
         *
         * @param {PIXI.Point|PIXI.ObservablePoint} value - The value to set to.
         */,set:function set(value){this.tileTransform.scale.copy(value);}/**
         * The offset of the image that is being tiled
         *
         * @member {PIXI.ObservablePoint}
         * @memberof PIXI.TilingSprite#
         */},{key:'tilePosition',get:function get(){return this.tileTransform.position;}/**
         * Copies the point to the position of the tiled image.
         *
         * @param {PIXI.Point|PIXI.ObservablePoint} value - The value to set to.
         */,set:function set(value){this.tileTransform.position.copy(value);}},{key:'width',get:function get(){return this._width;}/**
         * Sets the width.
         *
         * @param {number} value - The value to set to.
         */,set:function set(value){this._width=value;}/**
         * The height of the TilingSprite, setting this will actually modify the scale to achieve the value set
         *
         * @member {number}
         * @memberof PIXI.extras.TilingSprite#
         */},{key:'height',get:function get(){return this._height;}/**
         * Sets the width.
         *
         * @param {number} value - The value to set to.
         */,set:function set(value){this._height=value;}}]);return TilingSprite;}(core.Sprite);exports.default=TilingSprite;},{"../core":61,"../core/sprites/canvas/CanvasTinter":100,"./TextureTransform":126}],128:[function(require,module,exports){'use strict';var _core=require('../core');var core=_interopRequireWildcard(_core);function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj;}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key];}}newObj.default=obj;return newObj;}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}var DisplayObject=core.DisplayObject;var _tempMatrix=new core.Matrix();DisplayObject.prototype._cacheAsBitmap=false;DisplayObject.prototype._cacheData=false;// figured theres no point adding ALL the extra variables to prototype.
// this model can hold the information needed. This can also be generated on demand as
// most objects are not cached as bitmaps.
/**
 * @class
 * @ignore
 */var CacheData=/**
 *
 */function CacheData(){_classCallCheck(this,CacheData);this.originalRenderWebGL=null;this.originalRenderCanvas=null;this.originalCalculateBounds=null;this.originalGetLocalBounds=null;this.originalUpdateTransform=null;this.originalHitTest=null;this.originalDestroy=null;this.originalMask=null;this.originalFilterArea=null;this.sprite=null;};Object.defineProperties(DisplayObject.prototype,{/**
     * Set this to true if you want this display object to be cached as a bitmap.
     * This basically takes a snap shot of the display object as it is at that moment. It can
     * provide a performance benefit for complex static displayObjects.
     * To remove simply set this property to 'false'
     *
     * @member {boolean}
     * @memberof PIXI.DisplayObject#
     */cacheAsBitmap:{get:function get(){return this._cacheAsBitmap;},set:function set(value){if(this._cacheAsBitmap===value){return;}this._cacheAsBitmap=value;var data=void 0;if(value){if(!this._cacheData){this._cacheData=new CacheData();}data=this._cacheData;data.originalRenderWebGL=this.renderWebGL;data.originalRenderCanvas=this.renderCanvas;data.originalUpdateTransform=this.updateTransform;data.originalCalculateBounds=this._calculateBounds;data.originalGetLocalBounds=this.getLocalBounds;data.originalDestroy=this.destroy;data.originalContainsPoint=this.containsPoint;data.originalMask=this._mask;data.originalFilterArea=this.filterArea;this.renderWebGL=this._renderCachedWebGL;this.renderCanvas=this._renderCachedCanvas;this.destroy=this._cacheAsBitmapDestroy;}else{data=this._cacheData;if(data.sprite){this._destroyCachedDisplayObject();}this.renderWebGL=data.originalRenderWebGL;this.renderCanvas=data.originalRenderCanvas;this._calculateBounds=data.originalCalculateBounds;this.getLocalBounds=data.originalGetLocalBounds;this.destroy=data.originalDestroy;this.updateTransform=data.originalUpdateTransform;this.containsPoint=data.originalContainsPoint;this._mask=data.originalMask;this.filterArea=data.originalFilterArea;}}}});/**
 * Renders a cached version of the sprite with WebGL
 *
 * @private
 * @memberof PIXI.DisplayObject#
 * @param {PIXI.WebGLRenderer} renderer - the WebGL renderer
 */DisplayObject.prototype._renderCachedWebGL=function _renderCachedWebGL(renderer){if(!this.visible||this.worldAlpha<=0||!this.renderable){return;}this._initCachedDisplayObject(renderer);this._cacheData.sprite._transformID=-1;this._cacheData.sprite.worldAlpha=this.worldAlpha;this._cacheData.sprite._renderWebGL(renderer);};/**
 * Prepares the WebGL renderer to cache the sprite
 *
 * @private
 * @memberof PIXI.DisplayObject#
 * @param {PIXI.WebGLRenderer} renderer - the WebGL renderer
 */DisplayObject.prototype._initCachedDisplayObject=function _initCachedDisplayObject(renderer){if(this._cacheData&&this._cacheData.sprite){return;}// make sure alpha is set to 1 otherwise it will get rendered as invisible!
var cacheAlpha=this.alpha;this.alpha=1;// first we flush anything left in the renderer (otherwise it would get rendered to the cached texture)
renderer.currentRenderer.flush();// this.filters= [];
// next we find the dimensions of the untransformed object
// this function also calls updatetransform on all its children as part of the measuring.
// This means we don't need to update the transform again in this function
// TODO pass an object to clone too? saves having to create a new one each time!
var bounds=this.getLocalBounds().clone();// add some padding!
if(this._filters){var padding=this._filters[0].padding;bounds.pad(padding);}// for now we cache the current renderTarget that the webGL renderer is currently using.
// this could be more elegent..
var cachedRenderTarget=renderer._activeRenderTarget;// We also store the filter stack - I will definitely look to change how this works a little later down the line.
var stack=renderer.filterManager.filterStack;// this renderTexture will be used to store the cached DisplayObject
var renderTexture=core.RenderTexture.create(bounds.width|0,bounds.height|0);// need to set //
var m=_tempMatrix;m.tx=-bounds.x;m.ty=-bounds.y;// reset
this.transform.worldTransform.identity();// set all properties to there original so we can render to a texture
this.renderWebGL=this._cacheData.originalRenderWebGL;renderer.render(this,renderTexture,true,m,true);// now restore the state be setting the new properties
renderer.bindRenderTarget(cachedRenderTarget);renderer.filterManager.filterStack=stack;this.renderWebGL=this._renderCachedWebGL;this.updateTransform=this.displayObjectUpdateTransform;this._mask=null;this.filterArea=null;// create our cached sprite
var cachedSprite=new core.Sprite(renderTexture);cachedSprite.transform.worldTransform=this.transform.worldTransform;cachedSprite.anchor.x=-(bounds.x/bounds.width);cachedSprite.anchor.y=-(bounds.y/bounds.height);cachedSprite.alpha=cacheAlpha;cachedSprite._bounds=this._bounds;// easy bounds..
this._calculateBounds=this._calculateCachedBounds;this.getLocalBounds=this._getCachedLocalBounds;this._cacheData.sprite=cachedSprite;this.transform._parentID=-1;// restore the transform of the cached sprite to avoid the nasty flicker..
this.updateTransform();// map the hit test..
this.containsPoint=cachedSprite.containsPoint.bind(cachedSprite);};/**
 * Renders a cached version of the sprite with canvas
 *
 * @private
 * @memberof PIXI.DisplayObject#
 * @param {PIXI.WebGLRenderer} renderer - the WebGL renderer
 */DisplayObject.prototype._renderCachedCanvas=function _renderCachedCanvas(renderer){if(!this.visible||this.worldAlpha<=0||!this.renderable){return;}this._initCachedDisplayObjectCanvas(renderer);this._cacheData.sprite.worldAlpha=this.worldAlpha;this._cacheData.sprite.renderCanvas(renderer);};// TODO this can be the same as the webGL verison.. will need to do a little tweaking first though..
/**
 * Prepares the Canvas renderer to cache the sprite
 *
 * @private
 * @memberof PIXI.DisplayObject#
 * @param {PIXI.WebGLRenderer} renderer - the WebGL renderer
 */DisplayObject.prototype._initCachedDisplayObjectCanvas=function _initCachedDisplayObjectCanvas(renderer){if(this._cacheData&&this._cacheData.sprite){return;}// get bounds actually transforms the object for us already!
var bounds=this.getLocalBounds();var cacheAlpha=this.alpha;this.alpha=1;var cachedRenderTarget=renderer.context;var renderTexture=core.RenderTexture.create(bounds.width|0,bounds.height|0);// need to set //
var m=_tempMatrix;this.transform.worldTransform.copy(m);m.invert();m.tx-=bounds.x;m.ty-=bounds.y;// m.append(this.transform.worldTransform.)
// set all properties to there original so we can render to a texture
this.renderCanvas=this._cacheData.originalRenderCanvas;// renderTexture.render(this, m, true);
renderer.render(this,renderTexture,true,m,false);// now restore the state be setting the new properties
renderer.context=cachedRenderTarget;this.renderCanvas=this._renderCachedCanvas;this._calculateBounds=this._calculateCachedBounds;this._mask=null;this.filterArea=null;// create our cached sprite
var cachedSprite=new core.Sprite(renderTexture);cachedSprite.transform.worldTransform=this.transform.worldTransform;cachedSprite.anchor.x=-(bounds.x/bounds.width);cachedSprite.anchor.y=-(bounds.y/bounds.height);cachedSprite._bounds=this._bounds;cachedSprite.alpha=cacheAlpha;this.updateTransform();this.updateTransform=this.displayObjectUpdateTransform;this._cacheData.sprite=cachedSprite;this.containsPoint=cachedSprite.containsPoint.bind(cachedSprite);};/**
 * Calculates the bounds of the cached sprite
 *
 * @private
 */DisplayObject.prototype._calculateCachedBounds=function _calculateCachedBounds(){this._cacheData.sprite._calculateBounds();};/**
 * Gets the bounds of the cached sprite.
 *
 * @private
 * @return {Rectangle} The local bounds.
 */DisplayObject.prototype._getCachedLocalBounds=function _getCachedLocalBounds(){return this._cacheData.sprite.getLocalBounds();};/**
 * Destroys the cached sprite.
 *
 * @private
 */DisplayObject.prototype._destroyCachedDisplayObject=function _destroyCachedDisplayObject(){this._cacheData.sprite._texture.destroy(true);this._cacheData.sprite=null;};/**
 * Destroys the cached object.
 *
 * @private
 */DisplayObject.prototype._cacheAsBitmapDestroy=function _cacheAsBitmapDestroy(){this.cacheAsBitmap=false;this.destroy();};},{"../core":61}],129:[function(require,module,exports){'use strict';var _core=require('../core');var core=_interopRequireWildcard(_core);function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj;}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key];}}newObj.default=obj;return newObj;}}/**
 * The instance name of the object.
 *
 * @memberof PIXI.DisplayObject#
 * @member {string}
 */core.DisplayObject.prototype.name=null;/**
 * Returns the display object in the container
 *
 * @memberof PIXI.Container#
 * @param {string} name - instance name
 * @return {PIXI.DisplayObject} The child with the specified name.
 */core.Container.prototype.getChildByName=function getChildByName(name){for(var i=0;i<this.children.length;i++){if(this.children[i].name===name){return this.children[i];}}return null;};},{"../core":61}],130:[function(require,module,exports){'use strict';var _core=require('../core');var core=_interopRequireWildcard(_core);function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj;}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key];}}newObj.default=obj;return newObj;}}/**
 * Returns the global position of the displayObject. Does not depend on object scale, rotation and pivot.
 *
 * @memberof PIXI.DisplayObject#
 * @param {Point} point - the point to write the global value to. If null a new point will be returned
 * @param {boolean} skipUpdate - setting to true will stop the transforms of the scene graph from
 *  being updated. This means the calculation returned MAY be out of date BUT will give you a
 *  nice performance boost
 * @return {Point} The updated point
 */core.DisplayObject.prototype.getGlobalPosition=function getGlobalPosition(){var point=arguments.length<=0||arguments[0]===undefined?new core.Point():arguments[0];var skipUpdate=arguments.length<=1||arguments[1]===undefined?false:arguments[1];if(this.parent){this.parent.toGlobal(this.position,point,skipUpdate);}else{point.x=this.position.x;point.y=this.position.y;}return point;};},{"../core":61}],131:[function(require,module,exports){'use strict';exports.__esModule=true;exports.BitmapText=exports.TilingSpriteRenderer=exports.TilingSprite=exports.AnimatedSprite=exports.TextureTransform=undefined;var _TextureTransform=require('./TextureTransform');Object.defineProperty(exports,'TextureTransform',{enumerable:true,get:function get(){return _interopRequireDefault(_TextureTransform).default;}});var _AnimatedSprite=require('./AnimatedSprite');Object.defineProperty(exports,'AnimatedSprite',{enumerable:true,get:function get(){return _interopRequireDefault(_AnimatedSprite).default;}});var _TilingSprite=require('./TilingSprite');Object.defineProperty(exports,'TilingSprite',{enumerable:true,get:function get(){return _interopRequireDefault(_TilingSprite).default;}});var _TilingSpriteRenderer=require('./webgl/TilingSpriteRenderer');Object.defineProperty(exports,'TilingSpriteRenderer',{enumerable:true,get:function get(){return _interopRequireDefault(_TilingSpriteRenderer).default;}});var _BitmapText=require('./BitmapText');Object.defineProperty(exports,'BitmapText',{enumerable:true,get:function get(){return _interopRequireDefault(_BitmapText).default;}});require('./cacheAsBitmap');require('./getChildByName');require('./getGlobalPosition');function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}// imported for side effect of extending the prototype only, contains no exports
},{"./AnimatedSprite":124,"./BitmapText":125,"./TextureTransform":126,"./TilingSprite":127,"./cacheAsBitmap":128,"./getChildByName":129,"./getGlobalPosition":130,"./webgl/TilingSpriteRenderer":132}],132:[function(require,module,exports){'use strict';exports.__esModule=true;var _core=require('../../core');var core=_interopRequireWildcard(_core);var _const=require('../../core/const');var _path=require('path');function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj;}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key];}}newObj.default=obj;return newObj;}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return call&&((typeof call==="undefined"?"undefined":_typeof2(call))==="object"||typeof call==="function")?call:self;}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof2(superClass)));}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass;}var tempMat=new core.Matrix();var tempArray=new Float32Array(4);/**
 * WebGL renderer plugin for tiling sprites
 */var TilingSpriteRenderer=function(_core$ObjectRenderer){_inherits(TilingSpriteRenderer,_core$ObjectRenderer);/**
     * constructor for renderer
     *
     * @param {WebGLRenderer} renderer The renderer this tiling awesomeness works for.
     */function TilingSpriteRenderer(renderer){_classCallCheck(this,TilingSpriteRenderer);var _this=_possibleConstructorReturn(this,_core$ObjectRenderer.call(this,renderer));_this.shader=null;_this.simpleShader=null;_this.quad=null;return _this;}/**
     * Sets up the renderer context and necessary buffers.
     *
     * @private
     */TilingSpriteRenderer.prototype.onContextChange=function onContextChange(){var gl=this.renderer.gl;this.shader=new core.Shader(gl,'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n    gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n    vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n','varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\nuniform mat3 uMapCoord;\nuniform vec4 uClampFrame;\nuniform vec2 uClampOffset;\n\nvoid main(void)\n{\n    vec2 coord = mod(vTextureCoord - uClampOffset, vec2(1.0, 1.0)) + uClampOffset;\n    coord = (uMapCoord * vec3(coord, 1.0)).xy;\n    coord = clamp(coord, uClampFrame.xy, uClampFrame.zw);\n\n    vec4 sample = texture2D(uSampler, coord);\n    vec4 color = vec4(uColor.rgb * uColor.a, uColor.a);\n\n    gl_FragColor = sample * color ;\n}\n');this.simpleShader=new core.Shader(gl,'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n    gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n    vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n','varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\n\nvoid main(void)\n{\n    vec4 sample = texture2D(uSampler, vTextureCoord);\n    vec4 color = vec4(uColor.rgb * uColor.a, uColor.a);\n    gl_FragColor = sample * color;\n}\n');this.renderer.bindVao(null);this.quad=new core.Quad(gl,this.renderer.state.attribState);this.quad.initVao(this.shader);};/**
     *
     * @param {PIXI.extras.TilingSprite} ts tilingSprite to be rendered
     */TilingSpriteRenderer.prototype.render=function render(ts){var renderer=this.renderer;var quad=this.quad;renderer.bindVao(quad.vao);var vertices=quad.vertices;vertices[0]=vertices[6]=ts._width*-ts.anchor.x;vertices[1]=vertices[3]=ts._height*-ts.anchor.y;vertices[2]=vertices[4]=ts._width*(1.0-ts.anchor.x);vertices[5]=vertices[7]=ts._height*(1.0-ts.anchor.y);vertices=quad.uvs;vertices[0]=vertices[6]=-ts.anchor.x;vertices[1]=vertices[3]=-ts.anchor.y;vertices[2]=vertices[4]=1.0-ts.anchor.x;vertices[5]=vertices[7]=1.0-ts.anchor.y;quad.upload();var tex=ts._texture;var baseTex=tex.baseTexture;var lt=ts.tileTransform.localTransform;var uv=ts.uvTransform;var isSimple=baseTex.isPowerOfTwo&&tex.frame.width===baseTex.width&&tex.frame.height===baseTex.height;// auto, force repeat wrapMode for big tiling textures
if(isSimple){if(!baseTex._glTextures[renderer.CONTEXT_UID]){if(baseTex.wrapMode===_const.WRAP_MODES.CLAMP){baseTex.wrapMode=_const.WRAP_MODES.REPEAT;}}else{isSimple=baseTex.wrapMode!==_const.WRAP_MODES.CLAMP;}}var shader=isSimple?this.simpleShader:this.shader;renderer.bindShader(shader);var w=tex.width;var h=tex.height;var W=ts._width;var H=ts._height;tempMat.set(lt.a*w/W,lt.b*w/H,lt.c*h/W,lt.d*h/H,lt.tx/W,lt.ty/H);// that part is the same as above:
// tempMat.identity();
// tempMat.scale(tex.width, tex.height);
// tempMat.prepend(lt);
// tempMat.scale(1.0 / ts._width, 1.0 / ts._height);
tempMat.invert();if(isSimple){tempMat.append(uv.mapCoord);}else{shader.uniforms.uMapCoord=uv.mapCoord.toArray(true);shader.uniforms.uClampFrame=uv.uClampFrame;shader.uniforms.uClampOffset=uv.uClampOffset;}shader.uniforms.uTransform=tempMat.toArray(true);var color=tempArray;core.utils.hex2rgb(ts.tint,color);color[3]=ts.worldAlpha;shader.uniforms.uColor=color;shader.uniforms.translationMatrix=ts.transform.worldTransform.toArray(true);shader.uniforms.uSampler=renderer.bindTexture(tex);renderer.setBlendMode(ts.blendMode);quad.vao.draw(this.renderer.gl.TRIANGLES,6,0);};return TilingSpriteRenderer;}(core.ObjectRenderer);exports.default=TilingSpriteRenderer;core.WebGLRenderer.registerPlugin('tilingSprite',TilingSpriteRenderer);},{"../../core":61,"../../core/const":42,"path":22}],133:[function(require,module,exports){'use strict';exports.__esModule=true;var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor);}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor;};}();var _core=require('../../core');var core=_interopRequireWildcard(_core);var _BlurXFilter=require('./BlurXFilter');var _BlurXFilter2=_interopRequireDefault(_BlurXFilter);var _BlurYFilter=require('./BlurYFilter');var _BlurYFilter2=_interopRequireDefault(_BlurYFilter);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj;}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key];}}newObj.default=obj;return newObj;}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return call&&((typeof call==="undefined"?"undefined":_typeof2(call))==="object"||typeof call==="function")?call:self;}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof2(superClass)));}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass;}/**
 * The BlurFilter applies a Gaussian blur to an object.
 * The strength of the blur can be set for x- and y-axis separately.
 *
 * @class
 * @extends PIXI.Filter
 * @memberof PIXI.filters
 */var BlurFilter=function(_core$Filter){_inherits(BlurFilter,_core$Filter);/**
   * @param {number} strength - The strength of the blur filter.
   * @param {number} quality - The quality of the blur filter.
   * @param {number} resolution - The resolution of the blur filter.
   * @param {number} [kernelSize=5] - The kernelSize of the blur filter.Options: 5, 7, 9, 11, 13, 15.
   */function BlurFilter(strength,quality,resolution,kernelSize){_classCallCheck(this,BlurFilter);var _this=_possibleConstructorReturn(this,_core$Filter.call(this));_this.blurXFilter=new _BlurXFilter2.default(strength,quality,resolution,kernelSize);_this.blurYFilter=new _BlurYFilter2.default(strength,quality,resolution,kernelSize);_this.resolution=1;_this.padding=0;_this.resolution=resolution||1;_this.quality=quality||4;_this.blur=strength||8;return _this;}/**
   * Applies the filter.
   *
   * @param {PIXI.FilterManager} filterManager - The manager.
   * @param {PIXI.RenderTarget} input - The input target.
   * @param {PIXI.RenderTarget} output - The output target.
   */BlurFilter.prototype.apply=function apply(filterManager,input,output){var renderTarget=filterManager.getRenderTarget(true);this.blurXFilter.apply(filterManager,input,renderTarget,true);this.blurYFilter.apply(filterManager,renderTarget,output,false);filterManager.returnRenderTarget(renderTarget);};/**
   * Sets the strength of both the blurX and blurY properties simultaneously
   *
   * @member {number}
   * @memberOf PIXI.filters.BlurFilter#
   * @default 2
   */_createClass(BlurFilter,[{key:'blur',get:function get(){return this.blurXFilter.blur;}/**
     * Sets the strength of the blur.
     *
     * @param {number} value - The value to set.
     */,set:function set(value){this.blurXFilter.blur=this.blurYFilter.blur=value;this.padding=Math.max(Math.abs(this.blurXFilter.strength),Math.abs(this.blurYFilter.strength))*2;}/**
     * Sets the number of passes for blur. More passes means higher quaility bluring.
     *
     * @member {number}
     * @memberof PIXI.filters.BlurYFilter#
     * @default 1
     */},{key:'quality',get:function get(){return this.blurXFilter.quality;}/**
     * Sets the quality of the blur.
     *
     * @param {number} value - The value to set.
     */,set:function set(value){this.blurXFilter.quality=this.blurYFilter.quality=value;}/**
     * Sets the strength of the blurX property
     *
     * @member {number}
     * @memberOf PIXI.filters.BlurFilter#
     * @default 2
     */},{key:'blurX',get:function get(){return this.blurXFilter.blur;}/**
     * Sets the strength of the blurX.
     *
     * @param {number} value - The value to set.
     */,set:function set(value){this.blurXFilter.blur=value;this.padding=Math.max(Math.abs(this.blurXFilter.strength),Math.abs(this.blurYFilter.strength))*2;}/**
     * Sets the strength of the blurY property
     *
     * @member {number}
     * @memberOf PIXI.filters.BlurFilter#
     * @default 2
     */},{key:'blurY',get:function get(){return this.blurYFilter.blur;}/**
     * Sets the strength of the blurY.
     *
     * @param {number} value - The value to set.
     */,set:function set(value){this.blurYFilter.blur=value;this.padding=Math.max(Math.abs(this.blurXFilter.strength),Math.abs(this.blurYFilter.strength))*2;}}]);return BlurFilter;}(core.Filter);exports.default=BlurFilter;},{"../../core":61,"./BlurXFilter":134,"./BlurYFilter":135}],134:[function(require,module,exports){'use strict';exports.__esModule=true;var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor);}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor;};}();var _core=require('../../core');var core=_interopRequireWildcard(_core);var _generateBlurVertSource=require('./generateBlurVertSource');var _generateBlurVertSource2=_interopRequireDefault(_generateBlurVertSource);var _generateBlurFragSource=require('./generateBlurFragSource');var _generateBlurFragSource2=_interopRequireDefault(_generateBlurFragSource);var _getMaxBlurKernelSize=require('./getMaxBlurKernelSize');var _getMaxBlurKernelSize2=_interopRequireDefault(_getMaxBlurKernelSize);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj;}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key];}}newObj.default=obj;return newObj;}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return call&&((typeof call==="undefined"?"undefined":_typeof2(call))==="object"||typeof call==="function")?call:self;}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof2(superClass)));}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass;}/**
 * The BlurXFilter applies a horizontal Gaussian blur to an object.
 *
 * @class
 * @extends PIXI.Filter
 * @memberof PIXI.filters
 */var BlurXFilter=function(_core$Filter){_inherits(BlurXFilter,_core$Filter);/**
     * @param {number} strength - The strength of the blur filter.
     * @param {number} quality - The quality of the blur filter.
     * @param {number} resolution - The resolution of the blur filter.
     * @param {number} [kernelSize=5] - The kernelSize of the blur filter.Options: 5, 7, 9, 11, 13, 15.
     */function BlurXFilter(strength,quality,resolution,kernelSize){_classCallCheck(this,BlurXFilter);kernelSize=kernelSize||5;var vertSrc=(0,_generateBlurVertSource2.default)(kernelSize,true);var fragSrc=(0,_generateBlurFragSource2.default)(kernelSize);var _this=_possibleConstructorReturn(this,_core$Filter.call(this,// vertex shader
vertSrc,// fragment shader
fragSrc));_this.resolution=resolution||1;_this._quality=0;_this.quality=quality||4;_this.strength=strength||8;_this.firstRun=true;return _this;}/**
     * Applies the filter.
     *
     * @param {PIXI.FilterManager} filterManager - The manager.
     * @param {PIXI.RenderTarget} input - The input target.
     * @param {PIXI.RenderTarget} output - The output target.
     * @param {boolean} clear - Should the output be cleared before rendering?
     */BlurXFilter.prototype.apply=function apply(filterManager,input,output,clear){if(this.firstRun){var gl=filterManager.renderer.gl;var kernelSize=(0,_getMaxBlurKernelSize2.default)(gl);this.vertexSrc=(0,_generateBlurVertSource2.default)(kernelSize,true);this.fragmentSrc=(0,_generateBlurFragSource2.default)(kernelSize);this.firstRun=false;}this.uniforms.strength=1/output.size.width*(output.size.width/input.size.width);// screen space!
this.uniforms.strength*=this.strength;this.uniforms.strength/=this.passes;// / this.passes//Math.pow(1, this.passes);
if(this.passes===1){filterManager.applyFilter(this,input,output,clear);}else{var renderTarget=filterManager.getRenderTarget(true);var flip=input;var flop=renderTarget;for(var i=0;i<this.passes-1;i++){filterManager.applyFilter(this,flip,flop,true);var temp=flop;flop=flip;flip=temp;}filterManager.applyFilter(this,flip,output,clear);filterManager.returnRenderTarget(renderTarget);}};/**
     * Sets the strength of both the blur.
     *
     * @member {number}
     * @memberof PIXI.filters.BlurXFilter#
     * @default 16
     */_createClass(BlurXFilter,[{key:'blur',get:function get(){return this.strength;}/**
         * Sets the strength of the blur.
         *
         * @param {number} value - The value to set.
         */,set:function set(value){this.padding=Math.abs(value)*2;this.strength=value;}/**
        * Sets the quality of the blur by modifying the number of passes. More passes means higher
        * quaility bluring but the lower the performance.
        *
        * @member {number}
        * @memberof PIXI.filters.BlurXFilter#
        * @default 4
        */},{key:'quality',get:function get(){return this._quality;}/**
         * Sets the quality of the blur.
         *
         * @param {number} value - The value to set.
         */,set:function set(value){this._quality=value;this.passes=value;}}]);return BlurXFilter;}(core.Filter);exports.default=BlurXFilter;},{"../../core":61,"./generateBlurFragSource":136,"./generateBlurVertSource":137,"./getMaxBlurKernelSize":138}],135:[function(require,module,exports){'use strict';exports.__esModule=true;var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor);}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor;};}();var _core=require('../../core');var core=_interopRequireWildcard(_core);var _generateBlurVertSource=require('./generateBlurVertSource');var _generateBlurVertSource2=_interopRequireDefault(_generateBlurVertSource);var _generateBlurFragSource=require('./generateBlurFragSource');var _generateBlurFragSource2=_interopRequireDefault(_generateBlurFragSource);var _getMaxBlurKernelSize=require('./getMaxBlurKernelSize');var _getMaxBlurKernelSize2=_interopRequireDefault(_getMaxBlurKernelSize);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj;}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key];}}newObj.default=obj;return newObj;}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return call&&((typeof call==="undefined"?"undefined":_typeof2(call))==="object"||typeof call==="function")?call:self;}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof2(superClass)));}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass;}/**
 * The BlurYFilter applies a horizontal Gaussian blur to an object.
 *
 * @class
 * @extends PIXI.Filter
 * @memberof PIXI.filters
 */var BlurYFilter=function(_core$Filter){_inherits(BlurYFilter,_core$Filter);/**
     * @param {number} strength - The strength of the blur filter.
     * @param {number} quality - The quality of the blur filter.
     * @param {number} resolution - The resolution of the blur filter.
     * @param {number} [kernelSize=5] - The kernelSize of the blur filter.Options: 5, 7, 9, 11, 13, 15.
     */function BlurYFilter(strength,quality,resolution,kernelSize){_classCallCheck(this,BlurYFilter);kernelSize=kernelSize||5;var vertSrc=(0,_generateBlurVertSource2.default)(kernelSize,false);var fragSrc=(0,_generateBlurFragSource2.default)(kernelSize);var _this=_possibleConstructorReturn(this,_core$Filter.call(this,// vertex shader
vertSrc,// fragment shader
fragSrc));_this.resolution=resolution||1;_this._quality=0;_this.quality=quality||4;_this.strength=strength||8;_this.firstRun=true;return _this;}/**
     * Applies the filter.
     *
     * @param {PIXI.FilterManager} filterManager - The manager.
     * @param {PIXI.RenderTarget} input - The input target.
     * @param {PIXI.RenderTarget} output - The output target.
     * @param {boolean} clear - Should the output be cleared before rendering?
     */BlurYFilter.prototype.apply=function apply(filterManager,input,output,clear){if(this.firstRun){var gl=filterManager.renderer.gl;var kernelSize=(0,_getMaxBlurKernelSize2.default)(gl);this.vertexSrc=(0,_generateBlurVertSource2.default)(kernelSize,false);this.fragmentSrc=(0,_generateBlurFragSource2.default)(kernelSize);this.firstRun=false;}this.uniforms.strength=1/output.size.height*(output.size.height/input.size.height);this.uniforms.strength*=this.strength;this.uniforms.strength/=this.passes;if(this.passes===1){filterManager.applyFilter(this,input,output,clear);}else{var renderTarget=filterManager.getRenderTarget(true);var flip=input;var flop=renderTarget;for(var i=0;i<this.passes-1;i++){filterManager.applyFilter(this,flip,flop,true);var temp=flop;flop=flip;flip=temp;}filterManager.applyFilter(this,flip,output,clear);filterManager.returnRenderTarget(renderTarget);}};/**
     * Sets the strength of both the blur.
     *
     * @member {number}
     * @memberof PIXI.filters.BlurYFilter#
     * @default 2
     */_createClass(BlurYFilter,[{key:'blur',get:function get(){return this.strength;}/**
         * Sets the strength of the blur.
         *
         * @param {number} value - The value to set.
         */,set:function set(value){this.padding=Math.abs(value)*2;this.strength=value;}/**
         * Sets the quality of the blur by modifying the number of passes. More passes means higher
         * quaility bluring but the lower the performance.
         *
         * @member {number}
         * @memberof PIXI.filters.BlurXFilter#
         * @default 4
         */},{key:'quality',get:function get(){return this._quality;}/**
         * Sets the quality of the blur.
         *
         * @param {number} value - The value to set.
         */,set:function set(value){this._quality=value;this.passes=value;}}]);return BlurYFilter;}(core.Filter);exports.default=BlurYFilter;},{"../../core":61,"./generateBlurFragSource":136,"./generateBlurVertSource":137,"./getMaxBlurKernelSize":138}],136:[function(require,module,exports){'use strict';exports.__esModule=true;exports.default=generateFragBlurSource;var GAUSSIAN_VALUES={5:[0.153388,0.221461,0.250301],7:[0.071303,0.131514,0.189879,0.214607],9:[0.028532,0.067234,0.124009,0.179044,0.20236],11:[0.0093,0.028002,0.065984,0.121703,0.175713,0.198596],13:[0.002406,0.009255,0.027867,0.065666,0.121117,0.174868,0.197641],15:[0.000489,0.002403,0.009246,0.02784,0.065602,0.120999,0.174697,0.197448]};var fragTemplate=['varying vec2 vBlurTexCoords[%size%];','uniform sampler2D uSampler;','void main(void)','{','    gl_FragColor = vec4(0.0);','    %blur%','}'].join('\n');function generateFragBlurSource(kernelSize){var kernel=GAUSSIAN_VALUES[kernelSize];var halfLength=kernel.length;var fragSource=fragTemplate;var blurLoop='';var template='gl_FragColor += texture2D(uSampler, vBlurTexCoords[%index%]) * %value%;';var value=void 0;for(var i=0;i<kernelSize;i++){var blur=template.replace('%index%',i);value=i;if(i>=halfLength){value=kernelSize-i-1;}blur=blur.replace('%value%',kernel[value]);blurLoop+=blur;blurLoop+='\n';}fragSource=fragSource.replace('%blur%',blurLoop);fragSource=fragSource.replace('%size%',kernelSize);return fragSource;}},{}],137:[function(require,module,exports){'use strict';exports.__esModule=true;exports.default=generateVertBlurSource;var vertTemplate=['attribute vec2 aVertexPosition;','attribute vec2 aTextureCoord;','uniform float strength;','uniform mat3 projectionMatrix;','varying vec2 vBlurTexCoords[%size%];','void main(void)','{','gl_Position = vec4((projectionMatrix * vec3((aVertexPosition), 1.0)).xy, 0.0, 1.0);','%blur%','}'].join('\n');function generateVertBlurSource(kernelSize,x){var halfLength=Math.ceil(kernelSize/2);var vertSource=vertTemplate;var blurLoop='';var template=void 0;// let value;
if(x){template='vBlurTexCoords[%index%] = aTextureCoord + vec2(%sampleIndex% * strength, 0.0);';}else{template='vBlurTexCoords[%index%] = aTextureCoord + vec2(0.0, %sampleIndex% * strength);';}for(var i=0;i<kernelSize;i++){var blur=template.replace('%index%',i);// value = i;
// if(i >= halfLength)
// {
//     value = kernelSize - i - 1;
// }
blur=blur.replace('%sampleIndex%',i-(halfLength-1)+'.0');blurLoop+=blur;blurLoop+='\n';}vertSource=vertSource.replace('%blur%',blurLoop);vertSource=vertSource.replace('%size%',kernelSize);return vertSource;}},{}],138:[function(require,module,exports){"use strict";exports.__esModule=true;exports.default=getMaxKernelSize;function getMaxKernelSize(gl){var maxVaryings=gl.getParameter(gl.MAX_VARYING_VECTORS);var kernelSize=15;while(kernelSize>maxVaryings){kernelSize-=2;}return kernelSize;}},{}],139:[function(require,module,exports){'use strict';exports.__esModule=true;var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor);}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor;};}();var _core=require('../../core');var core=_interopRequireWildcard(_core);var _path=require('path');function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj;}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key];}}newObj.default=obj;return newObj;}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return call&&((typeof call==="undefined"?"undefined":_typeof2(call))==="object"||typeof call==="function")?call:self;}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof2(superClass)));}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass;}/**
 * The ColorMatrixFilter class lets you apply a 5x4 matrix transformation on the RGBA
 * color and alpha values of every pixel on your displayObject to produce a result
 * with a new set of RGBA color and alpha values. It's pretty powerful!
 *
 * ```js
 *  let colorMatrix = new PIXI.ColorMatrixFilter();
 *  container.filters = [colorMatrix];
 *  colorMatrix.contrast(2);
 * ```
 * @author Clément Chenebault <clement@goodboydigital.com>
 * @class
 * @extends PIXI.Filter
 * @memberof PIXI.filters
 */var ColorMatrixFilter=function(_core$Filter){_inherits(ColorMatrixFilter,_core$Filter);/**
     *
     */function ColorMatrixFilter(){_classCallCheck(this,ColorMatrixFilter);var _this=_possibleConstructorReturn(this,_core$Filter.call(this,// vertex shader
'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n    gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n    vTextureCoord = aTextureCoord;\n}',// fragment shader
'varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform float m[20];\n\nvoid main(void)\n{\n\n    vec4 c = texture2D(uSampler, vTextureCoord);\n\n    gl_FragColor.r = (m[0] * c.r);\n        gl_FragColor.r += (m[1] * c.g);\n        gl_FragColor.r += (m[2] * c.b);\n        gl_FragColor.r += (m[3] * c.a);\n        gl_FragColor.r += m[4] * c.a;\n\n    gl_FragColor.g = (m[5] * c.r);\n        gl_FragColor.g += (m[6] * c.g);\n        gl_FragColor.g += (m[7] * c.b);\n        gl_FragColor.g += (m[8] * c.a);\n        gl_FragColor.g += m[9] * c.a;\n\n     gl_FragColor.b = (m[10] * c.r);\n        gl_FragColor.b += (m[11] * c.g);\n        gl_FragColor.b += (m[12] * c.b);\n        gl_FragColor.b += (m[13] * c.a);\n        gl_FragColor.b += m[14] * c.a;\n\n     gl_FragColor.a = (m[15] * c.r);\n        gl_FragColor.a += (m[16] * c.g);\n        gl_FragColor.a += (m[17] * c.b);\n        gl_FragColor.a += (m[18] * c.a);\n        gl_FragColor.a += m[19] * c.a;\n\n//    gl_FragColor = vec4(m[0]);\n}\n'));_this.uniforms.m=[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0];return _this;}/**
     * Transforms current matrix and set the new one
     *
     * @param {number[]} matrix - 5x4 matrix
     * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false,
     *  just set the current matrix with @param matrix
     */ColorMatrixFilter.prototype._loadMatrix=function _loadMatrix(matrix){var multiply=arguments.length<=1||arguments[1]===undefined?false:arguments[1];var newMatrix=matrix;if(multiply){this._multiply(newMatrix,this.uniforms.m,matrix);newMatrix=this._colorMatrix(newMatrix);}// set the new matrix
this.uniforms.m=newMatrix;};/**
     * Multiplies two mat5's
     *
     * @private
     * @param {number[]} out - 5x4 matrix the receiving matrix
     * @param {number[]} a - 5x4 matrix the first operand
     * @param {number[]} b - 5x4 matrix the second operand
     * @returns {number[]} 5x4 matrix
     */ColorMatrixFilter.prototype._multiply=function _multiply(out,a,b){// Red Channel
out[0]=a[0]*b[0]+a[1]*b[5]+a[2]*b[10]+a[3]*b[15];out[1]=a[0]*b[1]+a[1]*b[6]+a[2]*b[11]+a[3]*b[16];out[2]=a[0]*b[2]+a[1]*b[7]+a[2]*b[12]+a[3]*b[17];out[3]=a[0]*b[3]+a[1]*b[8]+a[2]*b[13]+a[3]*b[18];out[4]=a[0]*b[4]+a[1]*b[9]+a[2]*b[14]+a[3]*b[19];// Green Channel
out[5]=a[5]*b[0]+a[6]*b[5]+a[7]*b[10]+a[8]*b[15];out[6]=a[5]*b[1]+a[6]*b[6]+a[7]*b[11]+a[8]*b[16];out[7]=a[5]*b[2]+a[6]*b[7]+a[7]*b[12]+a[8]*b[17];out[8]=a[5]*b[3]+a[6]*b[8]+a[7]*b[13]+a[8]*b[18];out[9]=a[5]*b[4]+a[6]*b[9]+a[7]*b[14]+a[8]*b[19];// Blue Channel
out[10]=a[10]*b[0]+a[11]*b[5]+a[12]*b[10]+a[13]*b[15];out[11]=a[10]*b[1]+a[11]*b[6]+a[12]*b[11]+a[13]*b[16];out[12]=a[10]*b[2]+a[11]*b[7]+a[12]*b[12]+a[13]*b[17];out[13]=a[10]*b[3]+a[11]*b[8]+a[12]*b[13]+a[13]*b[18];out[14]=a[10]*b[4]+a[11]*b[9]+a[12]*b[14]+a[13]*b[19];// Alpha Channel
out[15]=a[15]*b[0]+a[16]*b[5]+a[17]*b[10]+a[18]*b[15];out[16]=a[15]*b[1]+a[16]*b[6]+a[17]*b[11]+a[18]*b[16];out[17]=a[15]*b[2]+a[16]*b[7]+a[17]*b[12]+a[18]*b[17];out[18]=a[15]*b[3]+a[16]*b[8]+a[17]*b[13]+a[18]*b[18];out[19]=a[15]*b[4]+a[16]*b[9]+a[17]*b[14]+a[18]*b[19];return out;};/**
     * Create a Float32 Array and normalize the offset component to 0-1
     *
     * @private
     * @param {number[]} matrix - 5x4 matrix
     * @return {number[]} 5x4 matrix with all values between 0-1
     */ColorMatrixFilter.prototype._colorMatrix=function _colorMatrix(matrix){// Create a Float32 Array and normalize the offset component to 0-1
var m=new Float32Array(matrix);m[4]/=255;m[9]/=255;m[14]/=255;m[19]/=255;return m;};/**
     * Adjusts brightness
     *
     * @param {number} b - value of the brigthness (0-1, where 0 is black)
     * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false,
     *  just set the current matrix with @param matrix
     */ColorMatrixFilter.prototype.brightness=function brightness(b,multiply){var matrix=[b,0,0,0,0,0,b,0,0,0,0,0,b,0,0,0,0,0,1,0];this._loadMatrix(matrix,multiply);};/**
     * Set the matrices in grey scales
     *
     * @param {number} scale - value of the grey (0-1, where 0 is black)
     * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false,
     *  just set the current matrix with @param matrix
     */ColorMatrixFilter.prototype.greyscale=function greyscale(scale,multiply){var matrix=[scale,scale,scale,0,0,scale,scale,scale,0,0,scale,scale,scale,0,0,0,0,0,1,0];this._loadMatrix(matrix,multiply);};/**
     * Set the black and white matrice.
     *
     * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false,
     *  just set the current matrix with @param matrix
     */ColorMatrixFilter.prototype.blackAndWhite=function blackAndWhite(multiply){var matrix=[0.3,0.6,0.1,0,0,0.3,0.6,0.1,0,0,0.3,0.6,0.1,0,0,0,0,0,1,0];this._loadMatrix(matrix,multiply);};/**
     * Set the hue property of the color
     *
     * @param {number} rotation - in degrees
     * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false,
     *  just set the current matrix with @param matrix
     */ColorMatrixFilter.prototype.hue=function hue(rotation,multiply){rotation=(rotation||0)/180*Math.PI;var cosR=Math.cos(rotation);var sinR=Math.sin(rotation);var sqrt=Math.sqrt;/* a good approximation for hue rotation
         This matrix is far better than the versions with magic luminance constants
         formerly used here, but also used in the starling framework (flash) and known from this
         old part of the internet: quasimondo.com/archives/000565.php
          This new matrix is based on rgb cube rotation in space. Look here for a more descriptive
         implementation as a shader not a general matrix:
         https://github.com/evanw/glfx.js/blob/58841c23919bd59787effc0333a4897b43835412/src/filters/adjust/huesaturation.js
          This is the source for the code:
         see http://stackoverflow.com/questions/8507885/shift-hue-of-an-rgb-color/8510751#8510751
         */var w=1/3;var sqrW=sqrt(w);// weight is
var a00=cosR+(1.0-cosR)*w;var a01=w*(1.0-cosR)-sqrW*sinR;var a02=w*(1.0-cosR)+sqrW*sinR;var a10=w*(1.0-cosR)+sqrW*sinR;var a11=cosR+w*(1.0-cosR);var a12=w*(1.0-cosR)-sqrW*sinR;var a20=w*(1.0-cosR)-sqrW*sinR;var a21=w*(1.0-cosR)+sqrW*sinR;var a22=cosR+w*(1.0-cosR);var matrix=[a00,a01,a02,0,0,a10,a11,a12,0,0,a20,a21,a22,0,0,0,0,0,1,0];this._loadMatrix(matrix,multiply);};/**
     * Set the contrast matrix, increase the separation between dark and bright
     * Increase contrast : shadows darker and highlights brighter
     * Decrease contrast : bring the shadows up and the highlights down
     *
     * @param {number} amount - value of the contrast (0-1)
     * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false,
     *  just set the current matrix with @param matrix
     */ColorMatrixFilter.prototype.contrast=function contrast(amount,multiply){var v=(amount||0)+1;var o=-128*(v-1);var matrix=[v,0,0,0,o,0,v,0,0,o,0,0,v,0,o,0,0,0,1,0];this._loadMatrix(matrix,multiply);};/**
     * Set the saturation matrix, increase the separation between colors
     * Increase saturation : increase contrast, brightness, and sharpness
     *
     * @param {number} amount - The saturation amount (0-1)
     * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false,
     *  just set the current matrix with @param matrix
     */ColorMatrixFilter.prototype.saturate=function saturate(){var amount=arguments.length<=0||arguments[0]===undefined?0:arguments[0];var multiply=arguments[1];var x=amount*2/3+1;var y=(x-1)*-0.5;var matrix=[x,y,y,0,0,y,x,y,0,0,y,y,x,0,0,0,0,0,1,0];this._loadMatrix(matrix,multiply);};/**
     * Desaturate image (remove color)
     *
     * Call the saturate function
     *
     */ColorMatrixFilter.prototype.desaturate=function desaturate()// eslint-disable-line no-unused-vars
{this.saturate(-1);};/**
     * Negative image (inverse of classic rgb matrix)
     *
     * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false,
     *  just set the current matrix with @param matrix
     */ColorMatrixFilter.prototype.negative=function negative(multiply){var matrix=[0,1,1,0,0,1,0,1,0,0,1,1,0,0,0,0,0,0,1,0];this._loadMatrix(matrix,multiply);};/**
     * Sepia image
     *
     * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false,
     *  just set the current matrix with @param matrix
     */ColorMatrixFilter.prototype.sepia=function sepia(multiply){var matrix=[0.393,0.7689999,0.18899999,0,0,0.349,0.6859999,0.16799999,0,0,0.272,0.5339999,0.13099999,0,0,0,0,0,1,0];this._loadMatrix(matrix,multiply);};/**
     * Color motion picture process invented in 1916 (thanks Dominic Szablewski)
     *
     * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false,
     *  just set the current matrix with @param matrix
     */ColorMatrixFilter.prototype.technicolor=function technicolor(multiply){var matrix=[1.9125277891456083,-0.8545344976951645,-0.09155508482755585,0,11.793603434377337,-0.3087833385928097,1.7658908555458428,-0.10601743074722245,0,-70.35205161461398,-0.231103377548616,-0.7501899197440212,1.847597816108189,0,30.950940869491138,0,0,0,1,0];this._loadMatrix(matrix,multiply);};/**
     * Polaroid filter
     *
     * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false,
     *  just set the current matrix with @param matrix
     */ColorMatrixFilter.prototype.polaroid=function polaroid(multiply){var matrix=[1.438,-0.062,-0.062,0,0,-0.122,1.378,-0.122,0,0,-0.016,-0.016,1.483,0,0,0,0,0,1,0];this._loadMatrix(matrix,multiply);};/**
     * Filter who transforms : Red -> Blue and Blue -> Red
     *
     * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false,
     *  just set the current matrix with @param matrix
     */ColorMatrixFilter.prototype.toBGR=function toBGR(multiply){var matrix=[0,0,1,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,1,0];this._loadMatrix(matrix,multiply);};/**
     * Color reversal film introduced by Eastman Kodak in 1935. (thanks Dominic Szablewski)
     *
     * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false,
     *  just set the current matrix with @param matrix
     */ColorMatrixFilter.prototype.kodachrome=function kodachrome(multiply){var matrix=[1.1285582396593525,-0.3967382283601348,-0.03992559172921793,0,63.72958762196502,-0.16404339962244616,1.0835251566291304,-0.05498805115633132,0,24.732407896706203,-0.16786010706155763,-0.5603416277695248,1.6014850761964943,0,35.62982807460946,0,0,0,1,0];this._loadMatrix(matrix,multiply);};/**
     * Brown delicious browni filter (thanks Dominic Szablewski)
     *
     * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false,
     *  just set the current matrix with @param matrix
     */ColorMatrixFilter.prototype.browni=function browni(multiply){var matrix=[0.5997023498159715,0.34553243048391263,-0.2708298674538042,0,47.43192855600873,-0.037703249837783157,0.8609577587992641,0.15059552388459913,0,-36.96841498319127,0.24113635128153335,-0.07441037908422492,0.44972182064877153,0,-7.562075277591283,0,0,0,1,0];this._loadMatrix(matrix,multiply);};/**
     * Vintage filter (thanks Dominic Szablewski)
     *
     * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false,
     *  just set the current matrix with @param matrix
     */ColorMatrixFilter.prototype.vintage=function vintage(multiply){var matrix=[0.6279345635605994,0.3202183420819367,-0.03965408211312453,0,9.651285835294123,0.02578397704808868,0.6441188644374771,0.03259127616149294,0,7.462829176470591,0.0466055556782719,-0.0851232987247891,0.5241648018700465,0,5.159190588235296,0,0,0,1,0];this._loadMatrix(matrix,multiply);};/**
     * We don't know exactly what it does, kind of gradient map, but funny to play with!
     *
     * @param {number} desaturation - Tone values.
     * @param {number} toned - Tone values.
     * @param {string} lightColor - Tone values, example: `0xFFE580`
     * @param {string} darkColor - Tone values, example: `0xFFE580`
     * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false,
     *  just set the current matrix with @param matrix
     */ColorMatrixFilter.prototype.colorTone=function colorTone(desaturation,toned,lightColor,darkColor,multiply){desaturation=desaturation||0.2;toned=toned||0.15;lightColor=lightColor||0xFFE580;darkColor=darkColor||0x338000;var lR=(lightColor>>16&0xFF)/255;var lG=(lightColor>>8&0xFF)/255;var lB=(lightColor&0xFF)/255;var dR=(darkColor>>16&0xFF)/255;var dG=(darkColor>>8&0xFF)/255;var dB=(darkColor&0xFF)/255;var matrix=[0.3,0.59,0.11,0,0,lR,lG,lB,desaturation,0,dR,dG,dB,toned,0,lR-dR,lG-dG,lB-dB,0,0];this._loadMatrix(matrix,multiply);};/**
     * Night effect
     *
     * @param {number} intensity - The intensity of the night effect.
     * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false,
     *  just set the current matrix with @param matrix
     */ColorMatrixFilter.prototype.night=function night(intensity,multiply){intensity=intensity||0.1;var matrix=[intensity*-2.0,-intensity,0,0,0,-intensity,0,intensity,0,0,0,intensity,intensity*2.0,0,0,0,0,0,1,0];this._loadMatrix(matrix,multiply);};/**
     * Predator effect
     *
     * Erase the current matrix by setting a new indepent one
     *
     * @param {number} amount - how much the predator feels his future victim
     * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false,
     *  just set the current matrix with @param matrix
     */ColorMatrixFilter.prototype.predator=function predator(amount,multiply){var matrix=[// row 1
11.224130630493164*amount,-4.794486999511719*amount,-2.8746118545532227*amount,0*amount,0.40342438220977783*amount,// row 2
-3.6330697536468506*amount,9.193157196044922*amount,-2.951810836791992*amount,0*amount,-1.316135048866272*amount,// row 3
-3.2184197902679443*amount,-4.2375030517578125*amount,7.476448059082031*amount,0*amount,0.8044459223747253*amount,// row 4
0,0,0,1,0];this._loadMatrix(matrix,multiply);};/**
     * LSD effect
     *
     * Multiply the current matrix
     *
     * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false,
     *  just set the current matrix with @param matrix
     */ColorMatrixFilter.prototype.lsd=function lsd(multiply){var matrix=[2,-0.4,0.5,0,0,-0.5,2,-0.4,0,0,-0.4,-0.5,3,0,0,0,0,0,1,0];this._loadMatrix(matrix,multiply);};/**
     * Erase the current matrix by setting the default one
     *
     */ColorMatrixFilter.prototype.reset=function reset(){var matrix=[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0];this._loadMatrix(matrix,false);};/**
     * The matrix of the color matrix filter
     *
     * @member {number[]}
     * @memberof PIXI.filters.ColorMatrixFilter#
     * @default [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0]
     */_createClass(ColorMatrixFilter,[{key:'matrix',get:function get(){return this.uniforms.m;}/**
         * Sets the matrix directly.
         *
         * @param {number[]} value - the value to set to.
         */,set:function set(value){this.uniforms.m=value;}}]);return ColorMatrixFilter;}(core.Filter);// Americanized alias
exports.default=ColorMatrixFilter;ColorMatrixFilter.prototype.grayscale=ColorMatrixFilter.prototype.greyscale;},{"../../core":61,"path":22}],140:[function(require,module,exports){'use strict';exports.__esModule=true;var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor);}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor;};}();var _core=require('../../core');var core=_interopRequireWildcard(_core);var _path=require('path');function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj;}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key];}}newObj.default=obj;return newObj;}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return call&&((typeof call==="undefined"?"undefined":_typeof2(call))==="object"||typeof call==="function")?call:self;}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof2(superClass)));}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass;}/**
 * The DisplacementFilter class uses the pixel values from the specified texture
 * (called the displacement map) to perform a displacement of an object. You can
 * use this filter to apply all manor of crazy warping effects. Currently the r
 * property of the texture is used to offset the x and the g property of the texture
 * is used to offset the y.
 *
 * @class
 * @extends PIXI.Filter
 * @memberof PIXI.filters
 */var DisplacementFilter=function(_core$Filter){_inherits(DisplacementFilter,_core$Filter);/**
     * @param {PIXI.Sprite} sprite - The sprite used for the displacement map. (make sure its added to the scene!)
     * @param {number} scale - The scale of the displacement
     */function DisplacementFilter(sprite,scale){_classCallCheck(this,DisplacementFilter);var maskMatrix=new core.Matrix();sprite.renderable=false;var _this=_possibleConstructorReturn(this,_core$Filter.call(this,// vertex shader
'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 filterMatrix;\n\nvarying vec2 vTextureCoord;\nvarying vec2 vFilterCoord;\n\nvoid main(void)\n{\n   gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n   vFilterCoord = ( filterMatrix * vec3( aTextureCoord, 1.0)  ).xy;\n   vTextureCoord = aTextureCoord;\n}',// fragment shader
'varying vec2 vFilterCoord;\nvarying vec2 vTextureCoord;\n\nuniform vec2 scale;\n\nuniform sampler2D uSampler;\nuniform sampler2D mapSampler;\n\nuniform vec4 filterClamp;\n\nvoid main(void)\n{\n   vec4 map =  texture2D(mapSampler, vFilterCoord);\n\n   map -= 0.5;\n   map.xy *= scale;\n\n   gl_FragColor = texture2D(uSampler, clamp(vec2(vTextureCoord.x + map.x, vTextureCoord.y + map.y), filterClamp.xy, filterClamp.zw));\n}\n'));_this.maskSprite=sprite;_this.maskMatrix=maskMatrix;_this.uniforms.mapSampler=sprite.texture;_this.uniforms.filterMatrix=maskMatrix.toArray(true);_this.uniforms.scale={x:1,y:1};if(scale===null||scale===undefined){scale=20;}_this.scale=new core.Point(scale,scale);return _this;}/**
     * Applies the filter.
     *
     * @param {PIXI.FilterManager} filterManager - The manager.
     * @param {PIXI.RenderTarget} input - The input target.
     * @param {PIXI.RenderTarget} output - The output target.
     */DisplacementFilter.prototype.apply=function apply(filterManager,input,output){var ratio=1/output.destinationFrame.width*(output.size.width/input.size.width);this.uniforms.filterMatrix=filterManager.calculateSpriteMatrix(this.maskMatrix,this.maskSprite);this.uniforms.scale.x=this.scale.x*ratio;this.uniforms.scale.y=this.scale.y*ratio;// draw the filter...
filterManager.applyFilter(this,input,output);};/**
     * The texture used for the displacement map. Must be power of 2 sized texture.
     *
     * @member {PIXI.Texture}
     * @memberof PIXI.filters.DisplacementFilter#
     */_createClass(DisplacementFilter,[{key:'map',get:function get(){return this.uniforms.mapSampler;}/**
         * Sets the texture to use for the displacement.
         *
         * @param {PIXI.Texture} value - The texture to set to.
         */,set:function set(value){this.uniforms.mapSampler=value;}}]);return DisplacementFilter;}(core.Filter);exports.default=DisplacementFilter;},{"../../core":61,"path":22}],141:[function(require,module,exports){'use strict';exports.__esModule=true;var _core=require('../../core');var core=_interopRequireWildcard(_core);var _path=require('path');function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj;}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key];}}newObj.default=obj;return newObj;}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return call&&((typeof call==="undefined"?"undefined":_typeof2(call))==="object"||typeof call==="function")?call:self;}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof2(superClass)));}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass;}/**
 *
 * Basic FXAA implementation based on the code on geeks3d.com with the
 * modification that the texture2DLod stuff was removed since it's
 * unsupported by WebGL.
 *
 * @see https://github.com/mitsuhiko/webgl-meincraft
 *
 * @class
 * @extends PIXI.Filter
 * @memberof PIXI.filters
 *
 */var FXAAFilter=function(_core$Filter){_inherits(FXAAFilter,_core$Filter);/**
     *
     */function FXAAFilter(){_classCallCheck(this,FXAAFilter);// TODO - needs work
return _possibleConstructorReturn(this,_core$Filter.call(this,// vertex shader
'\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 v_rgbNW;\nvarying vec2 v_rgbNE;\nvarying vec2 v_rgbSW;\nvarying vec2 v_rgbSE;\nvarying vec2 v_rgbM;\n\nuniform vec4 filterArea;\n\nvarying vec2 vTextureCoord;\n\nvec2 mapCoord( vec2 coord )\n{\n    coord *= filterArea.xy;\n    coord += filterArea.zw;\n\n    return coord;\n}\n\nvec2 unmapCoord( vec2 coord )\n{\n    coord -= filterArea.zw;\n    coord /= filterArea.xy;\n\n    return coord;\n}\n\nvoid texcoords(vec2 fragCoord, vec2 resolution,\n               out vec2 v_rgbNW, out vec2 v_rgbNE,\n               out vec2 v_rgbSW, out vec2 v_rgbSE,\n               out vec2 v_rgbM) {\n    vec2 inverseVP = 1.0 / resolution.xy;\n    v_rgbNW = (fragCoord + vec2(-1.0, -1.0)) * inverseVP;\n    v_rgbNE = (fragCoord + vec2(1.0, -1.0)) * inverseVP;\n    v_rgbSW = (fragCoord + vec2(-1.0, 1.0)) * inverseVP;\n    v_rgbSE = (fragCoord + vec2(1.0, 1.0)) * inverseVP;\n    v_rgbM = vec2(fragCoord * inverseVP);\n}\n\nvoid main(void) {\n\n   gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n   vTextureCoord = aTextureCoord;\n\n   vec2 fragCoord = vTextureCoord * filterArea.xy;\n\n   texcoords(fragCoord, filterArea.xy, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n}',// fragment shader
'varying vec2 v_rgbNW;\nvarying vec2 v_rgbNE;\nvarying vec2 v_rgbSW;\nvarying vec2 v_rgbSE;\nvarying vec2 v_rgbM;\n\nvarying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform vec4 filterArea;\n\n/**\n Basic FXAA implementation based on the code on geeks3d.com with the\n modification that the texture2DLod stuff was removed since it\'s\n unsupported by WebGL.\n \n --\n \n From:\n https://github.com/mitsuhiko/webgl-meincraft\n \n Copyright (c) 2011 by Armin Ronacher.\n \n Some rights reserved.\n \n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are\n met:\n \n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n \n * Redistributions in binary form must reproduce the above\n copyright notice, this list of conditions and the following\n disclaimer in the documentation and/or other materials provided\n with the distribution.\n \n * The names of the contributors may not be used to endorse or\n promote products derived from this software without specific\n prior written permission.\n \n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#ifndef FXAA_REDUCE_MIN\n#define FXAA_REDUCE_MIN   (1.0/ 128.0)\n#endif\n#ifndef FXAA_REDUCE_MUL\n#define FXAA_REDUCE_MUL   (1.0 / 8.0)\n#endif\n#ifndef FXAA_SPAN_MAX\n#define FXAA_SPAN_MAX     8.0\n#endif\n\n//optimized version for mobile, where dependent\n//texture reads can be a bottleneck\nvec4 fxaa(sampler2D tex, vec2 fragCoord, vec2 resolution,\n          vec2 v_rgbNW, vec2 v_rgbNE,\n          vec2 v_rgbSW, vec2 v_rgbSE,\n          vec2 v_rgbM) {\n    vec4 color;\n    mediump vec2 inverseVP = vec2(1.0 / resolution.x, 1.0 / resolution.y);\n    vec3 rgbNW = texture2D(tex, v_rgbNW).xyz;\n    vec3 rgbNE = texture2D(tex, v_rgbNE).xyz;\n    vec3 rgbSW = texture2D(tex, v_rgbSW).xyz;\n    vec3 rgbSE = texture2D(tex, v_rgbSE).xyz;\n    vec4 texColor = texture2D(tex, v_rgbM);\n    vec3 rgbM  = texColor.xyz;\n    vec3 luma = vec3(0.299, 0.587, 0.114);\n    float lumaNW = dot(rgbNW, luma);\n    float lumaNE = dot(rgbNE, luma);\n    float lumaSW = dot(rgbSW, luma);\n    float lumaSE = dot(rgbSE, luma);\n    float lumaM  = dot(rgbM,  luma);\n    float lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\n    float lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\n    \n    mediump vec2 dir;\n    dir.x = -((lumaNW + lumaNE) - (lumaSW + lumaSE));\n    dir.y =  ((lumaNW + lumaSW) - (lumaNE + lumaSE));\n    \n    float dirReduce = max((lumaNW + lumaNE + lumaSW + lumaSE) *\n                          (0.25 * FXAA_REDUCE_MUL), FXAA_REDUCE_MIN);\n    \n    float rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\n    dir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\n              max(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\n                  dir * rcpDirMin)) * inverseVP;\n    \n    vec3 rgbA = 0.5 * (\n                       texture2D(tex, fragCoord * inverseVP + dir * (1.0 / 3.0 - 0.5)).xyz +\n                       texture2D(tex, fragCoord * inverseVP + dir * (2.0 / 3.0 - 0.5)).xyz);\n    vec3 rgbB = rgbA * 0.5 + 0.25 * (\n                                     texture2D(tex, fragCoord * inverseVP + dir * -0.5).xyz +\n                                     texture2D(tex, fragCoord * inverseVP + dir * 0.5).xyz);\n    \n    float lumaB = dot(rgbB, luma);\n    if ((lumaB < lumaMin) || (lumaB > lumaMax))\n        color = vec4(rgbA, texColor.a);\n    else\n        color = vec4(rgbB, texColor.a);\n    return color;\n}\n\nvoid main() {\n\n      vec2 fragCoord = vTextureCoord * filterArea.xy;\n\n      vec4 color;\n\n    color = fxaa(uSampler, fragCoord, filterArea.xy, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n\n      gl_FragColor = color;\n}\n'));}return FXAAFilter;}(core.Filter);exports.default=FXAAFilter;},{"../../core":61,"path":22}],142:[function(require,module,exports){'use strict';exports.__esModule=true;var _FXAAFilter=require('./fxaa/FXAAFilter');Object.defineProperty(exports,'FXAAFilter',{enumerable:true,get:function get(){return _interopRequireDefault(_FXAAFilter).default;}});var _NoiseFilter=require('./noise/NoiseFilter');Object.defineProperty(exports,'NoiseFilter',{enumerable:true,get:function get(){return _interopRequireDefault(_NoiseFilter).default;}});var _DisplacementFilter=require('./displacement/DisplacementFilter');Object.defineProperty(exports,'DisplacementFilter',{enumerable:true,get:function get(){return _interopRequireDefault(_DisplacementFilter).default;}});var _BlurFilter=require('./blur/BlurFilter');Object.defineProperty(exports,'BlurFilter',{enumerable:true,get:function get(){return _interopRequireDefault(_BlurFilter).default;}});var _BlurXFilter=require('./blur/BlurXFilter');Object.defineProperty(exports,'BlurXFilter',{enumerable:true,get:function get(){return _interopRequireDefault(_BlurXFilter).default;}});var _BlurYFilter=require('./blur/BlurYFilter');Object.defineProperty(exports,'BlurYFilter',{enumerable:true,get:function get(){return _interopRequireDefault(_BlurYFilter).default;}});var _ColorMatrixFilter=require('./colormatrix/ColorMatrixFilter');Object.defineProperty(exports,'ColorMatrixFilter',{enumerable:true,get:function get(){return _interopRequireDefault(_ColorMatrixFilter).default;}});var _VoidFilter=require('./void/VoidFilter');Object.defineProperty(exports,'VoidFilter',{enumerable:true,get:function get(){return _interopRequireDefault(_VoidFilter).default;}});function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}},{"./blur/BlurFilter":133,"./blur/BlurXFilter":134,"./blur/BlurYFilter":135,"./colormatrix/ColorMatrixFilter":139,"./displacement/DisplacementFilter":140,"./fxaa/FXAAFilter":141,"./noise/NoiseFilter":143,"./void/VoidFilter":144}],143:[function(require,module,exports){'use strict';exports.__esModule=true;var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor);}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor;};}();var _core=require('../../core');var core=_interopRequireWildcard(_core);var _path=require('path');function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj;}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key];}}newObj.default=obj;return newObj;}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return call&&((typeof call==="undefined"?"undefined":_typeof2(call))==="object"||typeof call==="function")?call:self;}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof2(superClass)));}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass;}/**
 * @author Vico @vicocotea
 * original filter: https://github.com/evanw/glfx.js/blob/master/src/filters/adjust/noise.js
 *//**
 * A Noise effect filter.
 *
 * @class
 * @extends PIXI.Filter
 * @memberof PIXI.filters
 */var NoiseFilter=function(_core$Filter){_inherits(NoiseFilter,_core$Filter);/**
   *
   */function NoiseFilter(){_classCallCheck(this,NoiseFilter);var _this=_possibleConstructorReturn(this,_core$Filter.call(this,// vertex shader
'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n    gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n    vTextureCoord = aTextureCoord;\n}',// fragment shader
'precision highp float;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\n\nuniform float noise;\nuniform sampler2D uSampler;\n\nfloat rand(vec2 co)\n{\n    return fract(sin(dot(co.xy, vec2(12.9898, 78.233))) * 43758.5453);\n}\n\nvoid main()\n{\n    vec4 color = texture2D(uSampler, vTextureCoord);\n\n    float diff = (rand(gl_FragCoord.xy) - 0.5) * noise;\n\n    color.r += diff;\n    color.g += diff;\n    color.b += diff;\n\n    gl_FragColor = color;\n}\n'));_this.noise=0.5;return _this;}/**
   * The amount of noise to apply.
   *
   * @member {number}
   * @memberof PIXI.filters.NoiseFilter#
   * @default 0.5
   */_createClass(NoiseFilter,[{key:'noise',get:function get(){return this.uniforms.noise;}/**
     * Sets the amount of noise to apply.
     *
     * @param {number} value - The value to set to.
     */,set:function set(value){this.uniforms.noise=value;}}]);return NoiseFilter;}(core.Filter);exports.default=NoiseFilter;},{"../../core":61,"path":22}],144:[function(require,module,exports){'use strict';exports.__esModule=true;var _core=require('../../core');var core=_interopRequireWildcard(_core);var _path=require('path');function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj;}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key];}}newObj.default=obj;return newObj;}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return call&&((typeof call==="undefined"?"undefined":_typeof2(call))==="object"||typeof call==="function")?call:self;}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof2(superClass)));}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass;}/**
 * Does nothing. Very handy.
 *
 * @class
 * @extends PIXI.Filter
 * @memberof PIXI.filters
 */var VoidFilter=function(_core$Filter){_inherits(VoidFilter,_core$Filter);/**
     *
     */function VoidFilter(){_classCallCheck(this,VoidFilter);var _this=_possibleConstructorReturn(this,_core$Filter.call(this,// vertex shader
'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n    gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n    vTextureCoord = aTextureCoord;\n}',// fragment shader
'varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\n\nvoid main(void)\n{\n   gl_FragColor = texture2D(uSampler, vTextureCoord);\n}\n'));_this.glShaderKey='void';return _this;}return VoidFilter;}(core.Filter);exports.default=VoidFilter;},{"../../core":61,"path":22}],145:[function(require,module,exports){'use strict';exports.__esModule=true;var _core=require('../core');var core=_interopRequireWildcard(_core);function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj;}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key];}}newObj.default=obj;return newObj;}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}/**
 * Holds all information related to an Interaction event
 *
 * @class
 * @memberof PIXI.interaction
 */var InteractionData=function(){/**
   *
   */function InteractionData(){_classCallCheck(this,InteractionData);/**
     * This point stores the global coords of where the touch/mouse event happened
     *
     * @member {PIXI.Point}
     */this.global=new core.Point();/**
     * The target Sprite that was interacted with
     *
     * @member {PIXI.Sprite}
     */this.target=null;/**
     * When passed to an event handler, this will be the original DOM Event that was captured
     *
     * @member {Event}
     */this.originalEvent=null;}/**
   * This will return the local coordinates of the specified displayObject for this InteractionData
   *
   * @param {PIXI.DisplayObject} displayObject - The DisplayObject that you would like the local
   *  coords off
   * @param {PIXI.Point} [point] - A Point object in which to store the value, optional (otherwise
   *  will create a new point)
   * @param {PIXI.Point} [globalPos] - A Point object containing your custom global coords, optional
   *  (otherwise will use the current global coords)
   * @return {PIXI.Point} A point containing the coordinates of the InteractionData position relative
   *  to the DisplayObject
   */InteractionData.prototype.getLocalPosition=function getLocalPosition(displayObject,point,globalPos){return displayObject.worldTransform.applyInverse(globalPos||this.global,point);};return InteractionData;}();exports.default=InteractionData;},{"../core":61}],146:[function(require,module,exports){"use strict";exports.__esModule=true;function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}/**
 * Event class that mimics native DOM events.
 *
 * @class
 * @memberof PIXI.interaction
 */var InteractionEvent=function(){/**
   *
   */function InteractionEvent(){_classCallCheck(this,InteractionEvent);/**
     * Whether this event will continue propagating in the tree
     *
     * @member {boolean}
     */this.stopped=false;/**
     * The object which caused this event to be dispatched.
     * For listener callback see {@link PIXI.interaction.InteractionEvent.currentTarget}.
     *
     * @member {PIXI.DisplayObject}
     */this.target=null;/**
     * The object whose event listener’s callback is currently being invoked.
     *
     * @member {PIXI.DisplayObject}
     */this.currentTarget=null;/*
     * Type of the event
     *
     * @member {string}
     */this.type=null;/*
     * InteractionData related to this event
     *
     * @member {PIXI.interaction.InteractionData}
     */this.data=null;}/**
   * Prevents event from reaching any objects other than the current object.
   *
   */InteractionEvent.prototype.stopPropagation=function stopPropagation(){this.stopped=true;};/**
   * Prevents event from reaching any objects other than the current object.
   *
   * @private
   */InteractionEvent.prototype._reset=function _reset(){this.stopped=false;this.currentTarget=null;this.target=null;};return InteractionEvent;}();exports.default=InteractionEvent;},{}],147:[function(require,module,exports){'use strict';exports.__esModule=true;var _core=require('../core');var core=_interopRequireWildcard(_core);var _InteractionData=require('./InteractionData');var _InteractionData2=_interopRequireDefault(_InteractionData);var _InteractionEvent=require('./InteractionEvent');var _InteractionEvent2=_interopRequireDefault(_InteractionEvent);var _eventemitter=require('eventemitter3');var _eventemitter2=_interopRequireDefault(_eventemitter);var _interactiveTarget=require('./interactiveTarget');var _interactiveTarget2=_interopRequireDefault(_interactiveTarget);var _ismobilejs=require('ismobilejs');var _ismobilejs2=_interopRequireDefault(_ismobilejs);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj;}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key];}}newObj.default=obj;return newObj;}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return call&&((typeof call==="undefined"?"undefined":_typeof2(call))==="object"||typeof call==="function")?call:self;}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof2(superClass)));}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass;}// Mix interactiveTarget into core.DisplayObject.prototype
Object.assign(core.DisplayObject.prototype,_interactiveTarget2.default);/**
 * The interaction manager deals with mouse and touch events. Any DisplayObject can be interactive
 * if its interactive parameter is set to true
 * This manager also supports multitouch.
 * By default, an instance of this class is automatically created, and can be found at renderer.plugins.interaction
 *
 * @class
 * @extends EventEmitter
 * @memberof PIXI.interaction
 */var InteractionManager=function(_EventEmitter){_inherits(InteractionManager,_EventEmitter);/**
     * @param {PIXI.CanvasRenderer|PIXI.WebGLRenderer} renderer - A reference to the current renderer
     * @param {object} [options] - The options for the manager.
     * @param {boolean} [options.autoPreventDefault=true] - Should the manager automatically prevent default browser actions.
     * @param {number} [options.interactionFrequency=10] - Frequency increases the interaction events will be checked.
     */function InteractionManager(renderer,options){_classCallCheck(this,InteractionManager);var _this=_possibleConstructorReturn(this,_EventEmitter.call(this));options=options||{};/**
         * The renderer this interaction manager works for.
         *
         * @member {PIXI.SystemRenderer}
         */_this.renderer=renderer;/**
         * Should default browser actions automatically be prevented.
         * Does not apply to pointer events for backwards compatibility
         * preventDefault on pointer events stops mouse events from firing
         * Thus, for every pointer event, there will always be either a mouse of touch event alongside it.
         *
         * @member {boolean}
         * @default true
         */_this.autoPreventDefault=options.autoPreventDefault!==undefined?options.autoPreventDefault:true;/**
         * Frequency in milliseconds that the mousemove, moveover & mouseout interaction events will be checked.
         *
         * @member {number}
         * @default 10
         */_this.interactionFrequency=options.interactionFrequency||10;/**
         * The mouse data
         *
         * @member {PIXI.interaction.InteractionData}
         */_this.mouse=new _InteractionData2.default();// setting the mouse to start off far off screen will mean that mouse over does
//  not get called before we even move the mouse.
_this.mouse.global.set(-999999);/**
         * The pointer data
         *
         * @member {PIXI.interaction.InteractionData}
         */_this.pointer=new _InteractionData2.default();// setting the pointer to start off far off screen will mean that pointer over does
//  not get called before we even move the pointer.
_this.pointer.global.set(-999999);/**
         * An event data object to handle all the event tracking/dispatching
         *
         * @member {object}
         */_this.eventData=new _InteractionEvent2.default();/**
         * Tiny little interactiveData pool !
         *
         * @member {PIXI.interaction.InteractionData[]}
         */_this.interactiveDataPool=[];/**
         * The DOM element to bind to.
         *
         * @private
         * @member {HTMLElement}
         */_this.interactionDOMElement=null;/**
         * This property determines if mousemove and touchmove events are fired only when the cursor
         * is over the object.
         * Setting to true will make things work more in line with how the DOM verison works.
         * Setting to false can make things easier for things like dragging
         * It is currently set to false as this is how pixi used to work. This will be set to true in
         * future versions of pixi.
         *
         * @member {boolean} moveWhenInside
         * @memberof PIXI.interaction.InteractionManager#
         * @default false
         */_this.moveWhenInside=false;/**
         * Have events been attached to the dom element?
         *
         * @private
         * @member {boolean}
         */_this.eventsAdded=false;/**
         * Is the mouse hovering over the renderer?
         *
         * @private
         * @member {boolean}
         */_this.mouseOverRenderer=false;/**
         * Does the device support touch events
         * https://www.w3.org/TR/touch-events/
         *
         * @readonly
         * @member {boolean}
         */_this.supportsTouchEvents='ontouchstart'in window;/**
         * Does the device support pointer events
         * https://www.w3.org/Submission/pointer-events/
         *
         * @readonly
         * @member {boolean}
         */_this.supportsPointerEvents=!!window.PointerEvent;/**
         * Are touch events being 'normalized' and converted into pointer events if pointer events are not supported
         * For example, on a touch screen mobile device, a touchstart would also be emitted as a pointerdown
         *
         * @private
         * @readonly
         * @member {boolean}
         */_this.normalizeTouchEvents=!_this.supportsPointerEvents&&_this.supportsTouchEvents;/**
         * Are mouse events being 'normalized' and converted into pointer events if pointer events are not supported
         * For example, on a desktop pc, a mousedown would also be emitted as a pointerdown
         *
         * @private
         * @readonly
         * @member {boolean}
         */_this.normalizeMouseEvents=!_this.supportsPointerEvents&&!_ismobilejs2.default.any;// this will make it so that you don't have to call bind all the time
/**
         * @private
         * @member {Function}
         */_this.onMouseUp=_this.onMouseUp.bind(_this);_this.processMouseUp=_this.processMouseUp.bind(_this);/**
         * @private
         * @member {Function}
         */_this.onMouseDown=_this.onMouseDown.bind(_this);_this.processMouseDown=_this.processMouseDown.bind(_this);/**
         * @private
         * @member {Function}
         */_this.onMouseMove=_this.onMouseMove.bind(_this);_this.processMouseMove=_this.processMouseMove.bind(_this);/**
         * @private
         * @member {Function}
         */_this.onMouseOut=_this.onMouseOut.bind(_this);_this.processMouseOverOut=_this.processMouseOverOut.bind(_this);/**
        * @private
        * @member {Function}
        */_this.onMouseOver=_this.onMouseOver.bind(_this);/**
         * @private
         * @member {Function}
         */_this.onPointerUp=_this.onPointerUp.bind(_this);_this.processPointerUp=_this.processPointerUp.bind(_this);/**
         * @private
         * @member {Function}
         */_this.onPointerDown=_this.onPointerDown.bind(_this);_this.processPointerDown=_this.processPointerDown.bind(_this);/**
         * @private
         * @member {Function}
         */_this.onPointerMove=_this.onPointerMove.bind(_this);_this.processPointerMove=_this.processPointerMove.bind(_this);/**
         * @private
         * @member {Function}
         */_this.onPointerOut=_this.onPointerOut.bind(_this);_this.processPointerOverOut=_this.processPointerOverOut.bind(_this);/**
         * @private
         * @member {Function}
         */_this.onPointerOver=_this.onPointerOver.bind(_this);/**
         * @private
         * @member {Function}
         */_this.onTouchStart=_this.onTouchStart.bind(_this);_this.processTouchStart=_this.processTouchStart.bind(_this);/**
         * @private
         * @member {Function}
         */_this.onTouchEnd=_this.onTouchEnd.bind(_this);_this.processTouchEnd=_this.processTouchEnd.bind(_this);/**
         * @private
         * @member {Function}
         */_this.onTouchMove=_this.onTouchMove.bind(_this);_this.processTouchMove=_this.processTouchMove.bind(_this);/**
         * Every update cursor will be reset to this value, if some element wont override it in
         * its hitTest.
         *
         * @member {string}
         * @default 'inherit'
         */_this.defaultCursorStyle='inherit';/**
         * The css style of the cursor that is being used.
         *
         * @member {string}
         */_this.currentCursorStyle='inherit';/**
         * Internal cached let.
         *
         * @private
         * @member {PIXI.Point}
         */_this._tempPoint=new core.Point();/**
         * The current resolution / device pixel ratio.
         *
         * @member {number}
         * @default 1
         */_this.resolution=1;_this.setTargetElement(_this.renderer.view,_this.renderer.resolution);/**
         * Fired when a pointer device button (usually a mouse button) is pressed on the display
         * object.
         *
         * @event mousedown
         * @memberof PIXI.interaction.InteractionManager#
         *//**
         * Fired when a pointer device secondary button (usually a mouse right-button) is pressed
         * on the display object.
         *
         * @event rightdown
         * @memberof PIXI.interaction.InteractionManager#
         *//**
         * Fired when a pointer device button (usually a mouse button) is released over the display
         * object.
         *
         * @event mouseup
         * @memberof PIXI.interaction.InteractionManager#
         *//**
         * Fired when a pointer device secondary button (usually a mouse right-button) is released
         * over the display object.
         *
         * @event rightup
         * @memberof PIXI.interaction.InteractionManager#
         *//**
         * Fired when a pointer device button (usually a mouse button) is pressed and released on
         * the display object.
         *
         * @event click
         * @memberof PIXI.interaction.InteractionManager#
         *//**
         * Fired when a pointer device secondary button (usually a mouse right-button) is pressed
         * and released on the display object.
         *
         * @event rightclick
         * @memberof PIXI.interaction.InteractionManager#
         *//**
         * Fired when a pointer device button (usually a mouse button) is released outside the
         * display object that initially registered a
         * [mousedown]{@link PIXI.interaction.InteractionManager#event:mousedown}.
         *
         * @event mouseupoutside
         * @memberof PIXI.interaction.InteractionManager#
         *//**
         * Fired when a pointer device secondary button (usually a mouse right-button) is released
         * outside the display object that initially registered a
         * [rightdown]{@link PIXI.interaction.InteractionManager#event:rightdown}.
         *
         * @event rightupoutside
         * @memberof PIXI.interaction.InteractionManager#
         *//**
         * Fired when a pointer device (usually a mouse) is moved while over the display object
         *
         * @event mousemove
         * @memberof PIXI.interaction.InteractionManager#
         *//**
         * Fired when a pointer device (usually a mouse) is moved onto the display object
         *
         * @event mouseover
         * @memberof PIXI.interaction.InteractionManager#
         *//**
         * Fired when a pointer device (usually a mouse) is moved off the display object
         *
         * @event mouseout
         * @memberof PIXI.interaction.InteractionManager#
         *//**
         * Fired when a pointer device button is pressed on the display object.
         *
         * @event pointerdown
         * @memberof PIXI.interaction.InteractionManager#
         *//**
         * Fired when a pointer device button is released over the display object.
         *
         * @event pointerup
         * @memberof PIXI.interaction.InteractionManager#
         *//**
         * Fired when a pointer device button is pressed and released on the display object.
         *
         * @event pointertap
         * @memberof PIXI.interaction.InteractionManager#
         *//**
         * Fired when a pointer device button is released outside the display object that initially
         * registered a [pointerdown]{@link PIXI.interaction.InteractionManager#event:pointerdown}.
         *
         * @event pointerupoutside
         * @memberof PIXI.interaction.InteractionManager#
         *//**
         * Fired when a pointer device is moved while over the display object
         *
         * @event pointermove
         * @memberof PIXI.interaction.InteractionManager#
         *//**
         * Fired when a pointer device is moved onto the display object
         *
         * @event pointerover
         * @memberof PIXI.interaction.InteractionManager#
         *//**
         * Fired when a pointer device is moved off the display object
         *
         * @event pointerout
         * @memberof PIXI.interaction.InteractionManager#
         *//**
         * Fired when a touch point is placed on the display object.
         *
         * @event touchstart
         * @memberof PIXI.interaction.InteractionManager#
         *//**
         * Fired when a touch point is removed from the display object.
         *
         * @event touchend
         * @memberof PIXI.interaction.InteractionManager#
         *//**
         * Fired when a touch point is placed and removed from the display object.
         *
         * @event tap
         * @memberof PIXI.interaction.InteractionManager#
         *//**
         * Fired when a touch point is removed outside of the display object that initially
         * registered a [touchstart]{@link PIXI.interaction.InteractionManager#event:touchstart}.
         *
         * @event touchendoutside
         * @memberof PIXI.interaction.InteractionManager#
         *//**
         * Fired when a touch point is moved along the display object.
         *
         * @event touchmove
         * @memberof PIXI.interaction.InteractionManager#
         */return _this;}/**
     * Sets the DOM element which will receive mouse/touch events. This is useful for when you have
     * other DOM elements on top of the renderers Canvas element. With this you'll be bale to deletegate
     * another DOM element to receive those events.
     *
     * @param {HTMLCanvasElement} element - the DOM element which will receive mouse and touch events.
     * @param {number} [resolution=1] - The resolution / device pixel ratio of the new element (relative to the canvas).
     * @private
     */InteractionManager.prototype.setTargetElement=function setTargetElement(element){var resolution=arguments.length<=1||arguments[1]===undefined?1:arguments[1];this.removeEvents();this.interactionDOMElement=element;this.resolution=resolution;this.addEvents();};/**
     * Registers all the DOM events
     *
     * @private
     */InteractionManager.prototype.addEvents=function addEvents(){if(!this.interactionDOMElement){return;}core.ticker.shared.add(this.update,this);if(window.navigator.msPointerEnabled){this.interactionDOMElement.style['-ms-content-zooming']='none';this.interactionDOMElement.style['-ms-touch-action']='none';}else if(this.supportsPointerEvents){this.interactionDOMElement.style['touch-action']='none';}/**
         * These events are added first, so that if pointer events are normalised, they are fired
         * in the same order as non-normalised events. ie. pointer event 1st, mouse / touch 2nd
         */if(this.supportsPointerEvents){window.document.addEventListener('pointermove',this.onPointerMove,true);this.interactionDOMElement.addEventListener('pointerdown',this.onPointerDown,true);this.interactionDOMElement.addEventListener('pointerout',this.onPointerOut,true);this.interactionDOMElement.addEventListener('pointerover',this.onPointerOver,true);window.addEventListener('pointerup',this.onPointerUp,true);}else{/**
             * If pointer events aren't available on a device, this will turn either the touch or
             * mouse events into pointer events. This allows a developer to just listen for emitted
             * pointer events on interactive sprites
             */if(this.normalizeTouchEvents){this.interactionDOMElement.addEventListener('touchstart',this.onPointerDown,true);this.interactionDOMElement.addEventListener('touchend',this.onPointerUp,true);this.interactionDOMElement.addEventListener('touchmove',this.onPointerMove,true);}if(this.normalizeMouseEvents){window.document.addEventListener('mousemove',this.onPointerMove,true);this.interactionDOMElement.addEventListener('mousedown',this.onPointerDown,true);this.interactionDOMElement.addEventListener('mouseout',this.onPointerOut,true);this.interactionDOMElement.addEventListener('mouseover',this.onPointerOver,true);window.addEventListener('mouseup',this.onPointerUp,true);}}window.document.addEventListener('mousemove',this.onMouseMove,true);this.interactionDOMElement.addEventListener('mousedown',this.onMouseDown,true);this.interactionDOMElement.addEventListener('mouseout',this.onMouseOut,true);this.interactionDOMElement.addEventListener('mouseover',this.onMouseOver,true);window.addEventListener('mouseup',this.onMouseUp,true);if(this.supportsTouchEvents){this.interactionDOMElement.addEventListener('touchstart',this.onTouchStart,true);this.interactionDOMElement.addEventListener('touchend',this.onTouchEnd,true);this.interactionDOMElement.addEventListener('touchmove',this.onTouchMove,true);}this.eventsAdded=true;};/**
     * Removes all the DOM events that were previously registered
     *
     * @private
     */InteractionManager.prototype.removeEvents=function removeEvents(){if(!this.interactionDOMElement){return;}core.ticker.shared.remove(this.update,this);if(window.navigator.msPointerEnabled){this.interactionDOMElement.style['-ms-content-zooming']='';this.interactionDOMElement.style['-ms-touch-action']='';}else if(this.supportsPointerEvents){this.interactionDOMElement.style['touch-action']='';}if(this.supportsPointerEvents){window.document.removeEventListener('pointermove',this.onPointerMove,true);this.interactionDOMElement.removeEventListener('pointerdown',this.onPointerDown,true);this.interactionDOMElement.removeEventListener('pointerout',this.onPointerOut,true);this.interactionDOMElement.removeEventListener('pointerover',this.onPointerOver,true);window.removeEventListener('pointerup',this.onPointerUp,true);}else{/**
             * If pointer events aren't available on a device, this will turn either the touch or
             * mouse events into pointer events. This allows a developer to just listen for emitted
             * pointer events on interactive sprites
             */if(this.normalizeTouchEvents){this.interactionDOMElement.removeEventListener('touchstart',this.onPointerDown,true);this.interactionDOMElement.removeEventListener('touchend',this.onPointerUp,true);this.interactionDOMElement.removeEventListener('touchmove',this.onPointerMove,true);}if(this.normalizeMouseEvents){window.document.removeEventListener('mousemove',this.onPointerMove,true);this.interactionDOMElement.removeEventListener('mousedown',this.onPointerDown,true);this.interactionDOMElement.removeEventListener('mouseout',this.onPointerOut,true);this.interactionDOMElement.removeEventListener('mouseover',this.onPointerOver,true);window.removeEventListener('mouseup',this.onPointerUp,true);}}window.document.removeEventListener('mousemove',this.onMouseMove,true);this.interactionDOMElement.removeEventListener('mousedown',this.onMouseDown,true);this.interactionDOMElement.removeEventListener('mouseout',this.onMouseOut,true);this.interactionDOMElement.removeEventListener('mouseover',this.onMouseOver,true);window.removeEventListener('mouseup',this.onMouseUp,true);if(this.supportsTouchEvents){this.interactionDOMElement.removeEventListener('touchstart',this.onTouchStart,true);this.interactionDOMElement.removeEventListener('touchend',this.onTouchEnd,true);this.interactionDOMElement.removeEventListener('touchmove',this.onTouchMove,true);}this.interactionDOMElement=null;this.eventsAdded=false;};/**
     * Updates the state of interactive objects.
     * Invoked by a throttled ticker update from {@link PIXI.ticker.shared}.
     *
     * @param {number} deltaTime - time delta since last tick
     */InteractionManager.prototype.update=function update(deltaTime){this._deltaTime+=deltaTime;if(this._deltaTime<this.interactionFrequency){return;}this._deltaTime=0;if(!this.interactionDOMElement){return;}// if the user move the mouse this check has already been dfone using the mouse move!
if(this.didMove){this.didMove=false;return;}this.cursor=this.defaultCursorStyle;// Resets the flag as set by a stopPropagation call. This flag is usually reset by a user interaction of any kind,
// but there was a scenario of a display object moving under a static mouse cursor.
// In this case, mouseover and mouseevents would not pass the flag test in dispatchEvent function
this.eventData._reset();this.processInteractive(this.mouse.global,this.renderer._lastObjectRendered,this.processMouseOverOut,true);if(this.currentCursorStyle!==this.cursor){this.currentCursorStyle=this.cursor;this.interactionDOMElement.style.cursor=this.cursor;}// TODO
};/**
     * Dispatches an event on the display object that was interacted with
     *
     * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - the display object in question
     * @param {string} eventString - the name of the event (e.g, mousedown)
     * @param {object} eventData - the event data object
     * @private
     */InteractionManager.prototype.dispatchEvent=function dispatchEvent(displayObject,eventString,eventData){if(!eventData.stopped){eventData.currentTarget=displayObject;eventData.type=eventString;displayObject.emit(eventString,eventData);if(displayObject[eventString]){displayObject[eventString](eventData);}}};/**
     * Maps x and y coords from a DOM object and maps them correctly to the pixi view. The
     * resulting value is stored in the point. This takes into account the fact that the DOM
     * element could be scaled and positioned anywhere on the screen.
     *
     * @param  {PIXI.Point} point - the point that the result will be stored in
     * @param  {number} x - the x coord of the position to map
     * @param  {number} y - the y coord of the position to map
     */InteractionManager.prototype.mapPositionToPoint=function mapPositionToPoint(point,x,y){var rect=void 0;// IE 11 fix
if(!this.interactionDOMElement.parentElement){rect={x:0,y:0,width:0,height:0};}else{rect=this.interactionDOMElement.getBoundingClientRect();}var resolutionMultiplier=navigator.isCocoonJS?1.0:1.0/this.resolution;point.x=(x-rect.left)*(this.interactionDOMElement.width/rect.width)*resolutionMultiplier;point.y=(y-rect.top)*(this.interactionDOMElement.height/rect.height)*resolutionMultiplier;};/**
     * This function is provides a neat way of crawling through the scene graph and running a
     * specified function on all interactive objects it finds. It will also take care of hit
     * testing the interactive objects and passes the hit across in the function.
     *
     * @param {PIXI.Point} point - the point that is tested for collision
     * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - the displayObject
     *  that will be hit test (recursively crawls its children)
     * @param {Function} [func] - the function that will be called on each interactive object. The
     *  displayObject and hit will be passed to the function
     * @param {boolean} [hitTest] - this indicates if the objects inside should be hit test against the point
     * @param {boolean} [interactive] - Whether the displayObject is interactive
     * @return {boolean} returns true if the displayObject hit the point
     */InteractionManager.prototype.processInteractive=function processInteractive(point,displayObject,func,hitTest,interactive){if(!displayObject||!displayObject.visible){return false;}// Took a little while to rework this function correctly! But now it is done and nice and optimised. ^_^
//
// This function will now loop through all objects and then only hit test the objects it HAS
// to, not all of them. MUCH faster..
// An object will be hit test if the following is true:
//
// 1: It is interactive.
// 2: It belongs to a parent that is interactive AND one of the parents children have not already been hit.
//
// As another little optimisation once an interactive object has been hit we can carry on
// through the scenegraph, but we know that there will be no more hits! So we can avoid extra hit tests
// A final optimisation is that an object is not hit test directly if a child has already been hit.
interactive=displayObject.interactive||interactive;var hit=false;var interactiveParent=interactive;// if the displayobject has a hitArea, then it does not need to hitTest children.
if(displayObject.hitArea){interactiveParent=false;}// it has a mask! Then lets hit test that before continuing..
if(hitTest&&displayObject._mask){if(!displayObject._mask.containsPoint(point)){hitTest=false;}}// it has a filterArea! Same as mask but easier, its a rectangle
if(hitTest&&displayObject.filterArea){if(!displayObject.filterArea.contains(point.x,point.y)){hitTest=false;}}// ** FREE TIP **! If an object is not interactive or has no buttons in it
// (such as a game scene!) set interactiveChildren to false for that displayObject.
// This will allow pixi to completely ignore and bypass checking the displayObjects children.
if(displayObject.interactiveChildren&&displayObject.children){var children=displayObject.children;for(var i=children.length-1;i>=0;i--){var child=children[i];// time to get recursive.. if this function will return if something is hit..
if(this.processInteractive(point,child,func,hitTest,interactiveParent)){// its a good idea to check if a child has lost its parent.
// this means it has been removed whilst looping so its best
if(!child.parent){continue;}hit=true;// we no longer need to hit test any more objects in this container as we we
// now know the parent has been hit
interactiveParent=false;// If the child is interactive , that means that the object hit was actually
// interactive and not just the child of an interactive object.
// This means we no longer need to hit test anything else. We still need to run
// through all objects, but we don't need to perform any hit tests.
// {
hitTest=false;// }
// we can break now as we have hit an object.
}}}// no point running this if the item is not interactive or does not have an interactive parent.
if(interactive){// if we are hit testing (as in we have no hit any objects yet)
// We also don't need to worry about hit testing if once of the displayObjects children
// has already been hit!
if(hitTest&&!hit){if(displayObject.hitArea){displayObject.worldTransform.applyInverse(point,this._tempPoint);hit=displayObject.hitArea.contains(this._tempPoint.x,this._tempPoint.y);}else if(displayObject.containsPoint){hit=displayObject.containsPoint(point);}}if(displayObject.interactive){if(hit&&!this.eventData.target){this.eventData.target=displayObject;this.mouse.target=displayObject;this.pointer.target=displayObject;}func(displayObject,hit);}}return hit;};/**
     * Is called when the mouse button is pressed down on the renderer element
     *
     * @private
     * @param {MouseEvent} event - The DOM event of a mouse button being pressed down
     */InteractionManager.prototype.onMouseDown=function onMouseDown(event){this.mouse.originalEvent=event;this.eventData.data=this.mouse;this.eventData._reset();// Update internal mouse reference
this.mapPositionToPoint(this.mouse.global,event.clientX,event.clientY);if(this.autoPreventDefault){this.mouse.originalEvent.preventDefault();}this.processInteractive(this.mouse.global,this.renderer._lastObjectRendered,this.processMouseDown,true);var isRightButton=event.button===2||event.which===3;this.emit(isRightButton?'rightdown':'mousedown',this.eventData);};/**
     * Processes the result of the mouse down check and dispatches the event if need be
     *
     * @private
     * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested
     * @param {boolean} hit - the result of the hit test on the display object
     */InteractionManager.prototype.processMouseDown=function processMouseDown(displayObject,hit){var e=this.mouse.originalEvent;var isRightButton=e.button===2||e.which===3;if(hit){displayObject[isRightButton?'_isRightDown':'_isLeftDown']=true;this.dispatchEvent(displayObject,isRightButton?'rightdown':'mousedown',this.eventData);}};/**
     * Is called when the mouse button is released on the renderer element
     *
     * @private
     * @param {MouseEvent} event - The DOM event of a mouse button being released
     */InteractionManager.prototype.onMouseUp=function onMouseUp(event){this.mouse.originalEvent=event;this.eventData.data=this.mouse;this.eventData._reset();// Update internal mouse reference
this.mapPositionToPoint(this.mouse.global,event.clientX,event.clientY);this.processInteractive(this.mouse.global,this.renderer._lastObjectRendered,this.processMouseUp,true);var isRightButton=event.button===2||event.which===3;this.emit(isRightButton?'rightup':'mouseup',this.eventData);};/**
     * Processes the result of the mouse up check and dispatches the event if need be
     *
     * @private
     * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested
     * @param {boolean} hit - the result of the hit test on the display object
     */InteractionManager.prototype.processMouseUp=function processMouseUp(displayObject,hit){var e=this.mouse.originalEvent;var isRightButton=e.button===2||e.which===3;var isDown=isRightButton?'_isRightDown':'_isLeftDown';if(hit){this.dispatchEvent(displayObject,isRightButton?'rightup':'mouseup',this.eventData);if(displayObject[isDown]){displayObject[isDown]=false;this.dispatchEvent(displayObject,isRightButton?'rightclick':'click',this.eventData);}}else if(displayObject[isDown]){displayObject[isDown]=false;this.dispatchEvent(displayObject,isRightButton?'rightupoutside':'mouseupoutside',this.eventData);}};/**
     * Is called when the mouse moves across the renderer element
     *
     * @private
     * @param {MouseEvent} event - The DOM event of the mouse moving
     */InteractionManager.prototype.onMouseMove=function onMouseMove(event){this.mouse.originalEvent=event;this.eventData.data=this.mouse;this.eventData._reset();this.mapPositionToPoint(this.mouse.global,event.clientX,event.clientY);this.didMove=true;this.cursor=this.defaultCursorStyle;this.processInteractive(this.mouse.global,this.renderer._lastObjectRendered,this.processMouseMove,true);this.emit('mousemove',this.eventData);if(this.currentCursorStyle!==this.cursor){this.currentCursorStyle=this.cursor;this.interactionDOMElement.style.cursor=this.cursor;}// TODO BUG for parents interactive object (border order issue)
};/**
     * Processes the result of the mouse move check and dispatches the event if need be
     *
     * @private
     * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested
     * @param {boolean} hit - the result of the hit test on the display object
     */InteractionManager.prototype.processMouseMove=function processMouseMove(displayObject,hit){this.processMouseOverOut(displayObject,hit);// only display on mouse over
if(!this.moveWhenInside||hit){this.dispatchEvent(displayObject,'mousemove',this.eventData);}};/**
     * Is called when the mouse is moved out of the renderer element
     *
     * @private
     * @param {MouseEvent} event - The DOM event of the mouse being moved out
     */InteractionManager.prototype.onMouseOut=function onMouseOut(event){this.mouseOverRenderer=false;this.mouse.originalEvent=event;this.eventData.data=this.mouse;this.eventData._reset();// Update internal mouse reference
this.mapPositionToPoint(this.mouse.global,event.clientX,event.clientY);this.interactionDOMElement.style.cursor=this.defaultCursorStyle;// TODO optimize by not check EVERY TIME! maybe half as often? //
this.mapPositionToPoint(this.mouse.global,event.clientX,event.clientY);this.processInteractive(this.mouse.global,this.renderer._lastObjectRendered,this.processMouseOverOut,false);this.emit('mouseout',this.eventData);};/**
     * Processes the result of the mouse over/out check and dispatches the event if need be
     *
     * @private
     * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested
     * @param {boolean} hit - the result of the hit test on the display object
     */InteractionManager.prototype.processMouseOverOut=function processMouseOverOut(displayObject,hit){if(hit&&this.mouseOverRenderer){if(!displayObject._mouseOver){displayObject._mouseOver=true;this.dispatchEvent(displayObject,'mouseover',this.eventData);}if(displayObject.buttonMode){this.cursor=displayObject.defaultCursor;}}else if(displayObject._mouseOver){displayObject._mouseOver=false;this.dispatchEvent(displayObject,'mouseout',this.eventData);}};/**
     * Is called when the mouse enters the renderer element area
     *
     * @private
     * @param {MouseEvent} event - The DOM event of the mouse moving into the renderer view
     */InteractionManager.prototype.onMouseOver=function onMouseOver(event){this.mouseOverRenderer=true;this.mouse.originalEvent=event;this.eventData.data=this.mouse;this.eventData._reset();this.emit('mouseover',this.eventData);};/**
     * Is called when the pointer button is pressed down on the renderer element
     *
     * @private
     * @param {PointerEvent} event - The DOM event of a pointer button being pressed down
     */InteractionManager.prototype.onPointerDown=function onPointerDown(event){this.normalizeToPointerData(event);this.pointer.originalEvent=event;this.eventData.data=this.pointer;this.eventData._reset();// Update internal pointer reference
this.mapPositionToPoint(this.pointer.global,event.clientX,event.clientY);/**
         * No need to prevent default on natural pointer events, as there are no side effects
         * Normalized events, however, may have the double mousedown/touchstart issue on the native android browser,
         * so still need to be prevented.
         */if(this.autoPreventDefault&&(this.normalizeMouseEvents||this.normalizeTouchEvents)){this.pointer.originalEvent.preventDefault();}this.processInteractive(this.pointer.global,this.renderer._lastObjectRendered,this.processPointerDown,true);this.emit('pointerdown',this.eventData);};/**
     * Processes the result of the pointer down check and dispatches the event if need be
     *
     * @private
     * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested
     * @param {boolean} hit - the result of the hit test on the display object
     */InteractionManager.prototype.processPointerDown=function processPointerDown(displayObject,hit){if(hit){displayObject._pointerDown=true;this.dispatchEvent(displayObject,'pointerdown',this.eventData);}};/**
     * Is called when the pointer button is released on the renderer element
     *
     * @private
     * @param {PointerEvent} event - The DOM event of a pointer button being released
     */InteractionManager.prototype.onPointerUp=function onPointerUp(event){this.normalizeToPointerData(event);this.pointer.originalEvent=event;this.eventData.data=this.pointer;this.eventData._reset();// Update internal pointer reference
this.mapPositionToPoint(this.pointer.global,event.clientX,event.clientY);this.processInteractive(this.pointer.global,this.renderer._lastObjectRendered,this.processPointerUp,true);this.emit('pointerup',this.eventData);};/**
     * Processes the result of the pointer up check and dispatches the event if need be
     *
     * @private
     * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested
     * @param {boolean} hit - the result of the hit test on the display object
     */InteractionManager.prototype.processPointerUp=function processPointerUp(displayObject,hit){if(hit){this.dispatchEvent(displayObject,'pointerup',this.eventData);if(displayObject._pointerDown){displayObject._pointerDown=false;this.dispatchEvent(displayObject,'pointertap',this.eventData);}}else if(displayObject._pointerDown){displayObject._pointerDown=false;this.dispatchEvent(displayObject,'pointerupoutside',this.eventData);}};/**
     * Is called when the pointer moves across the renderer element
     *
     * @private
     * @param {PointerEvent} event - The DOM event of a pointer moving
     */InteractionManager.prototype.onPointerMove=function onPointerMove(event){this.normalizeToPointerData(event);this.pointer.originalEvent=event;this.eventData.data=this.pointer;this.eventData._reset();this.mapPositionToPoint(this.pointer.global,event.clientX,event.clientY);this.processInteractive(this.pointer.global,this.renderer._lastObjectRendered,this.processPointerMove,true);this.emit('pointermove',this.eventData);};/**
     * Processes the result of the pointer move check and dispatches the event if need be
     *
     * @private
     * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested
     * @param {boolean} hit - the result of the hit test on the display object
     */InteractionManager.prototype.processPointerMove=function processPointerMove(displayObject,hit){if(!this.pointer.originalEvent.changedTouches){this.processPointerOverOut(displayObject,hit);}if(!this.moveWhenInside||hit){this.dispatchEvent(displayObject,'pointermove',this.eventData);}};/**
     * Is called when the pointer is moved out of the renderer element
     *
     * @private
     * @param {PointerEvent} event - The DOM event of a pointer being moved out
     */InteractionManager.prototype.onPointerOut=function onPointerOut(event){this.normalizeToPointerData(event);this.pointer.originalEvent=event;this.eventData.data=this.pointer;this.eventData._reset();// Update internal pointer reference
this.mapPositionToPoint(this.pointer.global,event.clientX,event.clientY);this.processInteractive(this.pointer.global,this.renderer._lastObjectRendered,this.processPointerOverOut,false);this.emit('pointerout',this.eventData);};/**
     * Processes the result of the pointer over/out check and dispatches the event if need be
     *
     * @private
     * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested
     * @param {boolean} hit - the result of the hit test on the display object
     */InteractionManager.prototype.processPointerOverOut=function processPointerOverOut(displayObject,hit){if(hit&&this.mouseOverRenderer){if(!displayObject._pointerOver){displayObject._pointerOver=true;this.dispatchEvent(displayObject,'pointerover',this.eventData);}}else if(displayObject._pointerOver){displayObject._pointerOver=false;this.dispatchEvent(displayObject,'pointerout',this.eventData);}};/**
     * Is called when the pointer is moved into the renderer element
     *
     * @private
     * @param {PointerEvent} event - The DOM event of a pointer button being moved into the renderer view
     */InteractionManager.prototype.onPointerOver=function onPointerOver(event){this.pointer.originalEvent=event;this.eventData.data=this.pointer;this.eventData._reset();this.emit('pointerover',this.eventData);};/**
     * Is called when a touch is started on the renderer element
     *
     * @private
     * @param {TouchEvent} event - The DOM event of a touch starting on the renderer view
     */InteractionManager.prototype.onTouchStart=function onTouchStart(event){if(this.autoPreventDefault){event.preventDefault();}var changedTouches=event.changedTouches;var cLength=changedTouches.length;for(var i=0;i<cLength;i++){var touch=changedTouches[i];var touchData=this.getTouchData(touch);touchData.originalEvent=event;this.eventData.data=touchData;this.eventData._reset();this.processInteractive(touchData.global,this.renderer._lastObjectRendered,this.processTouchStart,true);this.emit('touchstart',this.eventData);this.returnTouchData(touchData);}};/**
     * Processes the result of a touch check and dispatches the event if need be
     *
     * @private
     * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested
     * @param {boolean} hit - the result of the hit test on the display object
     */InteractionManager.prototype.processTouchStart=function processTouchStart(displayObject,hit){if(hit){displayObject._touchDown=true;this.dispatchEvent(displayObject,'touchstart',this.eventData);}};/**
     * Is called when a touch ends on the renderer element
     *
     * @private
     * @param {TouchEvent} event - The DOM event of a touch ending on the renderer view
     */InteractionManager.prototype.onTouchEnd=function onTouchEnd(event){if(this.autoPreventDefault){event.preventDefault();}var changedTouches=event.changedTouches;var cLength=changedTouches.length;for(var i=0;i<cLength;i++){var touchEvent=changedTouches[i];var touchData=this.getTouchData(touchEvent);touchData.originalEvent=event;// TODO this should be passed along.. no set
this.eventData.data=touchData;this.eventData._reset();this.processInteractive(touchData.global,this.renderer._lastObjectRendered,this.processTouchEnd,true);this.emit('touchend',this.eventData);this.returnTouchData(touchData);}};/**
     * Processes the result of the end of a touch and dispatches the event if need be
     *
     * @private
     * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested
     * @param {boolean} hit - the result of the hit test on the display object
     */InteractionManager.prototype.processTouchEnd=function processTouchEnd(displayObject,hit){if(hit){this.dispatchEvent(displayObject,'touchend',this.eventData);if(displayObject._touchDown){displayObject._touchDown=false;this.dispatchEvent(displayObject,'tap',this.eventData);}}else if(displayObject._touchDown){if(this.eventData.data.originalEvent.targetTouches.length<=0)displayObject._touchDown=false;this.dispatchEvent(displayObject,'touchendoutside',this.eventData);}};/**
     * Is called when a touch is moved across the renderer element
     *
     * @private
     * @param {TouchEvent} event - The DOM event of a touch moving accross the renderer view
     */InteractionManager.prototype.onTouchMove=function onTouchMove(event){if(this.autoPreventDefault){event.preventDefault();}var changedTouches=event.changedTouches;var cLength=changedTouches.length;for(var i=0;i<cLength;i++){var touchEvent=changedTouches[i];var touchData=this.getTouchData(touchEvent);touchData.originalEvent=event;this.eventData.data=touchData;this.eventData._reset();this.processInteractive(touchData.global,this.renderer._lastObjectRendered,this.processTouchMove,this.moveWhenInside);this.emit('touchmove',this.eventData);this.returnTouchData(touchData);}};/**
     * Processes the result of a touch move check and dispatches the event if need be
     *
     * @private
     * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested
     * @param {boolean} hit - the result of the hit test on the display object
     */InteractionManager.prototype.processTouchMove=function processTouchMove(displayObject,hit){if(!this.moveWhenInside||hit){this.dispatchEvent(displayObject,'touchmove',this.eventData);}};/**
     * Grabs an interaction data object from the internal pool
     *
     * @private
     * @param {Touch} touch - The touch data we need to pair with an interactionData object
     * @return {PIXI.interaction.InteractionData} The built data object.
     */InteractionManager.prototype.getTouchData=function getTouchData(touch){var touchData=this.interactiveDataPool.pop()||new _InteractionData2.default();touchData.identifier=touch.identifier;this.mapPositionToPoint(touchData.global,touch.clientX,touch.clientY);if(navigator.isCocoonJS){touchData.global.x=touchData.global.x/this.resolution;touchData.global.y=touchData.global.y/this.resolution;}touch.globalX=touchData.global.x;touch.globalY=touchData.global.y;return touchData;};/**
     * Returns an interaction data object to the internal pool
     *
     * @private
     * @param {PIXI.interaction.InteractionData} touchData - The touch data object we want to return to the pool
     */InteractionManager.prototype.returnTouchData=function returnTouchData(touchData){this.interactiveDataPool.push(touchData);};/**
     * Ensures that the original event object contains all data that a regular pointer event would have
     *
     * @private
     * @param {TouchEvent|MouseEvent} event - The original event data from a touch or mouse event
     */InteractionManager.prototype.normalizeToPointerData=function normalizeToPointerData(event){if(this.normalizeTouchEvents&&event.changedTouches){if(typeof event.button==='undefined')event.button=event.touches.length?1:0;if(typeof event.buttons==='undefined')event.buttons=event.touches.length?1:0;if(typeof event.isPrimary==='undefined')event.isPrimary=event.touches.length===1;if(typeof event.width==='undefined')event.width=event.changedTouches[0].radiusX||1;if(typeof event.height==='undefined')event.height=event.changedTouches[0].radiusY||1;if(typeof event.tiltX==='undefined')event.tiltX=0;if(typeof event.tiltY==='undefined')event.tiltY=0;if(typeof event.pointerType==='undefined')event.pointerType='touch';if(typeof event.pointerId==='undefined')event.pointerId=event.changedTouches[0].identifier||0;if(typeof event.pressure==='undefined')event.pressure=event.changedTouches[0].force||0.5;if(typeof event.rotation==='undefined')event.rotation=event.changedTouches[0].rotationAngle||0;if(typeof event.clientX==='undefined')event.clientX=event.changedTouches[0].clientX;if(typeof event.clientY==='undefined')event.clientY=event.changedTouches[0].clientY;if(typeof event.pageX==='undefined')event.pageX=event.changedTouches[0].pageX;if(typeof event.pageY==='undefined')event.pageY=event.changedTouches[0].pageY;if(typeof event.screenX==='undefined')event.screenX=event.changedTouches[0].screenX;if(typeof event.screenY==='undefined')event.screenY=event.changedTouches[0].screenY;if(typeof event.layerX==='undefined')event.layerX=event.offsetX=event.clientX;if(typeof event.layerY==='undefined')event.layerY=event.offsetY=event.clientY;}else if(this.normalizeMouseEvents){if(typeof event.isPrimary==='undefined')event.isPrimary=true;if(typeof event.width==='undefined')event.width=1;if(typeof event.height==='undefined')event.height=1;if(typeof event.tiltX==='undefined')event.tiltX=0;if(typeof event.tiltY==='undefined')event.tiltY=0;if(typeof event.pointerType==='undefined')event.pointerType='mouse';if(typeof event.pointerId==='undefined')event.pointerId=1;if(typeof event.pressure==='undefined')event.pressure=0.5;if(typeof event.rotation==='undefined')event.rotation=0;}};/**
     * Destroys the interaction manager
     *
     */InteractionManager.prototype.destroy=function destroy(){this.removeEvents();this.removeAllListeners();this.renderer=null;this.mouse=null;this.eventData=null;this.interactiveDataPool=null;this.interactionDOMElement=null;this.onMouseDown=null;this.processMouseDown=null;this.onMouseUp=null;this.processMouseUp=null;this.onMouseMove=null;this.processMouseMove=null;this.onMouseOut=null;this.processMouseOverOut=null;this.onMouseOver=null;this.onPointerDown=null;this.processPointerDown=null;this.onPointerUp=null;this.processPointerUp=null;this.onPointerMove=null;this.processPointerMove=null;this.onPointerOut=null;this.processPointerOverOut=null;this.onPointerOver=null;this.onTouchStart=null;this.processTouchStart=null;this.onTouchEnd=null;this.processTouchEnd=null;this.onTouchMove=null;this.processTouchMove=null;this._tempPoint=null;};return InteractionManager;}(_eventemitter2.default);exports.default=InteractionManager;core.WebGLRenderer.registerPlugin('interaction',InteractionManager);core.CanvasRenderer.registerPlugin('interaction',InteractionManager);},{"../core":61,"./InteractionData":145,"./InteractionEvent":146,"./interactiveTarget":149,"eventemitter3":3,"ismobilejs":4}],148:[function(require,module,exports){'use strict';exports.__esModule=true;var _InteractionData=require('./InteractionData');Object.defineProperty(exports,'InteractionData',{enumerable:true,get:function get(){return _interopRequireDefault(_InteractionData).default;}});var _InteractionManager=require('./InteractionManager');Object.defineProperty(exports,'InteractionManager',{enumerable:true,get:function get(){return _interopRequireDefault(_InteractionManager).default;}});var _interactiveTarget=require('./interactiveTarget');Object.defineProperty(exports,'interactiveTarget',{enumerable:true,get:function get(){return _interopRequireDefault(_interactiveTarget).default;}});function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}},{"./InteractionData":145,"./InteractionManager":147,"./interactiveTarget":149}],149:[function(require,module,exports){'use strict';exports.__esModule=true;/**
 * Default property values of interactive objects
 * Used by {@link PIXI.interaction.InteractionManager} to automatically give all DisplayObjects these properties
 *
 * @mixin
 * @name interactiveTarget
 * @memberof PIXI.interaction
 * @example
 *      function MyObject() {}
 *
 *      Object.assign(
 *          MyObject.prototype,
 *          PIXI.interaction.interactiveTarget
 *      );
 */exports.default={/**
   * Determines if the displayObject be clicked/touched
   *
   * @inner {boolean}
   */interactive:false,/**
   * Determines if the children to the displayObject can be clicked/touched
   * Setting this to false allows pixi to bypass a recursive hitTest function
   *
   * @inner {boolean}
   */interactiveChildren:true,/**
   * Interaction shape. Children will be hit first, then this shape will be checked.
   * Setting this will cause this shape to be checked in hit tests rather than the displayObject's bounds.
   *
   * @inner {PIXI.Rectangle|PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.RoundedRectangle}
   */hitArea:null,/**
   * If enabled, the mouse cursor will change when hovered over the displayObject if it is interactive
   *
   * @inner {boolean}
   */buttonMode:false,/**
   * If buttonMode is enabled, this defines what CSS cursor property is used when the mouse cursor
   * is hovered over the displayObject
   *
   * @see https://developer.mozilla.org/en/docs/Web/CSS/cursor
   *
   * @inner {string}
   */defaultCursor:'pointer',// some internal checks..
/**
   * Internal check to detect if the mouse cursor is hovered over the displayObject
   *
   * @inner {boolean}
   * @private
   */_over:false,/**
   * Internal check to detect if the left mouse button is pressed on the displayObject
   *
   * @inner {boolean}
   * @private
   */_isLeftDown:false,/**
   * Internal check to detect if the right mouse button is pressed on the displayObject
   *
   * @inner {boolean}
   * @private
   */_isRightDown:false,/**
   * Internal check to detect if the pointer cursor is hovered over the displayObject
   *
   * @inner {boolean}
   * @private
   */_pointerOver:false,/**
   * Internal check to detect if the pointer is down on the displayObject
   *
   * @inner {boolean}
   * @private
   */_pointerDown:false,/**
   * Internal check to detect if a user has touched the displayObject
   *
   * @inner {boolean}
   * @private
   */_touchDown:false};},{}],150:[function(require,module,exports){'use strict';exports.__esModule=true;exports.parse=parse;exports.default=function(){return function bitmapFontParser(resource,next){// skip if no data or not xml data
if(!resource.data||resource.type!==_resourceLoader.Resource.TYPE.XML){next();return;}// skip if not bitmap font data, using some silly duck-typing
if(resource.data.getElementsByTagName('page').length===0||resource.data.getElementsByTagName('info').length===0||resource.data.getElementsByTagName('info')[0].getAttribute('face')===null){next();return;}var xmlUrl=!resource.isDataUrl?path.dirname(resource.url):'';if(resource.isDataUrl){if(xmlUrl==='.'){xmlUrl='';}if(this.baseUrl&&xmlUrl){// if baseurl has a trailing slash then add one to xmlUrl so the replace works below
if(this.baseUrl.charAt(this.baseUrl.length-1)==='/'){xmlUrl+='/';}// remove baseUrl from xmlUrl
xmlUrl=xmlUrl.replace(this.baseUrl,'');}}// if there is an xmlUrl now, it needs a trailing slash. Ensure that it does if the string isn't empty.
if(xmlUrl&&xmlUrl.charAt(xmlUrl.length-1)!=='/'){xmlUrl+='/';}var textureUrl=xmlUrl+resource.data.getElementsByTagName('page')[0].getAttribute('file');if(_core.utils.TextureCache[textureUrl]){// reuse existing texture
parse(resource,_core.utils.TextureCache[textureUrl]);next();}else{var loadOptions={crossOrigin:resource.crossOrigin,loadType:_resourceLoader.Resource.LOAD_TYPE.IMAGE,metadata:resource.metadata.imageMetadata,parentResource:resource};// load the texture for the font
this.add(resource.name+'_image',textureUrl,loadOptions,function(res){parse(resource,res.texture);next();});}};};var _path=require('path');var path=_interopRequireWildcard(_path);var _core=require('../core');var _resourceLoader=require('resource-loader');var _extras=require('../extras');function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj;}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key];}}newObj.default=obj;return newObj;}}function parse(resource,texture){var data={};var info=resource.data.getElementsByTagName('info')[0];var common=resource.data.getElementsByTagName('common')[0];data.font=info.getAttribute('face');data.size=parseInt(info.getAttribute('size'),10);data.lineHeight=parseInt(common.getAttribute('lineHeight'),10);data.chars={};// parse letters
var letters=resource.data.getElementsByTagName('char');for(var i=0;i<letters.length;i++){var charCode=parseInt(letters[i].getAttribute('id'),10);var textureRect=new _core.Rectangle(parseInt(letters[i].getAttribute('x'),10)+texture.frame.x,parseInt(letters[i].getAttribute('y'),10)+texture.frame.y,parseInt(letters[i].getAttribute('width'),10),parseInt(letters[i].getAttribute('height'),10));data.chars[charCode]={xOffset:parseInt(letters[i].getAttribute('xoffset'),10),yOffset:parseInt(letters[i].getAttribute('yoffset'),10),xAdvance:parseInt(letters[i].getAttribute('xadvance'),10),kerning:{},texture:new _core.Texture(texture.baseTexture,textureRect)};}// parse kernings
var kernings=resource.data.getElementsByTagName('kerning');for(var _i=0;_i<kernings.length;_i++){var first=parseInt(kernings[_i].getAttribute('first'),10);var second=parseInt(kernings[_i].getAttribute('second'),10);var amount=parseInt(kernings[_i].getAttribute('amount'),10);if(data.chars[second]){data.chars[second].kerning[first]=amount;}}resource.bitmapFont=data;// I'm leaving this as a temporary fix so we can test the bitmap fonts in v3
// but it's very likely to change
_extras.BitmapText.fonts[data.font]=data;}},{"../core":61,"../extras":131,"path":22,"resource-loader":34}],151:[function(require,module,exports){'use strict';exports.__esModule=true;var _loader=require('./loader');Object.defineProperty(exports,'Loader',{enumerable:true,get:function get(){return _interopRequireDefault(_loader).default;}});var _bitmapFontParser=require('./bitmapFontParser');Object.defineProperty(exports,'bitmapFontParser',{enumerable:true,get:function get(){return _interopRequireDefault(_bitmapFontParser).default;}});Object.defineProperty(exports,'parseBitmapFontData',{enumerable:true,get:function get(){return _bitmapFontParser.parse;}});var _spritesheetParser=require('./spritesheetParser');Object.defineProperty(exports,'spritesheetParser',{enumerable:true,get:function get(){return _interopRequireDefault(_spritesheetParser).default;}});var _textureParser=require('./textureParser');Object.defineProperty(exports,'textureParser',{enumerable:true,get:function get(){return _interopRequireDefault(_textureParser).default;}});var _resourceLoader=require('resource-loader');Object.defineProperty(exports,'Resource',{enumerable:true,get:function get(){return _resourceLoader.Resource;}});function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}},{"./bitmapFontParser":150,"./loader":152,"./spritesheetParser":153,"./textureParser":154,"resource-loader":34}],152:[function(require,module,exports){'use strict';exports.__esModule=true;var _resourceLoader=require('resource-loader');var _resourceLoader2=_interopRequireDefault(_resourceLoader);var _blob=require('resource-loader/lib/middlewares/parsing/blob');var _eventemitter=require('eventemitter3');var _eventemitter2=_interopRequireDefault(_eventemitter);var _textureParser=require('./textureParser');var _textureParser2=_interopRequireDefault(_textureParser);var _spritesheetParser=require('./spritesheetParser');var _spritesheetParser2=_interopRequireDefault(_spritesheetParser);var _bitmapFontParser=require('./bitmapFontParser');var _bitmapFontParser2=_interopRequireDefault(_bitmapFontParser);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return call&&((typeof call==="undefined"?"undefined":_typeof2(call))==="object"||typeof call==="function")?call:self;}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof2(superClass)));}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass;}/**
 *
 * The new loader, extends Resource Loader by Chad Engler : https://github.com/englercj/resource-loader
 *
 * ```js
 * let loader = PIXI.loader; // pixi exposes a premade instance for you to use.
 * //or
 * let loader = new PIXI.loaders.Loader(); // you can also create your own if you want
 *
 * loader.add('bunny', 'data/bunny.png');
 * loader.add('spaceship', 'assets/spritesheet.json');
 * loader.add('scoreFont', 'assets/score.fnt');
 *
 * loader.once('complete',onAssetsLoaded);
 *
 * loader.load();
 * ```
 *
 * @see https://github.com/englercj/resource-loader
 *
 * @class
 * @extends module:resource-loader.ResourceLoader
 * @memberof PIXI.loaders
 */var Loader=function(_ResourceLoader){_inherits(Loader,_ResourceLoader);/**
     * @param {string} [baseUrl=''] - The base url for all resources loaded by this loader.
     * @param {number} [concurrency=10] - The number of resources to load concurrently.
     */function Loader(baseUrl,concurrency){_classCallCheck(this,Loader);var _this=_possibleConstructorReturn(this,_ResourceLoader.call(this,baseUrl,concurrency));_eventemitter2.default.call(_this);for(var i=0;i<Loader._pixiMiddleware.length;++i){_this.use(Loader._pixiMiddleware[i]());}// Compat layer, translate the new v2 signals into old v1 events.
_this.onStart.add(function(l){return _this.emit('start',l);});_this.onProgress.add(function(l,r){return _this.emit('progress',l,r);});_this.onError.add(function(e,l,r){return _this.emit('error',e,l,r);});_this.onLoad.add(function(l,r){return _this.emit('load',l,r);});_this.onComplete.add(function(l,r){return _this.emit('complete',l,r);});return _this;}/**
     * Adds a default middleware to the pixi loader.
     *
     * @static
     * @param {Function} fn - The middleware to add.
     */Loader.addPixiMiddleware=function addPixiMiddleware(fn){Loader._pixiMiddleware.push(fn);};return Loader;}(_resourceLoader2.default);// Copy EE3 prototype (mixin)
exports.default=Loader;for(var k in _eventemitter2.default.prototype){Loader.prototype[k]=_eventemitter2.default.prototype[k];}Loader._pixiMiddleware=[// parse any blob into more usable objects (e.g. Image)
_blob.blobMiddlewareFactory,// parse any Image objects into textures
_textureParser2.default,// parse any spritesheet data into multiple textures
_spritesheetParser2.default,// parse bitmap font data into multiple textures
_bitmapFontParser2.default];// Add custom extentions
var Resource=_resourceLoader2.default.Resource;Resource.setExtensionXhrType('fnt',Resource.XHR_RESPONSE_TYPE.DOCUMENT);},{"./bitmapFontParser":150,"./spritesheetParser":153,"./textureParser":154,"eventemitter3":3,"resource-loader":34,"resource-loader/lib/middlewares/parsing/blob":35}],153:[function(require,module,exports){'use strict';exports.__esModule=true;exports.default=function(){return function spritesheetParser(resource,next){var resourcePath=void 0;var imageResourceName=resource.name+'_image';// skip if no data, its not json, it isn't spritesheet data, or the image resource already exists
if(!resource.data||resource.type!==_resourceLoader.Resource.TYPE.JSON||!resource.data.frames||this.resources[imageResourceName]){next();return;}var loadOptions={crossOrigin:resource.crossOrigin,loadType:_resourceLoader.Resource.LOAD_TYPE.IMAGE,metadata:resource.metadata.imageMetadata,parentResource:resource};// Prepend url path unless the resource image is a data url
if(resource.isDataUrl){resourcePath=resource.data.meta.image;}else{resourcePath=_path2.default.dirname(resource.url.replace(this.baseUrl,''))+'/'+resource.data.meta.image;}// load the image for this sheet
this.add(imageResourceName,resourcePath,loadOptions,function onImageLoad(res){resource.textures={};var frames=resource.data.frames;var frameKeys=Object.keys(frames);var baseTexture=res.texture.baseTexture;var scale=resource.data.meta.scale;// Use a defaultValue of `null` to check if a url-based resolution is set
var resolution=core.utils.getResolutionOfUrl(resource.url,null);// No resolution found via URL
if(resolution===null){// Use the scale value or default to 1
resolution=scale!==undefined?scale:1;}// For non-1 resolutions, update baseTexture
if(resolution!==1){baseTexture.resolution=resolution;baseTexture.update();}var batchIndex=0;function processFrames(initialFrameIndex,maxFrames){var frameIndex=initialFrameIndex;while(frameIndex-initialFrameIndex<maxFrames&&frameIndex<frameKeys.length){var i=frameKeys[frameIndex];var rect=frames[i].frame;if(rect){var frame=null;var trim=null;var orig=new core.Rectangle(0,0,frames[i].sourceSize.w/resolution,frames[i].sourceSize.h/resolution);if(frames[i].rotated){frame=new core.Rectangle(rect.x/resolution,rect.y/resolution,rect.h/resolution,rect.w/resolution);}else{frame=new core.Rectangle(rect.x/resolution,rect.y/resolution,rect.w/resolution,rect.h/resolution);}//  Check to see if the sprite is trimmed
if(frames[i].trimmed){trim=new core.Rectangle(frames[i].spriteSourceSize.x/resolution,frames[i].spriteSourceSize.y/resolution,rect.w/resolution,rect.h/resolution);}resource.textures[i]=new core.Texture(baseTexture,frame,orig,trim,frames[i].rotated?2:0);// lets also add the frame to pixi's global cache for fromFrame and fromImage functions
core.utils.TextureCache[i]=resource.textures[i];}frameIndex++;}}function shouldProcessNextBatch(){return batchIndex*BATCH_SIZE<frameKeys.length;}function processNextBatch(done){processFrames(batchIndex*BATCH_SIZE,BATCH_SIZE);batchIndex++;setTimeout(done,0);}function iteration(){processNextBatch(function(){if(shouldProcessNextBatch()){iteration();}else{next();}});}if(frameKeys.length<=BATCH_SIZE){processFrames(0,BATCH_SIZE);next();}else{iteration();}});};};var _resourceLoader=require('resource-loader');var _path=require('path');var _path2=_interopRequireDefault(_path);var _core=require('../core');var core=_interopRequireWildcard(_core);function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj;}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key];}}newObj.default=obj;return newObj;}}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}var BATCH_SIZE=1000;},{"../core":61,"path":22,"resource-loader":34}],154:[function(require,module,exports){'use strict';exports.__esModule=true;exports.default=function(){return function textureParser(resource,next){// create a new texture if the data is an Image object
if(resource.data&&resource.type===_resourceLoader.Resource.TYPE.IMAGE){var baseTexture=new core.BaseTexture(resource.data,null,core.utils.getResolutionOfUrl(resource.url));baseTexture.imageUrl=resource.url;resource.texture=new core.Texture(baseTexture);// lets also add the frame to pixi's global cache for fromFrame and fromImage fucntions
core.utils.BaseTextureCache[resource.name]=baseTexture;core.utils.TextureCache[resource.name]=resource.texture;// also add references by url if they are different.
if(resource.name!==resource.url){core.utils.BaseTextureCache[resource.url]=baseTexture;core.utils.TextureCache[resource.url]=resource.texture;}}next();};};var _core=require('../core');var core=_interopRequireWildcard(_core);var _resourceLoader=require('resource-loader');function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj;}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key];}}newObj.default=obj;return newObj;}}},{"../core":61,"resource-loader":34}],155:[function(require,module,exports){'use strict';exports.__esModule=true;var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor);}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor;};}();var _core=require('../core');var core=_interopRequireWildcard(_core);function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj;}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key];}}newObj.default=obj;return newObj;}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return call&&((typeof call==="undefined"?"undefined":_typeof2(call))==="object"||typeof call==="function")?call:self;}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof2(superClass)));}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass;}var tempPoint=new core.Point();var tempPolygon=new core.Polygon();/**
 * Base mesh class
 * @class
 * @extends PIXI.Container
 * @memberof PIXI.mesh
 */var Mesh=function(_core$Container){_inherits(Mesh,_core$Container);/**
   * @param {PIXI.Texture} texture - The texture to use
   * @param {Float32Array} [vertices] - if you want to specify the vertices
   * @param {Float32Array} [uvs] - if you want to specify the uvs
   * @param {Uint16Array} [indices] - if you want to specify the indices
   * @param {number} [drawMode] - the drawMode, can be any of the Mesh.DRAW_MODES consts
   */function Mesh(texture,vertices,uvs,indices,drawMode){_classCallCheck(this,Mesh);/**
     * The texture of the Mesh
     *
     * @member {PIXI.Texture}
     * @private
     */var _this=_possibleConstructorReturn(this,_core$Container.call(this));_this._texture=null;/**
     * The Uvs of the Mesh
     *
     * @member {Float32Array}
     */_this.uvs=uvs||new Float32Array([0,0,1,0,1,1,0,1]);/**
     * An array of vertices
     *
     * @member {Float32Array}
     */_this.vertices=vertices||new Float32Array([0,0,100,0,100,100,0,100]);/*
     * @member {Uint16Array} An array containing the indices of the vertices
     *///  TODO auto generate this based on draw mode!
_this.indices=indices||new Uint16Array([0,1,3,2]);/**
     * Version of mesh uvs are dirty or not
     *
     * @member {number}
     */_this.dirty=0;/**
     * Version of mesh indices
     *
     * @member {number}
     */_this.indexDirty=0;/**
     * The blend mode to be applied to the sprite. Set to `PIXI.BLEND_MODES.NORMAL` to remove
     * any blend mode.
     *
     * @member {number}
     * @default PIXI.BLEND_MODES.NORMAL
     * @see PIXI.BLEND_MODES
     */_this.blendMode=core.BLEND_MODES.NORMAL;/**
     * Triangles in canvas mode are automatically antialiased, use this value to force triangles
     * to overlap a bit with each other.
     *
     * @member {number}
     */_this.canvasPadding=0;/**
     * The way the Mesh should be drawn, can be any of the {@link PIXI.mesh.Mesh.DRAW_MODES} consts
     *
     * @member {number}
     * @see PIXI.mesh.Mesh.DRAW_MODES
     */_this.drawMode=drawMode||Mesh.DRAW_MODES.TRIANGLE_MESH;// run texture setter;
_this.texture=texture;/**
     * The default shader that is used if a mesh doesn't have a more specific one.
     *
     * @member {PIXI.Shader}
     */_this.shader=null;/**
     * The tint applied to the mesh. This is a [r,g,b] value. A value of [1,1,1] will remove any
     * tint effect.
     *
     * @member {number}
     * @memberof PIXI.mesh.Mesh#
     */_this.tintRgb=new Float32Array([1,1,1]);/**
     * A map of renderer IDs to webgl render data
     *
     * @private
     * @member {object<number, object>}
     */_this._glDatas={};/**
     * Plugin that is responsible for rendering this element.
     * Allows to customize the rendering process without overriding '_renderWebGL' & '_renderCanvas' methods.
     *
     * @member {string}
     * @default 'mesh'
     */_this.pluginName='mesh';return _this;}/**
   * Renders the object using the WebGL renderer
   *
   * @private
   * @param {PIXI.WebGLRenderer} renderer - a reference to the WebGL renderer
   */Mesh.prototype._renderWebGL=function _renderWebGL(renderer){renderer.setObjectRenderer(renderer.plugins[this.pluginName]);renderer.plugins[this.pluginName].render(this);};/**
   * Renders the object using the Canvas renderer
   *
   * @private
   * @param {PIXI.CanvasRenderer} renderer - The canvas renderer.
   */Mesh.prototype._renderCanvas=function _renderCanvas(renderer){renderer.plugins[this.pluginName].render(this);};/**
   * When the texture is updated, this event will fire to update the scale and frame
   *
   * @private
   */Mesh.prototype._onTextureUpdate=function _onTextureUpdate(){}/* empty *//**
   * Returns the bounds of the mesh as a rectangle. The bounds calculation takes the worldTransform into account.
   *
   */;Mesh.prototype._calculateBounds=function _calculateBounds(){// TODO - we can cache local bounds and use them if they are dirty (like graphics)
this._bounds.addVertices(this.transform,this.vertices,0,this.vertices.length);};/**
   * Tests if a point is inside this mesh. Works only for TRIANGLE_MESH
   *
   * @param {PIXI.Point} point - the point to test
   * @return {boolean} the result of the test
   */Mesh.prototype.containsPoint=function containsPoint(point){if(!this.getBounds().contains(point.x,point.y)){return false;}this.worldTransform.applyInverse(point,tempPoint);var vertices=this.vertices;var points=tempPolygon.points;var indices=this.indices;var len=this.indices.length;var step=this.drawMode===Mesh.DRAW_MODES.TRIANGLES?3:1;for(var i=0;i+2<len;i+=step){var ind0=indices[i]*2;var ind1=indices[i+1]*2;var ind2=indices[i+2]*2;points[0]=vertices[ind0];points[1]=vertices[ind0+1];points[2]=vertices[ind1];points[3]=vertices[ind1+1];points[4]=vertices[ind2];points[5]=vertices[ind2+1];if(tempPolygon.contains(tempPoint.x,tempPoint.y)){return true;}}return false;};/**
   * The texture that the mesh uses.
   *
   * @member {PIXI.Texture}
   * @memberof PIXI.mesh.Mesh#
   */_createClass(Mesh,[{key:'texture',get:function get(){return this._texture;}/**
     * Sets the texture the mesh uses.
     *
     * @param {Texture} value - The value to set.
     */,set:function set(value){if(this._texture===value){return;}this._texture=value;if(value){// wait for the texture to load
if(value.baseTexture.hasLoaded){this._onTextureUpdate();}else{value.once('update',this._onTextureUpdate,this);}}}/**
     * The tint applied to the mesh. This is a hex value. A value of 0xFFFFFF will remove any tint effect.
     *
     * @member {number}
     * @memberof PIXI.mesh.Mesh#
     * @default 0xFFFFFF
     */},{key:'tint',get:function get(){return core.utils.rgb2hex(this.tintRgb);}/**
     * Sets the tint the mesh uses.
     *
     * @param {number} value - The value to set.
     */,set:function set(value){this.tintRgb=core.utils.hex2rgb(value,this.tintRgb);}}]);return Mesh;}(core.Container);/**
 * Different drawing buffer modes supported
 *
 * @static
 * @constant
 * @type {object}
 * @property {number} TRIANGLE_MESH
 * @property {number} TRIANGLES
 */exports.default=Mesh;Mesh.DRAW_MODES={TRIANGLE_MESH:0,TRIANGLES:1};},{"../core":61}],156:[function(require,module,exports){'use strict';exports.__esModule=true;var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor);}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor;};}();var _Plane2=require('./Plane');var _Plane3=_interopRequireDefault(_Plane2);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return call&&((typeof call==="undefined"?"undefined":_typeof2(call))==="object"||typeof call==="function")?call:self;}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof2(superClass)));}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass;}var DEFAULT_BORDER_SIZE=10;/**
 * The NineSlicePlane allows you to stretch a texture using 9-slice scaling. The corners will remain unscaled (useful
 * for buttons with rounded corners for example) and the other areas will be scaled horizontally and or vertically
 *
 *```js
 * let Plane9 = new PIXI.NineSlicePlane(PIXI.Texture.fromImage('BoxWithRoundedCorners.png'), 15, 15, 15, 15);
 *  ```
 * <pre>
 *      A                          B
 *    +---+----------------------+---+
 *  C | 1 |          2           | 3 |
 *    +---+----------------------+---+
 *    |   |                      |   |
 *    | 4 |          5           | 6 |
 *    |   |                      |   |
 *    +---+----------------------+---+
 *  D | 7 |          8           | 9 |
 *    +---+----------------------+---+

 *  When changing this objects width and/or height:
 *     areas 1 3 7 and 9 will remain unscaled.
 *     areas 2 and 8 will be stretched horizontally
 *     areas 4 and 6 will be stretched vertically
 *     area 5 will be stretched both horizontally and vertically
 * </pre>
 *
 * @class
 * @extends PIXI.mesh.Plane
 * @memberof PIXI.mesh
 *
 */var NineSlicePlane=function(_Plane){_inherits(NineSlicePlane,_Plane);/**
     * @param {PIXI.Texture} texture - The texture to use on the NineSlicePlane.
     * @param {int} [leftWidth=10] size of the left vertical bar (A)
     * @param {int} [topHeight=10] size of the top horizontal bar (C)
     * @param {int} [rightWidth=10] size of the right vertical bar (B)
     * @param {int} [bottomHeight=10] size of the bottom horizontal bar (D)
     */function NineSlicePlane(texture,leftWidth,topHeight,rightWidth,bottomHeight){_classCallCheck(this,NineSlicePlane);var _this=_possibleConstructorReturn(this,_Plane.call(this,texture,4,4));var uvs=_this.uvs;// right and bottom uv's are always 1
uvs[6]=uvs[14]=uvs[22]=uvs[30]=1;uvs[25]=uvs[27]=uvs[29]=uvs[31]=1;_this._origWidth=texture.width;_this._origHeight=texture.height;_this._uvw=1/_this._origWidth;_this._uvh=1/_this._origHeight;/**
         * The width of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane
         *
         * @member {number}
         * @memberof PIXI.NineSlicePlane#
         * @override
         */_this.width=texture.width;/**
         * The height of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane
         *
         * @member {number}
         * @memberof PIXI.NineSlicePlane#
         * @override
         */_this.height=texture.height;uvs[2]=uvs[10]=uvs[18]=uvs[26]=_this._uvw*leftWidth;uvs[4]=uvs[12]=uvs[20]=uvs[28]=1-_this._uvw*rightWidth;uvs[9]=uvs[11]=uvs[13]=uvs[15]=_this._uvh*topHeight;uvs[17]=uvs[19]=uvs[21]=uvs[23]=1-_this._uvh*bottomHeight;/**
         * The width of the left column (a)
         *
         * @member {number}
         */_this.leftWidth=typeof leftWidth!=='undefined'?leftWidth:DEFAULT_BORDER_SIZE;/**
         * The width of the right column (b)
         *
         * @member {number}
         */_this.rightWidth=typeof rightWidth!=='undefined'?rightWidth:DEFAULT_BORDER_SIZE;/**
         * The height of the top row (c)
         *
         * @member {number}
         */_this.topHeight=typeof topHeight!=='undefined'?topHeight:DEFAULT_BORDER_SIZE;/**
         * The height of the bottom row (d)
         *
         * @member {number}
         */_this.bottomHeight=typeof bottomHeight!=='undefined'?bottomHeight:DEFAULT_BORDER_SIZE;return _this;}/**
     * Updates the horizontal vertices.
     *
     */NineSlicePlane.prototype.updateHorizontalVertices=function updateHorizontalVertices(){var vertices=this.vertices;vertices[9]=vertices[11]=vertices[13]=vertices[15]=this._topHeight;vertices[17]=vertices[19]=vertices[21]=vertices[23]=this._height-this._bottomHeight;vertices[25]=vertices[27]=vertices[29]=vertices[31]=this._height;};/**
     * Updates the vertical vertices.
     *
     */NineSlicePlane.prototype.updateVerticalVertices=function updateVerticalVertices(){var vertices=this.vertices;vertices[2]=vertices[10]=vertices[18]=vertices[26]=this._leftWidth;vertices[4]=vertices[12]=vertices[20]=vertices[28]=this._width-this._rightWidth;vertices[6]=vertices[14]=vertices[22]=vertices[30]=this._width;};/**
     * Renders the object using the Canvas renderer
     *
     * @private
     * @param {PIXI.CanvasRenderer} renderer - The canvas renderer to render with.
     */NineSlicePlane.prototype._renderCanvas=function _renderCanvas(renderer){var context=renderer.context;context.globalAlpha=this.worldAlpha;var transform=this.worldTransform;var res=renderer.resolution;if(renderer.roundPixels){context.setTransform(transform.a*res,transform.b*res,transform.c*res,transform.d*res,transform.tx*res|0,transform.ty*res|0);}else{context.setTransform(transform.a*res,transform.b*res,transform.c*res,transform.d*res,transform.tx*res,transform.ty*res);}var base=this._texture.baseTexture;var textureSource=base.source;var w=base.width;var h=base.height;this.drawSegment(context,textureSource,w,h,0,1,10,11);this.drawSegment(context,textureSource,w,h,2,3,12,13);this.drawSegment(context,textureSource,w,h,4,5,14,15);this.drawSegment(context,textureSource,w,h,8,9,18,19);this.drawSegment(context,textureSource,w,h,10,11,20,21);this.drawSegment(context,textureSource,w,h,12,13,22,23);this.drawSegment(context,textureSource,w,h,16,17,26,27);this.drawSegment(context,textureSource,w,h,18,19,28,29);this.drawSegment(context,textureSource,w,h,20,21,30,31);};/**
     * Renders one segment of the plane.
     * to mimic the exact drawing behavior of stretching the image like WebGL does, we need to make sure
     * that the source area is at least 1 pixel in size, otherwise nothing gets drawn when a slice size of 0 is used.
     *
     * @private
     * @param {CanvasRenderingContext2D} context - The context to draw with.
     * @param {CanvasImageSource} textureSource - The source to draw.
     * @param {number} w - width of the texture
     * @param {number} h - height of the texture
     * @param {number} x1 - x index 1
     * @param {number} y1 - y index 1
     * @param {number} x2 - x index 2
     * @param {number} y2 - y index 2
     */NineSlicePlane.prototype.drawSegment=function drawSegment(context,textureSource,w,h,x1,y1,x2,y2){// otherwise you get weird results when using slices of that are 0 wide or high.
var uvs=this.uvs;var vertices=this.vertices;var sw=(uvs[x2]-uvs[x1])*w;var sh=(uvs[y2]-uvs[y1])*h;var dw=vertices[x2]-vertices[x1];var dh=vertices[y2]-vertices[y1];// make sure the source is at least 1 pixel wide and high, otherwise nothing will be drawn.
if(sw<1){sw=1;}if(sh<1){sh=1;}// make sure destination is at least 1 pixel wide and high, otherwise you get
// lines when rendering close to original size.
if(dw<1){dw=1;}if(dh<1){dh=1;}context.drawImage(textureSource,uvs[x1]*w,uvs[y1]*h,sw,sh,vertices[x1],vertices[y1],dw,dh);};/**
     * The width of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane
     *
     * @member {number}
     * @memberof PIXI.NineSlicePlane#
     */_createClass(NineSlicePlane,[{key:'width',get:function get(){return this._width;}/**
         * Sets the width.
         *
         * @param {number} value - the value to set to.
         */,set:function set(value){this._width=value;this.updateVerticalVertices();}/**
         * The height of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane
         *
         * @member {number}
         * @memberof PIXI.NineSlicePlane#
         */},{key:'height',get:function get(){return this._height;}/**
         * Sets the height.
         *
         * @param {number} value - the value to set to.
         */,set:function set(value){this._height=value;this.updateHorizontalVertices();}/**
         * The width of the left column
         *
         * @member {number}
         */},{key:'leftWidth',get:function get(){return this._leftWidth;}/**
         * Sets the width of the left column.
         *
         * @param {number} value - the value to set to.
         */,set:function set(value){this._leftWidth=value;var uvs=this.uvs;var vertices=this.vertices;uvs[2]=uvs[10]=uvs[18]=uvs[26]=this._uvw*value;vertices[2]=vertices[10]=vertices[18]=vertices[26]=value;this.dirty=true;}/**
         * The width of the right column
         *
         * @member {number}
         */},{key:'rightWidth',get:function get(){return this._rightWidth;}/**
         * Sets the width of the right column.
         *
         * @param {number} value - the value to set to.
         */,set:function set(value){this._rightWidth=value;var uvs=this.uvs;var vertices=this.vertices;uvs[4]=uvs[12]=uvs[20]=uvs[28]=1-this._uvw*value;vertices[4]=vertices[12]=vertices[20]=vertices[28]=this._width-value;this.dirty=true;}/**
         * The height of the top row
         *
         * @member {number}
         */},{key:'topHeight',get:function get(){return this._topHeight;}/**
         * Sets the height of the top row.
         *
         * @param {number} value - the value to set to.
         */,set:function set(value){this._topHeight=value;var uvs=this.uvs;var vertices=this.vertices;uvs[9]=uvs[11]=uvs[13]=uvs[15]=this._uvh*value;vertices[9]=vertices[11]=vertices[13]=vertices[15]=value;this.dirty=true;}/**
         * The height of the bottom row
         *
         * @member {number}
         */},{key:'bottomHeight',get:function get(){return this._bottomHeight;}/**
         * Sets the height of the bottom row.
         *
         * @param {number} value - the value to set to.
         */,set:function set(value){this._bottomHeight=value;var uvs=this.uvs;var vertices=this.vertices;uvs[17]=uvs[19]=uvs[21]=uvs[23]=1-this._uvh*value;vertices[17]=vertices[19]=vertices[21]=vertices[23]=this._height-value;this.dirty=true;}}]);return NineSlicePlane;}(_Plane3.default);exports.default=NineSlicePlane;},{"./Plane":157}],157:[function(require,module,exports){'use strict';exports.__esModule=true;var _Mesh2=require('./Mesh');var _Mesh3=_interopRequireDefault(_Mesh2);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return call&&((typeof call==="undefined"?"undefined":_typeof2(call))==="object"||typeof call==="function")?call:self;}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof2(superClass)));}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass;}/**
 * The Plane allows you to draw a texture across several points and them manipulate these points
 *
 *```js
 * for (let i = 0; i < 20; i++) {
 *     points.push(new PIXI.Point(i * 50, 0));
 * };
 * let Plane = new PIXI.Plane(PIXI.Texture.fromImage("snake.png"), points);
 *  ```
 *
 * @class
 * @extends PIXI.mesh.Mesh
 * @memberof PIXI.mesh
 *
 */var Plane=function(_Mesh){_inherits(Plane,_Mesh);/**
     * @param {PIXI.Texture} texture - The texture to use on the Plane.
     * @param {number} verticesX - The number of vertices in the x-axis
     * @param {number} verticesY - The number of vertices in the y-axis
     */function Plane(texture,verticesX,verticesY){_classCallCheck(this,Plane);/**
         * Tracker for if the Plane is ready to be drawn. Needed because Mesh ctor can
         * call _onTextureUpdated which could call refresh too early.
         *
         * @member {boolean}
         * @private
         */var _this=_possibleConstructorReturn(this,_Mesh.call(this,texture));_this._ready=true;_this.verticesX=verticesX||10;_this.verticesY=verticesY||10;_this.drawMode=_Mesh3.default.DRAW_MODES.TRIANGLES;_this.refresh();return _this;}/**
     * Refreshes
     *
     */Plane.prototype.refresh=function refresh(){var total=this.verticesX*this.verticesY;var verts=[];var colors=[];var uvs=[];var indices=[];var texture=this.texture;var segmentsX=this.verticesX-1;var segmentsY=this.verticesY-1;var sizeX=texture.width/segmentsX;var sizeY=texture.height/segmentsY;for(var i=0;i<total;i++){if(texture._uvs){var x=i%this.verticesX;var y=i/this.verticesX|0;verts.push(x*sizeX,y*sizeY);// this works for rectangular textures.
uvs.push(texture._uvs.x0+(texture._uvs.x1-texture._uvs.x0)*(x/(this.verticesX-1)),texture._uvs.y0+(texture._uvs.y3-texture._uvs.y0)*(y/(this.verticesY-1)));}else{uvs.push(0);}}//  cons
var totalSub=segmentsX*segmentsY;for(var _i=0;_i<totalSub;_i++){var xpos=_i%segmentsX;var ypos=_i/segmentsX|0;var value=ypos*this.verticesX+xpos;var value2=ypos*this.verticesX+xpos+1;var value3=(ypos+1)*this.verticesX+xpos;var value4=(ypos+1)*this.verticesX+xpos+1;indices.push(value,value2,value3);indices.push(value2,value4,value3);}// console.log(indices)
this.vertices=new Float32Array(verts);this.uvs=new Float32Array(uvs);this.colors=new Float32Array(colors);this.indices=new Uint16Array(indices);this.indexDirty=true;};/**
     * Clear texture UVs when new texture is set
     *
     * @private
     */Plane.prototype._onTextureUpdate=function _onTextureUpdate(){_Mesh3.default.prototype._onTextureUpdate.call(this);// wait for the Plane ctor to finish before calling refresh
if(this._ready){this.refresh();}};return Plane;}(_Mesh3.default);exports.default=Plane;},{"./Mesh":155}],158:[function(require,module,exports){'use strict';exports.__esModule=true;var _Mesh2=require('./Mesh');var _Mesh3=_interopRequireDefault(_Mesh2);var _core=require('../core');var core=_interopRequireWildcard(_core);function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj;}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key];}}newObj.default=obj;return newObj;}}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return call&&((typeof call==="undefined"?"undefined":_typeof2(call))==="object"||typeof call==="function")?call:self;}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof2(superClass)));}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass;}/**
 * The rope allows you to draw a texture across several points and them manipulate these points
 *
 *```js
 * for (let i = 0; i < 20; i++) {
 *     points.push(new PIXI.Point(i * 50, 0));
 * };
 * let rope = new PIXI.Rope(PIXI.Texture.fromImage("snake.png"), points);
 *  ```
 *
 * @class
 * @extends PIXI.mesh.Mesh
 * @memberof PIXI.mesh
 *
 */var Rope=function(_Mesh){_inherits(Rope,_Mesh);/**
     * @param {PIXI.Texture} texture - The texture to use on the rope.
     * @param {PIXI.Point[]} points - An array of {@link PIXI.Point} objects to construct this rope.
     */function Rope(texture,points){_classCallCheck(this,Rope);/*
         * @member {PIXI.Point[]} An array of points that determine the rope
         */var _this=_possibleConstructorReturn(this,_Mesh.call(this,texture));_this.points=points;/*
         * @member {Float32Array} An array of vertices used to construct this rope.
         */_this.vertices=new Float32Array(points.length*4);/*
         * @member {Float32Array} The WebGL Uvs of the rope.
         */_this.uvs=new Float32Array(points.length*4);/*
         * @member {Float32Array} An array containing the color components
         */_this.colors=new Float32Array(points.length*2);/*
         * @member {Uint16Array} An array containing the indices of the vertices
         */_this.indices=new Uint16Array(points.length*2);/**
         * Tracker for if the rope is ready to be drawn. Needed because Mesh ctor can
         * call _onTextureUpdated which could call refresh too early.
         *
         * @member {boolean}
         * @private
         */_this._ready=true;_this.refresh();return _this;}/**
     * Refreshes
     *
     */Rope.prototype.refresh=function refresh(){var points=this.points;// if too little points, or texture hasn't got UVs set yet just move on.
if(points.length<1||!this._texture._uvs){return;}// if the number of points has changed we will need to recreate the arraybuffers
if(this.vertices.length/4!==points.length){this.vertices=new Float32Array(points.length*4);this.uvs=new Float32Array(points.length*4);this.colors=new Float32Array(points.length*2);this.indices=new Uint16Array(points.length*2);}var uvs=this.uvs;var indices=this.indices;var colors=this.colors;var textureUvs=this._texture._uvs;var offset=new core.Point(textureUvs.x0,textureUvs.y0);var factor=new core.Point(textureUvs.x2-textureUvs.x0,textureUvs.y2-textureUvs.y0);uvs[0]=0+offset.x;uvs[1]=0+offset.y;uvs[2]=0+offset.x;uvs[3]=Number(factor.y)+offset.y;colors[0]=1;colors[1]=1;indices[0]=0;indices[1]=1;var total=points.length;for(var i=1;i<total;i++){// time to do some smart drawing!
var index=i*4;var amount=i/(total-1);uvs[index]=amount*factor.x+offset.x;uvs[index+1]=0+offset.y;uvs[index+2]=amount*factor.x+offset.x;uvs[index+3]=Number(factor.y)+offset.y;index=i*2;colors[index]=1;colors[index+1]=1;index=i*2;indices[index]=index;indices[index+1]=index+1;}// ensure that the changes are uploaded
this.dirty++;this.indexDirty++;};/**
     * Clear texture UVs when new texture is set
     *
     * @private
     */Rope.prototype._onTextureUpdate=function _onTextureUpdate(){_Mesh.prototype._onTextureUpdate.call(this);// wait for the Rope ctor to finish before calling refresh
if(this._ready){this.refresh();}};/**
     * Updates the object transform for rendering
     *
     * @private
     */Rope.prototype.updateTransform=function updateTransform(){var points=this.points;if(points.length<1){return;}var lastPoint=points[0];var nextPoint=void 0;var perpX=0;var perpY=0;// this.count -= 0.2;
var vertices=this.vertices;var total=points.length;for(var i=0;i<total;i++){var point=points[i];var index=i*4;if(i<points.length-1){nextPoint=points[i+1];}else{nextPoint=point;}perpY=-(nextPoint.x-lastPoint.x);perpX=nextPoint.y-lastPoint.y;var ratio=(1-i/(total-1))*10;if(ratio>1){ratio=1;}var perpLength=Math.sqrt(perpX*perpX+perpY*perpY);var num=this._texture.height/2;// (20 + Math.abs(Math.sin((i + this.count) * 0.3) * 50) )* ratio;
perpX/=perpLength;perpY/=perpLength;perpX*=num;perpY*=num;vertices[index]=point.x+perpX;vertices[index+1]=point.y+perpY;vertices[index+2]=point.x-perpX;vertices[index+3]=point.y-perpY;lastPoint=point;}this.containerUpdateTransform();};return Rope;}(_Mesh3.default);exports.default=Rope;},{"../core":61,"./Mesh":155}],159:[function(require,module,exports){'use strict';exports.__esModule=true;var _core=require('../../core');var core=_interopRequireWildcard(_core);var _Mesh=require('../Mesh');var _Mesh2=_interopRequireDefault(_Mesh);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj;}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key];}}newObj.default=obj;return newObj;}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}/**
 * Renderer dedicated to meshes.
 *
 * @class
 * @private
 * @memberof PIXI
 */var MeshSpriteRenderer=function(){/**
     * @param {PIXI.CanvasRenderer} renderer - The renderer this downport works for
     */function MeshSpriteRenderer(renderer){_classCallCheck(this,MeshSpriteRenderer);this.renderer=renderer;}/**
     * Renders the Mesh
     *
     * @param {PIXI.mesh.Mesh} mesh - the Mesh to render
     */MeshSpriteRenderer.prototype.render=function render(mesh){var renderer=this.renderer;var context=renderer.context;var transform=mesh.worldTransform;var res=renderer.resolution;if(renderer.roundPixels){context.setTransform(transform.a*res,transform.b*res,transform.c*res,transform.d*res,transform.tx*res|0,transform.ty*res|0);}else{context.setTransform(transform.a*res,transform.b*res,transform.c*res,transform.d*res,transform.tx*res,transform.ty*res);}renderer.setBlendMode(mesh.blendMode);if(mesh.drawMode===_Mesh2.default.DRAW_MODES.TRIANGLE_MESH){this._renderTriangleMesh(mesh);}else{this._renderTriangles(mesh);}};/**
     * Draws the object in Triangle Mesh mode
     *
     * @private
     * @param {PIXI.mesh.Mesh} mesh - the Mesh to render
     */MeshSpriteRenderer.prototype._renderTriangleMesh=function _renderTriangleMesh(mesh){// draw triangles!!
var length=mesh.vertices.length/2;for(var i=0;i<length-2;i++){// draw some triangles!
var index=i*2;this._renderDrawTriangle(mesh,index,index+2,index+4);}};/**
     * Draws the object in triangle mode using canvas
     *
     * @private
     * @param {PIXI.mesh.Mesh} mesh - the current mesh
     */MeshSpriteRenderer.prototype._renderTriangles=function _renderTriangles(mesh){// draw triangles!!
var indices=mesh.indices;var length=indices.length;for(var i=0;i<length;i+=3){// draw some triangles!
var index0=indices[i]*2;var index1=indices[i+1]*2;var index2=indices[i+2]*2;this._renderDrawTriangle(mesh,index0,index1,index2);}};/**
     * Draws one of the triangles that from the Mesh
     *
     * @private
     * @param {PIXI.mesh.Mesh} mesh - the current mesh
     * @param {number} index0 - the index of the first vertex
     * @param {number} index1 - the index of the second vertex
     * @param {number} index2 - the index of the third vertex
     */MeshSpriteRenderer.prototype._renderDrawTriangle=function _renderDrawTriangle(mesh,index0,index1,index2){var context=this.renderer.context;var uvs=mesh.uvs;var vertices=mesh.vertices;var texture=mesh._texture;if(!texture.valid){return;}var base=texture.baseTexture;var textureSource=base.source;var textureWidth=base.width;var textureHeight=base.height;var u0=uvs[index0]*base.width;var u1=uvs[index1]*base.width;var u2=uvs[index2]*base.width;var v0=uvs[index0+1]*base.height;var v1=uvs[index1+1]*base.height;var v2=uvs[index2+1]*base.height;var x0=vertices[index0];var x1=vertices[index1];var x2=vertices[index2];var y0=vertices[index0+1];var y1=vertices[index1+1];var y2=vertices[index2+1];if(mesh.canvasPadding>0){var paddingX=mesh.canvasPadding/mesh.worldTransform.a;var paddingY=mesh.canvasPadding/mesh.worldTransform.d;var centerX=(x0+x1+x2)/3;var centerY=(y0+y1+y2)/3;var normX=x0-centerX;var normY=y0-centerY;var dist=Math.sqrt(normX*normX+normY*normY);x0=centerX+normX/dist*(dist+paddingX);y0=centerY+normY/dist*(dist+paddingY);//
normX=x1-centerX;normY=y1-centerY;dist=Math.sqrt(normX*normX+normY*normY);x1=centerX+normX/dist*(dist+paddingX);y1=centerY+normY/dist*(dist+paddingY);normX=x2-centerX;normY=y2-centerY;dist=Math.sqrt(normX*normX+normY*normY);x2=centerX+normX/dist*(dist+paddingX);y2=centerY+normY/dist*(dist+paddingY);}context.save();context.beginPath();context.moveTo(x0,y0);context.lineTo(x1,y1);context.lineTo(x2,y2);context.closePath();context.clip();// Compute matrix transform
var delta=u0*v1+v0*u2+u1*v2-v1*u2-v0*u1-u0*v2;var deltaA=x0*v1+v0*x2+x1*v2-v1*x2-v0*x1-x0*v2;var deltaB=u0*x1+x0*u2+u1*x2-x1*u2-x0*u1-u0*x2;var deltaC=u0*v1*x2+v0*x1*u2+x0*u1*v2-x0*v1*u2-v0*u1*x2-u0*x1*v2;var deltaD=y0*v1+v0*y2+y1*v2-v1*y2-v0*y1-y0*v2;var deltaE=u0*y1+y0*u2+u1*y2-y1*u2-y0*u1-u0*y2;var deltaF=u0*v1*y2+v0*y1*u2+y0*u1*v2-y0*v1*u2-v0*u1*y2-u0*y1*v2;context.transform(deltaA/delta,deltaD/delta,deltaB/delta,deltaE/delta,deltaC/delta,deltaF/delta);context.drawImage(textureSource,0,0,textureWidth*base.resolution,textureHeight*base.resolution,0,0,textureWidth,textureHeight);context.restore();};/**
     * Renders a flat Mesh
     *
     * @private
     * @param {PIXI.mesh.Mesh} mesh - The Mesh to render
     */MeshSpriteRenderer.prototype.renderMeshFlat=function renderMeshFlat(mesh){var context=this.renderer.context;var vertices=mesh.vertices;var length=vertices.length/2;// this.count++;
context.beginPath();for(var i=1;i<length-2;++i){// draw some triangles!
var index=i*2;var x0=vertices[index];var y0=vertices[index+1];var x1=vertices[index+2];var y1=vertices[index+3];var x2=vertices[index+4];var y2=vertices[index+5];context.moveTo(x0,y0);context.lineTo(x1,y1);context.lineTo(x2,y2);}context.fillStyle='#FF0000';context.fill();context.closePath();};/**
     * destroy the the renderer.
     *
     */MeshSpriteRenderer.prototype.destroy=function destroy(){this.renderer=null;};return MeshSpriteRenderer;}();exports.default=MeshSpriteRenderer;core.CanvasRenderer.registerPlugin('mesh',MeshSpriteRenderer);},{"../../core":61,"../Mesh":155}],160:[function(require,module,exports){'use strict';exports.__esModule=true;var _Mesh=require('./Mesh');Object.defineProperty(exports,'Mesh',{enumerable:true,get:function get(){return _interopRequireDefault(_Mesh).default;}});var _MeshRenderer=require('./webgl/MeshRenderer');Object.defineProperty(exports,'MeshRenderer',{enumerable:true,get:function get(){return _interopRequireDefault(_MeshRenderer).default;}});var _CanvasMeshRenderer=require('./canvas/CanvasMeshRenderer');Object.defineProperty(exports,'CanvasMeshRenderer',{enumerable:true,get:function get(){return _interopRequireDefault(_CanvasMeshRenderer).default;}});var _Plane=require('./Plane');Object.defineProperty(exports,'Plane',{enumerable:true,get:function get(){return _interopRequireDefault(_Plane).default;}});var _NineSlicePlane=require('./NineSlicePlane');Object.defineProperty(exports,'NineSlicePlane',{enumerable:true,get:function get(){return _interopRequireDefault(_NineSlicePlane).default;}});var _Rope=require('./Rope');Object.defineProperty(exports,'Rope',{enumerable:true,get:function get(){return _interopRequireDefault(_Rope).default;}});function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}},{"./Mesh":155,"./NineSlicePlane":156,"./Plane":157,"./Rope":158,"./canvas/CanvasMeshRenderer":159,"./webgl/MeshRenderer":161}],161:[function(require,module,exports){'use strict';exports.__esModule=true;var _core=require('../../core');var core=_interopRequireWildcard(_core);var _pixiGlCore=require('pixi-gl-core');var _pixiGlCore2=_interopRequireDefault(_pixiGlCore);var _Mesh=require('../Mesh');var _Mesh2=_interopRequireDefault(_Mesh);var _path=require('path');function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj;}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key];}}newObj.default=obj;return newObj;}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return call&&((typeof call==="undefined"?"undefined":_typeof2(call))==="object"||typeof call==="function")?call:self;}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof2(superClass)));}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass;}/**
 * WebGL renderer plugin for tiling sprites
 */var MeshRenderer=function(_core$ObjectRenderer){_inherits(MeshRenderer,_core$ObjectRenderer);/**
     * constructor for renderer
     *
     * @param {WebGLRenderer} renderer The renderer this tiling awesomeness works for.
     */function MeshRenderer(renderer){_classCallCheck(this,MeshRenderer);var _this=_possibleConstructorReturn(this,_core$ObjectRenderer.call(this,renderer));_this.shader=null;return _this;}/**
     * Sets up the renderer context and necessary buffers.
     *
     * @private
     */MeshRenderer.prototype.onContextChange=function onContextChange(){var gl=this.renderer.gl;this.shader=new core.Shader(gl,'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 translationMatrix;\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n    gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n    vTextureCoord = aTextureCoord;\n}\n','varying vec2 vTextureCoord;\nuniform float alpha;\nuniform vec3 tint;\n\nuniform sampler2D uSampler;\n\nvoid main(void)\n{\n    gl_FragColor = texture2D(uSampler, vTextureCoord) * vec4(tint * alpha, alpha);\n}\n');};/**
     * renders mesh
     *
     * @param {PIXI.mesh.Mesh} mesh mesh instance
     */MeshRenderer.prototype.render=function render(mesh){var renderer=this.renderer;var gl=renderer.gl;var texture=mesh._texture;if(!texture.valid){return;}var glData=mesh._glDatas[renderer.CONTEXT_UID];if(!glData){renderer.bindVao(null);glData={shader:this.shader,vertexBuffer:_pixiGlCore2.default.GLBuffer.createVertexBuffer(gl,mesh.vertices,gl.STREAM_DRAW),uvBuffer:_pixiGlCore2.default.GLBuffer.createVertexBuffer(gl,mesh.uvs,gl.STREAM_DRAW),indexBuffer:_pixiGlCore2.default.GLBuffer.createIndexBuffer(gl,mesh.indices,gl.STATIC_DRAW),// build the vao object that will render..
vao:null,dirty:mesh.dirty,indexDirty:mesh.indexDirty};// build the vao object that will render..
glData.vao=new _pixiGlCore2.default.VertexArrayObject(gl).addIndex(glData.indexBuffer).addAttribute(glData.vertexBuffer,glData.shader.attributes.aVertexPosition,gl.FLOAT,false,2*4,0).addAttribute(glData.uvBuffer,glData.shader.attributes.aTextureCoord,gl.FLOAT,false,2*4,0);mesh._glDatas[renderer.CONTEXT_UID]=glData;}if(mesh.dirty!==glData.dirty){glData.dirty=mesh.dirty;glData.uvBuffer.upload(mesh.uvs);}if(mesh.indexDirty!==glData.indexDirty){glData.indexDirty=mesh.indexDirty;glData.indexBuffer.upload(mesh.indices);}glData.vertexBuffer.upload(mesh.vertices);renderer.bindShader(glData.shader);glData.shader.uniforms.uSampler=renderer.bindTexture(texture);renderer.state.setBlendMode(mesh.blendMode);glData.shader.uniforms.translationMatrix=mesh.worldTransform.toArray(true);glData.shader.uniforms.alpha=mesh.worldAlpha;glData.shader.uniforms.tint=mesh.tintRgb;var drawMode=mesh.drawMode===_Mesh2.default.DRAW_MODES.TRIANGLE_MESH?gl.TRIANGLE_STRIP:gl.TRIANGLES;renderer.bindVao(glData.vao);glData.vao.draw(drawMode,mesh.indices.length,0);};return MeshRenderer;}(core.ObjectRenderer);exports.default=MeshRenderer;core.WebGLRenderer.registerPlugin('mesh',MeshRenderer);},{"../../core":61,"../Mesh":155,"path":22,"pixi-gl-core":12}],162:[function(require,module,exports){'use strict';exports.__esModule=true;var _core=require('../core');var core=_interopRequireWildcard(_core);function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj;}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key];}}newObj.default=obj;return newObj;}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return call&&((typeof call==="undefined"?"undefined":_typeof2(call))==="object"||typeof call==="function")?call:self;}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof2(superClass)));}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass;}/**
 * The ParticleContainer class is a really fast version of the Container built solely for speed,
 * so use when you need a lot of sprites or particles. The tradeoff of the ParticleContainer is that advanced
 * functionality will not work. ParticleContainer implements only the basic object transform (position, scale, rotation).
 * Any other functionality like tinting, masking, etc will not work on sprites in this batch.
 *
 * It's extremely easy to use :
 *
 * ```js
 * let container = new ParticleContainer();
 *
 * for (let i = 0; i < 100; ++i)
 * {
 *     let sprite = new PIXI.Sprite.fromImage("myImage.png");
 *     container.addChild(sprite);
 * }
 * ```
 *
 * And here you have a hundred sprites that will be renderer at the speed of light.
 *
 * @class
 * @extends PIXI.Container
 * @memberof PIXI.particles
 */var ParticleContainer=function(_core$Container){_inherits(ParticleContainer,_core$Container);/**
     * @param {number} [maxSize=15000] - The maximum number of particles that can be renderer by the container.
     * @param {object} [properties] - The properties of children that should be uploaded to the gpu and applied.
     * @param {boolean} [properties.scale=false] - When true, scale be uploaded and applied.
     * @param {boolean} [properties.position=true] - When true, position be uploaded and applied.
     * @param {boolean} [properties.rotation=false] - When true, rotation be uploaded and applied.
     * @param {boolean} [properties.uvs=false] - When true, uvs be uploaded and applied.
     * @param {boolean} [properties.alpha=false] - When true, alpha be uploaded and applied.
     * @param {number} [batchSize=15000] - Number of particles per batch.
     */function ParticleContainer(){var maxSize=arguments.length<=0||arguments[0]===undefined?1500:arguments[0];var properties=arguments[1];var batchSize=arguments.length<=2||arguments[2]===undefined?16384:arguments[2];_classCallCheck(this,ParticleContainer);// Making sure the batch size is valid
// 65535 is max vertex index in the index buffer (see ParticleRenderer)
// so max number of particles is 65536 / 4 = 16384
var _this=_possibleConstructorReturn(this,_core$Container.call(this));var maxBatchSize=16384;if(batchSize>maxBatchSize){batchSize=maxBatchSize;}if(batchSize>maxSize){batchSize=maxSize;}/**
         * Set properties to be dynamic (true) / static (false)
         *
         * @member {boolean[]}
         * @private
         */_this._properties=[false,true,false,false,false];/**
         * @member {number}
         * @private
         */_this._maxSize=maxSize;/**
         * @member {number}
         * @private
         */_this._batchSize=batchSize;/**
         * @member {object<number, WebGLBuffer>}
         * @private
         */_this._glBuffers={};/**
         * @member {number}
         * @private
         */_this._bufferToUpdate=0;/**
         * @member {boolean}
         *
         */_this.interactiveChildren=false;/**
         * The blend mode to be applied to the sprite. Apply a value of `PIXI.BLEND_MODES.NORMAL`
         * to reset the blend mode.
         *
         * @member {number}
         * @default PIXI.BLEND_MODES.NORMAL
         * @see PIXI.BLEND_MODES
         */_this.blendMode=core.BLEND_MODES.NORMAL;/**
         * Used for canvas renderering. If true then the elements will be positioned at the
         * nearest pixel. This provides a nice speed boost.
         *
         * @member {boolean}
         * @default true;
         */_this.roundPixels=true;/**
         * The texture used to render the children.
         *
         * @readonly
         * @member {BaseTexture}
         */_this.baseTexture=null;_this.setProperties(properties);return _this;}/**
     * Sets the private properties array to dynamic / static based on the passed properties object
     *
     * @param {object} properties - The properties to be uploaded
     */ParticleContainer.prototype.setProperties=function setProperties(properties){if(properties){this._properties[0]='scale'in properties?!!properties.scale:this._properties[0];this._properties[1]='position'in properties?!!properties.position:this._properties[1];this._properties[2]='rotation'in properties?!!properties.rotation:this._properties[2];this._properties[3]='uvs'in properties?!!properties.uvs:this._properties[3];this._properties[4]='alpha'in properties?!!properties.alpha:this._properties[4];}};/**
     * Updates the object transform for rendering
     *
     * @private
     */ParticleContainer.prototype.updateTransform=function updateTransform(){// TODO don't need to!
this.displayObjectUpdateTransform();//  PIXI.Container.prototype.updateTransform.call( this );
};/**
     * Renders the container using the WebGL renderer
     *
     * @private
     * @param {PIXI.WebGLRenderer} renderer - The webgl renderer
     */ParticleContainer.prototype.renderWebGL=function renderWebGL(renderer){var _this2=this;if(!this.visible||this.worldAlpha<=0||!this.children.length||!this.renderable){return;}if(!this.baseTexture){this.baseTexture=this.children[0]._texture.baseTexture;if(!this.baseTexture.hasLoaded){this.baseTexture.once('update',function(){return _this2.onChildrenChange(0);});}}renderer.setObjectRenderer(renderer.plugins.particle);renderer.plugins.particle.render(this);};/**
     * Set the flag that static data should be updated to true
     *
     * @private
     * @param {number} smallestChildIndex - The smallest child index
     */ParticleContainer.prototype.onChildrenChange=function onChildrenChange(smallestChildIndex){var bufferIndex=Math.floor(smallestChildIndex/this._batchSize);if(bufferIndex<this._bufferToUpdate){this._bufferToUpdate=bufferIndex;}};/**
     * Renders the object using the Canvas renderer
     *
     * @private
     * @param {PIXI.CanvasRenderer} renderer - The canvas renderer
     */ParticleContainer.prototype.renderCanvas=function renderCanvas(renderer){if(!this.visible||this.worldAlpha<=0||!this.children.length||!this.renderable){return;}var context=renderer.context;var transform=this.worldTransform;var isRotated=true;var positionX=0;var positionY=0;var finalWidth=0;var finalHeight=0;var compositeOperation=renderer.blendModes[this.blendMode];if(compositeOperation!==context.globalCompositeOperation){context.globalCompositeOperation=compositeOperation;}context.globalAlpha=this.worldAlpha;this.displayObjectUpdateTransform();for(var i=0;i<this.children.length;++i){var child=this.children[i];if(!child.visible){continue;}var frame=child._texture.frame;context.globalAlpha=this.worldAlpha*child.alpha;if(child.rotation%(Math.PI*2)===0){// this is the fastest  way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call
if(isRotated){context.setTransform(transform.a,transform.b,transform.c,transform.d,transform.tx*renderer.resolution,transform.ty*renderer.resolution);isRotated=false;}positionX=child.anchor.x*(-frame.width*child.scale.x)+child.position.x+0.5;positionY=child.anchor.y*(-frame.height*child.scale.y)+child.position.y+0.5;finalWidth=frame.width*child.scale.x;finalHeight=frame.height*child.scale.y;}else{if(!isRotated){isRotated=true;}child.displayObjectUpdateTransform();var childTransform=child.worldTransform;if(renderer.roundPixels){context.setTransform(childTransform.a,childTransform.b,childTransform.c,childTransform.d,childTransform.tx*renderer.resolution|0,childTransform.ty*renderer.resolution|0);}else{context.setTransform(childTransform.a,childTransform.b,childTransform.c,childTransform.d,childTransform.tx*renderer.resolution,childTransform.ty*renderer.resolution);}positionX=child.anchor.x*-frame.width+0.5;positionY=child.anchor.y*-frame.height+0.5;finalWidth=frame.width;finalHeight=frame.height;}var resolution=child._texture.baseTexture.resolution;context.drawImage(child._texture.baseTexture.source,frame.x*resolution,frame.y*resolution,frame.width*resolution,frame.height*resolution,positionX*resolution,positionY*resolution,finalWidth*resolution,finalHeight*resolution);}};/**
     * Destroys the container
     *
     * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options
     *  have been set to that value
     * @param {boolean} [options.children=false] - if set to true, all the children will have their
     *  destroy method called as well. 'options' will be passed on to those calls.
     */ParticleContainer.prototype.destroy=function destroy(options){_core$Container.prototype.destroy.call(this,options);if(this._buffers){for(var i=0;i<this._buffers.length;++i){this._buffers[i].destroy();}}this._properties=null;this._buffers=null;};return ParticleContainer;}(core.Container);exports.default=ParticleContainer;},{"../core":61}],163:[function(require,module,exports){'use strict';exports.__esModule=true;var _ParticleContainer=require('./ParticleContainer');Object.defineProperty(exports,'ParticleContainer',{enumerable:true,get:function get(){return _interopRequireDefault(_ParticleContainer).default;}});var _ParticleRenderer=require('./webgl/ParticleRenderer');Object.defineProperty(exports,'ParticleRenderer',{enumerable:true,get:function get(){return _interopRequireDefault(_ParticleRenderer).default;}});function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}},{"./ParticleContainer":162,"./webgl/ParticleRenderer":165}],164:[function(require,module,exports){'use strict';exports.__esModule=true;var _pixiGlCore=require('pixi-gl-core');var _pixiGlCore2=_interopRequireDefault(_pixiGlCore);var _createIndicesForQuads=require('../../core/utils/createIndicesForQuads');var _createIndicesForQuads2=_interopRequireDefault(_createIndicesForQuads);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}/**
 * @author Mat Groves
 *
 * Big thanks to the very clever Matt DesLauriers <mattdesl> https://github.com/mattdesl/
 * for creating the original pixi version!
 * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that
 * they now share 4 bytes on the vertex buffer
 *
 * Heavily inspired by LibGDX's ParticleBuffer:
 * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/ParticleBuffer.java
 *//**
 * The particle buffer manages the static and dynamic buffers for a particle container.
 *
 * @class
 * @private
 * @memberof PIXI
 */var ParticleBuffer=function(){/**
     * @param {WebGLRenderingContext} gl - The rendering context.
     * @param {object} properties - The properties to upload.
     * @param {boolean[]} dynamicPropertyFlags - Flags for which properties are dynamic.
     * @param {number} size - The size of the batch.
     */function ParticleBuffer(gl,properties,dynamicPropertyFlags,size){_classCallCheck(this,ParticleBuffer);/**
         * The current WebGL drawing context.
         *
         * @member {WebGLRenderingContext}
         */this.gl=gl;/**
         * Size of a single vertex.
         *
         * @member {number}
         */this.vertSize=2;/**
         * Size of a single vertex in bytes.
         *
         * @member {number}
         */this.vertByteSize=this.vertSize*4;/**
         * The number of particles the buffer can hold
         *
         * @member {number}
         */this.size=size;/**
         * A list of the properties that are dynamic.
         *
         * @member {object[]}
         */this.dynamicProperties=[];/**
         * A list of the properties that are static.
         *
         * @member {object[]}
         */this.staticProperties=[];for(var i=0;i<properties.length;++i){var property=properties[i];// Make copy of properties object so that when we edit the offset it doesn't
// change all other instances of the object literal
property={attribute:property.attribute,size:property.size,uploadFunction:property.uploadFunction,offset:property.offset};if(dynamicPropertyFlags[i]){this.dynamicProperties.push(property);}else{this.staticProperties.push(property);}}this.staticStride=0;this.staticBuffer=null;this.staticData=null;this.dynamicStride=0;this.dynamicBuffer=null;this.dynamicData=null;this.initBuffers();}/**
     * Sets up the renderer context and necessary buffers.
     *
     * @private
     */ParticleBuffer.prototype.initBuffers=function initBuffers(){var gl=this.gl;var dynamicOffset=0;/**
         * Holds the indices of the geometry (quads) to draw
         *
         * @member {Uint16Array}
         */this.indices=(0,_createIndicesForQuads2.default)(this.size);this.indexBuffer=_pixiGlCore2.default.GLBuffer.createIndexBuffer(gl,this.indices,gl.STATIC_DRAW);this.dynamicStride=0;for(var i=0;i<this.dynamicProperties.length;++i){var property=this.dynamicProperties[i];property.offset=dynamicOffset;dynamicOffset+=property.size;this.dynamicStride+=property.size;}this.dynamicData=new Float32Array(this.size*this.dynamicStride*4);this.dynamicBuffer=_pixiGlCore2.default.GLBuffer.createVertexBuffer(gl,this.dynamicData,gl.STREAM_DRAW);// static //
var staticOffset=0;this.staticStride=0;for(var _i=0;_i<this.staticProperties.length;++_i){var _property=this.staticProperties[_i];_property.offset=staticOffset;staticOffset+=_property.size;this.staticStride+=_property.size;}this.staticData=new Float32Array(this.size*this.staticStride*4);this.staticBuffer=_pixiGlCore2.default.GLBuffer.createVertexBuffer(gl,this.staticData,gl.STATIC_DRAW);this.vao=new _pixiGlCore2.default.VertexArrayObject(gl).addIndex(this.indexBuffer);for(var _i2=0;_i2<this.dynamicProperties.length;++_i2){var _property2=this.dynamicProperties[_i2];this.vao.addAttribute(this.dynamicBuffer,_property2.attribute,gl.FLOAT,false,this.dynamicStride*4,_property2.offset*4);}for(var _i3=0;_i3<this.staticProperties.length;++_i3){var _property3=this.staticProperties[_i3];this.vao.addAttribute(this.staticBuffer,_property3.attribute,gl.FLOAT,false,this.staticStride*4,_property3.offset*4);}};/**
     * Uploads the dynamic properties.
     *
     * @param {PIXI.DisplayObject[]} children - The children to upload.
     * @param {number} startIndex - The index to start at.
     * @param {number} amount - The number to upload.
     */ParticleBuffer.prototype.uploadDynamic=function uploadDynamic(children,startIndex,amount){for(var i=0;i<this.dynamicProperties.length;i++){var property=this.dynamicProperties[i];property.uploadFunction(children,startIndex,amount,this.dynamicData,this.dynamicStride,property.offset);}this.dynamicBuffer.upload();};/**
     * Uploads the static properties.
     *
     * @param {PIXI.DisplayObject[]} children - The children to upload.
     * @param {number} startIndex - The index to start at.
     * @param {number} amount - The number to upload.
     */ParticleBuffer.prototype.uploadStatic=function uploadStatic(children,startIndex,amount){for(var i=0;i<this.staticProperties.length;i++){var property=this.staticProperties[i];property.uploadFunction(children,startIndex,amount,this.staticData,this.staticStride,property.offset);}this.staticBuffer.upload();};/**
     * Destroys the ParticleBuffer.
     *
     */ParticleBuffer.prototype.destroy=function destroy(){this.dynamicProperties=null;this.dynamicData=null;this.dynamicBuffer.destroy();this.staticProperties=null;this.staticData=null;this.staticBuffer.destroy();};return ParticleBuffer;}();exports.default=ParticleBuffer;},{"../../core/utils/createIndicesForQuads":115,"pixi-gl-core":12}],165:[function(require,module,exports){'use strict';exports.__esModule=true;var _core=require('../../core');var core=_interopRequireWildcard(_core);var _ParticleShader=require('./ParticleShader');var _ParticleShader2=_interopRequireDefault(_ParticleShader);var _ParticleBuffer=require('./ParticleBuffer');var _ParticleBuffer2=_interopRequireDefault(_ParticleBuffer);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj;}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key];}}newObj.default=obj;return newObj;}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return call&&((typeof call==="undefined"?"undefined":_typeof2(call))==="object"||typeof call==="function")?call:self;}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof2(superClass)));}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass;}/**
 * @author Mat Groves
 *
 * Big thanks to the very clever Matt DesLauriers <mattdesl> https://github.com/mattdesl/
 * for creating the original pixi version!
 * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they now
 * share 4 bytes on the vertex buffer
 *
 * Heavily inspired by LibGDX's ParticleRenderer:
 * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/ParticleRenderer.java
 *//**
 *
 * @class
 * @private
 * @memberof PIXI
 */var ParticleRenderer=function(_core$ObjectRenderer){_inherits(ParticleRenderer,_core$ObjectRenderer);/**
     * @param {PIXI.WebGLRenderer} renderer - The renderer this sprite batch works for.
     */function ParticleRenderer(renderer){_classCallCheck(this,ParticleRenderer);// 65535 is max vertex index in the index buffer (see ParticleRenderer)
// so max number of particles is 65536 / 4 = 16384
// and max number of element in the index buffer is 16384 * 6 = 98304
// Creating a full index buffer, overhead is 98304 * 2 = 196Ko
// let numIndices = 98304;
/**
         * The default shader that is used if a sprite doesn't have a more specific one.
         *
         * @member {PIXI.Shader}
         */var _this=_possibleConstructorReturn(this,_core$ObjectRenderer.call(this,renderer));_this.shader=null;_this.indexBuffer=null;_this.properties=null;_this.tempMatrix=new core.Matrix();_this.CONTEXT_UID=0;return _this;}/**
     * When there is a WebGL context change
     *
     * @private
     */ParticleRenderer.prototype.onContextChange=function onContextChange(){var gl=this.renderer.gl;this.CONTEXT_UID=this.renderer.CONTEXT_UID;// setup default shader
this.shader=new _ParticleShader2.default(gl);this.properties=[// verticesData
{attribute:this.shader.attributes.aVertexPosition,size:2,uploadFunction:this.uploadVertices,offset:0},// positionData
{attribute:this.shader.attributes.aPositionCoord,size:2,uploadFunction:this.uploadPosition,offset:0},// rotationData
{attribute:this.shader.attributes.aRotation,size:1,uploadFunction:this.uploadRotation,offset:0},// uvsData
{attribute:this.shader.attributes.aTextureCoord,size:2,uploadFunction:this.uploadUvs,offset:0},// alphaData
{attribute:this.shader.attributes.aColor,size:1,uploadFunction:this.uploadAlpha,offset:0}];};/**
     * Starts a new particle batch.
     *
     */ParticleRenderer.prototype.start=function start(){this.renderer.bindShader(this.shader);};/**
     * Renders the particle container object.
     *
     * @param {PIXI.ParticleContainer} container - The container to render using this ParticleRenderer
     */ParticleRenderer.prototype.render=function render(container){var children=container.children;var maxSize=container._maxSize;var batchSize=container._batchSize;var renderer=this.renderer;var totalChildren=children.length;if(totalChildren===0){return;}else if(totalChildren>maxSize){totalChildren=maxSize;}var buffers=container._glBuffers[renderer.CONTEXT_UID];if(!buffers){buffers=container._glBuffers[renderer.CONTEXT_UID]=this.generateBuffers(container);}// if the uvs have not updated then no point rendering just yet!
this.renderer.setBlendMode(container.blendMode);var gl=renderer.gl;var m=container.worldTransform.copy(this.tempMatrix);m.prepend(renderer._activeRenderTarget.projectionMatrix);this.shader.uniforms.projectionMatrix=m.toArray(true);this.shader.uniforms.uAlpha=container.worldAlpha;// make sure the texture is bound..
var baseTexture=children[0]._texture.baseTexture;this.shader.uniforms.uSampler=renderer.bindTexture(baseTexture);// now lets upload and render the buffers..
for(var i=0,j=0;i<totalChildren;i+=batchSize,j+=1){var amount=totalChildren-i;if(amount>batchSize){amount=batchSize;}var buffer=buffers[j];// we always upload the dynamic
buffer.uploadDynamic(children,i,amount);// we only upload the static content when we have to!
if(container._bufferToUpdate===j){buffer.uploadStatic(children,i,amount);container._bufferToUpdate=j+1;}// bind the buffer
renderer.bindVao(buffer.vao);buffer.vao.draw(gl.TRIANGLES,amount*6);}};/**
     * Creates one particle buffer for each child in the container we want to render and updates internal properties
     *
     * @param {PIXI.ParticleContainer} container - The container to render using this ParticleRenderer
     * @return {PIXI.ParticleBuffer[]} The buffers
     */ParticleRenderer.prototype.generateBuffers=function generateBuffers(container){var gl=this.renderer.gl;var buffers=[];var size=container._maxSize;var batchSize=container._batchSize;var dynamicPropertyFlags=container._properties;for(var i=0;i<size;i+=batchSize){buffers.push(new _ParticleBuffer2.default(gl,this.properties,dynamicPropertyFlags,batchSize));}return buffers;};/**
     * Uploads the verticies.
     *
     * @param {PIXI.DisplayObject[]} children - the array of display objects to render
     * @param {number} startIndex - the index to start from in the children array
     * @param {number} amount - the amount of children that will have their vertices uploaded
     * @param {number[]} array - The vertices to upload.
     * @param {number} stride - Stride to use for iteration.
     * @param {number} offset - Offset to start at.
     */ParticleRenderer.prototype.uploadVertices=function uploadVertices(children,startIndex,amount,array,stride,offset){var w0=0;var w1=0;var h0=0;var h1=0;for(var i=0;i<amount;++i){var sprite=children[startIndex+i];var texture=sprite._texture;var sx=sprite.scale.x;var sy=sprite.scale.y;var trim=texture.trim;var orig=texture.orig;if(trim){// if the sprite is trimmed and is not a tilingsprite then we need to add the
// extra space before transforming the sprite coords..
w1=trim.x-sprite.anchor.x*orig.width;w0=w1+trim.width;h1=trim.y-sprite.anchor.y*orig.height;h0=h1+trim.height;}else{w0=orig.width*(1-sprite.anchor.x);w1=orig.width*-sprite.anchor.x;h0=orig.height*(1-sprite.anchor.y);h1=orig.height*-sprite.anchor.y;}array[offset]=w1*sx;array[offset+1]=h1*sy;array[offset+stride]=w0*sx;array[offset+stride+1]=h1*sy;array[offset+stride*2]=w0*sx;array[offset+stride*2+1]=h0*sy;array[offset+stride*3]=w1*sx;array[offset+stride*3+1]=h0*sy;offset+=stride*4;}};/**
     *
     * @param {PIXI.DisplayObject[]} children - the array of display objects to render
     * @param {number} startIndex - the index to start from in the children array
     * @param {number} amount - the amount of children that will have their positions uploaded
     * @param {number[]} array - The vertices to upload.
     * @param {number} stride - Stride to use for iteration.
     * @param {number} offset - Offset to start at.
     */ParticleRenderer.prototype.uploadPosition=function uploadPosition(children,startIndex,amount,array,stride,offset){for(var i=0;i<amount;i++){var spritePosition=children[startIndex+i].position;array[offset]=spritePosition.x;array[offset+1]=spritePosition.y;array[offset+stride]=spritePosition.x;array[offset+stride+1]=spritePosition.y;array[offset+stride*2]=spritePosition.x;array[offset+stride*2+1]=spritePosition.y;array[offset+stride*3]=spritePosition.x;array[offset+stride*3+1]=spritePosition.y;offset+=stride*4;}};/**
     *
     * @param {PIXI.DisplayObject[]} children - the array of display objects to render
     * @param {number} startIndex - the index to start from in the children array
     * @param {number} amount - the amount of children that will have their rotation uploaded
     * @param {number[]} array - The vertices to upload.
     * @param {number} stride - Stride to use for iteration.
     * @param {number} offset - Offset to start at.
     */ParticleRenderer.prototype.uploadRotation=function uploadRotation(children,startIndex,amount,array,stride,offset){for(var i=0;i<amount;i++){var spriteRotation=children[startIndex+i].rotation;array[offset]=spriteRotation;array[offset+stride]=spriteRotation;array[offset+stride*2]=spriteRotation;array[offset+stride*3]=spriteRotation;offset+=stride*4;}};/**
     *
     * @param {PIXI.DisplayObject[]} children - the array of display objects to render
     * @param {number} startIndex - the index to start from in the children array
     * @param {number} amount - the amount of children that will have their rotation uploaded
     * @param {number[]} array - The vertices to upload.
     * @param {number} stride - Stride to use for iteration.
     * @param {number} offset - Offset to start at.
     */ParticleRenderer.prototype.uploadUvs=function uploadUvs(children,startIndex,amount,array,stride,offset){for(var i=0;i<amount;++i){var textureUvs=children[startIndex+i]._texture._uvs;if(textureUvs){array[offset]=textureUvs.x0;array[offset+1]=textureUvs.y0;array[offset+stride]=textureUvs.x1;array[offset+stride+1]=textureUvs.y1;array[offset+stride*2]=textureUvs.x2;array[offset+stride*2+1]=textureUvs.y2;array[offset+stride*3]=textureUvs.x3;array[offset+stride*3+1]=textureUvs.y3;offset+=stride*4;}else{// TODO you know this can be easier!
array[offset]=0;array[offset+1]=0;array[offset+stride]=0;array[offset+stride+1]=0;array[offset+stride*2]=0;array[offset+stride*2+1]=0;array[offset+stride*3]=0;array[offset+stride*3+1]=0;offset+=stride*4;}}};/**
     *
     * @param {PIXI.DisplayObject[]} children - the array of display objects to render
     * @param {number} startIndex - the index to start from in the children array
     * @param {number} amount - the amount of children that will have their rotation uploaded
     * @param {number[]} array - The vertices to upload.
     * @param {number} stride - Stride to use for iteration.
     * @param {number} offset - Offset to start at.
     */ParticleRenderer.prototype.uploadAlpha=function uploadAlpha(children,startIndex,amount,array,stride,offset){for(var i=0;i<amount;i++){var spriteAlpha=children[startIndex+i].alpha;array[offset]=spriteAlpha;array[offset+stride]=spriteAlpha;array[offset+stride*2]=spriteAlpha;array[offset+stride*3]=spriteAlpha;offset+=stride*4;}};/**
     * Destroys the ParticleRenderer.
     *
     */ParticleRenderer.prototype.destroy=function destroy(){if(this.renderer.gl){this.renderer.gl.deleteBuffer(this.indexBuffer);}_core$ObjectRenderer.prototype.destroy.call(this);this.shader.destroy();this.indices=null;this.tempMatrix=null;};return ParticleRenderer;}(core.ObjectRenderer);exports.default=ParticleRenderer;core.WebGLRenderer.registerPlugin('particle',ParticleRenderer);},{"../../core":61,"./ParticleBuffer":164,"./ParticleShader":166}],166:[function(require,module,exports){'use strict';exports.__esModule=true;var _Shader2=require('../../core/Shader');var _Shader3=_interopRequireDefault(_Shader2);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return call&&((typeof call==="undefined"?"undefined":_typeof2(call))==="object"||typeof call==="function")?call:self;}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof2(superClass)));}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass;}/**
 * @class
 * @extends PIXI.Shader
 * @memberof PIXI
 */var ParticleShader=function(_Shader){_inherits(ParticleShader,_Shader);/**
     * @param {PIXI.Shader} gl - The webgl shader manager this shader works for.
     */function ParticleShader(gl){_classCallCheck(this,ParticleShader);return _possibleConstructorReturn(this,_Shader.call(this,gl,// vertex shader
['attribute vec2 aVertexPosition;','attribute vec2 aTextureCoord;','attribute float aColor;','attribute vec2 aPositionCoord;','attribute vec2 aScale;','attribute float aRotation;','uniform mat3 projectionMatrix;','varying vec2 vTextureCoord;','varying float vColor;','void main(void){','   vec2 v = aVertexPosition;','   v.x = (aVertexPosition.x) * cos(aRotation) - (aVertexPosition.y) * sin(aRotation);','   v.y = (aVertexPosition.x) * sin(aRotation) + (aVertexPosition.y) * cos(aRotation);','   v = v + aPositionCoord;','   gl_Position = vec4((projectionMatrix * vec3(v, 1.0)).xy, 0.0, 1.0);','   vTextureCoord = aTextureCoord;','   vColor = aColor;','}'].join('\n'),// hello
['varying vec2 vTextureCoord;','varying float vColor;','uniform sampler2D uSampler;','uniform float uAlpha;','void main(void){','  vec4 color = texture2D(uSampler, vTextureCoord) * vColor * uAlpha;','  if (color.a == 0.0) discard;','  gl_FragColor = color;','}'].join('\n')));}return ParticleShader;}(_Shader3.default);exports.default=ParticleShader;},{"../../core/Shader":41}],167:[function(require,module,exports){"use strict";// References:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign
if(!Math.sign){Math.sign=function mathSign(x){x=Number(x);if(x===0||isNaN(x)){return x;}return x>0?1:-1;};}},{}],168:[function(require,module,exports){'use strict';var _objectAssign=require('object-assign');var _objectAssign2=_interopRequireDefault(_objectAssign);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}if(!Object.assign){Object.assign=_objectAssign2.default;}// References:
// https://github.com/sindresorhus/object-assign
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
},{"object-assign":5}],169:[function(require,module,exports){'use strict';require('./Object.assign');require('./requestAnimationFrame');require('./Math.sign');if(!window.ArrayBuffer){window.ArrayBuffer=Array;}if(!window.Float32Array){window.Float32Array=Array;}if(!window.Uint32Array){window.Uint32Array=Array;}if(!window.Uint16Array){window.Uint16Array=Array;}},{"./Math.sign":167,"./Object.assign":168,"./requestAnimationFrame":170}],170:[function(require,module,exports){(function(global){'use strict';// References:
// http://paulirish.com/2011/requestanimationframe-for-smart-animating/
// https://gist.github.com/1579671
// http://updates.html5rocks.com/2012/05/requestAnimationFrame-API-now-with-sub-millisecond-precision
// https://gist.github.com/timhall/4078614
// https://github.com/Financial-Times/polyfill-service/tree/master/polyfills/requestAnimationFrame
// Expected to be used with Browserfiy
// Browserify automatically detects the use of `global` and passes the
// correct reference of `global`, `self`, and finally `window`
var ONE_FRAME_TIME=16;// Date.now
if(!(Date.now&&Date.prototype.getTime)){Date.now=function now(){return new Date().getTime();};}// performance.now
if(!(global.performance&&global.performance.now)){(function(){var startTime=Date.now();if(!global.performance){global.performance={};}global.performance.now=function(){return Date.now()-startTime;};})();}// requestAnimationFrame
var lastTime=Date.now();var vendors=['ms','moz','webkit','o'];for(var x=0;x<vendors.length&&!global.requestAnimationFrame;++x){var p=vendors[x];global.requestAnimationFrame=global[p+'RequestAnimationFrame'];global.cancelAnimationFrame=global[p+'CancelAnimationFrame']||global[p+'CancelRequestAnimationFrame'];}if(!global.requestAnimationFrame){global.requestAnimationFrame=function(callback){if(typeof callback!=='function'){throw new TypeError(callback+'is not a function');}var currentTime=Date.now();var delay=ONE_FRAME_TIME+lastTime-currentTime;if(delay<0){delay=0;}lastTime=currentTime;return setTimeout(function(){lastTime=Date.now();callback(performance.now());},delay);};}if(!global.cancelAnimationFrame){global.cancelAnimationFrame=function(id){return clearTimeout(id);};}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{});},{}],171:[function(require,module,exports){'use strict';exports.__esModule=true;var _core=require('../core');var core=_interopRequireWildcard(_core);var _CountLimiter=require('./limiters/CountLimiter');var _CountLimiter2=_interopRequireDefault(_CountLimiter);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj;}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key];}}newObj.default=obj;return newObj;}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}var SharedTicker=core.ticker.shared;/**
 * Default number of uploads per frame using prepare plugin.
 *
 * @static
 * @memberof PIXI.settings
 * @name UPLOADS_PER_FRAME
 * @type {number}
 * @default 4
 */core.settings.UPLOADS_PER_FRAME=4;/**
 * The prepare manager provides functionality to upload content to the GPU. BasePrepare handles
 * basic queuing functionality and is extended by {@link PIXI.prepare.WebGLPrepare} and {@link PIXI.prepare.CanvasPrepare}
 * to provide preparation capabilities specific to their respective renderers.
 *
 * @abstract
 * @class
 * @memberof PIXI
 */var BasePrepare=function(){/**
     * @param {PIXI.SystemRenderer} renderer - A reference to the current renderer
     */function BasePrepare(renderer){var _this=this;_classCallCheck(this,BasePrepare);/**
         * The limiter to be used to control how quickly items are prepared.
         * @type {PIXI.prepare.CountLimiter|PIXI.prepare.TimeLimiter}
         */this.limiter=new _CountLimiter2.default(core.settings.UPLOADS_PER_FRAME);/**
         * Reference to the renderer.
         * @type {PIXI.SystemRenderer}
         * @protected
         */this.renderer=renderer;/**
         * The only real difference between CanvasPrepare and WebGLPrepare is what they pass
         * to upload hooks. That different parameter is stored here.
         * @type {PIXI.prepare.CanvasPrepare|PIXI.WebGLRenderer}
         * @protected
         */this.uploadHookHelper=null;/**
         * Collection of items to uploads at once.
         * @type {Array<*>}
         * @private
         */this.queue=[];/**
         * Collection of additional hooks for finding assets.
         * @type {Array<Function>}
         * @private
         */this.addHooks=[];/**
         * Collection of additional hooks for processing assets.
         * @type {Array<Function>}
         * @private
         */this.uploadHooks=[];/**
         * Callback to call after completed.
         * @type {Array<Function>}
         * @private
         */this.completes=[];/**
         * If prepare is ticking (running).
         * @type {boolean}
         * @private
         */this.ticking=false;/**
         * 'bound' call for prepareItems().
         * @type {Function}
         * @private
         */this.delayedTick=function(){// unlikely, but in case we were destroyed between tick() and delayedTick()
if(!_this.queue){return;}_this.prepareItems();};this.register(findText,drawText);this.register(findTextStyle,calculateTextStyle);}/**
     * Upload all the textures and graphics to the GPU.
     *
     * @param {Function|PIXI.DisplayObject|PIXI.Container} item - Either
     *        the container or display object to search for items to upload or
     *        the callback function, if items have been added using `prepare.add`.
     * @param {Function} [done] - Optional callback when all queued uploads have completed
     */BasePrepare.prototype.upload=function upload(item,done){if(typeof item==='function'){done=item;item=null;}// If a display object, search for items
// that we could upload
if(item){this.add(item);}// Get the items for upload from the display
if(this.queue.length){if(done){this.completes.push(done);}if(!this.ticking){this.ticking=true;SharedTicker.addOnce(this.tick,this);}}else if(done){done();}};/**
     * Handle tick update
     *
     * @private
     */BasePrepare.prototype.tick=function tick(){setTimeout(this.delayedTick,0);};/**
     * Actually prepare items. This is handled outside of the tick because it will take a while
     * and we do NOT want to block the current animation frame from rendering.
     *
     * @private
     */BasePrepare.prototype.prepareItems=function prepareItems(){this.limiter.beginFrame();// Upload the graphics
while(this.queue.length&&this.limiter.allowedToUpload()){var item=this.queue[0];var uploaded=false;for(var i=0,len=this.uploadHooks.length;i<len;i++){if(this.uploadHooks[i](this.uploadHookHelper,item)){this.queue.shift();uploaded=true;break;}}if(!uploaded){this.queue.shift();}}// We're finished
if(!this.queue.length){this.ticking=false;var completes=this.completes.slice(0);this.completes.length=0;for(var _i=0,_len=completes.length;_i<_len;_i++){completes[_i]();}}else{// if we are not finished, on the next rAF do this again
SharedTicker.addOnce(this.tick,this);}};/**
     * Adds hooks for finding and uploading items.
     *
     * @param {Function} [addHook] - Function call that takes two parameters: `item:*, queue:Array`
              function must return `true` if it was able to add item to the queue.
     * @param {Function} [uploadHook] - Function call that takes two parameters: `prepare:CanvasPrepare, item:*` and
     *        function must return `true` if it was able to handle upload of item.
     * @return {PIXI.CanvasPrepare} Instance of plugin for chaining.
     */BasePrepare.prototype.register=function register(addHook,uploadHook){if(addHook){this.addHooks.push(addHook);}if(uploadHook){this.uploadHooks.push(uploadHook);}return this;};/**
     * Manually add an item to the uploading queue.
     *
     * @param {PIXI.DisplayObject|PIXI.Container|*} item - Object to add to the queue
     * @return {PIXI.CanvasPrepare} Instance of plugin for chaining.
     */BasePrepare.prototype.add=function add(item){// Add additional hooks for finding elements on special
// types of objects that
for(var i=0,len=this.addHooks.length;i<len;i++){if(this.addHooks[i](item,this.queue)){break;}}// Get childen recursively
if(item instanceof core.Container){for(var _i2=item.children.length-1;_i2>=0;_i2--){this.add(item.children[_i2]);}}return this;};/**
     * Destroys the plugin, don't use after this.
     *
     */BasePrepare.prototype.destroy=function destroy(){if(this.ticking){SharedTicker.remove(this.tick,this);}this.ticking=false;this.addHooks=null;this.uploadHooks=null;this.renderer=null;this.completes=null;this.queue=null;this.limiter=null;this.uploadHookHelper=null;};return BasePrepare;}();/**
 * Built-in hook to draw PIXI.Text to its texture.
 *
 * @private
 * @param {PIXI.WebGLRenderer|PIXI.CanvasPrepare} helper - Not used by this upload handler
 * @param {PIXI.DisplayObject} item - Item to check
 * @return {boolean} If item was uploaded.
 */exports.default=BasePrepare;function drawText(helper,item){if(item instanceof core.Text){// updating text will return early if it is not dirty
item.updateText(true);return true;}return false;}/**
 * Built-in hook to calculate a text style for a PIXI.Text object.
 *
 * @private
 * @param {PIXI.WebGLRenderer|PIXI.CanvasPrepare} helper - Not used by this upload handler
 * @param {PIXI.DisplayObject} item - Item to check
 * @return {boolean} If item was uploaded.
 */function calculateTextStyle(helper,item){if(item instanceof core.TextStyle){var font=core.Text.getFontStyle(item);if(!core.Text.fontPropertiesCache[font]){core.Text.calculateFontProperties(font);}return true;}return false;}/**
 * Built-in hook to find Text objects.
 *
 * @private
 * @param {PIXI.DisplayObject} item - Display object to check
 * @param {Array<*>} queue - Collection of items to upload
 * @return {boolean} if a PIXI.Text object was found.
 */function findText(item,queue){if(item instanceof core.Text){// push the text style to prepare it - this can be really expensive
if(queue.indexOf(item.style)===-1){queue.push(item.style);}// also push the text object so that we can render it (to canvas/texture) if needed
if(queue.indexOf(item)===-1){queue.push(item);}// also push the Text's texture for upload to GPU
var texture=item._texture.baseTexture;if(queue.indexOf(texture)===-1){queue.push(texture);}return true;}return false;}/**
 * Built-in hook to find TextStyle objects.
 *
 * @private
 * @param {PIXI.TextStyle} item - Display object to check
 * @param {Array<*>} queue - Collection of items to upload
 * @return {boolean} if a PIXI.TextStyle object was found.
 */function findTextStyle(item,queue){if(item instanceof core.TextStyle){if(queue.indexOf(item)===-1){queue.push(item);}return true;}return false;}},{"../core":61,"./limiters/CountLimiter":174}],172:[function(require,module,exports){'use strict';exports.__esModule=true;var _core=require('../../core');var core=_interopRequireWildcard(_core);var _BasePrepare2=require('../BasePrepare');var _BasePrepare3=_interopRequireDefault(_BasePrepare2);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj;}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key];}}newObj.default=obj;return newObj;}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return call&&((typeof call==="undefined"?"undefined":_typeof2(call))==="object"||typeof call==="function")?call:self;}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof2(superClass)));}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass;}var CANVAS_START_SIZE=16;/**
 * The prepare manager provides functionality to upload content to the GPU
 * This cannot be done directly for Canvas like in WebGL, but the effect can be achieved by drawing
 * textures to an offline canvas.
 * This draw call will force the texture to be moved onto the GPU.
 *
 * @class
 * @memberof PIXI
 */var CanvasPrepare=function(_BasePrepare){_inherits(CanvasPrepare,_BasePrepare);/**
     * @param {PIXI.CanvasRenderer} renderer - A reference to the current renderer
     */function CanvasPrepare(renderer){_classCallCheck(this,CanvasPrepare);var _this=_possibleConstructorReturn(this,_BasePrepare.call(this,renderer));_this.uploadHookHelper=_this;/**
        * An offline canvas to render textures to
        * @type {HTMLCanvasElement}
        * @private
        */_this.canvas=document.createElement('canvas');_this.canvas.width=CANVAS_START_SIZE;_this.canvas.height=CANVAS_START_SIZE;/**
         * The context to the canvas
        * @type {CanvasRenderingContext2D}
        * @private
        */_this.ctx=_this.canvas.getContext('2d');// Add textures to upload
_this.register(findBaseTextures,uploadBaseTextures);return _this;}/**
     * Destroys the plugin, don't use after this.
     *
     */CanvasPrepare.prototype.destroy=function destroy(){_BasePrepare.prototype.destroy.call(this);this.ctx=null;this.canvas=null;};return CanvasPrepare;}(_BasePrepare3.default);/**
 * Built-in hook to upload PIXI.Texture objects to the GPU.
 *
 * @private
 * @param {*} prepare - Instance of CanvasPrepare
 * @param {*} item - Item to check
 * @return {boolean} If item was uploaded.
 */exports.default=CanvasPrepare;function uploadBaseTextures(prepare,item){if(item instanceof core.BaseTexture){var image=item.source;// Sometimes images (like atlas images) report a size of zero, causing errors on windows phone.
// So if the width or height is equal to zero then use the canvas size
// Otherwise use whatever is smaller, the image dimensions or the canvas dimensions.
var imageWidth=image.width===0?prepare.canvas.width:Math.min(prepare.canvas.width,image.width);var imageHeight=image.height===0?prepare.canvas.height:Math.min(prepare.canvas.height,image.height);// Only a small subsections is required to be drawn to have the whole texture uploaded to the GPU
// A smaller draw can be faster.
prepare.ctx.drawImage(image,0,0,imageWidth,imageHeight,0,0,prepare.canvas.width,prepare.canvas.height);return true;}return false;}/**
 * Built-in hook to find textures from Sprites.
 *
 * @private
 * @param {PIXI.DisplayObject} item  -Display object to check
 * @param {Array<*>} queue - Collection of items to upload
 * @return {boolean} if a PIXI.Texture object was found.
 */function findBaseTextures(item,queue){// Objects with textures, like Sprites/Text
if(item instanceof core.BaseTexture){if(queue.indexOf(item)===-1){queue.push(item);}return true;}else if(item._texture&&item._texture instanceof core.Texture){var texture=item._texture.baseTexture;if(queue.indexOf(texture)===-1){queue.push(texture);}return true;}return false;}core.CanvasRenderer.registerPlugin('prepare',CanvasPrepare);},{"../../core":61,"../BasePrepare":171}],173:[function(require,module,exports){'use strict';exports.__esModule=true;var _WebGLPrepare=require('./webgl/WebGLPrepare');Object.defineProperty(exports,'webgl',{enumerable:true,get:function get(){return _interopRequireDefault(_WebGLPrepare).default;}});var _CanvasPrepare=require('./canvas/CanvasPrepare');Object.defineProperty(exports,'canvas',{enumerable:true,get:function get(){return _interopRequireDefault(_CanvasPrepare).default;}});var _BasePrepare=require('./BasePrepare');Object.defineProperty(exports,'BasePrepare',{enumerable:true,get:function get(){return _interopRequireDefault(_BasePrepare).default;}});var _CountLimiter=require('./limiters/CountLimiter');Object.defineProperty(exports,'CountLimiter',{enumerable:true,get:function get(){return _interopRequireDefault(_CountLimiter).default;}});var _TimeLimiter=require('./limiters/TimeLimiter');Object.defineProperty(exports,'TimeLimiter',{enumerable:true,get:function get(){return _interopRequireDefault(_TimeLimiter).default;}});function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}},{"./BasePrepare":171,"./canvas/CanvasPrepare":172,"./limiters/CountLimiter":174,"./limiters/TimeLimiter":175,"./webgl/WebGLPrepare":176}],174:[function(require,module,exports){"use strict";exports.__esModule=true;function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}/**
 * CountLimiter limits the number of items handled by a {@link PIXI.prepare.BasePrepare} to a specified
 * number of items per frame.
 *
 * @class
 * @memberof PIXI
 */var CountLimiter=function(){/**
   * @param {number} maxItemsPerFrame - The maximum number of items that can be prepared each frame.
   */function CountLimiter(maxItemsPerFrame){_classCallCheck(this,CountLimiter);/**
     * The maximum number of items that can be prepared each frame.
     * @private
     */this.maxItemsPerFrame=maxItemsPerFrame;/**
     * The number of items that can be prepared in the current frame.
     * @type {number}
     * @private
     */this.itemsLeft=0;}/**
   * Resets any counting properties to start fresh on a new frame.
   */CountLimiter.prototype.beginFrame=function beginFrame(){this.itemsLeft=this.maxItemsPerFrame;};/**
   * Checks to see if another item can be uploaded. This should only be called once per item.
   * @return {boolean} If the item is allowed to be uploaded.
   */CountLimiter.prototype.allowedToUpload=function allowedToUpload(){return this.itemsLeft-->0;};return CountLimiter;}();exports.default=CountLimiter;},{}],175:[function(require,module,exports){"use strict";exports.__esModule=true;function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}/**
 * TimeLimiter limits the number of items handled by a {@link PIXI.BasePrepare} to a specified
 * number of milliseconds per frame.
 *
 * @class
 * @memberof PIXI
 */var TimeLimiter=function(){/**
   * @param {number} maxMilliseconds - The maximum milliseconds that can be spent preparing items each frame.
   */function TimeLimiter(maxMilliseconds){_classCallCheck(this,TimeLimiter);/**
     * The maximum milliseconds that can be spent preparing items each frame.
     * @private
     */this.maxMilliseconds=maxMilliseconds;/**
     * The start time of the current frame.
     * @type {number}
     * @private
     */this.frameStart=0;}/**
   * Resets any counting properties to start fresh on a new frame.
   */TimeLimiter.prototype.beginFrame=function beginFrame(){this.frameStart=Date.now();};/**
   * Checks to see if another item can be uploaded. This should only be called once per item.
   * @return {boolean} If the item is allowed to be uploaded.
   */TimeLimiter.prototype.allowedToUpload=function allowedToUpload(){return Date.now()-this.frameStart<this.maxMilliseconds;};return TimeLimiter;}();exports.default=TimeLimiter;},{}],176:[function(require,module,exports){'use strict';exports.__esModule=true;var _core=require('../../core');var core=_interopRequireWildcard(_core);var _BasePrepare2=require('../BasePrepare');var _BasePrepare3=_interopRequireDefault(_BasePrepare2);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj;}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key];}}newObj.default=obj;return newObj;}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return call&&((typeof call==="undefined"?"undefined":_typeof2(call))==="object"||typeof call==="function")?call:self;}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof2(superClass)));}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass;}/**
 * The prepare manager provides functionality to upload content to the GPU.
 *
 * @class
 * @memberof PIXI
 */var WebGLPrepare=function(_BasePrepare){_inherits(WebGLPrepare,_BasePrepare);/**
     * @param {PIXI.WebGLRenderer} renderer - A reference to the current renderer
     */function WebGLPrepare(renderer){_classCallCheck(this,WebGLPrepare);var _this=_possibleConstructorReturn(this,_BasePrepare.call(this,renderer));_this.uploadHookHelper=_this.renderer;// Add textures and graphics to upload
_this.register(findBaseTextures,uploadBaseTextures).register(findGraphics,uploadGraphics);return _this;}return WebGLPrepare;}(_BasePrepare3.default);/**
 * Built-in hook to upload PIXI.Texture objects to the GPU.
 *
 * @private
 * @param {PIXI.WebGLRenderer} renderer - instance of the webgl renderer
 * @param {PIXI.DisplayObject} item - Item to check
 * @return {boolean} If item was uploaded.
 */exports.default=WebGLPrepare;function uploadBaseTextures(renderer,item){if(item instanceof core.BaseTexture){// if the texture already has a GL texture, then the texture has been prepared or rendered
// before now. If the texture changed, then the changer should be calling texture.update() which
// reuploads the texture without need for preparing it again
if(!item._glTextures[renderer.CONTEXT_UID]){renderer.textureManager.updateTexture(item);}return true;}return false;}/**
 * Built-in hook to upload PIXI.Graphics to the GPU.
 *
 * @private
 * @param {PIXI.WebGLRenderer} renderer - instance of the webgl renderer
 * @param {PIXI.DisplayObject} item - Item to check
 * @return {boolean} If item was uploaded.
 */function uploadGraphics(renderer,item){if(item instanceof core.Graphics){// if the item is not dirty and already has webgl data, then it got prepared or rendered
// before now and we shouldn't waste time updating it again
if(item.dirty||item.clearDirty||!item._webGL[renderer.plugins.graphics.CONTEXT_UID]){renderer.plugins.graphics.updateGraphics(item);}return true;}return false;}/**
 * Built-in hook to find textures from Sprites.
 *
 * @private
 * @param {PIXI.DisplayObject} item - Display object to check
 * @param {Array<*>} queue - Collection of items to upload
 * @return {boolean} if a PIXI.Texture object was found.
 */function findBaseTextures(item,queue){// Objects with textures, like Sprites/Text
if(item instanceof core.BaseTexture){if(queue.indexOf(item)===-1){queue.push(item);}return true;}else if(item._texture&&item._texture instanceof core.Texture){var texture=item._texture.baseTexture;if(queue.indexOf(texture)===-1){queue.push(texture);}return true;}return false;}/**
 * Built-in hook to find graphics.
 *
 * @private
 * @param {PIXI.DisplayObject} item - Display object to check
 * @param {Array<*>} queue - Collection of items to upload
 * @return {boolean} if a PIXI.Graphics object was found.
 */function findGraphics(item,queue){if(item instanceof core.Graphics){queue.push(item);return true;}return false;}core.WebGLRenderer.registerPlugin('prepare',WebGLPrepare);},{"../../core":61,"../BasePrepare":171}],177:[function(require,module,exports){(function(global){'use strict';exports.__esModule=true;exports.loader=exports.prepare=exports.particles=exports.mesh=exports.loaders=exports.interaction=exports.filters=exports.extras=exports.extract=exports.accessibility=undefined;var _deprecation=require('./deprecation');Object.keys(_deprecation).forEach(function(key){if(key==="default"||key==="__esModule")return;Object.defineProperty(exports,key,{enumerable:true,get:function get(){return _deprecation[key];}});});var _core=require('./core');Object.keys(_core).forEach(function(key){if(key==="default"||key==="__esModule")return;Object.defineProperty(exports,key,{enumerable:true,get:function get(){return _core[key];}});});require('./polyfill');var _accessibility=require('./accessibility');var accessibility=_interopRequireWildcard(_accessibility);var _extract=require('./extract');var extract=_interopRequireWildcard(_extract);var _extras=require('./extras');var extras=_interopRequireWildcard(_extras);var _filters=require('./filters');var filters=_interopRequireWildcard(_filters);var _interaction=require('./interaction');var interaction=_interopRequireWildcard(_interaction);var _loaders=require('./loaders');var loaders=_interopRequireWildcard(_loaders);var _mesh=require('./mesh');var mesh=_interopRequireWildcard(_mesh);var _particles=require('./particles');var particles=_interopRequireWildcard(_particles);var _prepare=require('./prepare');var prepare=_interopRequireWildcard(_prepare);function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj;}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key];}}newObj.default=obj;return newObj;}}// import polyfills
exports.accessibility=accessibility;exports.extract=extract;exports.extras=extras;exports.filters=filters;exports.interaction=interaction;exports.loaders=loaders;exports.mesh=mesh;exports.particles=particles;exports.prepare=prepare;/**
 * A premade instance of the loader that can be used to load resources.
 *
 * @name loader
 * @memberof PIXI
 * @property {PIXI.loaders.Loader}
 */// export libs
// export core
var loader=loaders&&loaders.Loader?new loaders.Loader():null;// check is there in case user excludes loader lib
exports.loader=loader;// Always export pixi globally.
global.PIXI=exports;// eslint-disable-line
}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{});},{"./accessibility":40,"./core":61,"./deprecation":120,"./extract":122,"./extras":131,"./filters":142,"./interaction":148,"./loaders":151,"./mesh":160,"./particles":163,"./polyfill":169,"./prepare":173}]},{},[177])(177);});//# sourceMappingURL=pixi.js.map
/*!
 * VERSION: 1.19.1
 * DATE: 2017-01-17
 * UPDATES AND DOCS AT: http://greensock.com
 * 
 * Includes all of the following: TweenLite, TweenMax, TimelineLite, TimelineMax, EasePack, CSSPlugin, RoundPropsPlugin, BezierPlugin, AttrPlugin, DirectionalRotationPlugin
 *
 * @license Copyright (c) 2008-2017, GreenSock. All rights reserved.
 * This work is subject to the terms at http://greensock.com/standard-license or for
 * Club GreenSock members, the software agreement that was issued with your membership.
 * 
 * @author: Jack Doyle, jack@greensock.com
 **/
var _gsScope = (typeof(module) !== "undefined" && module.exports && typeof(global) !== "undefined") ? global : this || window; //helps ensure compatibility with AMD/RequireJS and CommonJS/Node
(_gsScope._gsQueue || (_gsScope._gsQueue = [])).push( function() {

	"use strict";

	_gsScope._gsDefine("TweenMax", ["core.Animation","core.SimpleTimeline","TweenLite"], function(Animation, SimpleTimeline, TweenLite) {

		var _slice = function(a) { //don't use [].slice because that doesn't work in IE8 with a NodeList that's returned by querySelectorAll()
				var b = [],
					l = a.length,
					i;
				for (i = 0; i !== l; b.push(a[i++]));
				return b;
			},
			_applyCycle = function(vars, targets, i) {
				var alt = vars.cycle,
					p, val;
				for (p in alt) {
					val = alt[p];
					vars[p] = (typeof(val) === "function") ? val(i, targets[i]) : val[i % val.length];
				}
				delete vars.cycle;
			},
			TweenMax = function(target, duration, vars) {
				TweenLite.call(this, target, duration, vars);
				this._cycle = 0;
				this._yoyo = (this.vars.yoyo === true);
				this._repeat = this.vars.repeat || 0;
				this._repeatDelay = this.vars.repeatDelay || 0;
				this._dirty = true; //ensures that if there is any repeat, the totalDuration will get recalculated to accurately report it.
				this.render = TweenMax.prototype.render; //speed optimization (avoid prototype lookup on this "hot" method)
			},
			_tinyNum = 0.0000000001,
			TweenLiteInternals = TweenLite._internals,
			_isSelector = TweenLiteInternals.isSelector,
			_isArray = TweenLiteInternals.isArray,
			p = TweenMax.prototype = TweenLite.to({}, 0.1, {}),
			_blankArray = [];

		TweenMax.version = "1.19.1";
		p.constructor = TweenMax;
		p.kill()._gc = false;
		TweenMax.killTweensOf = TweenMax.killDelayedCallsTo = TweenLite.killTweensOf;
		TweenMax.getTweensOf = TweenLite.getTweensOf;
		TweenMax.lagSmoothing = TweenLite.lagSmoothing;
		TweenMax.ticker = TweenLite.ticker;
		TweenMax.render = TweenLite.render;

		p.invalidate = function() {
			this._yoyo = (this.vars.yoyo === true);
			this._repeat = this.vars.repeat || 0;
			this._repeatDelay = this.vars.repeatDelay || 0;
			this._uncache(true);
			return TweenLite.prototype.invalidate.call(this);
		};
		
		p.updateTo = function(vars, resetDuration) {
			var curRatio = this.ratio,
				immediate = this.vars.immediateRender || vars.immediateRender,
				p;
			if (resetDuration && this._startTime < this._timeline._time) {
				this._startTime = this._timeline._time;
				this._uncache(false);
				if (this._gc) {
					this._enabled(true, false);
				} else {
					this._timeline.insert(this, this._startTime - this._delay); //ensures that any necessary re-sequencing of Animations in the timeline occurs to make sure the rendering order is correct.
				}
			}
			for (p in vars) {
				this.vars[p] = vars[p];
			}
			if (this._initted || immediate) {
				if (resetDuration) {
					this._initted = false;
					if (immediate) {
						this.render(0, true, true);
					}
				} else {
					if (this._gc) {
						this._enabled(true, false);
					}
					if (this._notifyPluginsOfEnabled && this._firstPT) {
						TweenLite._onPluginEvent("_onDisable", this); //in case a plugin like MotionBlur must perform some cleanup tasks
					}
					if (this._time / this._duration > 0.998) { //if the tween has finished (or come extremely close to finishing), we just need to rewind it to 0 and then render it again at the end which forces it to re-initialize (parsing the new vars). We allow tweens that are close to finishing (but haven't quite finished) to work this way too because otherwise, the values are so small when determining where to project the starting values that binary math issues creep in and can make the tween appear to render incorrectly when run backwards. 
						var prevTime = this._totalTime;
						this.render(0, true, false);
						this._initted = false;
						this.render(prevTime, true, false);
					} else {
						this._initted = false;
						this._init();
						if (this._time > 0 || immediate) {
							var inv = 1 / (1 - curRatio),
								pt = this._firstPT, endValue;
							while (pt) {
								endValue = pt.s + pt.c;
								pt.c *= inv;
								pt.s = endValue - pt.c;
								pt = pt._next;
							}
						}
					}
				}
			}
			return this;
		};
				
		p.render = function(time, suppressEvents, force) {
			if (!this._initted) if (this._duration === 0 && this.vars.repeat) { //zero duration tweens that render immediately have render() called from TweenLite's constructor, before TweenMax's constructor has finished setting _repeat, _repeatDelay, and _yoyo which are critical in determining totalDuration() so we need to call invalidate() which is a low-kb way to get those set properly.
				this.invalidate();
			}
			var totalDur = (!this._dirty) ? this._totalDuration : this.totalDuration(),
				prevTime = this._time,
				prevTotalTime = this._totalTime, 
				prevCycle = this._cycle,
				duration = this._duration,
				prevRawPrevTime = this._rawPrevTime,
				isComplete, callback, pt, cycleDuration, r, type, pow, rawPrevTime;
			if (time >= totalDur - 0.0000001 && time >= 0) { //to work around occasional floating point math artifacts.
				this._totalTime = totalDur;
				this._cycle = this._repeat;
				if (this._yoyo && (this._cycle & 1) !== 0) {
					this._time = 0;
					this.ratio = this._ease._calcEnd ? this._ease.getRatio(0) : 0;
				} else {
					this._time = duration;
					this.ratio = this._ease._calcEnd ? this._ease.getRatio(1) : 1;
				}
				if (!this._reversed) {
					isComplete = true;
					callback = "onComplete";
					force = (force || this._timeline.autoRemoveChildren); //otherwise, if the animation is unpaused/activated after it's already finished, it doesn't get removed from the parent timeline.
				}
				if (duration === 0) if (this._initted || !this.vars.lazy || force) { //zero-duration tweens are tricky because we must discern the momentum/direction of time in order to determine whether the starting values should be rendered or the ending values. If the "playhead" of its timeline goes past the zero-duration tween in the forward direction or lands directly on it, the end values should be rendered, but if the timeline's "playhead" moves past it in the backward direction (from a postitive time to a negative time), the starting values must be rendered.
					if (this._startTime === this._timeline._duration) { //if a zero-duration tween is at the VERY end of a timeline and that timeline renders at its end, it will typically add a tiny bit of cushion to the render time to prevent rounding errors from getting in the way of tweens rendering their VERY end. If we then reverse() that timeline, the zero-duration tween will trigger its onReverseComplete even though technically the playhead didn't pass over it again. It's a very specific edge case we must accommodate.
						time = 0;
					}
					if (prevRawPrevTime < 0 || (time <= 0 && time >= -0.0000001) || (prevRawPrevTime === _tinyNum && this.data !== "isPause")) if (prevRawPrevTime !== time) { //note: when this.data is "isPause", it's a callback added by addPause() on a timeline that we should not be triggered when LEAVING its exact start time. In other words, tl.addPause(1).play(1) shouldn't pause.
						force = true;
						if (prevRawPrevTime > _tinyNum) {
							callback = "onReverseComplete";
						}
					}
					this._rawPrevTime = rawPrevTime = (!suppressEvents || time || prevRawPrevTime === time) ? time : _tinyNum; //when the playhead arrives at EXACTLY time 0 (right on top) of a zero-duration tween, we need to discern if events are suppressed so that when the playhead moves again (next time), it'll trigger the callback. If events are NOT suppressed, obviously the callback would be triggered in this render. Basically, the callback should fire either when the playhead ARRIVES or LEAVES this exact spot, not both. Imagine doing a timeline.seek(0) and there's a callback that sits at 0. Since events are suppressed on that seek() by default, nothing will fire, but when the playhead moves off of that position, the callback should fire. This behavior is what people intuitively expect. We set the _rawPrevTime to be a precise tiny number to indicate this scenario rather than using another property/variable which would increase memory usage. This technique is less readable, but more efficient.
				}
				
			} else if (time < 0.0000001) { //to work around occasional floating point math artifacts, round super small values to 0.
				this._totalTime = this._time = this._cycle = 0;
				this.ratio = this._ease._calcEnd ? this._ease.getRatio(0) : 0;
				if (prevTotalTime !== 0 || (duration === 0 && prevRawPrevTime > 0)) {
					callback = "onReverseComplete";
					isComplete = this._reversed;
				}
				if (time < 0) {
					this._active = false;
					if (duration === 0) if (this._initted || !this.vars.lazy || force) { //zero-duration tweens are tricky because we must discern the momentum/direction of time in order to determine whether the starting values should be rendered or the ending values. If the "playhead" of its timeline goes past the zero-duration tween in the forward direction or lands directly on it, the end values should be rendered, but if the timeline's "playhead" moves past it in the backward direction (from a postitive time to a negative time), the starting values must be rendered.
						if (prevRawPrevTime >= 0) {
							force = true;
						}
						this._rawPrevTime = rawPrevTime = (!suppressEvents || time || prevRawPrevTime === time) ? time : _tinyNum; //when the playhead arrives at EXACTLY time 0 (right on top) of a zero-duration tween, we need to discern if events are suppressed so that when the playhead moves again (next time), it'll trigger the callback. If events are NOT suppressed, obviously the callback would be triggered in this render. Basically, the callback should fire either when the playhead ARRIVES or LEAVES this exact spot, not both. Imagine doing a timeline.seek(0) and there's a callback that sits at 0. Since events are suppressed on that seek() by default, nothing will fire, but when the playhead moves off of that position, the callback should fire. This behavior is what people intuitively expect. We set the _rawPrevTime to be a precise tiny number to indicate this scenario rather than using another property/variable which would increase memory usage. This technique is less readable, but more efficient.
					}
				}
				if (!this._initted) { //if we render the very beginning (time == 0) of a fromTo(), we must force the render (normal tweens wouldn't need to render at a time of 0 when the prevTime was also 0). This is also mandatory to make sure overwriting kicks in immediately.
					force = true;
				}
			} else {
				this._totalTime = this._time = time;
				if (this._repeat !== 0) {
					cycleDuration = duration + this._repeatDelay;
					this._cycle = (this._totalTime / cycleDuration) >> 0; //originally _totalTime % cycleDuration but floating point errors caused problems, so I normalized it. (4 % 0.8 should be 0 but some browsers report it as 0.79999999!)
					if (this._cycle !== 0) if (this._cycle === this._totalTime / cycleDuration && prevTotalTime <= time) {
						this._cycle--; //otherwise when rendered exactly at the end time, it will act as though it is repeating (at the beginning)
					}
					this._time = this._totalTime - (this._cycle * cycleDuration);
					if (this._yoyo) if ((this._cycle & 1) !== 0) {
						this._time = duration - this._time;
					}
					if (this._time > duration) {
						this._time = duration;
					} else if (this._time < 0) {
						this._time = 0;
					}
				}

				if (this._easeType) {
					r = this._time / duration;
					type = this._easeType;
					pow = this._easePower;
					if (type === 1 || (type === 3 && r >= 0.5)) {
						r = 1 - r;
					}
					if (type === 3) {
						r *= 2;
					}
					if (pow === 1) {
						r *= r;
					} else if (pow === 2) {
						r *= r * r;
					} else if (pow === 3) {
						r *= r * r * r;
					} else if (pow === 4) {
						r *= r * r * r * r;
					}

					if (type === 1) {
						this.ratio = 1 - r;
					} else if (type === 2) {
						this.ratio = r;
					} else if (this._time / duration < 0.5) {
						this.ratio = r / 2;
					} else {
						this.ratio = 1 - (r / 2);
					}

				} else {
					this.ratio = this._ease.getRatio(this._time / duration);
				}
				
			}
				
			if (prevTime === this._time && !force && prevCycle === this._cycle) {
				if (prevTotalTime !== this._totalTime) if (this._onUpdate) if (!suppressEvents) { //so that onUpdate fires even during the repeatDelay - as long as the totalTime changed, we should trigger onUpdate.
					this._callback("onUpdate");
				}
				return;
			} else if (!this._initted) {
				this._init();
				if (!this._initted || this._gc) { //immediateRender tweens typically won't initialize until the playhead advances (_time is greater than 0) in order to ensure that overwriting occurs properly. Also, if all of the tweening properties have been overwritten (which would cause _gc to be true, as set in _init()), we shouldn't continue otherwise an onStart callback could be called for example.
					return;
				} else if (!force && this._firstPT && ((this.vars.lazy !== false && this._duration) || (this.vars.lazy && !this._duration))) { //we stick it in the queue for rendering at the very end of the tick - this is a performance optimization because browsers invalidate styles and force a recalculation if you read, write, and then read style data (so it's better to read/read/read/write/write/write than read/write/read/write/read/write). The down side, of course, is that usually you WANT things to render immediately because you may have code running right after that which depends on the change. Like imagine running TweenLite.set(...) and then immediately after that, creating a nother tween that animates the same property to another value; the starting values of that 2nd tween wouldn't be accurate if lazy is true.
					this._time = prevTime;
					this._totalTime = prevTotalTime;
					this._rawPrevTime = prevRawPrevTime;
					this._cycle = prevCycle;
					TweenLiteInternals.lazyTweens.push(this);
					this._lazy = [time, suppressEvents];
					return;
				}
				//_ease is initially set to defaultEase, so now that init() has run, _ease is set properly and we need to recalculate the ratio. Overall this is faster than using conditional logic earlier in the method to avoid having to set ratio twice because we only init() once but renderTime() gets called VERY frequently.
				if (this._time && !isComplete) {
					this.ratio = this._ease.getRatio(this._time / duration);
				} else if (isComplete && this._ease._calcEnd) {
					this.ratio = this._ease.getRatio((this._time === 0) ? 0 : 1);
				}
			}
			if (this._lazy !== false) {
				this._lazy = false;
			}

			if (!this._active) if (!this._paused && this._time !== prevTime && time >= 0) {
				this._active = true; //so that if the user renders a tween (as opposed to the timeline rendering it), the timeline is forced to re-render and align it with the proper time/frame on the next rendering cycle. Maybe the tween already finished but the user manually re-renders it as halfway done.
			}
			if (prevTotalTime === 0) {
				if (this._initted === 2 && time > 0) {
					//this.invalidate();
					this._init(); //will just apply overwriting since _initted of (2) means it was a from() tween that had immediateRender:true
				}
				if (this._startAt) {
					if (time >= 0) {
						this._startAt.render(time, suppressEvents, force);
					} else if (!callback) {
						callback = "_dummyGS"; //if no callback is defined, use a dummy value just so that the condition at the end evaluates as true because _startAt should render AFTER the normal render loop when the time is negative. We could handle this in a more intuitive way, of course, but the render loop is the MOST important thing to optimize, so this technique allows us to avoid adding extra conditional logic in a high-frequency area.
					}
				}
				if (this.vars.onStart) if (this._totalTime !== 0 || duration === 0) if (!suppressEvents) {
					this._callback("onStart");
				}
			}
			
			pt = this._firstPT;
			while (pt) {
				if (pt.f) {
					pt.t[pt.p](pt.c * this.ratio + pt.s);
				} else {
					pt.t[pt.p] = pt.c * this.ratio + pt.s;
				}
				pt = pt._next;
			}
			
			if (this._onUpdate) {
				if (time < 0) if (this._startAt && this._startTime) { //if the tween is positioned at the VERY beginning (_startTime 0) of its parent timeline, it's illegal for the playhead to go back further, so we should not render the recorded startAt values.
					this._startAt.render(time, suppressEvents, force); //note: for performance reasons, we tuck this conditional logic inside less traveled areas (most tweens don't have an onUpdate). We'd just have it at the end before the onComplete, but the values should be updated before any onUpdate is called, so we ALSO put it here and then if it's not called, we do so later near the onComplete.
				}
				if (!suppressEvents) if (this._totalTime !== prevTotalTime || callback) {
					this._callback("onUpdate");
				}
			}
			if (this._cycle !== prevCycle) if (!suppressEvents) if (!this._gc) if (this.vars.onRepeat) {
				this._callback("onRepeat");
			}
			if (callback) if (!this._gc || force) { //check gc because there's a chance that kill() could be called in an onUpdate
				if (time < 0 && this._startAt && !this._onUpdate && this._startTime) { //if the tween is positioned at the VERY beginning (_startTime 0) of its parent timeline, it's illegal for the playhead to go back further, so we should not render the recorded startAt values.
					this._startAt.render(time, suppressEvents, force);
				}
				if (isComplete) {
					if (this._timeline.autoRemoveChildren) {
						this._enabled(false, false);
					}
					this._active = false;
				}
				if (!suppressEvents && this.vars[callback]) {
					this._callback(callback);
				}
				if (duration === 0 && this._rawPrevTime === _tinyNum && rawPrevTime !== _tinyNum) { //the onComplete or onReverseComplete could trigger movement of the playhead and for zero-duration tweens (which must discern direction) that land directly back on their start time, we don't want to fire again on the next render. Think of several addPause()'s in a timeline that forces the playhead to a certain spot, but what if it's already paused and another tween is tweening the "time" of the timeline? Each time it moves [forward] past that spot, it would move back, and since suppressEvents is true, it'd reset _rawPrevTime to _tinyNum so that when it begins again, the callback would fire (so ultimately it could bounce back and forth during that tween). Again, this is a very uncommon scenario, but possible nonetheless.
					this._rawPrevTime = 0;
				}
			}
		};
		
//---- STATIC FUNCTIONS -----------------------------------------------------------------------------------------------------------
		
		TweenMax.to = function(target, duration, vars) {
			return new TweenMax(target, duration, vars);
		};
		
		TweenMax.from = function(target, duration, vars) {
			vars.runBackwards = true;
			vars.immediateRender = (vars.immediateRender != false);
			return new TweenMax(target, duration, vars);
		};
		
		TweenMax.fromTo = function(target, duration, fromVars, toVars) {
			toVars.startAt = fromVars;
			toVars.immediateRender = (toVars.immediateRender != false && fromVars.immediateRender != false);
			return new TweenMax(target, duration, toVars);
		};
		
		TweenMax.staggerTo = TweenMax.allTo = function(targets, duration, vars, stagger, onCompleteAll, onCompleteAllParams, onCompleteAllScope) {
			stagger = stagger || 0;
			var delay = 0,
				a = [],
				finalComplete = function() {
					if (vars.onComplete) {
						vars.onComplete.apply(vars.onCompleteScope || this, arguments);
					}
					onCompleteAll.apply(onCompleteAllScope || vars.callbackScope || this, onCompleteAllParams || _blankArray);
				},
				cycle = vars.cycle,
				fromCycle = (vars.startAt && vars.startAt.cycle),
				l, copy, i, p;
			if (!_isArray(targets)) {
				if (typeof(targets) === "string") {
					targets = TweenLite.selector(targets) || targets;
				}
				if (_isSelector(targets)) {
					targets = _slice(targets);
				}
			}
			targets = targets || [];
			if (stagger < 0) {
				targets = _slice(targets);
				targets.reverse();
				stagger *= -1;
			}
			l = targets.length - 1;
			for (i = 0; i <= l; i++) {
				copy = {};
				for (p in vars) {
					copy[p] = vars[p];
				}
				if (cycle) {
					_applyCycle(copy, targets, i);
					if (copy.duration != null) {
						duration = copy.duration;
						delete copy.duration;
					}
				}
				if (fromCycle) {
					fromCycle = copy.startAt = {};
					for (p in vars.startAt) {
						fromCycle[p] = vars.startAt[p];
					}
					_applyCycle(copy.startAt, targets, i);
				}
				copy.delay = delay + (copy.delay || 0);
				if (i === l && onCompleteAll) {
					copy.onComplete = finalComplete;
				}
				a[i] = new TweenMax(targets[i], duration, copy);
				delay += stagger;
			}
			return a;
		};
		
		TweenMax.staggerFrom = TweenMax.allFrom = function(targets, duration, vars, stagger, onCompleteAll, onCompleteAllParams, onCompleteAllScope) {
			vars.runBackwards = true;
			vars.immediateRender = (vars.immediateRender != false);
			return TweenMax.staggerTo(targets, duration, vars, stagger, onCompleteAll, onCompleteAllParams, onCompleteAllScope);
		};
		
		TweenMax.staggerFromTo = TweenMax.allFromTo = function(targets, duration, fromVars, toVars, stagger, onCompleteAll, onCompleteAllParams, onCompleteAllScope) {
			toVars.startAt = fromVars;
			toVars.immediateRender = (toVars.immediateRender != false && fromVars.immediateRender != false);
			return TweenMax.staggerTo(targets, duration, toVars, stagger, onCompleteAll, onCompleteAllParams, onCompleteAllScope);
		};
				
		TweenMax.delayedCall = function(delay, callback, params, scope, useFrames) {
			return new TweenMax(callback, 0, {delay:delay, onComplete:callback, onCompleteParams:params, callbackScope:scope, onReverseComplete:callback, onReverseCompleteParams:params, immediateRender:false, useFrames:useFrames, overwrite:0});
		};
		
		TweenMax.set = function(target, vars) {
			return new TweenMax(target, 0, vars);
		};
		
		TweenMax.isTweening = function(target) {
			return (TweenLite.getTweensOf(target, true).length > 0);
		};
		
		var _getChildrenOf = function(timeline, includeTimelines) {
				var a = [],
					cnt = 0,
					tween = timeline._first;
				while (tween) {
					if (tween instanceof TweenLite) {
						a[cnt++] = tween;
					} else {
						if (includeTimelines) {
							a[cnt++] = tween;
						}
						a = a.concat(_getChildrenOf(tween, includeTimelines));
						cnt = a.length;
					}
					tween = tween._next;
				}
				return a;
			}, 
			getAllTweens = TweenMax.getAllTweens = function(includeTimelines) {
				return _getChildrenOf(Animation._rootTimeline, includeTimelines).concat( _getChildrenOf(Animation._rootFramesTimeline, includeTimelines) );
			};
		
		TweenMax.killAll = function(complete, tweens, delayedCalls, timelines) {
			if (tweens == null) {
				tweens = true;
			}
			if (delayedCalls == null) {
				delayedCalls = true;
			}
			var a = getAllTweens((timelines != false)),
				l = a.length,
				allTrue = (tweens && delayedCalls && timelines),
				isDC, tween, i;
			for (i = 0; i < l; i++) {
				tween = a[i];
				if (allTrue || (tween instanceof SimpleTimeline) || ((isDC = (tween.target === tween.vars.onComplete)) && delayedCalls) || (tweens && !isDC)) {
					if (complete) {
						tween.totalTime(tween._reversed ? 0 : tween.totalDuration());
					} else {
						tween._enabled(false, false);
					}
				}
			}
		};
		
		TweenMax.killChildTweensOf = function(parent, complete) {
			if (parent == null) {
				return;
			}
			var tl = TweenLiteInternals.tweenLookup,
				a, curParent, p, i, l;
			if (typeof(parent) === "string") {
				parent = TweenLite.selector(parent) || parent;
			}
			if (_isSelector(parent)) {
				parent = _slice(parent);
			}
			if (_isArray(parent)) {
				i = parent.length;
				while (--i > -1) {
					TweenMax.killChildTweensOf(parent[i], complete);
				}
				return;
			}
			a = [];
			for (p in tl) {
				curParent = tl[p].target.parentNode;
				while (curParent) {
					if (curParent === parent) {
						a = a.concat(tl[p].tweens);
					}
					curParent = curParent.parentNode;
				}
			}
			l = a.length;
			for (i = 0; i < l; i++) {
				if (complete) {
					a[i].totalTime(a[i].totalDuration());
				}
				a[i]._enabled(false, false);
			}
		};

		var _changePause = function(pause, tweens, delayedCalls, timelines) {
			tweens = (tweens !== false);
			delayedCalls = (delayedCalls !== false);
			timelines = (timelines !== false);
			var a = getAllTweens(timelines),
				allTrue = (tweens && delayedCalls && timelines),
				i = a.length,
				isDC, tween;
			while (--i > -1) {
				tween = a[i];
				if (allTrue || (tween instanceof SimpleTimeline) || ((isDC = (tween.target === tween.vars.onComplete)) && delayedCalls) || (tweens && !isDC)) {
					tween.paused(pause);
				}
			}
		};
		
		TweenMax.pauseAll = function(tweens, delayedCalls, timelines) {
			_changePause(true, tweens, delayedCalls, timelines);
		};
		
		TweenMax.resumeAll = function(tweens, delayedCalls, timelines) {
			_changePause(false, tweens, delayedCalls, timelines);
		};

		TweenMax.globalTimeScale = function(value) {
			var tl = Animation._rootTimeline,
				t = TweenLite.ticker.time;
			if (!arguments.length) {
				return tl._timeScale;
			}
			value = value || _tinyNum; //can't allow zero because it'll throw the math off
			tl._startTime = t - ((t - tl._startTime) * tl._timeScale / value);
			tl = Animation._rootFramesTimeline;
			t = TweenLite.ticker.frame;
			tl._startTime = t - ((t - tl._startTime) * tl._timeScale / value);
			tl._timeScale = Animation._rootTimeline._timeScale = value;
			return value;
		};
		
	
//---- GETTERS / SETTERS ----------------------------------------------------------------------------------------------------------
		
		p.progress = function(value, suppressEvents) {
			return (!arguments.length) ? this._time / this.duration() : this.totalTime( this.duration() * ((this._yoyo && (this._cycle & 1) !== 0) ? 1 - value : value) + (this._cycle * (this._duration + this._repeatDelay)), suppressEvents);
		};
		
		p.totalProgress = function(value, suppressEvents) {
			return (!arguments.length) ? this._totalTime / this.totalDuration() : this.totalTime( this.totalDuration() * value, suppressEvents);
		};
		
		p.time = function(value, suppressEvents) {
			if (!arguments.length) {
				return this._time;
			}
			if (this._dirty) {
				this.totalDuration();
			}
			if (value > this._duration) {
				value = this._duration;
			}
			if (this._yoyo && (this._cycle & 1) !== 0) {
				value = (this._duration - value) + (this._cycle * (this._duration + this._repeatDelay));
			} else if (this._repeat !== 0) {
				value += this._cycle * (this._duration + this._repeatDelay);
			}
			return this.totalTime(value, suppressEvents);
		};

		p.duration = function(value) {
			if (!arguments.length) {
				return this._duration; //don't set _dirty = false because there could be repeats that haven't been factored into the _totalDuration yet. Otherwise, if you create a repeated TweenMax and then immediately check its duration(), it would cache the value and the totalDuration would not be correct, thus repeats wouldn't take effect.
			}
			return Animation.prototype.duration.call(this, value);
		};

		p.totalDuration = function(value) {
			if (!arguments.length) {
				if (this._dirty) {
					//instead of Infinity, we use 999999999999 so that we can accommodate reverses
					this._totalDuration = (this._repeat === -1) ? 999999999999 : this._duration * (this._repeat + 1) + (this._repeatDelay * this._repeat);
					this._dirty = false;
				}
				return this._totalDuration;
			}
			return (this._repeat === -1) ? this : this.duration( (value - (this._repeat * this._repeatDelay)) / (this._repeat + 1) );
		};
		
		p.repeat = function(value) {
			if (!arguments.length) {
				return this._repeat;
			}
			this._repeat = value;
			return this._uncache(true);
		};
		
		p.repeatDelay = function(value) {
			if (!arguments.length) {
				return this._repeatDelay;
			}
			this._repeatDelay = value;
			return this._uncache(true);
		};
		
		p.yoyo = function(value) {
			if (!arguments.length) {
				return this._yoyo;
			}
			this._yoyo = value;
			return this;
		};
		
		
		return TweenMax;
		
	}, true);








/*
 * ----------------------------------------------------------------
 * TimelineLite
 * ----------------------------------------------------------------
 */
	_gsScope._gsDefine("TimelineLite", ["core.Animation","core.SimpleTimeline","TweenLite"], function(Animation, SimpleTimeline, TweenLite) {

		var TimelineLite = function(vars) {
				SimpleTimeline.call(this, vars);
				this._labels = {};
				this.autoRemoveChildren = (this.vars.autoRemoveChildren === true);
				this.smoothChildTiming = (this.vars.smoothChildTiming === true);
				this._sortChildren = true;
				this._onUpdate = this.vars.onUpdate;
				var v = this.vars,
					val, p;
				for (p in v) {
					val = v[p];
					if (_isArray(val)) if (val.join("").indexOf("{self}") !== -1) {
						v[p] = this._swapSelfInParams(val);
					}
				}
				if (_isArray(v.tweens)) {
					this.add(v.tweens, 0, v.align, v.stagger);
				}
			},
			_tinyNum = 0.0000000001,
			TweenLiteInternals = TweenLite._internals,
			_internals = TimelineLite._internals = {},
			_isSelector = TweenLiteInternals.isSelector,
			_isArray = TweenLiteInternals.isArray,
			_lazyTweens = TweenLiteInternals.lazyTweens,
			_lazyRender = TweenLiteInternals.lazyRender,
			_globals = _gsScope._gsDefine.globals,
			_copy = function(vars) {
				var copy = {}, p;
				for (p in vars) {
					copy[p] = vars[p];
				}
				return copy;
			},
			_applyCycle = function(vars, targets, i) {
				var alt = vars.cycle,
					p, val;
				for (p in alt) {
					val = alt[p];
					vars[p] = (typeof(val) === "function") ? val(i, targets[i]) : val[i % val.length];
				}
				delete vars.cycle;
			},
			_pauseCallback = _internals.pauseCallback = function() {},
			_slice = function(a) { //don't use [].slice because that doesn't work in IE8 with a NodeList that's returned by querySelectorAll()
				var b = [],
					l = a.length,
					i;
				for (i = 0; i !== l; b.push(a[i++]));
				return b;
			},
			p = TimelineLite.prototype = new SimpleTimeline();

		TimelineLite.version = "1.19.1";
		p.constructor = TimelineLite;
		p.kill()._gc = p._forcingPlayhead = p._hasPause = false;

		/* might use later...
		//translates a local time inside an animation to the corresponding time on the root/global timeline, factoring in all nesting and timeScales.
		function localToGlobal(time, animation) {
			while (animation) {
				time = (time / animation._timeScale) + animation._startTime;
				animation = animation.timeline;
			}
			return time;
		}

		//translates the supplied time on the root/global timeline into the corresponding local time inside a particular animation, factoring in all nesting and timeScales
		function globalToLocal(time, animation) {
			var scale = 1;
			time -= localToGlobal(0, animation);
			while (animation) {
				scale *= animation._timeScale;
				animation = animation.timeline;
			}
			return time * scale;
		}
		*/

		p.to = function(target, duration, vars, position) {
			var Engine = (vars.repeat && _globals.TweenMax) || TweenLite;
			return duration ? this.add( new Engine(target, duration, vars), position) : this.set(target, vars, position);
		};

		p.from = function(target, duration, vars, position) {
			return this.add( ((vars.repeat && _globals.TweenMax) || TweenLite).from(target, duration, vars), position);
		};

		p.fromTo = function(target, duration, fromVars, toVars, position) {
			var Engine = (toVars.repeat && _globals.TweenMax) || TweenLite;
			return duration ? this.add( Engine.fromTo(target, duration, fromVars, toVars), position) : this.set(target, toVars, position);
		};

		p.staggerTo = function(targets, duration, vars, stagger, position, onCompleteAll, onCompleteAllParams, onCompleteAllScope) {
			var tl = new TimelineLite({onComplete:onCompleteAll, onCompleteParams:onCompleteAllParams, callbackScope:onCompleteAllScope, smoothChildTiming:this.smoothChildTiming}),
				cycle = vars.cycle,
				copy, i;
			if (typeof(targets) === "string") {
				targets = TweenLite.selector(targets) || targets;
			}
			targets = targets || [];
			if (_isSelector(targets)) { //senses if the targets object is a selector. If it is, we should translate it into an array.
				targets = _slice(targets);
			}
			stagger = stagger || 0;
			if (stagger < 0) {
				targets = _slice(targets);
				targets.reverse();
				stagger *= -1;
			}
			for (i = 0; i < targets.length; i++) {
				copy = _copy(vars);
				if (copy.startAt) {
					copy.startAt = _copy(copy.startAt);
					if (copy.startAt.cycle) {
						_applyCycle(copy.startAt, targets, i);
					}
				}
				if (cycle) {
					_applyCycle(copy, targets, i);
					if (copy.duration != null) {
						duration = copy.duration;
						delete copy.duration;
					}
				}
				tl.to(targets[i], duration, copy, i * stagger);
			}
			return this.add(tl, position);
		};

		p.staggerFrom = function(targets, duration, vars, stagger, position, onCompleteAll, onCompleteAllParams, onCompleteAllScope) {
			vars.immediateRender = (vars.immediateRender != false);
			vars.runBackwards = true;
			return this.staggerTo(targets, duration, vars, stagger, position, onCompleteAll, onCompleteAllParams, onCompleteAllScope);
		};

		p.staggerFromTo = function(targets, duration, fromVars, toVars, stagger, position, onCompleteAll, onCompleteAllParams, onCompleteAllScope) {
			toVars.startAt = fromVars;
			toVars.immediateRender = (toVars.immediateRender != false && fromVars.immediateRender != false);
			return this.staggerTo(targets, duration, toVars, stagger, position, onCompleteAll, onCompleteAllParams, onCompleteAllScope);
		};

		p.call = function(callback, params, scope, position) {
			return this.add( TweenLite.delayedCall(0, callback, params, scope), position);
		};

		p.set = function(target, vars, position) {
			position = this._parseTimeOrLabel(position, 0, true);
			if (vars.immediateRender == null) {
				vars.immediateRender = (position === this._time && !this._paused);
			}
			return this.add( new TweenLite(target, 0, vars), position);
		};

		TimelineLite.exportRoot = function(vars, ignoreDelayedCalls) {
			vars = vars || {};
			if (vars.smoothChildTiming == null) {
				vars.smoothChildTiming = true;
			}
			var tl = new TimelineLite(vars),
				root = tl._timeline,
				tween, next;
			if (ignoreDelayedCalls == null) {
				ignoreDelayedCalls = true;
			}
			root._remove(tl, true);
			tl._startTime = 0;
			tl._rawPrevTime = tl._time = tl._totalTime = root._time;
			tween = root._first;
			while (tween) {
				next = tween._next;
				if (!ignoreDelayedCalls || !(tween instanceof TweenLite && tween.target === tween.vars.onComplete)) {
					tl.add(tween, tween._startTime - tween._delay);
				}
				tween = next;
			}
			root.add(tl, 0);
			return tl;
		};

		p.add = function(value, position, align, stagger) {
			var curTime, l, i, child, tl, beforeRawTime;
			if (typeof(position) !== "number") {
				position = this._parseTimeOrLabel(position, 0, true, value);
			}
			if (!(value instanceof Animation)) {
				if ((value instanceof Array) || (value && value.push && _isArray(value))) {
					align = align || "normal";
					stagger = stagger || 0;
					curTime = position;
					l = value.length;
					for (i = 0; i < l; i++) {
						if (_isArray(child = value[i])) {
							child = new TimelineLite({tweens:child});
						}
						this.add(child, curTime);
						if (typeof(child) !== "string" && typeof(child) !== "function") {
							if (align === "sequence") {
								curTime = child._startTime + (child.totalDuration() / child._timeScale);
							} else if (align === "start") {
								child._startTime -= child.delay();
							}
						}
						curTime += stagger;
					}
					return this._uncache(true);
				} else if (typeof(value) === "string") {
					return this.addLabel(value, position);
				} else if (typeof(value) === "function") {
					value = TweenLite.delayedCall(0, value);
				} else {
					throw("Cannot add " + value + " into the timeline; it is not a tween, timeline, function, or string.");
				}
			}

			SimpleTimeline.prototype.add.call(this, value, position);

			//if the timeline has already ended but the inserted tween/timeline extends the duration, we should enable this timeline again so that it renders properly. We should also align the playhead with the parent timeline's when appropriate.
			if (this._gc || this._time === this._duration) if (!this._paused) if (this._duration < this.duration()) {
				//in case any of the ancestors had completed but should now be enabled...
				tl = this;
				beforeRawTime = (tl.rawTime() > value._startTime); //if the tween is placed on the timeline so that it starts BEFORE the current rawTime, we should align the playhead (move the timeline). This is because sometimes users will create a timeline, let it finish, and much later append a tween and expect it to run instead of jumping to its end state. While technically one could argue that it should jump to its end state, that's not what users intuitively expect.
				while (tl._timeline) {
					if (beforeRawTime && tl._timeline.smoothChildTiming) {
						tl.totalTime(tl._totalTime, true); //moves the timeline (shifts its startTime) if necessary, and also enables it.
					} else if (tl._gc) {
						tl._enabled(true, false);
					}
					tl = tl._timeline;
				}
			}

			return this;
		};

		p.remove = function(value) {
			if (value instanceof Animation) {
				this._remove(value, false);
				var tl = value._timeline = value.vars.useFrames ? Animation._rootFramesTimeline : Animation._rootTimeline; //now that it's removed, default it to the root timeline so that if it gets played again, it doesn't jump back into this timeline.
				value._startTime = (value._paused ? value._pauseTime : tl._time) - ((!value._reversed ? value._totalTime : value.totalDuration() - value._totalTime) / value._timeScale); //ensure that if it gets played again, the timing is correct.
				return this;
			} else if (value instanceof Array || (value && value.push && _isArray(value))) {
				var i = value.length;
				while (--i > -1) {
					this.remove(value[i]);
				}
				return this;
			} else if (typeof(value) === "string") {
				return this.removeLabel(value);
			}
			return this.kill(null, value);
		};

		p._remove = function(tween, skipDisable) {
			SimpleTimeline.prototype._remove.call(this, tween, skipDisable);
			var last = this._last;
			if (!last) {
				this._time = this._totalTime = this._duration = this._totalDuration = 0;
			} else if (this._time > this.duration()) {
				this._time = this._duration;
				this._totalTime = this._totalDuration;
			}
			return this;
		};

		p.append = function(value, offsetOrLabel) {
			return this.add(value, this._parseTimeOrLabel(null, offsetOrLabel, true, value));
		};

		p.insert = p.insertMultiple = function(value, position, align, stagger) {
			return this.add(value, position || 0, align, stagger);
		};

		p.appendMultiple = function(tweens, offsetOrLabel, align, stagger) {
			return this.add(tweens, this._parseTimeOrLabel(null, offsetOrLabel, true, tweens), align, stagger);
		};

		p.addLabel = function(label, position) {
			this._labels[label] = this._parseTimeOrLabel(position);
			return this;
		};

		p.addPause = function(position, callback, params, scope) {
			var t = TweenLite.delayedCall(0, _pauseCallback, params, scope || this);
			t.vars.onComplete = t.vars.onReverseComplete = callback;
			t.data = "isPause";
			this._hasPause = true;
			return this.add(t, position);
		};

		p.removeLabel = function(label) {
			delete this._labels[label];
			return this;
		};

		p.getLabelTime = function(label) {
			return (this._labels[label] != null) ? this._labels[label] : -1;
		};

		p._parseTimeOrLabel = function(timeOrLabel, offsetOrLabel, appendIfAbsent, ignore) {
			var i;
			//if we're about to add a tween/timeline (or an array of them) that's already a child of this timeline, we should remove it first so that it doesn't contaminate the duration().
			if (ignore instanceof Animation && ignore.timeline === this) {
				this.remove(ignore);
			} else if (ignore && ((ignore instanceof Array) || (ignore.push && _isArray(ignore)))) {
				i = ignore.length;
				while (--i > -1) {
					if (ignore[i] instanceof Animation && ignore[i].timeline === this) {
						this.remove(ignore[i]);
					}
				}
			}
			if (typeof(offsetOrLabel) === "string") {
				return this._parseTimeOrLabel(offsetOrLabel, (appendIfAbsent && typeof(timeOrLabel) === "number" && this._labels[offsetOrLabel] == null) ? timeOrLabel - this.duration() : 0, appendIfAbsent);
			}
			offsetOrLabel = offsetOrLabel || 0;
			if (typeof(timeOrLabel) === "string" && (isNaN(timeOrLabel) || this._labels[timeOrLabel] != null)) { //if the string is a number like "1", check to see if there's a label with that name, otherwise interpret it as a number (absolute value).
				i = timeOrLabel.indexOf("=");
				if (i === -1) {
					if (this._labels[timeOrLabel] == null) {
						return appendIfAbsent ? (this._labels[timeOrLabel] = this.duration() + offsetOrLabel) : offsetOrLabel;
					}
					return this._labels[timeOrLabel] + offsetOrLabel;
				}
				offsetOrLabel = parseInt(timeOrLabel.charAt(i-1) + "1", 10) * Number(timeOrLabel.substr(i+1));
				timeOrLabel = (i > 1) ? this._parseTimeOrLabel(timeOrLabel.substr(0, i-1), 0, appendIfAbsent) : this.duration();
			} else if (timeOrLabel == null) {
				timeOrLabel = this.duration();
			}
			return Number(timeOrLabel) + offsetOrLabel;
		};

		p.seek = function(position, suppressEvents) {
			return this.totalTime((typeof(position) === "number") ? position : this._parseTimeOrLabel(position), (suppressEvents !== false));
		};

		p.stop = function() {
			return this.paused(true);
		};

		p.gotoAndPlay = function(position, suppressEvents) {
			return this.play(position, suppressEvents);
		};

		p.gotoAndStop = function(position, suppressEvents) {
			return this.pause(position, suppressEvents);
		};

		p.render = function(time, suppressEvents, force) {
			if (this._gc) {
				this._enabled(true, false);
			}
			var totalDur = (!this._dirty) ? this._totalDuration : this.totalDuration(),
				prevTime = this._time,
				prevStart = this._startTime,
				prevTimeScale = this._timeScale,
				prevPaused = this._paused,
				tween, isComplete, next, callback, internalForce, pauseTween, curTime;
			if (time >= totalDur - 0.0000001 && time >= 0) { //to work around occasional floating point math artifacts.
				this._totalTime = this._time = totalDur;
				if (!this._reversed) if (!this._hasPausedChild()) {
					isComplete = true;
					callback = "onComplete";
					internalForce = !!this._timeline.autoRemoveChildren; //otherwise, if the animation is unpaused/activated after it's already finished, it doesn't get removed from the parent timeline.
					if (this._duration === 0) if ((time <= 0 && time >= -0.0000001) || this._rawPrevTime < 0 || this._rawPrevTime === _tinyNum) if (this._rawPrevTime !== time && this._first) {
						internalForce = true;
						if (this._rawPrevTime > _tinyNum) {
							callback = "onReverseComplete";
						}
					}
				}
				this._rawPrevTime = (this._duration || !suppressEvents || time || this._rawPrevTime === time) ? time : _tinyNum; //when the playhead arrives at EXACTLY time 0 (right on top) of a zero-duration timeline or tween, we need to discern if events are suppressed so that when the playhead moves again (next time), it'll trigger the callback. If events are NOT suppressed, obviously the callback would be triggered in this render. Basically, the callback should fire either when the playhead ARRIVES or LEAVES this exact spot, not both. Imagine doing a timeline.seek(0) and there's a callback that sits at 0. Since events are suppressed on that seek() by default, nothing will fire, but when the playhead moves off of that position, the callback should fire. This behavior is what people intuitively expect. We set the _rawPrevTime to be a precise tiny number to indicate this scenario rather than using another property/variable which would increase memory usage. This technique is less readable, but more efficient.
				time = totalDur + 0.0001; //to avoid occasional floating point rounding errors - sometimes child tweens/timelines were not being fully completed (their progress might be 0.999999999999998 instead of 1 because when _time - tween._startTime is performed, floating point errors would return a value that was SLIGHTLY off). Try (999999999999.7 - 999999999999) * 1 = 0.699951171875 instead of 0.7.

			} else if (time < 0.0000001) { //to work around occasional floating point math artifacts, round super small values to 0.
				this._totalTime = this._time = 0;
				if (prevTime !== 0 || (this._duration === 0 && this._rawPrevTime !== _tinyNum && (this._rawPrevTime > 0 || (time < 0 && this._rawPrevTime >= 0)))) {
					callback = "onReverseComplete";
					isComplete = this._reversed;
				}
				if (time < 0) {
					this._active = false;
					if (this._timeline.autoRemoveChildren && this._reversed) { //ensures proper GC if a timeline is resumed after it's finished reversing.
						internalForce = isComplete = true;
						callback = "onReverseComplete";
					} else if (this._rawPrevTime >= 0 && this._first) { //when going back beyond the start, force a render so that zero-duration tweens that sit at the very beginning render their start values properly. Otherwise, if the parent timeline's playhead lands exactly at this timeline's startTime, and then moves backwards, the zero-duration tweens at the beginning would still be at their end state.
						internalForce = true;
					}
					this._rawPrevTime = time;
				} else {
					this._rawPrevTime = (this._duration || !suppressEvents || time || this._rawPrevTime === time) ? time : _tinyNum; //when the playhead arrives at EXACTLY time 0 (right on top) of a zero-duration timeline or tween, we need to discern if events are suppressed so that when the playhead moves again (next time), it'll trigger the callback. If events are NOT suppressed, obviously the callback would be triggered in this render. Basically, the callback should fire either when the playhead ARRIVES or LEAVES this exact spot, not both. Imagine doing a timeline.seek(0) and there's a callback that sits at 0. Since events are suppressed on that seek() by default, nothing will fire, but when the playhead moves off of that position, the callback should fire. This behavior is what people intuitively expect. We set the _rawPrevTime to be a precise tiny number to indicate this scenario rather than using another property/variable which would increase memory usage. This technique is less readable, but more efficient.
					if (time === 0 && isComplete) { //if there's a zero-duration tween at the very beginning of a timeline and the playhead lands EXACTLY at time 0, that tween will correctly render its end values, but we need to keep the timeline alive for one more render so that the beginning values render properly as the parent's playhead keeps moving beyond the begining. Imagine obj.x starts at 0 and then we do tl.set(obj, {x:100}).to(obj, 1, {x:200}) and then later we tl.reverse()...the goal is to have obj.x revert to 0. If the playhead happens to land on exactly 0, without this chunk of code, it'd complete the timeline and remove it from the rendering queue (not good).
						tween = this._first;
						while (tween && tween._startTime === 0) {
							if (!tween._duration) {
								isComplete = false;
							}
							tween = tween._next;
						}
					}
					time = 0; //to avoid occasional floating point rounding errors (could cause problems especially with zero-duration tweens at the very beginning of the timeline)
					if (!this._initted) {
						internalForce = true;
					}
				}

			} else {

				if (this._hasPause && !this._forcingPlayhead && !suppressEvents) {
					if (time >= prevTime) {
						tween = this._first;
						while (tween && tween._startTime <= time && !pauseTween) {
							if (!tween._duration) if (tween.data === "isPause" && !tween.ratio && !(tween._startTime === 0 && this._rawPrevTime === 0)) {
								pauseTween = tween;
							}
							tween = tween._next;
						}
					} else {
						tween = this._last;
						while (tween && tween._startTime >= time && !pauseTween) {
							if (!tween._duration) if (tween.data === "isPause" && tween._rawPrevTime > 0) {
								pauseTween = tween;
							}
							tween = tween._prev;
						}
					}
					if (pauseTween) {
						this._time = time = pauseTween._startTime;
						this._totalTime = time + (this._cycle * (this._totalDuration + this._repeatDelay));
					}
				}

				this._totalTime = this._time = this._rawPrevTime = time;
			}
			if ((this._time === prevTime || !this._first) && !force && !internalForce && !pauseTween) {
				return;
			} else if (!this._initted) {
				this._initted = true;
			}

			if (!this._active) if (!this._paused && this._time !== prevTime && time > 0) {
				this._active = true;  //so that if the user renders the timeline (as opposed to the parent timeline rendering it), it is forced to re-render and align it with the proper time/frame on the next rendering cycle. Maybe the timeline already finished but the user manually re-renders it as halfway done, for example.
			}

			if (prevTime === 0) if (this.vars.onStart) if (this._time !== 0 || !this._duration) if (!suppressEvents) {
				this._callback("onStart");
			}

			curTime = this._time;
			if (curTime >= prevTime) {
				tween = this._first;
				while (tween) {
					next = tween._next; //record it here because the value could change after rendering...
					if (curTime !== this._time || (this._paused && !prevPaused)) { //in case a tween pauses or seeks the timeline when rendering, like inside of an onUpdate/onComplete
						break;
					} else if (tween._active || (tween._startTime <= curTime && !tween._paused && !tween._gc)) {
						if (pauseTween === tween) {
							this.pause();
						}
						if (!tween._reversed) {
							tween.render((time - tween._startTime) * tween._timeScale, suppressEvents, force);
						} else {
							tween.render(((!tween._dirty) ? tween._totalDuration : tween.totalDuration()) - ((time - tween._startTime) * tween._timeScale), suppressEvents, force);
						}
					}
					tween = next;
				}
			} else {
				tween = this._last;
				while (tween) {
					next = tween._prev; //record it here because the value could change after rendering...
					if (curTime !== this._time || (this._paused && !prevPaused)) { //in case a tween pauses or seeks the timeline when rendering, like inside of an onUpdate/onComplete
						break;
					} else if (tween._active || (tween._startTime <= prevTime && !tween._paused && !tween._gc)) {
						if (pauseTween === tween) {
							pauseTween = tween._prev; //the linked list is organized by _startTime, thus it's possible that a tween could start BEFORE the pause and end after it, in which case it would be positioned before the pause tween in the linked list, but we should render it before we pause() the timeline and cease rendering. This is only a concern when going in reverse.
							while (pauseTween && pauseTween.endTime() > this._time) {
								pauseTween.render( (pauseTween._reversed ? pauseTween.totalDuration() - ((time - pauseTween._startTime) * pauseTween._timeScale) : (time - pauseTween._startTime) * pauseTween._timeScale), suppressEvents, force);
								pauseTween = pauseTween._prev;
							}
							pauseTween = null;
							this.pause();
						}
						if (!tween._reversed) {
							tween.render((time - tween._startTime) * tween._timeScale, suppressEvents, force);
						} else {
							tween.render(((!tween._dirty) ? tween._totalDuration : tween.totalDuration()) - ((time - tween._startTime) * tween._timeScale), suppressEvents, force);
						}
					}
					tween = next;
				}
			}

			if (this._onUpdate) if (!suppressEvents) {
				if (_lazyTweens.length) { //in case rendering caused any tweens to lazy-init, we should render them because typically when a timeline finishes, users expect things to have rendered fully. Imagine an onUpdate on a timeline that reports/checks tweened values.
					_lazyRender();
				}
				this._callback("onUpdate");
			}

			if (callback) if (!this._gc) if (prevStart === this._startTime || prevTimeScale !== this._timeScale) if (this._time === 0 || totalDur >= this.totalDuration()) { //if one of the tweens that was rendered altered this timeline's startTime (like if an onComplete reversed the timeline), it probably isn't complete. If it is, don't worry, because whatever call altered the startTime would complete if it was necessary at the new time. The only exception is the timeScale property. Also check _gc because there's a chance that kill() could be called in an onUpdate
				if (isComplete) {
					if (_lazyTweens.length) { //in case rendering caused any tweens to lazy-init, we should render them because typically when a timeline finishes, users expect things to have rendered fully. Imagine an onComplete on a timeline that reports/checks tweened values.
						_lazyRender();
					}
					if (this._timeline.autoRemoveChildren) {
						this._enabled(false, false);
					}
					this._active = false;
				}
				if (!suppressEvents && this.vars[callback]) {
					this._callback(callback);
				}
			}
		};

		p._hasPausedChild = function() {
			var tween = this._first;
			while (tween) {
				if (tween._paused || ((tween instanceof TimelineLite) && tween._hasPausedChild())) {
					return true;
				}
				tween = tween._next;
			}
			return false;
		};

		p.getChildren = function(nested, tweens, timelines, ignoreBeforeTime) {
			ignoreBeforeTime = ignoreBeforeTime || -9999999999;
			var a = [],
				tween = this._first,
				cnt = 0;
			while (tween) {
				if (tween._startTime < ignoreBeforeTime) {
					//do nothing
				} else if (tween instanceof TweenLite) {
					if (tweens !== false) {
						a[cnt++] = tween;
					}
				} else {
					if (timelines !== false) {
						a[cnt++] = tween;
					}
					if (nested !== false) {
						a = a.concat(tween.getChildren(true, tweens, timelines));
						cnt = a.length;
					}
				}
				tween = tween._next;
			}
			return a;
		};

		p.getTweensOf = function(target, nested) {
			var disabled = this._gc,
				a = [],
				cnt = 0,
				tweens, i;
			if (disabled) {
				this._enabled(true, true); //getTweensOf() filters out disabled tweens, and we have to mark them as _gc = true when the timeline completes in order to allow clean garbage collection, so temporarily re-enable the timeline here.
			}
			tweens = TweenLite.getTweensOf(target);
			i = tweens.length;
			while (--i > -1) {
				if (tweens[i].timeline === this || (nested && this._contains(tweens[i]))) {
					a[cnt++] = tweens[i];
				}
			}
			if (disabled) {
				this._enabled(false, true);
			}
			return a;
		};

		p.recent = function() {
			return this._recent;
		};

		p._contains = function(tween) {
			var tl = tween.timeline;
			while (tl) {
				if (tl === this) {
					return true;
				}
				tl = tl.timeline;
			}
			return false;
		};

		p.shiftChildren = function(amount, adjustLabels, ignoreBeforeTime) {
			ignoreBeforeTime = ignoreBeforeTime || 0;
			var tween = this._first,
				labels = this._labels,
				p;
			while (tween) {
				if (tween._startTime >= ignoreBeforeTime) {
					tween._startTime += amount;
				}
				tween = tween._next;
			}
			if (adjustLabels) {
				for (p in labels) {
					if (labels[p] >= ignoreBeforeTime) {
						labels[p] += amount;
					}
				}
			}
			return this._uncache(true);
		};

		p._kill = function(vars, target) {
			if (!vars && !target) {
				return this._enabled(false, false);
			}
			var tweens = (!target) ? this.getChildren(true, true, false) : this.getTweensOf(target),
				i = tweens.length,
				changed = false;
			while (--i > -1) {
				if (tweens[i]._kill(vars, target)) {
					changed = true;
				}
			}
			return changed;
		};

		p.clear = function(labels) {
			var tweens = this.getChildren(false, true, true),
				i = tweens.length;
			this._time = this._totalTime = 0;
			while (--i > -1) {
				tweens[i]._enabled(false, false);
			}
			if (labels !== false) {
				this._labels = {};
			}
			return this._uncache(true);
		};

		p.invalidate = function() {
			var tween = this._first;
			while (tween) {
				tween.invalidate();
				tween = tween._next;
			}
			return Animation.prototype.invalidate.call(this);;
		};

		p._enabled = function(enabled, ignoreTimeline) {
			if (enabled === this._gc) {
				var tween = this._first;
				while (tween) {
					tween._enabled(enabled, true);
					tween = tween._next;
				}
			}
			return SimpleTimeline.prototype._enabled.call(this, enabled, ignoreTimeline);
		};

		p.totalTime = function(time, suppressEvents, uncapped) {
			this._forcingPlayhead = true;
			var val = Animation.prototype.totalTime.apply(this, arguments);
			this._forcingPlayhead = false;
			return val;
		};

		p.duration = function(value) {
			if (!arguments.length) {
				if (this._dirty) {
					this.totalDuration(); //just triggers recalculation
				}
				return this._duration;
			}
			if (this.duration() !== 0 && value !== 0) {
				this.timeScale(this._duration / value);
			}
			return this;
		};

		p.totalDuration = function(value) {
			if (!arguments.length) {
				if (this._dirty) {
					var max = 0,
						tween = this._last,
						prevStart = 999999999999,
						prev, end;
					while (tween) {
						prev = tween._prev; //record it here in case the tween changes position in the sequence...
						if (tween._dirty) {
							tween.totalDuration(); //could change the tween._startTime, so make sure the tween's cache is clean before analyzing it.
						}
						if (tween._startTime > prevStart && this._sortChildren && !tween._paused) { //in case one of the tweens shifted out of order, it needs to be re-inserted into the correct position in the sequence
							this.add(tween, tween._startTime - tween._delay);
						} else {
							prevStart = tween._startTime;
						}
						if (tween._startTime < 0 && !tween._paused) { //children aren't allowed to have negative startTimes unless smoothChildTiming is true, so adjust here if one is found.
							max -= tween._startTime;
							if (this._timeline.smoothChildTiming) {
								this._startTime += tween._startTime / this._timeScale;
							}
							this.shiftChildren(-tween._startTime, false, -9999999999);
							prevStart = 0;
						}
						end = tween._startTime + (tween._totalDuration / tween._timeScale);
						if (end > max) {
							max = end;
						}
						tween = prev;
					}
					this._duration = this._totalDuration = max;
					this._dirty = false;
				}
				return this._totalDuration;
			}
			return (value && this.totalDuration()) ? this.timeScale(this._totalDuration / value) : this;
		};

		p.paused = function(value) {
			if (!value) { //if there's a pause directly at the spot from where we're unpausing, skip it.
				var tween = this._first,
					time = this._time;
				while (tween) {
					if (tween._startTime === time && tween.data === "isPause") {
						tween._rawPrevTime = 0; //remember, _rawPrevTime is how zero-duration tweens/callbacks sense directionality and determine whether or not to fire. If _rawPrevTime is the same as _startTime on the next render, it won't fire.
					}
					tween = tween._next;
				}
			}
			return Animation.prototype.paused.apply(this, arguments);
		};

		p.usesFrames = function() {
			var tl = this._timeline;
			while (tl._timeline) {
				tl = tl._timeline;
			}
			return (tl === Animation._rootFramesTimeline);
		};

		p.rawTime = function(wrapRepeats) {
			return (wrapRepeats && (this._paused || (this._repeat && this.time() > 0 && this.totalProgress() < 1))) ? this._totalTime % (this._duration + this._repeatDelay) : this._paused ? this._totalTime : (this._timeline.rawTime(wrapRepeats) - this._startTime) * this._timeScale;
		};

		return TimelineLite;

	}, true);








	
	
	
	
	
/*
 * ----------------------------------------------------------------
 * TimelineMax
 * ----------------------------------------------------------------
 */
	_gsScope._gsDefine("TimelineMax", ["TimelineLite","TweenLite","easing.Ease"], function(TimelineLite, TweenLite, Ease) {

		var TimelineMax = function(vars) {
				TimelineLite.call(this, vars);
				this._repeat = this.vars.repeat || 0;
				this._repeatDelay = this.vars.repeatDelay || 0;
				this._cycle = 0;
				this._yoyo = (this.vars.yoyo === true);
				this._dirty = true;
			},
			_tinyNum = 0.0000000001,
			TweenLiteInternals = TweenLite._internals,
			_lazyTweens = TweenLiteInternals.lazyTweens,
			_lazyRender = TweenLiteInternals.lazyRender,
			_globals = _gsScope._gsDefine.globals,
			_easeNone = new Ease(null, null, 1, 0),
			p = TimelineMax.prototype = new TimelineLite();

		p.constructor = TimelineMax;
		p.kill()._gc = false;
		TimelineMax.version = "1.19.1";

		p.invalidate = function() {
			this._yoyo = (this.vars.yoyo === true);
			this._repeat = this.vars.repeat || 0;
			this._repeatDelay = this.vars.repeatDelay || 0;
			this._uncache(true);
			return TimelineLite.prototype.invalidate.call(this);
		};

		p.addCallback = function(callback, position, params, scope) {
			return this.add( TweenLite.delayedCall(0, callback, params, scope), position);
		};

		p.removeCallback = function(callback, position) {
			if (callback) {
				if (position == null) {
					this._kill(null, callback);
				} else {
					var a = this.getTweensOf(callback, false),
						i = a.length,
						time = this._parseTimeOrLabel(position);
					while (--i > -1) {
						if (a[i]._startTime === time) {
							a[i]._enabled(false, false);
						}
					}
				}
			}
			return this;
		};

		p.removePause = function(position) {
			return this.removeCallback(TimelineLite._internals.pauseCallback, position);
		};

		p.tweenTo = function(position, vars) {
			vars = vars || {};
			var copy = {ease:_easeNone, useFrames:this.usesFrames(), immediateRender:false},
				Engine = (vars.repeat && _globals.TweenMax) || TweenLite,
				duration, p, t;
			for (p in vars) {
				copy[p] = vars[p];
			}
			copy.time = this._parseTimeOrLabel(position);
			duration = (Math.abs(Number(copy.time) - this._time) / this._timeScale) || 0.001;
			t = new Engine(this, duration, copy);
			copy.onStart = function() {
				t.target.paused(true);
				if (t.vars.time !== t.target.time() && duration === t.duration()) { //don't make the duration zero - if it's supposed to be zero, don't worry because it's already initting the tween and will complete immediately, effectively making the duration zero anyway. If we make duration zero, the tween won't run at all.
					t.duration( Math.abs( t.vars.time - t.target.time()) / t.target._timeScale );
				}
				if (vars.onStart) { //in case the user had an onStart in the vars - we don't want to overwrite it.
					vars.onStart.apply(vars.onStartScope || vars.callbackScope || t, vars.onStartParams || []); //don't use t._callback("onStart") or it'll point to the copy.onStart and we'll get a recursion error.
				}
			};
			return t;
		};

		p.tweenFromTo = function(fromPosition, toPosition, vars) {
			vars = vars || {};
			fromPosition = this._parseTimeOrLabel(fromPosition);
			vars.startAt = {onComplete:this.seek, onCompleteParams:[fromPosition], callbackScope:this};
			vars.immediateRender = (vars.immediateRender !== false);
			var t = this.tweenTo(toPosition, vars);
			return t.duration((Math.abs( t.vars.time - fromPosition) / this._timeScale) || 0.001);
		};

		p.render = function(time, suppressEvents, force) {
			if (this._gc) {
				this._enabled(true, false);
			}
			var totalDur = (!this._dirty) ? this._totalDuration : this.totalDuration(),
				dur = this._duration,
				prevTime = this._time,
				prevTotalTime = this._totalTime,
				prevStart = this._startTime,
				prevTimeScale = this._timeScale,
				prevRawPrevTime = this._rawPrevTime,
				prevPaused = this._paused,
				prevCycle = this._cycle,
				tween, isComplete, next, callback, internalForce, cycleDuration, pauseTween, curTime;
			if (time >= totalDur - 0.0000001 && time >= 0) { //to work around occasional floating point math artifacts.
				if (!this._locked) {
					this._totalTime = totalDur;
					this._cycle = this._repeat;
				}
				if (!this._reversed) if (!this._hasPausedChild()) {
					isComplete = true;
					callback = "onComplete";
					internalForce = !!this._timeline.autoRemoveChildren; //otherwise, if the animation is unpaused/activated after it's already finished, it doesn't get removed from the parent timeline.
					if (this._duration === 0) if ((time <= 0 && time >= -0.0000001) || prevRawPrevTime < 0 || prevRawPrevTime === _tinyNum) if (prevRawPrevTime !== time && this._first) {
						internalForce = true;
						if (prevRawPrevTime > _tinyNum) {
							callback = "onReverseComplete";
						}
					}
				}
				this._rawPrevTime = (this._duration || !suppressEvents || time || this._rawPrevTime === time) ? time : _tinyNum; //when the playhead arrives at EXACTLY time 0 (right on top) of a zero-duration timeline or tween, we need to discern if events are suppressed so that when the playhead moves again (next time), it'll trigger the callback. If events are NOT suppressed, obviously the callback would be triggered in this render. Basically, the callback should fire either when the playhead ARRIVES or LEAVES this exact spot, not both. Imagine doing a timeline.seek(0) and there's a callback that sits at 0. Since events are suppressed on that seek() by default, nothing will fire, but when the playhead moves off of that position, the callback should fire. This behavior is what people intuitively expect. We set the _rawPrevTime to be a precise tiny number to indicate this scenario rather than using another property/variable which would increase memory usage. This technique is less readable, but more efficient.
				if (this._yoyo && (this._cycle & 1) !== 0) {
					this._time = time = 0;
				} else {
					this._time = dur;
					time = dur + 0.0001; //to avoid occasional floating point rounding errors - sometimes child tweens/timelines were not being fully completed (their progress might be 0.999999999999998 instead of 1 because when _time - tween._startTime is performed, floating point errors would return a value that was SLIGHTLY off). Try (999999999999.7 - 999999999999) * 1 = 0.699951171875 instead of 0.7. We cannot do less then 0.0001 because the same issue can occur when the duration is extremely large like 999999999999 in which case adding 0.00000001, for example, causes it to act like nothing was added.
				}

			} else if (time < 0.0000001) { //to work around occasional floating point math artifacts, round super small values to 0.
				if (!this._locked) {
					this._totalTime = this._cycle = 0;
				}
				this._time = 0;
				if (prevTime !== 0 || (dur === 0 && prevRawPrevTime !== _tinyNum && (prevRawPrevTime > 0 || (time < 0 && prevRawPrevTime >= 0)) && !this._locked)) { //edge case for checking time < 0 && prevRawPrevTime >= 0: a zero-duration fromTo() tween inside a zero-duration timeline (yeah, very rare)
					callback = "onReverseComplete";
					isComplete = this._reversed;
				}
				if (time < 0) {
					this._active = false;
					if (this._timeline.autoRemoveChildren && this._reversed) {
						internalForce = isComplete = true;
						callback = "onReverseComplete";
					} else if (prevRawPrevTime >= 0 && this._first) { //when going back beyond the start, force a render so that zero-duration tweens that sit at the very beginning render their start values properly. Otherwise, if the parent timeline's playhead lands exactly at this timeline's startTime, and then moves backwards, the zero-duration tweens at the beginning would still be at their end state.
						internalForce = true;
					}
					this._rawPrevTime = time;
				} else {
					this._rawPrevTime = (dur || !suppressEvents || time || this._rawPrevTime === time) ? time : _tinyNum; //when the playhead arrives at EXACTLY time 0 (right on top) of a zero-duration timeline or tween, we need to discern if events are suppressed so that when the playhead moves again (next time), it'll trigger the callback. If events are NOT suppressed, obviously the callback would be triggered in this render. Basically, the callback should fire either when the playhead ARRIVES or LEAVES this exact spot, not both. Imagine doing a timeline.seek(0) and there's a callback that sits at 0. Since events are suppressed on that seek() by default, nothing will fire, but when the playhead moves off of that position, the callback should fire. This behavior is what people intuitively expect. We set the _rawPrevTime to be a precise tiny number to indicate this scenario rather than using another property/variable which would increase memory usage. This technique is less readable, but more efficient.
					if (time === 0 && isComplete) { //if there's a zero-duration tween at the very beginning of a timeline and the playhead lands EXACTLY at time 0, that tween will correctly render its end values, but we need to keep the timeline alive for one more render so that the beginning values render properly as the parent's playhead keeps moving beyond the begining. Imagine obj.x starts at 0 and then we do tl.set(obj, {x:100}).to(obj, 1, {x:200}) and then later we tl.reverse()...the goal is to have obj.x revert to 0. If the playhead happens to land on exactly 0, without this chunk of code, it'd complete the timeline and remove it from the rendering queue (not good).
						tween = this._first;
						while (tween && tween._startTime === 0) {
							if (!tween._duration) {
								isComplete = false;
							}
							tween = tween._next;
						}
					}
					time = 0; //to avoid occasional floating point rounding errors (could cause problems especially with zero-duration tweens at the very beginning of the timeline)
					if (!this._initted) {
						internalForce = true;
					}
				}

			} else {
				if (dur === 0 && prevRawPrevTime < 0) { //without this, zero-duration repeating timelines (like with a simple callback nested at the very beginning and a repeatDelay) wouldn't render the first time through.
					internalForce = true;
				}
				this._time = this._rawPrevTime = time;
				if (!this._locked) {
					this._totalTime = time;
					if (this._repeat !== 0) {
						cycleDuration = dur + this._repeatDelay;
						this._cycle = (this._totalTime / cycleDuration) >> 0; //originally _totalTime % cycleDuration but floating point errors caused problems, so I normalized it. (4 % 0.8 should be 0 but it gets reported as 0.79999999!)
						if (this._cycle !== 0) if (this._cycle === this._totalTime / cycleDuration && prevTotalTime <= time) {
							this._cycle--; //otherwise when rendered exactly at the end time, it will act as though it is repeating (at the beginning)
						}
						this._time = this._totalTime - (this._cycle * cycleDuration);
						if (this._yoyo) if ((this._cycle & 1) !== 0) {
							this._time = dur - this._time;
						}
						if (this._time > dur) {
							this._time = dur;
							time = dur + 0.0001; //to avoid occasional floating point rounding error
						} else if (this._time < 0) {
							this._time = time = 0;
						} else {
							time = this._time;
						}
					}
				}

				if (this._hasPause && !this._forcingPlayhead && !suppressEvents && time < dur) {
					time = this._time;
					if (time >= prevTime || (this._repeat && prevCycle !== this._cycle)) {
						tween = this._first;
						while (tween && tween._startTime <= time && !pauseTween) {
							if (!tween._duration) if (tween.data === "isPause" && !tween.ratio && !(tween._startTime === 0 && this._rawPrevTime === 0)) {
								pauseTween = tween;
							}
							tween = tween._next;
						}
					} else {
						tween = this._last;
						while (tween && tween._startTime >= time && !pauseTween) {
							if (!tween._duration) if (tween.data === "isPause" && tween._rawPrevTime > 0) {
								pauseTween = tween;
							}
							tween = tween._prev;
						}
					}
					if (pauseTween) {
						this._time = time = pauseTween._startTime;
						this._totalTime = time + (this._cycle * (this._totalDuration + this._repeatDelay));
					}
				}

			}

			if (this._cycle !== prevCycle) if (!this._locked) {
				/*
				make sure children at the end/beginning of the timeline are rendered properly. If, for example,
				a 3-second long timeline rendered at 2.9 seconds previously, and now renders at 3.2 seconds (which
				would get transated to 2.8 seconds if the timeline yoyos or 0.2 seconds if it just repeats), there
				could be a callback or a short tween that's at 2.95 or 3 seconds in which wouldn't render. So
				we need to push the timeline to the end (and/or beginning depending on its yoyo value). Also we must
				ensure that zero-duration tweens at the very beginning or end of the TimelineMax work.
				*/
				var backwards = (this._yoyo && (prevCycle & 1) !== 0),
					wrap = (backwards === (this._yoyo && (this._cycle & 1) !== 0)),
					recTotalTime = this._totalTime,
					recCycle = this._cycle,
					recRawPrevTime = this._rawPrevTime,
					recTime = this._time;

				this._totalTime = prevCycle * dur;
				if (this._cycle < prevCycle) {
					backwards = !backwards;
				} else {
					this._totalTime += dur;
				}
				this._time = prevTime; //temporarily revert _time so that render() renders the children in the correct order. Without this, tweens won't rewind correctly. We could arhictect things in a "cleaner" way by splitting out the rendering queue into a separate method but for performance reasons, we kept it all inside this method.

				this._rawPrevTime = (dur === 0) ? prevRawPrevTime - 0.0001 : prevRawPrevTime;
				this._cycle = prevCycle;
				this._locked = true; //prevents changes to totalTime and skips repeat/yoyo behavior when we recursively call render()
				prevTime = (backwards) ? 0 : dur;
				this.render(prevTime, suppressEvents, (dur === 0));
				if (!suppressEvents) if (!this._gc) {
					if (this.vars.onRepeat) {
						this._cycle = recCycle; //in case the onRepeat alters the playhead or invalidates(), we shouldn't stay locked or use the previous cycle.
						this._locked = false;
						this._callback("onRepeat");
					}
				}
				if (prevTime !== this._time) { //in case there's a callback like onComplete in a nested tween/timeline that changes the playhead position, like via seek(), we should just abort.
					return;
				}
				if (wrap) {
					this._cycle = prevCycle; //if there's an onRepeat, we reverted this above, so make sure it's set properly again. We also unlocked in that scenario, so reset that too.
					this._locked = true;
					prevTime = (backwards) ? dur + 0.0001 : -0.0001;
					this.render(prevTime, true, false);
				}
				this._locked = false;
				if (this._paused && !prevPaused) { //if the render() triggered callback that paused this timeline, we should abort (very rare, but possible)
					return;
				}
				this._time = recTime;
				this._totalTime = recTotalTime;
				this._cycle = recCycle;
				this._rawPrevTime = recRawPrevTime;
			}

			if ((this._time === prevTime || !this._first) && !force && !internalForce && !pauseTween) {
				if (prevTotalTime !== this._totalTime) if (this._onUpdate) if (!suppressEvents) { //so that onUpdate fires even during the repeatDelay - as long as the totalTime changed, we should trigger onUpdate.
					this._callback("onUpdate");
				}
				return;
			} else if (!this._initted) {
				this._initted = true;
			}

			if (!this._active) if (!this._paused && this._totalTime !== prevTotalTime && time > 0) {
				this._active = true;  //so that if the user renders the timeline (as opposed to the parent timeline rendering it), it is forced to re-render and align it with the proper time/frame on the next rendering cycle. Maybe the timeline already finished but the user manually re-renders it as halfway done, for example.
			}

			if (prevTotalTime === 0) if (this.vars.onStart) if (this._totalTime !== 0 || !this._totalDuration) if (!suppressEvents) {
				this._callback("onStart");
			}

			curTime = this._time;
			if (curTime >= prevTime) {
				tween = this._first;
				while (tween) {
					next = tween._next; //record it here because the value could change after rendering...
					if (curTime !== this._time || (this._paused && !prevPaused)) { //in case a tween pauses or seeks the timeline when rendering, like inside of an onUpdate/onComplete
						break;
					} else if (tween._active || (tween._startTime <= this._time && !tween._paused && !tween._gc)) {
						if (pauseTween === tween) {
							this.pause();
						}
						if (!tween._reversed) {
							tween.render((time - tween._startTime) * tween._timeScale, suppressEvents, force);
						} else {
							tween.render(((!tween._dirty) ? tween._totalDuration : tween.totalDuration()) - ((time - tween._startTime) * tween._timeScale), suppressEvents, force);
						}
					}
					tween = next;
				}
			} else {
				tween = this._last;
				while (tween) {
					next = tween._prev; //record it here because the value could change after rendering...
					if (curTime !== this._time || (this._paused && !prevPaused)) { //in case a tween pauses or seeks the timeline when rendering, like inside of an onUpdate/onComplete
						break;
					} else if (tween._active || (tween._startTime <= prevTime && !tween._paused && !tween._gc)) {
						if (pauseTween === tween) {
							pauseTween = tween._prev; //the linked list is organized by _startTime, thus it's possible that a tween could start BEFORE the pause and end after it, in which case it would be positioned before the pause tween in the linked list, but we should render it before we pause() the timeline and cease rendering. This is only a concern when going in reverse.
							while (pauseTween && pauseTween.endTime() > this._time) {
								pauseTween.render( (pauseTween._reversed ? pauseTween.totalDuration() - ((time - pauseTween._startTime) * pauseTween._timeScale) : (time - pauseTween._startTime) * pauseTween._timeScale), suppressEvents, force);
								pauseTween = pauseTween._prev;
							}
							pauseTween = null;
							this.pause();
						}
						if (!tween._reversed) {
							tween.render((time - tween._startTime) * tween._timeScale, suppressEvents, force);
						} else {
							tween.render(((!tween._dirty) ? tween._totalDuration : tween.totalDuration()) - ((time - tween._startTime) * tween._timeScale), suppressEvents, force);
						}
					}
					tween = next;
				}
			}

			if (this._onUpdate) if (!suppressEvents) {
				if (_lazyTweens.length) { //in case rendering caused any tweens to lazy-init, we should render them because typically when a timeline finishes, users expect things to have rendered fully. Imagine an onUpdate on a timeline that reports/checks tweened values.
					_lazyRender();
				}
				this._callback("onUpdate");
			}
			if (callback) if (!this._locked) if (!this._gc) if (prevStart === this._startTime || prevTimeScale !== this._timeScale) if (this._time === 0 || totalDur >= this.totalDuration()) { //if one of the tweens that was rendered altered this timeline's startTime (like if an onComplete reversed the timeline), it probably isn't complete. If it is, don't worry, because whatever call altered the startTime would complete if it was necessary at the new time. The only exception is the timeScale property. Also check _gc because there's a chance that kill() could be called in an onUpdate
				if (isComplete) {
					if (_lazyTweens.length) { //in case rendering caused any tweens to lazy-init, we should render them because typically when a timeline finishes, users expect things to have rendered fully. Imagine an onComplete on a timeline that reports/checks tweened values.
						_lazyRender();
					}
					if (this._timeline.autoRemoveChildren) {
						this._enabled(false, false);
					}
					this._active = false;
				}
				if (!suppressEvents && this.vars[callback]) {
					this._callback(callback);
				}
			}
		};

		p.getActive = function(nested, tweens, timelines) {
			if (nested == null) {
				nested = true;
			}
			if (tweens == null) {
				tweens = true;
			}
			if (timelines == null) {
				timelines = false;
			}
			var a = [],
				all = this.getChildren(nested, tweens, timelines),
				cnt = 0,
				l = all.length,
				i, tween;
			for (i = 0; i < l; i++) {
				tween = all[i];
				if (tween.isActive()) {
					a[cnt++] = tween;
				}
			}
			return a;
		};


		p.getLabelAfter = function(time) {
			if (!time) if (time !== 0) { //faster than isNan()
				time = this._time;
			}
			var labels = this.getLabelsArray(),
				l = labels.length,
				i;
			for (i = 0; i < l; i++) {
				if (labels[i].time > time) {
					return labels[i].name;
				}
			}
			return null;
		};

		p.getLabelBefore = function(time) {
			if (time == null) {
				time = this._time;
			}
			var labels = this.getLabelsArray(),
				i = labels.length;
			while (--i > -1) {
				if (labels[i].time < time) {
					return labels[i].name;
				}
			}
			return null;
		};

		p.getLabelsArray = function() {
			var a = [],
				cnt = 0,
				p;
			for (p in this._labels) {
				a[cnt++] = {time:this._labels[p], name:p};
			}
			a.sort(function(a,b) {
				return a.time - b.time;
			});
			return a;
		};

		p.invalidate = function() {
			this._locked = false; //unlock and set cycle in case invalidate() is called from inside an onRepeat
			return TimelineLite.prototype.invalidate.call(this);
		};


//---- GETTERS / SETTERS -------------------------------------------------------------------------------------------------------

		p.progress = function(value, suppressEvents) {
			return (!arguments.length) ? this._time / this.duration() : this.totalTime( this.duration() * ((this._yoyo && (this._cycle & 1) !== 0) ? 1 - value : value) + (this._cycle * (this._duration + this._repeatDelay)), suppressEvents);
		};

		p.totalProgress = function(value, suppressEvents) {
			return (!arguments.length) ? this._totalTime / this.totalDuration() : this.totalTime( this.totalDuration() * value, suppressEvents);
		};

		p.totalDuration = function(value) {
			if (!arguments.length) {
				if (this._dirty) {
					TimelineLite.prototype.totalDuration.call(this); //just forces refresh
					//Instead of Infinity, we use 999999999999 so that we can accommodate reverses.
					this._totalDuration = (this._repeat === -1) ? 999999999999 : this._duration * (this._repeat + 1) + (this._repeatDelay * this._repeat);
				}
				return this._totalDuration;
			}
			return (this._repeat === -1 || !value) ? this : this.timeScale( this.totalDuration() / value );
		};

		p.time = function(value, suppressEvents) {
			if (!arguments.length) {
				return this._time;
			}
			if (this._dirty) {
				this.totalDuration();
			}
			if (value > this._duration) {
				value = this._duration;
			}
			if (this._yoyo && (this._cycle & 1) !== 0) {
				value = (this._duration - value) + (this._cycle * (this._duration + this._repeatDelay));
			} else if (this._repeat !== 0) {
				value += this._cycle * (this._duration + this._repeatDelay);
			}
			return this.totalTime(value, suppressEvents);
		};

		p.repeat = function(value) {
			if (!arguments.length) {
				return this._repeat;
			}
			this._repeat = value;
			return this._uncache(true);
		};

		p.repeatDelay = function(value) {
			if (!arguments.length) {
				return this._repeatDelay;
			}
			this._repeatDelay = value;
			return this._uncache(true);
		};

		p.yoyo = function(value) {
			if (!arguments.length) {
				return this._yoyo;
			}
			this._yoyo = value;
			return this;
		};

		p.currentLabel = function(value) {
			if (!arguments.length) {
				return this.getLabelBefore(this._time + 0.00000001);
			}
			return this.seek(value, true);
		};

		return TimelineMax;

	}, true);
	




	
	
	
	
	
	
	
/*
 * ----------------------------------------------------------------
 * BezierPlugin
 * ----------------------------------------------------------------
 */
	(function() {

		var _RAD2DEG = 180 / Math.PI,
			_r1 = [],
			_r2 = [],
			_r3 = [],
			_corProps = {},
			_globals = _gsScope._gsDefine.globals,
			Segment = function(a, b, c, d) {
				if (c === d) { //if c and d match, the final autoRotate value could lock at -90 degrees, so differentiate them slightly.
					c = d - (d - b) / 1000000;
				}
				if (a === b) { //if a and b match, the starting autoRotate value could lock at -90 degrees, so differentiate them slightly.
					b = a + (c - a) / 1000000;
				}
				this.a = a;
				this.b = b;
				this.c = c;
				this.d = d;
				this.da = d - a;
				this.ca = c - a;
				this.ba = b - a;
			},
			_correlate = ",x,y,z,left,top,right,bottom,marginTop,marginLeft,marginRight,marginBottom,paddingLeft,paddingTop,paddingRight,paddingBottom,backgroundPosition,backgroundPosition_y,",
			cubicToQuadratic = function(a, b, c, d) {
				var q1 = {a:a},
					q2 = {},
					q3 = {},
					q4 = {c:d},
					mab = (a + b) / 2,
					mbc = (b + c) / 2,
					mcd = (c + d) / 2,
					mabc = (mab + mbc) / 2,
					mbcd = (mbc + mcd) / 2,
					m8 = (mbcd - mabc) / 8;
				q1.b = mab + (a - mab) / 4;
				q2.b = mabc + m8;
				q1.c = q2.a = (q1.b + q2.b) / 2;
				q2.c = q3.a = (mabc + mbcd) / 2;
				q3.b = mbcd - m8;
				q4.b = mcd + (d - mcd) / 4;
				q3.c = q4.a = (q3.b + q4.b) / 2;
				return [q1, q2, q3, q4];
			},
			_calculateControlPoints = function(a, curviness, quad, basic, correlate) {
				var l = a.length - 1,
					ii = 0,
					cp1 = a[0].a,
					i, p1, p2, p3, seg, m1, m2, mm, cp2, qb, r1, r2, tl;
				for (i = 0; i < l; i++) {
					seg = a[ii];
					p1 = seg.a;
					p2 = seg.d;
					p3 = a[ii+1].d;

					if (correlate) {
						r1 = _r1[i];
						r2 = _r2[i];
						tl = ((r2 + r1) * curviness * 0.25) / (basic ? 0.5 : _r3[i] || 0.5);
						m1 = p2 - (p2 - p1) * (basic ? curviness * 0.5 : (r1 !== 0 ? tl / r1 : 0));
						m2 = p2 + (p3 - p2) * (basic ? curviness * 0.5 : (r2 !== 0 ? tl / r2 : 0));
						mm = p2 - (m1 + (((m2 - m1) * ((r1 * 3 / (r1 + r2)) + 0.5) / 4) || 0));
					} else {
						m1 = p2 - (p2 - p1) * curviness * 0.5;
						m2 = p2 + (p3 - p2) * curviness * 0.5;
						mm = p2 - (m1 + m2) / 2;
					}
					m1 += mm;
					m2 += mm;

					seg.c = cp2 = m1;
					if (i !== 0) {
						seg.b = cp1;
					} else {
						seg.b = cp1 = seg.a + (seg.c - seg.a) * 0.6; //instead of placing b on a exactly, we move it inline with c so that if the user specifies an ease like Back.easeIn or Elastic.easeIn which goes BEYOND the beginning, it will do so smoothly.
					}

					seg.da = p2 - p1;
					seg.ca = cp2 - p1;
					seg.ba = cp1 - p1;

					if (quad) {
						qb = cubicToQuadratic(p1, cp1, cp2, p2);
						a.splice(ii, 1, qb[0], qb[1], qb[2], qb[3]);
						ii += 4;
					} else {
						ii++;
					}

					cp1 = m2;
				}
				seg = a[ii];
				seg.b = cp1;
				seg.c = cp1 + (seg.d - cp1) * 0.4; //instead of placing c on d exactly, we move it inline with b so that if the user specifies an ease like Back.easeOut or Elastic.easeOut which goes BEYOND the end, it will do so smoothly.
				seg.da = seg.d - seg.a;
				seg.ca = seg.c - seg.a;
				seg.ba = cp1 - seg.a;
				if (quad) {
					qb = cubicToQuadratic(seg.a, cp1, seg.c, seg.d);
					a.splice(ii, 1, qb[0], qb[1], qb[2], qb[3]);
				}
			},
			_parseAnchors = function(values, p, correlate, prepend) {
				var a = [],
					l, i, p1, p2, p3, tmp;
				if (prepend) {
					values = [prepend].concat(values);
					i = values.length;
					while (--i > -1) {
						if (typeof( (tmp = values[i][p]) ) === "string") if (tmp.charAt(1) === "=") {
							values[i][p] = prepend[p] + Number(tmp.charAt(0) + tmp.substr(2)); //accommodate relative values. Do it inline instead of breaking it out into a function for speed reasons
						}
					}
				}
				l = values.length - 2;
				if (l < 0) {
					a[0] = new Segment(values[0][p], 0, 0, values[(l < -1) ? 0 : 1][p]);
					return a;
				}
				for (i = 0; i < l; i++) {
					p1 = values[i][p];
					p2 = values[i+1][p];
					a[i] = new Segment(p1, 0, 0, p2);
					if (correlate) {
						p3 = values[i+2][p];
						_r1[i] = (_r1[i] || 0) + (p2 - p1) * (p2 - p1);
						_r2[i] = (_r2[i] || 0) + (p3 - p2) * (p3 - p2);
					}
				}
				a[i] = new Segment(values[i][p], 0, 0, values[i+1][p]);
				return a;
			},
			bezierThrough = function(values, curviness, quadratic, basic, correlate, prepend) {
				var obj = {},
					props = [],
					first = prepend || values[0],
					i, p, a, j, r, l, seamless, last;
				correlate = (typeof(correlate) === "string") ? ","+correlate+"," : _correlate;
				if (curviness == null) {
					curviness = 1;
				}
				for (p in values[0]) {
					props.push(p);
				}
				//check to see if the last and first values are identical (well, within 0.05). If so, make seamless by appending the second element to the very end of the values array and the 2nd-to-last element to the very beginning (we'll remove those segments later)
				if (values.length > 1) {
					last = values[values.length - 1];
					seamless = true;
					i = props.length;
					while (--i > -1) {
						p = props[i];
						if (Math.abs(first[p] - last[p]) > 0.05) { //build in a tolerance of +/-0.05 to accommodate rounding errors.
							seamless = false;
							break;
						}
					}
					if (seamless) {
						values = values.concat(); //duplicate the array to avoid contaminating the original which the user may be reusing for other tweens
						if (prepend) {
							values.unshift(prepend);
						}
						values.push(values[1]);
						prepend = values[values.length - 3];
					}
				}
				_r1.length = _r2.length = _r3.length = 0;
				i = props.length;
				while (--i > -1) {
					p = props[i];
					_corProps[p] = (correlate.indexOf(","+p+",") !== -1);
					obj[p] = _parseAnchors(values, p, _corProps[p], prepend);
				}
				i = _r1.length;
				while (--i > -1) {
					_r1[i] = Math.sqrt(_r1[i]);
					_r2[i] = Math.sqrt(_r2[i]);
				}
				if (!basic) {
					i = props.length;
					while (--i > -1) {
						if (_corProps[p]) {
							a = obj[props[i]];
							l = a.length - 1;
							for (j = 0; j < l; j++) {
								r = (a[j+1].da / _r2[j] + a[j].da / _r1[j]) || 0;
								_r3[j] = (_r3[j] || 0) + r * r;
							}
						}
					}
					i = _r3.length;
					while (--i > -1) {
						_r3[i] = Math.sqrt(_r3[i]);
					}
				}
				i = props.length;
				j = quadratic ? 4 : 1;
				while (--i > -1) {
					p = props[i];
					a = obj[p];
					_calculateControlPoints(a, curviness, quadratic, basic, _corProps[p]); //this method requires that _parseAnchors() and _setSegmentRatios() ran first so that _r1, _r2, and _r3 values are populated for all properties
					if (seamless) {
						a.splice(0, j);
						a.splice(a.length - j, j);
					}
				}
				return obj;
			},
			_parseBezierData = function(values, type, prepend) {
				type = type || "soft";
				var obj = {},
					inc = (type === "cubic") ? 3 : 2,
					soft = (type === "soft"),
					props = [],
					a, b, c, d, cur, i, j, l, p, cnt, tmp;
				if (soft && prepend) {
					values = [prepend].concat(values);
				}
				if (values == null || values.length < inc + 1) { throw "invalid Bezier data"; }
				for (p in values[0]) {
					props.push(p);
				}
				i = props.length;
				while (--i > -1) {
					p = props[i];
					obj[p] = cur = [];
					cnt = 0;
					l = values.length;
					for (j = 0; j < l; j++) {
						a = (prepend == null) ? values[j][p] : (typeof( (tmp = values[j][p]) ) === "string" && tmp.charAt(1) === "=") ? prepend[p] + Number(tmp.charAt(0) + tmp.substr(2)) : Number(tmp);
						if (soft) if (j > 1) if (j < l - 1) {
							cur[cnt++] = (a + cur[cnt-2]) / 2;
						}
						cur[cnt++] = a;
					}
					l = cnt - inc + 1;
					cnt = 0;
					for (j = 0; j < l; j += inc) {
						a = cur[j];
						b = cur[j+1];
						c = cur[j+2];
						d = (inc === 2) ? 0 : cur[j+3];
						cur[cnt++] = tmp = (inc === 3) ? new Segment(a, b, c, d) : new Segment(a, (2 * b + a) / 3, (2 * b + c) / 3, c);
					}
					cur.length = cnt;
				}
				return obj;
			},
			_addCubicLengths = function(a, steps, resolution) {
				var inc = 1 / resolution,
					j = a.length,
					d, d1, s, da, ca, ba, p, i, inv, bez, index;
				while (--j > -1) {
					bez = a[j];
					s = bez.a;
					da = bez.d - s;
					ca = bez.c - s;
					ba = bez.b - s;
					d = d1 = 0;
					for (i = 1; i <= resolution; i++) {
						p = inc * i;
						inv = 1 - p;
						d = d1 - (d1 = (p * p * da + 3 * inv * (p * ca + inv * ba)) * p);
						index = j * resolution + i - 1;
						steps[index] = (steps[index] || 0) + d * d;
					}
				}
			},
			_parseLengthData = function(obj, resolution) {
				resolution = resolution >> 0 || 6;
				var a = [],
					lengths = [],
					d = 0,
					total = 0,
					threshold = resolution - 1,
					segments = [],
					curLS = [], //current length segments array
					p, i, l, index;
				for (p in obj) {
					_addCubicLengths(obj[p], a, resolution);
				}
				l = a.length;
				for (i = 0; i < l; i++) {
					d += Math.sqrt(a[i]);
					index = i % resolution;
					curLS[index] = d;
					if (index === threshold) {
						total += d;
						index = (i / resolution) >> 0;
						segments[index] = curLS;
						lengths[index] = total;
						d = 0;
						curLS = [];
					}
				}
				return {length:total, lengths:lengths, segments:segments};
			},



			BezierPlugin = _gsScope._gsDefine.plugin({
					propName: "bezier",
					priority: -1,
					version: "1.3.7",
					API: 2,
					global:true,

					//gets called when the tween renders for the first time. This is where initial values should be recorded and any setup routines should run.
					init: function(target, vars, tween) {
						this._target = target;
						if (vars instanceof Array) {
							vars = {values:vars};
						}
						this._func = {};
						this._mod = {};
						this._props = [];
						this._timeRes = (vars.timeResolution == null) ? 6 : parseInt(vars.timeResolution, 10);
						var values = vars.values || [],
							first = {},
							second = values[0],
							autoRotate = vars.autoRotate || tween.vars.orientToBezier,
							p, isFunc, i, j, prepend;

						this._autoRotate = autoRotate ? (autoRotate instanceof Array) ? autoRotate : [["x","y","rotation",((autoRotate === true) ? 0 : Number(autoRotate) || 0)]] : null;
						for (p in second) {
							this._props.push(p);
						}

						i = this._props.length;
						while (--i > -1) {
							p = this._props[i];

							this._overwriteProps.push(p);
							isFunc = this._func[p] = (typeof(target[p]) === "function");
							first[p] = (!isFunc) ? parseFloat(target[p]) : target[ ((p.indexOf("set") || typeof(target["get" + p.substr(3)]) !== "function") ? p : "get" + p.substr(3)) ]();
							if (!prepend) if (first[p] !== values[0][p]) {
								prepend = first;
							}
						}
						this._beziers = (vars.type !== "cubic" && vars.type !== "quadratic" && vars.type !== "soft") ? bezierThrough(values, isNaN(vars.curviness) ? 1 : vars.curviness, false, (vars.type === "thruBasic"), vars.correlate, prepend) : _parseBezierData(values, vars.type, first);
						this._segCount = this._beziers[p].length;

						if (this._timeRes) {
							var ld = _parseLengthData(this._beziers, this._timeRes);
							this._length = ld.length;
							this._lengths = ld.lengths;
							this._segments = ld.segments;
							this._l1 = this._li = this._s1 = this._si = 0;
							this._l2 = this._lengths[0];
							this._curSeg = this._segments[0];
							this._s2 = this._curSeg[0];
							this._prec = 1 / this._curSeg.length;
						}

						if ((autoRotate = this._autoRotate)) {
							this._initialRotations = [];
							if (!(autoRotate[0] instanceof Array)) {
								this._autoRotate = autoRotate = [autoRotate];
							}
							i = autoRotate.length;
							while (--i > -1) {
								for (j = 0; j < 3; j++) {
									p = autoRotate[i][j];
									this._func[p] = (typeof(target[p]) === "function") ? target[ ((p.indexOf("set") || typeof(target["get" + p.substr(3)]) !== "function") ? p : "get" + p.substr(3)) ] : false;
								}
								p = autoRotate[i][2];
								this._initialRotations[i] = (this._func[p] ? this._func[p].call(this._target) : this._target[p]) || 0;
								this._overwriteProps.push(p);
							}
						}
						this._startRatio = tween.vars.runBackwards ? 1 : 0; //we determine the starting ratio when the tween inits which is always 0 unless the tween has runBackwards:true (indicating it's a from() tween) in which case it's 1.
						return true;
					},

					//called each time the values should be updated, and the ratio gets passed as the only parameter (typically it's a value between 0 and 1, but it can exceed those when using an ease like Elastic.easeOut or Back.easeOut, etc.)
					set: function(v) {
						var segments = this._segCount,
							func = this._func,
							target = this._target,
							notStart = (v !== this._startRatio),
							curIndex, inv, i, p, b, t, val, l, lengths, curSeg;
						if (!this._timeRes) {
							curIndex = (v < 0) ? 0 : (v >= 1) ? segments - 1 : (segments * v) >> 0;
							t = (v - (curIndex * (1 / segments))) * segments;
						} else {
							lengths = this._lengths;
							curSeg = this._curSeg;
							v *= this._length;
							i = this._li;
							//find the appropriate segment (if the currently cached one isn't correct)
							if (v > this._l2 && i < segments - 1) {
								l = segments - 1;
								while (i < l && (this._l2 = lengths[++i]) <= v) {	}
								this._l1 = lengths[i-1];
								this._li = i;
								this._curSeg = curSeg = this._segments[i];
								this._s2 = curSeg[(this._s1 = this._si = 0)];
							} else if (v < this._l1 && i > 0) {
								while (i > 0 && (this._l1 = lengths[--i]) >= v) { }
								if (i === 0 && v < this._l1) {
									this._l1 = 0;
								} else {
									i++;
								}
								this._l2 = lengths[i];
								this._li = i;
								this._curSeg = curSeg = this._segments[i];
								this._s1 = curSeg[(this._si = curSeg.length - 1) - 1] || 0;
								this._s2 = curSeg[this._si];
							}
							curIndex = i;
							//now find the appropriate sub-segment (we split it into the number of pieces that was defined by "precision" and measured each one)
							v -= this._l1;
							i = this._si;
							if (v > this._s2 && i < curSeg.length - 1) {
								l = curSeg.length - 1;
								while (i < l && (this._s2 = curSeg[++i]) <= v) {	}
								this._s1 = curSeg[i-1];
								this._si = i;
							} else if (v < this._s1 && i > 0) {
								while (i > 0 && (this._s1 = curSeg[--i]) >= v) {	}
								if (i === 0 && v < this._s1) {
									this._s1 = 0;
								} else {
									i++;
								}
								this._s2 = curSeg[i];
								this._si = i;
							}
							t = ((i + (v - this._s1) / (this._s2 - this._s1)) * this._prec) || 0;
						}
						inv = 1 - t;

						i = this._props.length;
						while (--i > -1) {
							p = this._props[i];
							b = this._beziers[p][curIndex];
							val = (t * t * b.da + 3 * inv * (t * b.ca + inv * b.ba)) * t + b.a;
							if (this._mod[p]) {
								val = this._mod[p](val, target);
							}
							if (func[p]) {
								target[p](val);
							} else {
								target[p] = val;
							}
						}

						if (this._autoRotate) {
							var ar = this._autoRotate,
								b2, x1, y1, x2, y2, add, conv;
							i = ar.length;
							while (--i > -1) {
								p = ar[i][2];
								add = ar[i][3] || 0;
								conv = (ar[i][4] === true) ? 1 : _RAD2DEG;
								b = this._beziers[ar[i][0]];
								b2 = this._beziers[ar[i][1]];

								if (b && b2) { //in case one of the properties got overwritten.
									b = b[curIndex];
									b2 = b2[curIndex];

									x1 = b.a + (b.b - b.a) * t;
									x2 = b.b + (b.c - b.b) * t;
									x1 += (x2 - x1) * t;
									x2 += ((b.c + (b.d - b.c) * t) - x2) * t;

									y1 = b2.a + (b2.b - b2.a) * t;
									y2 = b2.b + (b2.c - b2.b) * t;
									y1 += (y2 - y1) * t;
									y2 += ((b2.c + (b2.d - b2.c) * t) - y2) * t;

									val = notStart ? Math.atan2(y2 - y1, x2 - x1) * conv + add : this._initialRotations[i];

									if (this._mod[p]) {
										val = this._mod[p](val, target); //for modProps
									}

									if (func[p]) {
										target[p](val);
									} else {
										target[p] = val;
									}
								}
							}
						}
					}
			}),
			p = BezierPlugin.prototype;


		BezierPlugin.bezierThrough = bezierThrough;
		BezierPlugin.cubicToQuadratic = cubicToQuadratic;
		BezierPlugin._autoCSS = true; //indicates that this plugin can be inserted into the "css" object using the autoCSS feature of TweenLite
		BezierPlugin.quadraticToCubic = function(a, b, c) {
			return new Segment(a, (2 * b + a) / 3, (2 * b + c) / 3, c);
		};

		BezierPlugin._cssRegister = function() {
			var CSSPlugin = _globals.CSSPlugin;
			if (!CSSPlugin) {
				return;
			}
			var _internals = CSSPlugin._internals,
				_parseToProxy = _internals._parseToProxy,
				_setPluginRatio = _internals._setPluginRatio,
				CSSPropTween = _internals.CSSPropTween;
			_internals._registerComplexSpecialProp("bezier", {parser:function(t, e, prop, cssp, pt, plugin) {
				if (e instanceof Array) {
					e = {values:e};
				}
				plugin = new BezierPlugin();
				var values = e.values,
					l = values.length - 1,
					pluginValues = [],
					v = {},
					i, p, data;
				if (l < 0) {
					return pt;
				}
				for (i = 0; i <= l; i++) {
					data = _parseToProxy(t, values[i], cssp, pt, plugin, (l !== i));
					pluginValues[i] = data.end;
				}
				for (p in e) {
					v[p] = e[p]; //duplicate the vars object because we need to alter some things which would cause problems if the user plans to reuse the same vars object for another tween.
				}
				v.values = pluginValues;
				pt = new CSSPropTween(t, "bezier", 0, 0, data.pt, 2);
				pt.data = data;
				pt.plugin = plugin;
				pt.setRatio = _setPluginRatio;
				if (v.autoRotate === 0) {
					v.autoRotate = true;
				}
				if (v.autoRotate && !(v.autoRotate instanceof Array)) {
					i = (v.autoRotate === true) ? 0 : Number(v.autoRotate);
					v.autoRotate = (data.end.left != null) ? [["left","top","rotation",i,false]] : (data.end.x != null) ? [["x","y","rotation",i,false]] : false;
				}
				if (v.autoRotate) {
					if (!cssp._transform) {
						cssp._enableTransforms(false);
					}
					data.autoRotate = cssp._target._gsTransform;
					data.proxy.rotation = data.autoRotate.rotation || 0;
					cssp._overwriteProps.push("rotation");
				}
				plugin._onInitTween(data.proxy, v, cssp._tween);
				return pt;
			}});
		};

		p._mod = function(lookup) {
			var op = this._overwriteProps,
				i = op.length,
				val;
			while (--i > -1) {
				val = lookup[op[i]];
				if (val && typeof(val) === "function") {
					this._mod[op[i]] = val;
				}
			}
		};

		p._kill = function(lookup) {
			var a = this._props,
				p, i;
			for (p in this._beziers) {
				if (p in lookup) {
					delete this._beziers[p];
					delete this._func[p];
					i = a.length;
					while (--i > -1) {
						if (a[i] === p) {
							a.splice(i, 1);
						}
					}
				}
			}
			a = this._autoRotate;
			if (a) {
				i = a.length;
				while (--i > -1) {
					if (lookup[a[i][2]]) {
						a.splice(i, 1);
					}
				}
			}
			return this._super._kill.call(this, lookup);
		};

	}());






	
	
	
	
	
	
	
	
/*
 * ----------------------------------------------------------------
 * CSSPlugin
 * ----------------------------------------------------------------
 */
	_gsScope._gsDefine("plugins.CSSPlugin", ["plugins.TweenPlugin","TweenLite"], function(TweenPlugin, TweenLite) {

		/** @constructor **/
		var CSSPlugin = function() {
				TweenPlugin.call(this, "css");
				this._overwriteProps.length = 0;
				this.setRatio = CSSPlugin.prototype.setRatio; //speed optimization (avoid prototype lookup on this "hot" method)
			},
			_globals = _gsScope._gsDefine.globals,
			_hasPriority, //turns true whenever a CSSPropTween instance is created that has a priority other than 0. This helps us discern whether or not we should spend the time organizing the linked list or not after a CSSPlugin's _onInitTween() method is called.
			_suffixMap, //we set this in _onInitTween() each time as a way to have a persistent variable we can use in other methods like _parse() without having to pass it around as a parameter and we keep _parse() decoupled from a particular CSSPlugin instance
			_cs, //computed style (we store this in a shared variable to conserve memory and make minification tighter
			_overwriteProps, //alias to the currently instantiating CSSPlugin's _overwriteProps array. We use this closure in order to avoid having to pass a reference around from method to method and aid in minification.
			_specialProps = {},
			p = CSSPlugin.prototype = new TweenPlugin("css");

		p.constructor = CSSPlugin;
		CSSPlugin.version = "1.19.1";
		CSSPlugin.API = 2;
		CSSPlugin.defaultTransformPerspective = 0;
		CSSPlugin.defaultSkewType = "compensated";
		CSSPlugin.defaultSmoothOrigin = true;
		p = "px"; //we'll reuse the "p" variable to keep file size down
		CSSPlugin.suffixMap = {top:p, right:p, bottom:p, left:p, width:p, height:p, fontSize:p, padding:p, margin:p, perspective:p, lineHeight:""};


		var _numExp = /(?:\-|\.|\b)(\d|\.|e\-)+/g,
			_relNumExp = /(?:\d|\-\d|\.\d|\-\.\d|\+=\d|\-=\d|\+=.\d|\-=\.\d)+/g,
			_valuesExp = /(?:\+=|\-=|\-|\b)[\d\-\.]+[a-zA-Z0-9]*(?:%|\b)/gi, //finds all the values that begin with numbers or += or -= and then a number. Includes suffixes. We use this to split complex values apart like "1px 5px 20px rgb(255,102,51)"
			_NaNExp = /(?![+-]?\d*\.?\d+|[+-]|e[+-]\d+)[^0-9]/g, //also allows scientific notation and doesn't kill the leading -/+ in -= and +=
			_suffixExp = /(?:\d|\-|\+|=|#|\.)*/g,
			_opacityExp = /opacity *= *([^)]*)/i,
			_opacityValExp = /opacity:([^;]*)/i,
			_alphaFilterExp = /alpha\(opacity *=.+?\)/i,
			_rgbhslExp = /^(rgb|hsl)/,
			_capsExp = /([A-Z])/g,
			_camelExp = /-([a-z])/gi,
			_urlExp = /(^(?:url\(\"|url\())|(?:(\"\))$|\)$)/gi, //for pulling out urls from url(...) or url("...") strings (some browsers wrap urls in quotes, some don't when reporting things like backgroundImage)
			_camelFunc = function(s, g) { return g.toUpperCase(); },
			_horizExp = /(?:Left|Right|Width)/i,
			_ieGetMatrixExp = /(M11|M12|M21|M22)=[\d\-\.e]+/gi,
			_ieSetMatrixExp = /progid\:DXImageTransform\.Microsoft\.Matrix\(.+?\)/i,
			_commasOutsideParenExp = /,(?=[^\)]*(?:\(|$))/gi, //finds any commas that are not within parenthesis
			_complexExp = /[\s,\(]/i, //for testing a string to find if it has a space, comma, or open parenthesis (clues that it's a complex value)
			_DEG2RAD = Math.PI / 180,
			_RAD2DEG = 180 / Math.PI,
			_forcePT = {},
			_dummyElement = {style:{}},
			_doc = _gsScope.document || {createElement: function() {return _dummyElement;}},
			_createElement = function(type, ns) {
				return _doc.createElementNS ? _doc.createElementNS(ns || "http://www.w3.org/1999/xhtml", type) : _doc.createElement(type);
			},
			_tempDiv = _createElement("div"),
			_tempImg = _createElement("img"),
			_internals = CSSPlugin._internals = {_specialProps:_specialProps}, //provides a hook to a few internal methods that we need to access from inside other plugins
			_agent = (_gsScope.navigator || {}).userAgent || "",
			_autoRound,
			_reqSafariFix, //we won't apply the Safari transform fix until we actually come across a tween that affects a transform property (to maintain best performance).

			_isSafari,
			_isFirefox, //Firefox has a bug that causes 3D transformed elements to randomly disappear unless a repaint is forced after each update on each element.
			_isSafariLT6, //Safari (and Android 4 which uses a flavor of Safari) has a bug that prevents changes to "top" and "left" properties from rendering properly if changed on the same frame as a transform UNLESS we set the element's WebkitBackfaceVisibility to hidden (weird, I know). Doing this for Android 3 and earlier seems to actually cause other problems, though (fun!)
			_ieVers,
			_supportsOpacity = (function() { //we set _isSafari, _ieVers, _isFirefox, and _supportsOpacity all in one function here to reduce file size slightly, especially in the minified version.
				var i = _agent.indexOf("Android"),
					a = _createElement("a");
				_isSafari = (_agent.indexOf("Safari") !== -1 && _agent.indexOf("Chrome") === -1 && (i === -1 || parseFloat(_agent.substr(i+8, 2)) > 3));
				_isSafariLT6 = (_isSafari && (parseFloat(_agent.substr(_agent.indexOf("Version/")+8, 2)) < 6));
				_isFirefox = (_agent.indexOf("Firefox") !== -1);
				if ((/MSIE ([0-9]{1,}[\.0-9]{0,})/).exec(_agent) || (/Trident\/.*rv:([0-9]{1,}[\.0-9]{0,})/).exec(_agent)) {
					_ieVers = parseFloat( RegExp.$1 );
				}
				if (!a) {
					return false;
				}
				a.style.cssText = "top:1px;opacity:.55;";
				return /^0.55/.test(a.style.opacity);
			}()),
			_getIEOpacity = function(v) {
				return (_opacityExp.test( ((typeof(v) === "string") ? v : (v.currentStyle ? v.currentStyle.filter : v.style.filter) || "") ) ? ( parseFloat( RegExp.$1 ) / 100 ) : 1);
			},
			_log = function(s) {//for logging messages, but in a way that won't throw errors in old versions of IE.
				if (_gsScope.console) {
					console.log(s);
				}
			},
			_target, //when initting a CSSPlugin, we set this variable so that we can access it from within many other functions without having to pass it around as params
			_index, //when initting a CSSPlugin, we set this variable so that we can access it from within many other functions without having to pass it around as params

			_prefixCSS = "", //the non-camelCase vendor prefix like "-o-", "-moz-", "-ms-", or "-webkit-"
			_prefix = "", //camelCase vendor prefix like "O", "ms", "Webkit", or "Moz".

			// @private feed in a camelCase property name like "transform" and it will check to see if it is valid as-is or if it needs a vendor prefix. It returns the corrected camelCase property name (i.e. "WebkitTransform" or "MozTransform" or "transform" or null if no such property is found, like if the browser is IE8 or before, "transform" won't be found at all)
			_checkPropPrefix = function(p, e) {
				e = e || _tempDiv;
				var s = e.style,
					a, i;
				if (s[p] !== undefined) {
					return p;
				}
				p = p.charAt(0).toUpperCase() + p.substr(1);
				a = ["O","Moz","ms","Ms","Webkit"];
				i = 5;
				while (--i > -1 && s[a[i]+p] === undefined) { }
				if (i >= 0) {
					_prefix = (i === 3) ? "ms" : a[i];
					_prefixCSS = "-" + _prefix.toLowerCase() + "-";
					return _prefix + p;
				}
				return null;
			},

			_getComputedStyle = _doc.defaultView ? _doc.defaultView.getComputedStyle : function() {},

			/**
			 * @private Returns the css style for a particular property of an element. For example, to get whatever the current "left" css value for an element with an ID of "myElement", you could do:
			 * var currentLeft = CSSPlugin.getStyle( document.getElementById("myElement"), "left");
			 *
			 * @param {!Object} t Target element whose style property you want to query
			 * @param {!string} p Property name (like "left" or "top" or "marginTop", etc.)
			 * @param {Object=} cs Computed style object. This just provides a way to speed processing if you're going to get several properties on the same element in quick succession - you can reuse the result of the getComputedStyle() call.
			 * @param {boolean=} calc If true, the value will not be read directly from the element's "style" property (if it exists there), but instead the getComputedStyle() result will be used. This can be useful when you want to ensure that the browser itself is interpreting the value.
			 * @param {string=} dflt Default value that should be returned in the place of null, "none", "auto" or "auto auto".
			 * @return {?string} The current property value
			 */
			_getStyle = CSSPlugin.getStyle = function(t, p, cs, calc, dflt) {
				var rv;
				if (!_supportsOpacity) if (p === "opacity") { //several versions of IE don't use the standard "opacity" property - they use things like filter:alpha(opacity=50), so we parse that here.
					return _getIEOpacity(t);
				}
				if (!calc && t.style[p]) {
					rv = t.style[p];
				} else if ((cs = cs || _getComputedStyle(t))) {
					rv = cs[p] || cs.getPropertyValue(p) || cs.getPropertyValue(p.replace(_capsExp, "-$1").toLowerCase());
				} else if (t.currentStyle) {
					rv = t.currentStyle[p];
				}
				return (dflt != null && (!rv || rv === "none" || rv === "auto" || rv === "auto auto")) ? dflt : rv;
			},

			/**
			 * @private Pass the target element, the property name, the numeric value, and the suffix (like "%", "em", "px", etc.) and it will spit back the equivalent pixel number.
			 * @param {!Object} t Target element
			 * @param {!string} p Property name (like "left", "top", "marginLeft", etc.)
			 * @param {!number} v Value
			 * @param {string=} sfx Suffix (like "px" or "%" or "em")
			 * @param {boolean=} recurse If true, the call is a recursive one. In some browsers (like IE7/8), occasionally the value isn't accurately reported initially, but if we run the function again it will take effect.
			 * @return {number} value in pixels
			 */
			_convertToPixels = _internals.convertToPixels = function(t, p, v, sfx, recurse) {
				if (sfx === "px" || !sfx) { return v; }
				if (sfx === "auto" || !v) { return 0; }
				var horiz = _horizExp.test(p),
					node = t,
					style = _tempDiv.style,
					neg = (v < 0),
					precise = (v === 1),
					pix, cache, time;
				if (neg) {
					v = -v;
				}
				if (precise) {
					v *= 100;
				}
				if (sfx === "%" && p.indexOf("border") !== -1) {
					pix = (v / 100) * (horiz ? t.clientWidth : t.clientHeight);
				} else {
					style.cssText = "border:0 solid red;position:" + _getStyle(t, "position") + ";line-height:0;";
					if (sfx === "%" || !node.appendChild || sfx.charAt(0) === "v" || sfx === "rem") {
						node = t.parentNode || _doc.body;
						cache = node._gsCache;
						time = TweenLite.ticker.frame;
						if (cache && horiz && cache.time === time) { //performance optimization: we record the width of elements along with the ticker frame so that we can quickly get it again on the same tick (seems relatively safe to assume it wouldn't change on the same tick)
							return cache.width * v / 100;
						}
						style[(horiz ? "width" : "height")] = v + sfx;
					} else {
						style[(horiz ? "borderLeftWidth" : "borderTopWidth")] = v + sfx;
					}
					node.appendChild(_tempDiv);
					pix = parseFloat(_tempDiv[(horiz ? "offsetWidth" : "offsetHeight")]);
					node.removeChild(_tempDiv);
					if (horiz && sfx === "%" && CSSPlugin.cacheWidths !== false) {
						cache = node._gsCache = node._gsCache || {};
						cache.time = time;
						cache.width = pix / v * 100;
					}
					if (pix === 0 && !recurse) {
						pix = _convertToPixels(t, p, v, sfx, true);
					}
				}
				if (precise) {
					pix /= 100;
				}
				return neg ? -pix : pix;
			},
			_calculateOffset = _internals.calculateOffset = function(t, p, cs) { //for figuring out "top" or "left" in px when it's "auto". We need to factor in margin with the offsetLeft/offsetTop
				if (_getStyle(t, "position", cs) !== "absolute") { return 0; }
				var dim = ((p === "left") ? "Left" : "Top"),
					v = _getStyle(t, "margin" + dim, cs);
				return t["offset" + dim] - (_convertToPixels(t, p, parseFloat(v), v.replace(_suffixExp, "")) || 0);
			},

			// @private returns at object containing ALL of the style properties in camelCase and their associated values.
			_getAllStyles = function(t, cs) {
				var s = {},
					i, tr, p;
				if ((cs = cs || _getComputedStyle(t, null))) {
					if ((i = cs.length)) {
						while (--i > -1) {
							p = cs[i];
							if (p.indexOf("-transform") === -1 || _transformPropCSS === p) { //Some webkit browsers duplicate transform values, one non-prefixed and one prefixed ("transform" and "WebkitTransform"), so we must weed out the extra one here.
								s[p.replace(_camelExp, _camelFunc)] = cs.getPropertyValue(p);
							}
						}
					} else { //some browsers behave differently - cs.length is always 0, so we must do a for...in loop.
						for (i in cs) {
							if (i.indexOf("Transform") === -1 || _transformProp === i) { //Some webkit browsers duplicate transform values, one non-prefixed and one prefixed ("transform" and "WebkitTransform"), so we must weed out the extra one here.
								s[i] = cs[i];
							}
						}
					}
				} else if ((cs = t.currentStyle || t.style)) {
					for (i in cs) {
						if (typeof(i) === "string" && s[i] === undefined) {
							s[i.replace(_camelExp, _camelFunc)] = cs[i];
						}
					}
				}
				if (!_supportsOpacity) {
					s.opacity = _getIEOpacity(t);
				}
				tr = _getTransform(t, cs, false);
				s.rotation = tr.rotation;
				s.skewX = tr.skewX;
				s.scaleX = tr.scaleX;
				s.scaleY = tr.scaleY;
				s.x = tr.x;
				s.y = tr.y;
				if (_supports3D) {
					s.z = tr.z;
					s.rotationX = tr.rotationX;
					s.rotationY = tr.rotationY;
					s.scaleZ = tr.scaleZ;
				}
				if (s.filters) {
					delete s.filters;
				}
				return s;
			},

			// @private analyzes two style objects (as returned by _getAllStyles()) and only looks for differences between them that contain tweenable values (like a number or color). It returns an object with a "difs" property which refers to an object containing only those isolated properties and values for tweening, and a "firstMPT" property which refers to the first MiniPropTween instance in a linked list that recorded all the starting values of the different properties so that we can revert to them at the end or beginning of the tween - we don't want the cascading to get messed up. The forceLookup parameter is an optional generic object with properties that should be forced into the results - this is necessary for className tweens that are overwriting others because imagine a scenario where a rollover/rollout adds/removes a class and the user swipes the mouse over the target SUPER fast, thus nothing actually changed yet and the subsequent comparison of the properties would indicate they match (especially when px rounding is taken into consideration), thus no tweening is necessary even though it SHOULD tween and remove those properties after the tween (otherwise the inline styles will contaminate things). See the className SpecialProp code for details.
			_cssDif = function(t, s1, s2, vars, forceLookup) {
				var difs = {},
					style = t.style,
					val, p, mpt;
				for (p in s2) {
					if (p !== "cssText") if (p !== "length") if (isNaN(p)) if (s1[p] !== (val = s2[p]) || (forceLookup && forceLookup[p])) if (p.indexOf("Origin") === -1) if (typeof(val) === "number" || typeof(val) === "string") {
						difs[p] = (val === "auto" && (p === "left" || p === "top")) ? _calculateOffset(t, p) : ((val === "" || val === "auto" || val === "none") && typeof(s1[p]) === "string" && s1[p].replace(_NaNExp, "") !== "") ? 0 : val; //if the ending value is defaulting ("" or "auto"), we check the starting value and if it can be parsed into a number (a string which could have a suffix too, like 700px), then we swap in 0 for "" or "auto" so that things actually tween.
						if (style[p] !== undefined) { //for className tweens, we must remember which properties already existed inline - the ones that didn't should be removed when the tween isn't in progress because they were only introduced to facilitate the transition between classes.
							mpt = new MiniPropTween(style, p, style[p], mpt);
						}
					}
				}
				if (vars) {
					for (p in vars) { //copy properties (except className)
						if (p !== "className") {
							difs[p] = vars[p];
						}
					}
				}
				return {difs:difs, firstMPT:mpt};
			},
			_dimensions = {width:["Left","Right"], height:["Top","Bottom"]},
			_margins = ["marginLeft","marginRight","marginTop","marginBottom"],

			/**
			 * @private Gets the width or height of an element
			 * @param {!Object} t Target element
			 * @param {!string} p Property name ("width" or "height")
			 * @param {Object=} cs Computed style object (if one exists). Just a speed optimization.
			 * @return {number} Dimension (in pixels)
			 */
			_getDimension = function(t, p, cs) {
				if ((t.nodeName + "").toLowerCase() === "svg") { //Chrome no longer supports offsetWidth/offsetHeight on SVG elements.
					return (cs || _getComputedStyle(t))[p] || 0;
				} else if (t.getCTM && _isSVG(t)) {
					return t.getBBox()[p] || 0;
				}
				var v = parseFloat((p === "width") ? t.offsetWidth : t.offsetHeight),
					a = _dimensions[p],
					i = a.length;
				cs = cs || _getComputedStyle(t, null);
				while (--i > -1) {
					v -= parseFloat( _getStyle(t, "padding" + a[i], cs, true) ) || 0;
					v -= parseFloat( _getStyle(t, "border" + a[i] + "Width", cs, true) ) || 0;
				}
				return v;
			},

			// @private Parses position-related complex strings like "top left" or "50px 10px" or "70% 20%", etc. which are used for things like transformOrigin or backgroundPosition. Optionally decorates a supplied object (recObj) with the following properties: "ox" (offsetX), "oy" (offsetY), "oxp" (if true, "ox" is a percentage not a pixel value), and "oxy" (if true, "oy" is a percentage not a pixel value)
			_parsePosition = function(v, recObj) {
				if (v === "contain" || v === "auto" || v === "auto auto") { //note: Firefox uses "auto auto" as default whereas Chrome uses "auto".
					return v + " ";
				}
				if (v == null || v === "") {
					v = "0 0";
				}
				var a = v.split(" "),
					x = (v.indexOf("left") !== -1) ? "0%" : (v.indexOf("right") !== -1) ? "100%" : a[0],
					y = (v.indexOf("top") !== -1) ? "0%" : (v.indexOf("bottom") !== -1) ? "100%" : a[1],
					i;
				if (a.length > 3 && !recObj) { //multiple positions
					a = v.split(", ").join(",").split(",");
					v = [];
					for (i = 0; i < a.length; i++) {
						v.push(_parsePosition(a[i]));
					}
					return v.join(",");
				}
				if (y == null) {
					y = (x === "center") ? "50%" : "0";
				} else if (y === "center") {
					y = "50%";
				}
				if (x === "center" || (isNaN(parseFloat(x)) && (x + "").indexOf("=") === -1)) { //remember, the user could flip-flop the values and say "bottom center" or "center bottom", etc. "center" is ambiguous because it could be used to describe horizontal or vertical, hence the isNaN(). If there's an "=" sign in the value, it's relative.
					x = "50%";
				}
				v = x + " " + y + ((a.length > 2) ? " " + a[2] : "");
				if (recObj) {
					recObj.oxp = (x.indexOf("%") !== -1);
					recObj.oyp = (y.indexOf("%") !== -1);
					recObj.oxr = (x.charAt(1) === "=");
					recObj.oyr = (y.charAt(1) === "=");
					recObj.ox = parseFloat(x.replace(_NaNExp, ""));
					recObj.oy = parseFloat(y.replace(_NaNExp, ""));
					recObj.v = v;
				}
				return recObj || v;
			},

			/**
			 * @private Takes an ending value (typically a string, but can be a number) and a starting value and returns the change between the two, looking for relative value indicators like += and -= and it also ignores suffixes (but make sure the ending value starts with a number or +=/-= and that the starting value is a NUMBER!)
			 * @param {(number|string)} e End value which is typically a string, but could be a number
			 * @param {(number|string)} b Beginning value which is typically a string but could be a number
			 * @return {number} Amount of change between the beginning and ending values (relative values that have a "+=" or "-=" are recognized)
			 */
			_parseChange = function(e, b) {
				if (typeof(e) === "function") {
					e = e(_index, _target);
				}
				return (typeof(e) === "string" && e.charAt(1) === "=") ? parseInt(e.charAt(0) + "1", 10) * parseFloat(e.substr(2)) : (parseFloat(e) - parseFloat(b)) || 0;
			},

			/**
			 * @private Takes a value and a default number, checks if the value is relative, null, or numeric and spits back a normalized number accordingly. Primarily used in the _parseTransform() function.
			 * @param {Object} v Value to be parsed
			 * @param {!number} d Default value (which is also used for relative calculations if "+=" or "-=" is found in the first parameter)
			 * @return {number} Parsed value
			 */
			_parseVal = function(v, d) {
				if (typeof(v) === "function") {
					v = v(_index, _target);
				}
				return (v == null) ? d : (typeof(v) === "string" && v.charAt(1) === "=") ? parseInt(v.charAt(0) + "1", 10) * parseFloat(v.substr(2)) + d : parseFloat(v) || 0;
			},

			/**
			 * @private Translates strings like "40deg" or "40" or 40rad" or "+=40deg" or "270_short" or "-90_cw" or "+=45_ccw" to a numeric radian angle. Of course a starting/default value must be fed in too so that relative values can be calculated properly.
			 * @param {Object} v Value to be parsed
			 * @param {!number} d Default value (which is also used for relative calculations if "+=" or "-=" is found in the first parameter)
			 * @param {string=} p property name for directionalEnd (optional - only used when the parsed value is directional ("_short", "_cw", or "_ccw" suffix). We need a way to store the uncompensated value so that at the end of the tween, we set it to exactly what was requested with no directional compensation). Property name would be "rotation", "rotationX", or "rotationY"
			 * @param {Object=} directionalEnd An object that will store the raw end values for directional angles ("_short", "_cw", or "_ccw" suffix). We need a way to store the uncompensated value so that at the end of the tween, we set it to exactly what was requested with no directional compensation.
			 * @return {number} parsed angle in radians
			 */
			_parseAngle = function(v, d, p, directionalEnd) {
				var min = 0.000001,
					cap, split, dif, result, isRelative;
				if (typeof(v) === "function") {
					v = v(_index, _target);
				}
				if (v == null) {
					result = d;
				} else if (typeof(v) === "number") {
					result = v;
				} else {
					cap = 360;
					split = v.split("_");
					isRelative = (v.charAt(1) === "=");
					dif = (isRelative ? parseInt(v.charAt(0) + "1", 10) * parseFloat(split[0].substr(2)) : parseFloat(split[0])) * ((v.indexOf("rad") === -1) ? 1 : _RAD2DEG) - (isRelative ? 0 : d);
					if (split.length) {
						if (directionalEnd) {
							directionalEnd[p] = d + dif;
						}
						if (v.indexOf("short") !== -1) {
							dif = dif % cap;
							if (dif !== dif % (cap / 2)) {
								dif = (dif < 0) ? dif + cap : dif - cap;
							}
						}
						if (v.indexOf("_cw") !== -1 && dif < 0) {
							dif = ((dif + cap * 9999999999) % cap) - ((dif / cap) | 0) * cap;
						} else if (v.indexOf("ccw") !== -1 && dif > 0) {
							dif = ((dif - cap * 9999999999) % cap) - ((dif / cap) | 0) * cap;
						}
					}
					result = d + dif;
				}
				if (result < min && result > -min) {
					result = 0;
				}
				return result;
			},

			_colorLookup = {aqua:[0,255,255],
				lime:[0,255,0],
				silver:[192,192,192],
				black:[0,0,0],
				maroon:[128,0,0],
				teal:[0,128,128],
				blue:[0,0,255],
				navy:[0,0,128],
				white:[255,255,255],
				fuchsia:[255,0,255],
				olive:[128,128,0],
				yellow:[255,255,0],
				orange:[255,165,0],
				gray:[128,128,128],
				purple:[128,0,128],
				green:[0,128,0],
				red:[255,0,0],
				pink:[255,192,203],
				cyan:[0,255,255],
				transparent:[255,255,255,0]},

			_hue = function(h, m1, m2) {
				h = (h < 0) ? h + 1 : (h > 1) ? h - 1 : h;
				return ((((h * 6 < 1) ? m1 + (m2 - m1) * h * 6 : (h < 0.5) ? m2 : (h * 3 < 2) ? m1 + (m2 - m1) * (2 / 3 - h) * 6 : m1) * 255) + 0.5) | 0;
			},

			/**
			 * @private Parses a color (like #9F0, #FF9900, rgb(255,51,153) or hsl(108, 50%, 10%)) into an array with 3 elements for red, green, and blue or if toHSL parameter is true, it will populate the array with hue, saturation, and lightness values. If a relative value is found in an hsl() or hsla() string, it will preserve those relative prefixes and all the values in the array will be strings instead of numbers (in all other cases it will be populated with numbers).
			 * @param {(string|number)} v The value the should be parsed which could be a string like #9F0 or rgb(255,102,51) or rgba(255,0,0,0.5) or it could be a number like 0xFF00CC or even a named color like red, blue, purple, etc.
			 * @param {(boolean)} toHSL If true, an hsl() or hsla() value will be returned instead of rgb() or rgba()
			 * @return {Array.<number>} An array containing red, green, and blue (and optionally alpha) in that order, or if the toHSL parameter was true, the array will contain hue, saturation and lightness (and optionally alpha) in that order. Always numbers unless there's a relative prefix found in an hsl() or hsla() string and toHSL is true.
			 */
			_parseColor = CSSPlugin.parseColor = function(v, toHSL) {
				var a, r, g, b, h, s, l, max, min, d, wasHSL;
				if (!v) {
					a = _colorLookup.black;
				} else if (typeof(v) === "number") {
					a = [v >> 16, (v >> 8) & 255, v & 255];
				} else {
					if (v.charAt(v.length - 1) === ",") { //sometimes a trailing comma is included and we should chop it off (typically from a comma-delimited list of values like a textShadow:"2px 2px 2px blue, 5px 5px 5px rgb(255,0,0)" - in this example "blue," has a trailing comma. We could strip it out inside parseComplex() but we'd need to do it to the beginning and ending values plus it wouldn't provide protection from other potential scenarios like if the user passes in a similar value.
						v = v.substr(0, v.length - 1);
					}
					if (_colorLookup[v]) {
						a = _colorLookup[v];
					} else if (v.charAt(0) === "#") {
						if (v.length === 4) { //for shorthand like #9F0
							r = v.charAt(1);
							g = v.charAt(2);
							b = v.charAt(3);
							v = "#" + r + r + g + g + b + b;
						}
						v = parseInt(v.substr(1), 16);
						a = [v >> 16, (v >> 8) & 255, v & 255];
					} else if (v.substr(0, 3) === "hsl") {
						a = wasHSL = v.match(_numExp);
						if (!toHSL) {
							h = (Number(a[0]) % 360) / 360;
							s = Number(a[1]) / 100;
							l = Number(a[2]) / 100;
							g = (l <= 0.5) ? l * (s + 1) : l + s - l * s;
							r = l * 2 - g;
							if (a.length > 3) {
								a[3] = Number(v[3]);
							}
							a[0] = _hue(h + 1 / 3, r, g);
							a[1] = _hue(h, r, g);
							a[2] = _hue(h - 1 / 3, r, g);
						} else if (v.indexOf("=") !== -1) { //if relative values are found, just return the raw strings with the relative prefixes in place.
							return v.match(_relNumExp);
						}
					} else {
						a = v.match(_numExp) || _colorLookup.transparent;
					}
					a[0] = Number(a[0]);
					a[1] = Number(a[1]);
					a[2] = Number(a[2]);
					if (a.length > 3) {
						a[3] = Number(a[3]);
					}
				}
				if (toHSL && !wasHSL) {
					r = a[0] / 255;
					g = a[1] / 255;
					b = a[2] / 255;
					max = Math.max(r, g, b);
					min = Math.min(r, g, b);
					l = (max + min) / 2;
					if (max === min) {
						h = s = 0;
					} else {
						d = max - min;
						s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
						h = (max === r) ? (g - b) / d + (g < b ? 6 : 0) : (max === g) ? (b - r) / d + 2 : (r - g) / d + 4;
						h *= 60;
					}
					a[0] = (h + 0.5) | 0;
					a[1] = (s * 100 + 0.5) | 0;
					a[2] = (l * 100 + 0.5) | 0;
				}
				return a;
			},
			_formatColors = function(s, toHSL) {
				var colors = s.match(_colorExp) || [],
					charIndex = 0,
					parsed = colors.length ? "" : s,
					i, color, temp;
				for (i = 0; i < colors.length; i++) {
					color = colors[i];
					temp = s.substr(charIndex, s.indexOf(color, charIndex)-charIndex);
					charIndex += temp.length + color.length;
					color = _parseColor(color, toHSL);
					if (color.length === 3) {
						color.push(1);
					}
					parsed += temp + (toHSL ? "hsla(" + color[0] + "," + color[1] + "%," + color[2] + "%," + color[3] : "rgba(" + color.join(",")) + ")";
				}
				return parsed + s.substr(charIndex);
			},
			_colorExp = "(?:\\b(?:(?:rgb|rgba|hsl|hsla)\\(.+?\\))|\\B#(?:[0-9a-f]{3}){1,2}\\b"; //we'll dynamically build this Regular Expression to conserve file size. After building it, it will be able to find rgb(), rgba(), # (hexadecimal), and named color values like red, blue, purple, etc.

		for (p in _colorLookup) {
			_colorExp += "|" + p + "\\b";
		}
		_colorExp = new RegExp(_colorExp+")", "gi");

		CSSPlugin.colorStringFilter = function(a) {
			var combined = a[0] + a[1],
				toHSL;
			if (_colorExp.test(combined)) {
				toHSL = (combined.indexOf("hsl(") !== -1 || combined.indexOf("hsla(") !== -1);
				a[0] = _formatColors(a[0], toHSL);
				a[1] = _formatColors(a[1], toHSL);
			}
			_colorExp.lastIndex = 0;
		};

		if (!TweenLite.defaultStringFilter) {
			TweenLite.defaultStringFilter = CSSPlugin.colorStringFilter;
		}

		/**
		 * @private Returns a formatter function that handles taking a string (or number in some cases) and returning a consistently formatted one in terms of delimiters, quantity of values, etc. For example, we may get boxShadow values defined as "0px red" or "0px 0px 10px rgb(255,0,0)" or "0px 0px 20px 20px #F00" and we need to ensure that what we get back is described with 4 numbers and a color. This allows us to feed it into the _parseComplex() method and split the values up appropriately. The neat thing about this _getFormatter() function is that the dflt defines a pattern as well as a default, so for example, _getFormatter("0px 0px 0px 0px #777", true) not only sets the default as 0px for all distances and #777 for the color, but also sets the pattern such that 4 numbers and a color will always get returned.
		 * @param {!string} dflt The default value and pattern to follow. So "0px 0px 0px 0px #777" will ensure that 4 numbers and a color will always get returned.
		 * @param {boolean=} clr If true, the values should be searched for color-related data. For example, boxShadow values typically contain a color whereas borderRadius don't.
		 * @param {boolean=} collapsible If true, the value is a top/left/right/bottom style one that acts like margin or padding, where if only one value is received, it's used for all 4; if 2 are received, the first is duplicated for 3rd (bottom) and the 2nd is duplicated for the 4th spot (left), etc.
		 * @return {Function} formatter function
		 */
		var _getFormatter = function(dflt, clr, collapsible, multi) {
				if (dflt == null) {
					return function(v) {return v;};
				}
				var dColor = clr ? (dflt.match(_colorExp) || [""])[0] : "",
					dVals = dflt.split(dColor).join("").match(_valuesExp) || [],
					pfx = dflt.substr(0, dflt.indexOf(dVals[0])),
					sfx = (dflt.charAt(dflt.length - 1) === ")") ? ")" : "",
					delim = (dflt.indexOf(" ") !== -1) ? " " : ",",
					numVals = dVals.length,
					dSfx = (numVals > 0) ? dVals[0].replace(_numExp, "") : "",
					formatter;
				if (!numVals) {
					return function(v) {return v;};
				}
				if (clr) {
					formatter = function(v) {
						var color, vals, i, a;
						if (typeof(v) === "number") {
							v += dSfx;
						} else if (multi && _commasOutsideParenExp.test(v)) {
							a = v.replace(_commasOutsideParenExp, "|").split("|");
							for (i = 0; i < a.length; i++) {
								a[i] = formatter(a[i]);
							}
							return a.join(",");
						}
						color = (v.match(_colorExp) || [dColor])[0];
						vals = v.split(color).join("").match(_valuesExp) || [];
						i = vals.length;
						if (numVals > i--) {
							while (++i < numVals) {
								vals[i] = collapsible ? vals[(((i - 1) / 2) | 0)] : dVals[i];
							}
						}
						return pfx + vals.join(delim) + delim + color + sfx + (v.indexOf("inset") !== -1 ? " inset" : "");
					};
					return formatter;

				}
				formatter = function(v) {
					var vals, a, i;
					if (typeof(v) === "number") {
						v += dSfx;
					} else if (multi && _commasOutsideParenExp.test(v)) {
						a = v.replace(_commasOutsideParenExp, "|").split("|");
						for (i = 0; i < a.length; i++) {
							a[i] = formatter(a[i]);
						}
						return a.join(",");
					}
					vals = v.match(_valuesExp) || [];
					i = vals.length;
					if (numVals > i--) {
						while (++i < numVals) {
							vals[i] = collapsible ? vals[(((i - 1) / 2) | 0)] : dVals[i];
						}
					}
					return pfx + vals.join(delim) + sfx;
				};
				return formatter;
			},

			/**
			 * @private returns a formatter function that's used for edge-related values like marginTop, marginLeft, paddingBottom, paddingRight, etc. Just pass a comma-delimited list of property names related to the edges.
			 * @param {!string} props a comma-delimited list of property names in order from top to left, like "marginTop,marginRight,marginBottom,marginLeft"
			 * @return {Function} a formatter function
			 */
			_getEdgeParser = function(props) {
				props = props.split(",");
				return function(t, e, p, cssp, pt, plugin, vars) {
					var a = (e + "").split(" "),
						i;
					vars = {};
					for (i = 0; i < 4; i++) {
						vars[props[i]] = a[i] = a[i] || a[(((i - 1) / 2) >> 0)];
					}
					return cssp.parse(t, vars, pt, plugin);
				};
			},

			// @private used when other plugins must tween values first, like BezierPlugin or ThrowPropsPlugin, etc. That plugin's setRatio() gets called first so that the values are updated, and then we loop through the MiniPropTweens which handle copying the values into their appropriate slots so that they can then be applied correctly in the main CSSPlugin setRatio() method. Remember, we typically create a proxy object that has a bunch of uniquely-named properties that we feed to the sub-plugin and it does its magic normally, and then we must interpret those values and apply them to the css because often numbers must get combined/concatenated, suffixes added, etc. to work with css, like boxShadow could have 4 values plus a color.
			_setPluginRatio = _internals._setPluginRatio = function(v) {
				this.plugin.setRatio(v);
				var d = this.data,
					proxy = d.proxy,
					mpt = d.firstMPT,
					min = 0.000001,
					val, pt, i, str, p;
				while (mpt) {
					val = proxy[mpt.v];
					if (mpt.r) {
						val = Math.round(val);
					} else if (val < min && val > -min) {
						val = 0;
					}
					mpt.t[mpt.p] = val;
					mpt = mpt._next;
				}
				if (d.autoRotate) {
					d.autoRotate.rotation = d.mod ? d.mod(proxy.rotation, this.t) : proxy.rotation; //special case for ModifyPlugin to hook into an auto-rotating bezier
				}
				//at the end, we must set the CSSPropTween's "e" (end) value dynamically here because that's what is used in the final setRatio() method. Same for "b" at the beginning.
				if (v === 1 || v === 0) {
					mpt = d.firstMPT;
					p = (v === 1) ? "e" : "b";
					while (mpt) {
						pt = mpt.t;
						if (!pt.type) {
							pt[p] = pt.s + pt.xs0;
						} else if (pt.type === 1) {
							str = pt.xs0 + pt.s + pt.xs1;
							for (i = 1; i < pt.l; i++) {
								str += pt["xn"+i] + pt["xs"+(i+1)];
							}
							pt[p] = str;
						}
						mpt = mpt._next;
					}
				}
			},

			/**
			 * @private @constructor Used by a few SpecialProps to hold important values for proxies. For example, _parseToProxy() creates a MiniPropTween instance for each property that must get tweened on the proxy, and we record the original property name as well as the unique one we create for the proxy, plus whether or not the value needs to be rounded plus the original value.
			 * @param {!Object} t target object whose property we're tweening (often a CSSPropTween)
			 * @param {!string} p property name
			 * @param {(number|string|object)} v value
			 * @param {MiniPropTween=} next next MiniPropTween in the linked list
			 * @param {boolean=} r if true, the tweened value should be rounded to the nearest integer
			 */
			MiniPropTween = function(t, p, v, next, r) {
				this.t = t;
				this.p = p;
				this.v = v;
				this.r = r;
				if (next) {
					next._prev = this;
					this._next = next;
				}
			},

			/**
			 * @private Most other plugins (like BezierPlugin and ThrowPropsPlugin and others) can only tween numeric values, but CSSPlugin must accommodate special values that have a bunch of extra data (like a suffix or strings between numeric values, etc.). For example, boxShadow has values like "10px 10px 20px 30px rgb(255,0,0)" which would utterly confuse other plugins. This method allows us to split that data apart and grab only the numeric data and attach it to uniquely-named properties of a generic proxy object ({}) so that we can feed that to virtually any plugin to have the numbers tweened. However, we must also keep track of which properties from the proxy go with which CSSPropTween values and instances. So we create a linked list of MiniPropTweens. Each one records a target (the original CSSPropTween), property (like "s" or "xn1" or "xn2") that we're tweening and the unique property name that was used for the proxy (like "boxShadow_xn1" and "boxShadow_xn2") and whether or not they need to be rounded. That way, in the _setPluginRatio() method we can simply copy the values over from the proxy to the CSSPropTween instance(s). Then, when the main CSSPlugin setRatio() method runs and applies the CSSPropTween values accordingly, they're updated nicely. So the external plugin tweens the numbers, _setPluginRatio() copies them over, and setRatio() acts normally, applying css-specific values to the element.
			 * This method returns an object that has the following properties:
			 *  - proxy: a generic object containing the starting values for all the properties that will be tweened by the external plugin.  This is what we feed to the external _onInitTween() as the target
			 *  - end: a generic object containing the ending values for all the properties that will be tweened by the external plugin. This is what we feed to the external plugin's _onInitTween() as the destination values
			 *  - firstMPT: the first MiniPropTween in the linked list
			 *  - pt: the first CSSPropTween in the linked list that was created when parsing. If shallow is true, this linked list will NOT attach to the one passed into the _parseToProxy() as the "pt" (4th) parameter.
			 * @param {!Object} t target object to be tweened
			 * @param {!(Object|string)} vars the object containing the information about the tweening values (typically the end/destination values) that should be parsed
			 * @param {!CSSPlugin} cssp The CSSPlugin instance
			 * @param {CSSPropTween=} pt the next CSSPropTween in the linked list
			 * @param {TweenPlugin=} plugin the external TweenPlugin instance that will be handling tweening the numeric values
			 * @param {boolean=} shallow if true, the resulting linked list from the parse will NOT be attached to the CSSPropTween that was passed in as the "pt" (4th) parameter.
			 * @return An object containing the following properties: proxy, end, firstMPT, and pt (see above for descriptions)
			 */
			_parseToProxy = _internals._parseToProxy = function(t, vars, cssp, pt, plugin, shallow) {
				var bpt = pt,
					start = {},
					end = {},
					transform = cssp._transform,
					oldForce = _forcePT,
					i, p, xp, mpt, firstPT;
				cssp._transform = null;
				_forcePT = vars;
				pt = firstPT = cssp.parse(t, vars, pt, plugin);
				_forcePT = oldForce;
				//break off from the linked list so the new ones are isolated.
				if (shallow) {
					cssp._transform = transform;
					if (bpt) {
						bpt._prev = null;
						if (bpt._prev) {
							bpt._prev._next = null;
						}
					}
				}
				while (pt && pt !== bpt) {
					if (pt.type <= 1) {
						p = pt.p;
						end[p] = pt.s + pt.c;
						start[p] = pt.s;
						if (!shallow) {
							mpt = new MiniPropTween(pt, "s", p, mpt, pt.r);
							pt.c = 0;
						}
						if (pt.type === 1) {
							i = pt.l;
							while (--i > 0) {
								xp = "xn" + i;
								p = pt.p + "_" + xp;
								end[p] = pt.data[xp];
								start[p] = pt[xp];
								if (!shallow) {
									mpt = new MiniPropTween(pt, xp, p, mpt, pt.rxp[xp]);
								}
							}
						}
					}
					pt = pt._next;
				}
				return {proxy:start, end:end, firstMPT:mpt, pt:firstPT};
			},



			/**
			 * @constructor Each property that is tweened has at least one CSSPropTween associated with it. These instances store important information like the target, property, starting value, amount of change, etc. They can also optionally have a number of "extra" strings and numeric values named xs1, xn1, xs2, xn2, xs3, xn3, etc. where "s" indicates string and "n" indicates number. These can be pieced together in a complex-value tween (type:1) that has alternating types of data like a string, number, string, number, etc. For example, boxShadow could be "5px 5px 8px rgb(102, 102, 51)". In that value, there are 6 numbers that may need to tween and then pieced back together into a string again with spaces, suffixes, etc. xs0 is special in that it stores the suffix for standard (type:0) tweens, -OR- the first string (prefix) in a complex-value (type:1) CSSPropTween -OR- it can be the non-tweening value in a type:-1 CSSPropTween. We do this to conserve memory.
			 * CSSPropTweens have the following optional properties as well (not defined through the constructor):
			 *  - l: Length in terms of the number of extra properties that the CSSPropTween has (default: 0). For example, for a boxShadow we may need to tween 5 numbers in which case l would be 5; Keep in mind that the start/end values for the first number that's tweened are always stored in the s and c properties to conserve memory. All additional values thereafter are stored in xn1, xn2, etc.
			 *  - xfirst: The first instance of any sub-CSSPropTweens that are tweening properties of this instance. For example, we may split up a boxShadow tween so that there's a main CSSPropTween of type:1 that has various xs* and xn* values associated with the h-shadow, v-shadow, blur, color, etc. Then we spawn a CSSPropTween for each of those that has a higher priority and runs BEFORE the main CSSPropTween so that the values are all set by the time it needs to re-assemble them. The xfirst gives us an easy way to identify the first one in that chain which typically ends at the main one (because they're all prepende to the linked list)
			 *  - plugin: The TweenPlugin instance that will handle the tweening of any complex values. For example, sometimes we don't want to use normal subtweens (like xfirst refers to) to tween the values - we might want ThrowPropsPlugin or BezierPlugin some other plugin to do the actual tweening, so we create a plugin instance and store a reference here. We need this reference so that if we get a request to round values or disable a tween, we can pass along that request.
			 *  - data: Arbitrary data that needs to be stored with the CSSPropTween. Typically if we're going to have a plugin handle the tweening of a complex-value tween, we create a generic object that stores the END values that we're tweening to and the CSSPropTween's xs1, xs2, etc. have the starting values. We store that object as data. That way, we can simply pass that object to the plugin and use the CSSPropTween as the target.
			 *  - setRatio: Only used for type:2 tweens that require custom functionality. In this case, we call the CSSPropTween's setRatio() method and pass the ratio each time the tween updates. This isn't quite as efficient as doing things directly in the CSSPlugin's setRatio() method, but it's very convenient and flexible.
			 * @param {!Object} t Target object whose property will be tweened. Often a DOM element, but not always. It could be anything.
			 * @param {string} p Property to tween (name). For example, to tween element.width, p would be "width".
			 * @param {number} s Starting numeric value
			 * @param {number} c Change in numeric value over the course of the entire tween. For example, if element.width starts at 5 and should end at 100, c would be 95.
			 * @param {CSSPropTween=} next The next CSSPropTween in the linked list. If one is defined, we will define its _prev as the new instance, and the new instance's _next will be pointed at it.
			 * @param {number=} type The type of CSSPropTween where -1 = a non-tweening value, 0 = a standard simple tween, 1 = a complex value (like one that has multiple numbers in a comma- or space-delimited string like border:"1px solid red"), and 2 = one that uses a custom setRatio function that does all of the work of applying the values on each update.
			 * @param {string=} n Name of the property that should be used for overwriting purposes which is typically the same as p but not always. For example, we may need to create a subtween for the 2nd part of a "clip:rect(...)" tween in which case "p" might be xs1 but "n" is still "clip"
			 * @param {boolean=} r If true, the value(s) should be rounded
			 * @param {number=} pr Priority in the linked list order. Higher priority CSSPropTweens will be updated before lower priority ones. The default priority is 0.
			 * @param {string=} b Beginning value. We store this to ensure that it is EXACTLY what it was when the tween began without any risk of interpretation issues.
			 * @param {string=} e Ending value. We store this to ensure that it is EXACTLY what the user defined at the end of the tween without any risk of interpretation issues.
			 */
			CSSPropTween = _internals.CSSPropTween = function(t, p, s, c, next, type, n, r, pr, b, e) {
				this.t = t; //target
				this.p = p; //property
				this.s = s; //starting value
				this.c = c; //change value
				this.n = n || p; //name that this CSSPropTween should be associated to (usually the same as p, but not always - n is what overwriting looks at)
				if (!(t instanceof CSSPropTween)) {
					_overwriteProps.push(this.n);
				}
				this.r = r; //round (boolean)
				this.type = type || 0; //0 = normal tween, -1 = non-tweening (in which case xs0 will be applied to the target's property, like tp.t[tp.p] = tp.xs0), 1 = complex-value SpecialProp, 2 = custom setRatio() that does all the work
				if (pr) {
					this.pr = pr;
					_hasPriority = true;
				}
				this.b = (b === undefined) ? s : b;
				this.e = (e === undefined) ? s + c : e;
				if (next) {
					this._next = next;
					next._prev = this;
				}
			},

			_addNonTweeningNumericPT = function(target, prop, start, end, next, overwriteProp) { //cleans up some code redundancies and helps minification. Just a fast way to add a NUMERIC non-tweening CSSPropTween
				var pt = new CSSPropTween(target, prop, start, end - start, next, -1, overwriteProp);
				pt.b = start;
				pt.e = pt.xs0 = end;
				return pt;
			},

			/**
			 * Takes a target, the beginning value and ending value (as strings) and parses them into a CSSPropTween (possibly with child CSSPropTweens) that accommodates multiple numbers, colors, comma-delimited values, etc. For example:
			 * sp.parseComplex(element, "boxShadow", "5px 10px 20px rgb(255,102,51)", "0px 0px 0px red", true, "0px 0px 0px rgb(0,0,0,0)", pt);
			 * It will walk through the beginning and ending values (which should be in the same format with the same number and type of values) and figure out which parts are numbers, what strings separate the numeric/tweenable values, and then create the CSSPropTweens accordingly. If a plugin is defined, no child CSSPropTweens will be created. Instead, the ending values will be stored in the "data" property of the returned CSSPropTween like: {s:-5, xn1:-10, xn2:-20, xn3:255, xn4:0, xn5:0} so that it can be fed to any other plugin and it'll be plain numeric tweens but the recomposition of the complex value will be handled inside CSSPlugin's setRatio().
			 * If a setRatio is defined, the type of the CSSPropTween will be set to 2 and recomposition of the values will be the responsibility of that method.
			 *
			 * @param {!Object} t Target whose property will be tweened
			 * @param {!string} p Property that will be tweened (its name, like "left" or "backgroundColor" or "boxShadow")
			 * @param {string} b Beginning value
			 * @param {string} e Ending value
			 * @param {boolean} clrs If true, the value could contain a color value like "rgb(255,0,0)" or "#F00" or "red". The default is false, so no colors will be recognized (a performance optimization)
			 * @param {(string|number|Object)} dflt The default beginning value that should be used if no valid beginning value is defined or if the number of values inside the complex beginning and ending values don't match
			 * @param {?CSSPropTween} pt CSSPropTween instance that is the current head of the linked list (we'll prepend to this).
			 * @param {number=} pr Priority in the linked list order. Higher priority properties will be updated before lower priority ones. The default priority is 0.
			 * @param {TweenPlugin=} plugin If a plugin should handle the tweening of extra properties, pass the plugin instance here. If one is defined, then NO subtweens will be created for any extra properties (the properties will be created - just not additional CSSPropTween instances to tween them) because the plugin is expected to do so. However, the end values WILL be populated in the "data" property, like {s:100, xn1:50, xn2:300}
			 * @param {function(number)=} setRatio If values should be set in a custom function instead of being pieced together in a type:1 (complex-value) CSSPropTween, define that custom function here.
			 * @return {CSSPropTween} The first CSSPropTween in the linked list which includes the new one(s) added by the parseComplex() call.
			 */
			_parseComplex = CSSPlugin.parseComplex = function(t, p, b, e, clrs, dflt, pt, pr, plugin, setRatio) {
				//DEBUG: _log("parseComplex: "+p+", b: "+b+", e: "+e);
				b = b || dflt || "";
				if (typeof(e) === "function") {
					e = e(_index, _target);
				}
				pt = new CSSPropTween(t, p, 0, 0, pt, (setRatio ? 2 : 1), null, false, pr, b, e);
				e += ""; //ensures it's a string
				if (clrs && _colorExp.test(e + b)) { //if colors are found, normalize the formatting to rgba() or hsla().
					e = [b, e];
					CSSPlugin.colorStringFilter(e);
					b = e[0];
					e = e[1];
				}
				var ba = b.split(", ").join(",").split(" "), //beginning array
					ea = e.split(", ").join(",").split(" "), //ending array
					l = ba.length,
					autoRound = (_autoRound !== false),
					i, xi, ni, bv, ev, bnums, enums, bn, hasAlpha, temp, cv, str, useHSL;
				if (e.indexOf(",") !== -1 || b.indexOf(",") !== -1) {
					ba = ba.join(" ").replace(_commasOutsideParenExp, ", ").split(" ");
					ea = ea.join(" ").replace(_commasOutsideParenExp, ", ").split(" ");
					l = ba.length;
				}
				if (l !== ea.length) {
					//DEBUG: _log("mismatched formatting detected on " + p + " (" + b + " vs " + e + ")");
					ba = (dflt || "").split(" ");
					l = ba.length;
				}
				pt.plugin = plugin;
				pt.setRatio = setRatio;
				_colorExp.lastIndex = 0;
				for (i = 0; i < l; i++) {
					bv = ba[i];
					ev = ea[i];
					bn = parseFloat(bv);
					//if the value begins with a number (most common). It's fine if it has a suffix like px
					if (bn || bn === 0) {
						pt.appendXtra("", bn, _parseChange(ev, bn), ev.replace(_relNumExp, ""), (autoRound && ev.indexOf("px") !== -1), true);

					//if the value is a color
					} else if (clrs && _colorExp.test(bv)) {
						str = ev.indexOf(")") + 1;
						str = ")" + (str ? ev.substr(str) : ""); //if there's a comma or ) at the end, retain it.
						useHSL = (ev.indexOf("hsl") !== -1 && _supportsOpacity);
						bv = _parseColor(bv, useHSL);
						ev = _parseColor(ev, useHSL);
						hasAlpha = (bv.length + ev.length > 6);
						if (hasAlpha && !_supportsOpacity && ev[3] === 0) { //older versions of IE don't support rgba(), so if the destination alpha is 0, just use "transparent" for the end color
							pt["xs" + pt.l] += pt.l ? " transparent" : "transparent";
							pt.e = pt.e.split(ea[i]).join("transparent");
						} else {
							if (!_supportsOpacity) { //old versions of IE don't support rgba().
								hasAlpha = false;
							}
							if (useHSL) {
								pt.appendXtra((hasAlpha ? "hsla(" : "hsl("), bv[0], _parseChange(ev[0], bv[0]), ",", false, true)
									.appendXtra("", bv[1], _parseChange(ev[1], bv[1]), "%,", false)
									.appendXtra("", bv[2], _parseChange(ev[2], bv[2]), (hasAlpha ? "%," : "%" + str), false);
							} else {
								pt.appendXtra((hasAlpha ? "rgba(" : "rgb("), bv[0], ev[0] - bv[0], ",", true, true)
									.appendXtra("", bv[1], ev[1] - bv[1], ",", true)
									.appendXtra("", bv[2], ev[2] - bv[2], (hasAlpha ? "," : str), true);
							}

							if (hasAlpha) {
								bv = (bv.length < 4) ? 1 : bv[3];
								pt.appendXtra("", bv, ((ev.length < 4) ? 1 : ev[3]) - bv, str, false);
							}
						}
						_colorExp.lastIndex = 0; //otherwise the test() on the RegExp could move the lastIndex and taint future results.

					} else {
						bnums = bv.match(_numExp); //gets each group of numbers in the beginning value string and drops them into an array

						//if no number is found, treat it as a non-tweening value and just append the string to the current xs.
						if (!bnums) {
							pt["xs" + pt.l] += (pt.l || pt["xs" + pt.l]) ? " " + ev : ev;

						//loop through all the numbers that are found and construct the extra values on the pt.
						} else {
							enums = ev.match(_relNumExp); //get each group of numbers in the end value string and drop them into an array. We allow relative values too, like +=50 or -=.5
							if (!enums || enums.length !== bnums.length) {
								//DEBUG: _log("mismatched formatting detected on " + p + " (" + b + " vs " + e + ")");
								return pt;
							}
							ni = 0;
							for (xi = 0; xi < bnums.length; xi++) {
								cv = bnums[xi];
								temp = bv.indexOf(cv, ni);
								pt.appendXtra(bv.substr(ni, temp - ni), Number(cv), _parseChange(enums[xi], cv), "", (autoRound && bv.substr(temp + cv.length, 2) === "px"), (xi === 0));
								ni = temp + cv.length;
							}
							pt["xs" + pt.l] += bv.substr(ni);
						}
					}
				}
				//if there are relative values ("+=" or "-=" prefix), we need to adjust the ending value to eliminate the prefixes and combine the values properly.
				if (e.indexOf("=") !== -1) if (pt.data) {
					str = pt.xs0 + pt.data.s;
					for (i = 1; i < pt.l; i++) {
						str += pt["xs" + i] + pt.data["xn" + i];
					}
					pt.e = str + pt["xs" + i];
				}
				if (!pt.l) {
					pt.type = -1;
					pt.xs0 = pt.e;
				}
				return pt.xfirst || pt;
			},
			i = 9;


		p = CSSPropTween.prototype;
		p.l = p.pr = 0; //length (number of extra properties like xn1, xn2, xn3, etc.
		while (--i > 0) {
			p["xn" + i] = 0;
			p["xs" + i] = "";
		}
		p.xs0 = "";
		p._next = p._prev = p.xfirst = p.data = p.plugin = p.setRatio = p.rxp = null;


		/**
		 * Appends and extra tweening value to a CSSPropTween and automatically manages any prefix and suffix strings. The first extra value is stored in the s and c of the main CSSPropTween instance, but thereafter any extras are stored in the xn1, xn2, xn3, etc. The prefixes and suffixes are stored in the xs0, xs1, xs2, etc. properties. For example, if I walk through a clip value like "rect(10px, 5px, 0px, 20px)", the values would be stored like this:
		 * xs0:"rect(", s:10, xs1:"px, ", xn1:5, xs2:"px, ", xn2:0, xs3:"px, ", xn3:20, xn4:"px)"
		 * And they'd all get joined together when the CSSPlugin renders (in the setRatio() method).
		 * @param {string=} pfx Prefix (if any)
		 * @param {!number} s Starting value
		 * @param {!number} c Change in numeric value over the course of the entire tween. For example, if the start is 5 and the end is 100, the change would be 95.
		 * @param {string=} sfx Suffix (if any)
		 * @param {boolean=} r Round (if true).
		 * @param {boolean=} pad If true, this extra value should be separated by the previous one by a space. If there is no previous extra and pad is true, it will automatically drop the space.
		 * @return {CSSPropTween} returns itself so that multiple methods can be chained together.
		 */
		p.appendXtra = function(pfx, s, c, sfx, r, pad) {
			var pt = this,
				l = pt.l;
			pt["xs" + l] += (pad && (l || pt["xs" + l])) ? " " + pfx : pfx || "";
			if (!c) if (l !== 0 && !pt.plugin) { //typically we'll combine non-changing values right into the xs to optimize performance, but we don't combine them when there's a plugin that will be tweening the values because it may depend on the values being split apart, like for a bezier, if a value doesn't change between the first and second iteration but then it does on the 3rd, we'll run into trouble because there's no xn slot for that value!
				pt["xs" + l] += s + (sfx || "");
				return pt;
			}
			pt.l++;
			pt.type = pt.setRatio ? 2 : 1;
			pt["xs" + pt.l] = sfx || "";
			if (l > 0) {
				pt.data["xn" + l] = s + c;
				pt.rxp["xn" + l] = r; //round extra property (we need to tap into this in the _parseToProxy() method)
				pt["xn" + l] = s;
				if (!pt.plugin) {
					pt.xfirst = new CSSPropTween(pt, "xn" + l, s, c, pt.xfirst || pt, 0, pt.n, r, pt.pr);
					pt.xfirst.xs0 = 0; //just to ensure that the property stays numeric which helps modern browsers speed up processing. Remember, in the setRatio() method, we do pt.t[pt.p] = val + pt.xs0 so if pt.xs0 is "" (the default), it'll cast the end value as a string. When a property is a number sometimes and a string sometimes, it prevents the compiler from locking in the data type, slowing things down slightly.
				}
				return pt;
			}
			pt.data = {s:s + c};
			pt.rxp = {};
			pt.s = s;
			pt.c = c;
			pt.r = r;
			return pt;
		};

		/**
		 * @constructor A SpecialProp is basically a css property that needs to be treated in a non-standard way, like if it may contain a complex value like boxShadow:"5px 10px 15px rgb(255, 102, 51)" or if it is associated with another plugin like ThrowPropsPlugin or BezierPlugin. Every SpecialProp is associated with a particular property name like "boxShadow" or "throwProps" or "bezier" and it will intercept those values in the vars object that's passed to the CSSPlugin and handle them accordingly.
		 * @param {!string} p Property name (like "boxShadow" or "throwProps")
		 * @param {Object=} options An object containing any of the following configuration options:
		 *                      - defaultValue: the default value
		 *                      - parser: A function that should be called when the associated property name is found in the vars. This function should return a CSSPropTween instance and it should ensure that it is properly inserted into the linked list. It will receive 4 paramters: 1) The target, 2) The value defined in the vars, 3) The CSSPlugin instance (whose _firstPT should be used for the linked list), and 4) A computed style object if one was calculated (this is a speed optimization that allows retrieval of starting values quicker)
		 *                      - formatter: a function that formats any value received for this special property (for example, boxShadow could take "5px 5px red" and format it to "5px 5px 0px 0px red" so that both the beginning and ending values have a common order and quantity of values.)
		 *                      - prefix: if true, we'll determine whether or not this property requires a vendor prefix (like Webkit or Moz or ms or O)
		 *                      - color: set this to true if the value for this SpecialProp may contain color-related values like rgb(), rgba(), etc.
		 *                      - priority: priority in the linked list order. Higher priority SpecialProps will be updated before lower priority ones. The default priority is 0.
		 *                      - multi: if true, the formatter should accommodate a comma-delimited list of values, like boxShadow could have multiple boxShadows listed out.
		 *                      - collapsible: if true, the formatter should treat the value like it's a top/right/bottom/left value that could be collapsed, like "5px" would apply to all, "5px, 10px" would use 5px for top/bottom and 10px for right/left, etc.
		 *                      - keyword: a special keyword that can [optionally] be found inside the value (like "inset" for boxShadow). This allows us to validate beginning/ending values to make sure they match (if the keyword is found in one, it'll be added to the other for consistency by default).
		 */
		var SpecialProp = function(p, options) {
				options = options || {};
				this.p = options.prefix ? _checkPropPrefix(p) || p : p;
				_specialProps[p] = _specialProps[this.p] = this;
				this.format = options.formatter || _getFormatter(options.defaultValue, options.color, options.collapsible, options.multi);
				if (options.parser) {
					this.parse = options.parser;
				}
				this.clrs = options.color;
				this.multi = options.multi;
				this.keyword = options.keyword;
				this.dflt = options.defaultValue;
				this.pr = options.priority || 0;
			},

			//shortcut for creating a new SpecialProp that can accept multiple properties as a comma-delimited list (helps minification). dflt can be an array for multiple values (we don't do a comma-delimited list because the default value may contain commas, like rect(0px,0px,0px,0px)). We attach this method to the SpecialProp class/object instead of using a private _createSpecialProp() method so that we can tap into it externally if necessary, like from another plugin.
			_registerComplexSpecialProp = _internals._registerComplexSpecialProp = function(p, options, defaults) {
				if (typeof(options) !== "object") {
					options = {parser:defaults}; //to make backwards compatible with older versions of BezierPlugin and ThrowPropsPlugin
				}
				var a = p.split(","),
					d = options.defaultValue,
					i, temp;
				defaults = defaults || [d];
				for (i = 0; i < a.length; i++) {
					options.prefix = (i === 0 && options.prefix);
					options.defaultValue = defaults[i] || d;
					temp = new SpecialProp(a[i], options);
				}
			},

			//creates a placeholder special prop for a plugin so that the property gets caught the first time a tween of it is attempted, and at that time it makes the plugin register itself, thus taking over for all future tweens of that property. This allows us to not mandate that things load in a particular order and it also allows us to log() an error that informs the user when they attempt to tween an external plugin-related property without loading its .js file.
			_registerPluginProp = _internals._registerPluginProp = function(p) {
				if (!_specialProps[p]) {
					var pluginName = p.charAt(0).toUpperCase() + p.substr(1) + "Plugin";
					_registerComplexSpecialProp(p, {parser:function(t, e, p, cssp, pt, plugin, vars) {
						var pluginClass = _globals.com.greensock.plugins[pluginName];
						if (!pluginClass) {
							_log("Error: " + pluginName + " js file not loaded.");
							return pt;
						}
						pluginClass._cssRegister();
						return _specialProps[p].parse(t, e, p, cssp, pt, plugin, vars);
					}});
				}
			};


		p = SpecialProp.prototype;

		/**
		 * Alias for _parseComplex() that automatically plugs in certain values for this SpecialProp, like its property name, whether or not colors should be sensed, the default value, and priority. It also looks for any keyword that the SpecialProp defines (like "inset" for boxShadow) and ensures that the beginning and ending values have the same number of values for SpecialProps where multi is true (like boxShadow and textShadow can have a comma-delimited list)
		 * @param {!Object} t target element
		 * @param {(string|number|object)} b beginning value
		 * @param {(string|number|object)} e ending (destination) value
		 * @param {CSSPropTween=} pt next CSSPropTween in the linked list
		 * @param {TweenPlugin=} plugin If another plugin will be tweening the complex value, that TweenPlugin instance goes here.
		 * @param {function=} setRatio If a custom setRatio() method should be used to handle this complex value, that goes here.
		 * @return {CSSPropTween=} First CSSPropTween in the linked list
		 */
		p.parseComplex = function(t, b, e, pt, plugin, setRatio) {
			var kwd = this.keyword,
				i, ba, ea, l, bi, ei;
			//if this SpecialProp's value can contain a comma-delimited list of values (like boxShadow or textShadow), we must parse them in a special way, and look for a keyword (like "inset" for boxShadow) and ensure that the beginning and ending BOTH have it if the end defines it as such. We also must ensure that there are an equal number of values specified (we can't tween 1 boxShadow to 3 for example)
			if (this.multi) if (_commasOutsideParenExp.test(e) || _commasOutsideParenExp.test(b)) {
				ba = b.replace(_commasOutsideParenExp, "|").split("|");
				ea = e.replace(_commasOutsideParenExp, "|").split("|");
			} else if (kwd) {
				ba = [b];
				ea = [e];
			}
			if (ea) {
				l = (ea.length > ba.length) ? ea.length : ba.length;
				for (i = 0; i < l; i++) {
					b = ba[i] = ba[i] || this.dflt;
					e = ea[i] = ea[i] || this.dflt;
					if (kwd) {
						bi = b.indexOf(kwd);
						ei = e.indexOf(kwd);
						if (bi !== ei) {
							if (ei === -1) { //if the keyword isn't in the end value, remove it from the beginning one.
								ba[i] = ba[i].split(kwd).join("");
							} else if (bi === -1) { //if the keyword isn't in the beginning, add it.
								ba[i] += " " + kwd;
							}
						}
					}
				}
				b = ba.join(", ");
				e = ea.join(", ");
			}
			return _parseComplex(t, this.p, b, e, this.clrs, this.dflt, pt, this.pr, plugin, setRatio);
		};

		/**
		 * Accepts a target and end value and spits back a CSSPropTween that has been inserted into the CSSPlugin's linked list and conforms with all the conventions we use internally, like type:-1, 0, 1, or 2, setting up any extra property tweens, priority, etc. For example, if we have a boxShadow SpecialProp and call:
		 * this._firstPT = sp.parse(element, "5px 10px 20px rgb(2550,102,51)", "boxShadow", this);
		 * It should figure out the starting value of the element's boxShadow, compare it to the provided end value and create all the necessary CSSPropTweens of the appropriate types to tween the boxShadow. The CSSPropTween that gets spit back should already be inserted into the linked list (the 4th parameter is the current head, so prepend to that).
		 * @param {!Object} t Target object whose property is being tweened
		 * @param {Object} e End value as provided in the vars object (typically a string, but not always - like a throwProps would be an object).
		 * @param {!string} p Property name
		 * @param {!CSSPlugin} cssp The CSSPlugin instance that should be associated with this tween.
		 * @param {?CSSPropTween} pt The CSSPropTween that is the current head of the linked list (we'll prepend to it)
		 * @param {TweenPlugin=} plugin If a plugin will be used to tween the parsed value, this is the plugin instance.
		 * @param {Object=} vars Original vars object that contains the data for parsing.
		 * @return {CSSPropTween} The first CSSPropTween in the linked list which includes the new one(s) added by the parse() call.
		 */
		p.parse = function(t, e, p, cssp, pt, plugin, vars) {
			return this.parseComplex(t.style, this.format(_getStyle(t, this.p, _cs, false, this.dflt)), this.format(e), pt, plugin);
		};

		/**
		 * Registers a special property that should be intercepted from any "css" objects defined in tweens. This allows you to handle them however you want without CSSPlugin doing it for you. The 2nd parameter should be a function that accepts 3 parameters:
		 *  1) Target object whose property should be tweened (typically a DOM element)
		 *  2) The end/destination value (could be a string, number, object, or whatever you want)
		 *  3) The tween instance (you probably don't need to worry about this, but it can be useful for looking up information like the duration)
		 *
		 * Then, your function should return a function which will be called each time the tween gets rendered, passing a numeric "ratio" parameter to your function that indicates the change factor (usually between 0 and 1). For example:
		 *
		 * CSSPlugin.registerSpecialProp("myCustomProp", function(target, value, tween) {
		 *      var start = target.style.width;
		 *      return function(ratio) {
		 *              target.style.width = (start + value * ratio) + "px";
		 *              console.log("set width to " + target.style.width);
		 *          }
		 * }, 0);
		 *
		 * Then, when I do this tween, it will trigger my special property:
		 *
		 * TweenLite.to(element, 1, {css:{myCustomProp:100}});
		 *
		 * In the example, of course, we're just changing the width, but you can do anything you want.
		 *
		 * @param {!string} name Property name (or comma-delimited list of property names) that should be intercepted and handled by your function. For example, if I define "myCustomProp", then it would handle that portion of the following tween: TweenLite.to(element, 1, {css:{myCustomProp:100}})
		 * @param {!function(Object, Object, Object, string):function(number)} onInitTween The function that will be called when a tween of this special property is performed. The function will receive 4 parameters: 1) Target object that should be tweened, 2) Value that was passed to the tween, 3) The tween instance itself (rarely used), and 4) The property name that's being tweened. Your function should return a function that should be called on every update of the tween. That function will receive a single parameter that is a "change factor" value (typically between 0 and 1) indicating the amount of change as a ratio. You can use this to determine how to set the values appropriately in your function.
		 * @param {number=} priority Priority that helps the engine determine the order in which to set the properties (default: 0). Higher priority properties will be updated before lower priority ones.
		 */
		CSSPlugin.registerSpecialProp = function(name, onInitTween, priority) {
			_registerComplexSpecialProp(name, {parser:function(t, e, p, cssp, pt, plugin, vars) {
				var rv = new CSSPropTween(t, p, 0, 0, pt, 2, p, false, priority);
				rv.plugin = plugin;
				rv.setRatio = onInitTween(t, e, cssp._tween, p);
				return rv;
			}, priority:priority});
		};






		//transform-related methods and properties
		CSSPlugin.useSVGTransformAttr = true; //Safari and Firefox both have some rendering bugs when applying CSS transforms to SVG elements, so default to using the "transform" attribute instead (users can override this).
		var _transformProps = ("scaleX,scaleY,scaleZ,x,y,z,skewX,skewY,rotation,rotationX,rotationY,perspective,xPercent,yPercent").split(","),
			_transformProp = _checkPropPrefix("transform"), //the Javascript (camelCase) transform property, like msTransform, WebkitTransform, MozTransform, or OTransform.
			_transformPropCSS = _prefixCSS + "transform",
			_transformOriginProp = _checkPropPrefix("transformOrigin"),
			_supports3D = (_checkPropPrefix("perspective") !== null),
			Transform = _internals.Transform = function() {
				this.perspective = parseFloat(CSSPlugin.defaultTransformPerspective) || 0;
				this.force3D = (CSSPlugin.defaultForce3D === false || !_supports3D) ? false : CSSPlugin.defaultForce3D || "auto";
			},
			_SVGElement = _gsScope.SVGElement,
			_useSVGTransformAttr,
			//Some browsers (like Firefox and IE) don't honor transform-origin properly in SVG elements, so we need to manually adjust the matrix accordingly. We feature detect here rather than always doing the conversion for certain browsers because they may fix the problem at some point in the future.

			_createSVG = function(type, container, attributes) {
				var element = _doc.createElementNS("http://www.w3.org/2000/svg", type),
					reg = /([a-z])([A-Z])/g,
					p;
				for (p in attributes) {
					element.setAttributeNS(null, p.replace(reg, "$1-$2").toLowerCase(), attributes[p]);
				}
				container.appendChild(element);
				return element;
			},
			_docElement = _doc.documentElement || {},
			_forceSVGTransformAttr = (function() {
				//IE and Android stock don't support CSS transforms on SVG elements, so we must write them to the "transform" attribute. We populate this variable in the _parseTransform() method, and only if/when we come across an SVG element
				var force = _ieVers || (/Android/i.test(_agent) && !_gsScope.chrome),
					svg, rect, width;
				if (_doc.createElementNS && !force) { //IE8 and earlier doesn't support SVG anyway
					svg = _createSVG("svg", _docElement);
					rect = _createSVG("rect", svg, {width:100, height:50, x:100});
					width = rect.getBoundingClientRect().width;
					rect.style[_transformOriginProp] = "50% 50%";
					rect.style[_transformProp] = "scaleX(0.5)";
					force = (width === rect.getBoundingClientRect().width && !(_isFirefox && _supports3D)); //note: Firefox fails the test even though it does support CSS transforms in 3D. Since we can't push 3D stuff into the transform attribute, we force Firefox to pass the test here (as long as it does truly support 3D).
					_docElement.removeChild(svg);
				}
				return force;
			})(),
			_parseSVGOrigin = function(e, local, decoratee, absolute, smoothOrigin, skipRecord) {
				var tm = e._gsTransform,
					m = _getMatrix(e, true),
					v, x, y, xOrigin, yOrigin, a, b, c, d, tx, ty, determinant, xOriginOld, yOriginOld;
				if (tm) {
					xOriginOld = tm.xOrigin; //record the original values before we alter them.
					yOriginOld = tm.yOrigin;
				}
				if (!absolute || (v = absolute.split(" ")).length < 2) {
					b = e.getBBox();
					if (b.x === 0 && b.y === 0 && b.width + b.height === 0) { //some browsers (like Firefox) misreport the bounds if the element has zero width and height (it just assumes it's at x:0, y:0), thus we need to manually grab the position in that case.
						b = {x: parseFloat(e.hasAttribute("x") ? e.getAttribute("x") : e.hasAttribute("cx") ? e.getAttribute("cx") : 0) || 0, y: parseFloat(e.hasAttribute("y") ? e.getAttribute("y") : e.hasAttribute("cy") ? e.getAttribute("cy") : 0) || 0, width:0, height:0};
					}
					local = _parsePosition(local).split(" ");
					v = [(local[0].indexOf("%") !== -1 ? parseFloat(local[0]) / 100 * b.width : parseFloat(local[0])) + b.x,
						 (local[1].indexOf("%") !== -1 ? parseFloat(local[1]) / 100 * b.height : parseFloat(local[1])) + b.y];
				}
				decoratee.xOrigin = xOrigin = parseFloat(v[0]);
				decoratee.yOrigin = yOrigin = parseFloat(v[1]);
				if (absolute && m !== _identity2DMatrix) { //if svgOrigin is being set, we must invert the matrix and determine where the absolute point is, factoring in the current transforms. Otherwise, the svgOrigin would be based on the element's non-transformed position on the canvas.
					a = m[0];
					b = m[1];
					c = m[2];
					d = m[3];
					tx = m[4];
					ty = m[5];
					determinant = (a * d - b * c);
					if (determinant) { //if it's zero (like if scaleX and scaleY are zero), skip it to avoid errors with dividing by zero.
						x = xOrigin * (d / determinant) + yOrigin * (-c / determinant) + ((c * ty - d * tx) / determinant);
						y = xOrigin * (-b / determinant) + yOrigin * (a / determinant) - ((a * ty - b * tx) / determinant);
						xOrigin = decoratee.xOrigin = v[0] = x;
						yOrigin = decoratee.yOrigin = v[1] = y;
					}
				}
				if (tm) { //avoid jump when transformOrigin is changed - adjust the x/y values accordingly
					if (skipRecord) {
						decoratee.xOffset = tm.xOffset;
						decoratee.yOffset = tm.yOffset;
						tm = decoratee;
					}
					if (smoothOrigin || (smoothOrigin !== false && CSSPlugin.defaultSmoothOrigin !== false)) {
						x = xOrigin - xOriginOld;
						y = yOrigin - yOriginOld;
						//originally, we simply adjusted the x and y values, but that would cause problems if, for example, you created a rotational tween part-way through an x/y tween. Managing the offset in a separate variable gives us ultimate flexibility.
						//tm.x -= x - (x * m[0] + y * m[2]);
						//tm.y -= y - (x * m[1] + y * m[3]);
						tm.xOffset += (x * m[0] + y * m[2]) - x;
						tm.yOffset += (x * m[1] + y * m[3]) - y;
					} else {
						tm.xOffset = tm.yOffset = 0;
					}
				}
				if (!skipRecord) {
					e.setAttribute("data-svg-origin", v.join(" "));
				}
			},
			_getBBoxHack = function(swapIfPossible) { //works around issues in some browsers (like Firefox) that don't correctly report getBBox() on SVG elements inside a <defs> element and/or <mask>. We try creating an SVG, adding it to the documentElement and toss the element in there so that it's definitely part of the rendering tree, then grab the bbox and if it works, we actually swap out the original getBBox() method for our own that does these extra steps whenever getBBox is needed. This helps ensure that performance is optimal (only do all these extra steps when absolutely necessary...most elements don't need it).
				var svg = _createElement("svg", this.ownerSVGElement.getAttribute("xmlns") || "http://www.w3.org/2000/svg"),
					oldParent = this.parentNode,
					oldSibling = this.nextSibling,
					oldCSS = this.style.cssText,
					bbox;
				_docElement.appendChild(svg);
				svg.appendChild(this);
				this.style.display = "block";
				if (swapIfPossible) {
					try {
						bbox = this.getBBox();
						this._originalGetBBox = this.getBBox;
						this.getBBox = _getBBoxHack;
					} catch (e) { }
				} else if (this._originalGetBBox) {
					bbox = this._originalGetBBox();
				}
				if (oldSibling) {
					oldParent.insertBefore(this, oldSibling);
				} else {
					oldParent.appendChild(this);
				}
				_docElement.removeChild(svg);
				this.style.cssText = oldCSS;
				return bbox;
			},
			_getBBox = function(e) {
				try {
					return e.getBBox(); //Firefox throws errors if you try calling getBBox() on an SVG element that's not rendered (like in a <symbol> or <defs>). https://bugzilla.mozilla.org/show_bug.cgi?id=612118
				} catch (error) {
					return _getBBoxHack.call(e, true);
				}
			},
			_isSVG = function(e) { //reports if the element is an SVG on which getBBox() actually works
				return !!(_SVGElement && e.getCTM && _getBBox(e) && (!e.parentNode || e.ownerSVGElement));
			},
			_identity2DMatrix = [1,0,0,1,0,0],
			_getMatrix = function(e, force2D) {
				var tm = e._gsTransform || new Transform(),
					rnd = 100000,
					style = e.style,
					isDefault, s, m, n, dec, none;
				if (_transformProp) {
					s = _getStyle(e, _transformPropCSS, null, true);
				} else if (e.currentStyle) {
					//for older versions of IE, we need to interpret the filter portion that is in the format: progid:DXImageTransform.Microsoft.Matrix(M11=6.123233995736766e-17, M12=-1, M21=1, M22=6.123233995736766e-17, sizingMethod='auto expand') Notice that we need to swap b and c compared to a normal matrix.
					s = e.currentStyle.filter.match(_ieGetMatrixExp);
					s = (s && s.length === 4) ? [s[0].substr(4), Number(s[2].substr(4)), Number(s[1].substr(4)), s[3].substr(4), (tm.x || 0), (tm.y || 0)].join(",") : "";
				}
				isDefault = (!s || s === "none" || s === "matrix(1, 0, 0, 1, 0, 0)");
				if (isDefault && _transformProp && ((none = (_getComputedStyle(e).display === "none")) || !e.parentNode)) {
					if (none) { //browsers don't report transforms accurately unless the element is in the DOM and has a display value that's not "none".
						n = style.display;
						style.display = "block";
					}
					if (!e.parentNode) {
						dec = 1; //flag
						_docElement.appendChild(e);
					}
					s = _getStyle(e, _transformPropCSS, null, true);
					isDefault = (!s || s === "none" || s === "matrix(1, 0, 0, 1, 0, 0)");
					if (n) {
						style.display = n;
					} else if (none) {
						_removeProp(style, "display");
					}
					if (dec) {
						_docElement.removeChild(e);
					}
				}
				if (tm.svg || (e.getCTM && _isSVG(e))) {
					if (isDefault && (style[_transformProp] + "").indexOf("matrix") !== -1) { //some browsers (like Chrome 40) don't correctly report transforms that are applied inline on an SVG element (they don't get included in the computed style), so we double-check here and accept matrix values
						s = style[_transformProp];
						isDefault = 0;
					}
					m = e.getAttribute("transform");
					if (isDefault && m) {
						if (m.indexOf("matrix") !== -1) { //just in case there's a "transform" value specified as an attribute instead of CSS style. Accept either a matrix() or simple translate() value though.
							s = m;
							isDefault = 0;
						} else if (m.indexOf("translate") !== -1) {
							s = "matrix(1,0,0,1," + m.match(/(?:\-|\b)[\d\-\.e]+\b/gi).join(",") + ")";
							isDefault = 0;
						}
					}
				}
				if (isDefault) {
					return _identity2DMatrix;
				}
				//split the matrix values out into an array (m for matrix)
				m = (s || "").match(_numExp) || [];
				i = m.length;
				while (--i > -1) {
					n = Number(m[i]);
					m[i] = (dec = n - (n |= 0)) ? ((dec * rnd + (dec < 0 ? -0.5 : 0.5)) | 0) / rnd + n : n; //convert strings to Numbers and round to 5 decimal places to avoid issues with tiny numbers. Roughly 20x faster than Number.toFixed(). We also must make sure to round before dividing so that values like 0.9999999999 become 1 to avoid glitches in browser rendering and interpretation of flipped/rotated 3D matrices. And don't just multiply the number by rnd, floor it, and then divide by rnd because the bitwise operations max out at a 32-bit signed integer, thus it could get clipped at a relatively low value (like 22,000.00000 for example).
				}
				return (force2D && m.length > 6) ? [m[0], m[1], m[4], m[5], m[12], m[13]] : m;
			},

			/**
			 * Parses the transform values for an element, returning an object with x, y, z, scaleX, scaleY, scaleZ, rotation, rotationX, rotationY, skewX, and skewY properties. Note: by default (for performance reasons), all skewing is combined into skewX and rotation but skewY still has a place in the transform object so that we can record how much of the skew is attributed to skewX vs skewY. Remember, a skewY of 10 looks the same as a rotation of 10 and skewX of -10.
			 * @param {!Object} t target element
			 * @param {Object=} cs computed style object (optional)
			 * @param {boolean=} rec if true, the transform values will be recorded to the target element's _gsTransform object, like target._gsTransform = {x:0, y:0, z:0, scaleX:1...}
			 * @param {boolean=} parse if true, we'll ignore any _gsTransform values that already exist on the element, and force a reparsing of the css (calculated style)
			 * @return {object} object containing all of the transform properties/values like {x:0, y:0, z:0, scaleX:1...}
			 */
			_getTransform = _internals.getTransform = function(t, cs, rec, parse) {
				if (t._gsTransform && rec && !parse) {
					return t._gsTransform; //if the element already has a _gsTransform, use that. Note: some browsers don't accurately return the calculated style for the transform (particularly for SVG), so it's almost always safest to just use the values we've already applied rather than re-parsing things.
				}
				var tm = rec ? t._gsTransform || new Transform() : new Transform(),
					invX = (tm.scaleX < 0), //in order to interpret things properly, we need to know if the user applied a negative scaleX previously so that we can adjust the rotation and skewX accordingly. Otherwise, if we always interpret a flipped matrix as affecting scaleY and the user only wants to tween the scaleX on multiple sequential tweens, it would keep the negative scaleY without that being the user's intent.
					min = 0.00002,
					rnd = 100000,
					zOrigin = _supports3D ? parseFloat(_getStyle(t, _transformOriginProp, cs, false, "0 0 0").split(" ")[2]) || tm.zOrigin  || 0 : 0,
					defaultTransformPerspective = parseFloat(CSSPlugin.defaultTransformPerspective) || 0,
					m, i, scaleX, scaleY, rotation, skewX;

				tm.svg = !!(t.getCTM && _isSVG(t));
				if (tm.svg) {
					_parseSVGOrigin(t, _getStyle(t, _transformOriginProp, cs, false, "50% 50%") + "", tm, t.getAttribute("data-svg-origin"));
					_useSVGTransformAttr = CSSPlugin.useSVGTransformAttr || _forceSVGTransformAttr;
				}
				m = _getMatrix(t);
				if (m !== _identity2DMatrix) {

					if (m.length === 16) {
						//we'll only look at these position-related 6 variables first because if x/y/z all match, it's relatively safe to assume we don't need to re-parse everything which risks losing important rotational information (like rotationX:180 plus rotationY:180 would look the same as rotation:180 - there's no way to know for sure which direction was taken based solely on the matrix3d() values)
						var a11 = m[0], a21 = m[1], a31 = m[2], a41 = m[3],
							a12 = m[4], a22 = m[5], a32 = m[6], a42 = m[7],
							a13 = m[8], a23 = m[9], a33 = m[10],
							a14 = m[12], a24 = m[13], a34 = m[14],
							a43 = m[11],
							angle = Math.atan2(a32, a33),
							t1, t2, t3, t4, cos, sin;

						//we manually compensate for non-zero z component of transformOrigin to work around bugs in Safari
						if (tm.zOrigin) {
							a34 = -tm.zOrigin;
							a14 = a13*a34-m[12];
							a24 = a23*a34-m[13];
							a34 = a33*a34+tm.zOrigin-m[14];
						}
						tm.rotationX = angle * _RAD2DEG;
						//rotationX
						if (angle) {
							cos = Math.cos(-angle);
							sin = Math.sin(-angle);
							t1 = a12*cos+a13*sin;
							t2 = a22*cos+a23*sin;
							t3 = a32*cos+a33*sin;
							a13 = a12*-sin+a13*cos;
							a23 = a22*-sin+a23*cos;
							a33 = a32*-sin+a33*cos;
							a43 = a42*-sin+a43*cos;
							a12 = t1;
							a22 = t2;
							a32 = t3;
						}
						//rotationY
						angle = Math.atan2(-a31, a33);
						tm.rotationY = angle * _RAD2DEG;
						if (angle) {
							cos = Math.cos(-angle);
							sin = Math.sin(-angle);
							t1 = a11*cos-a13*sin;
							t2 = a21*cos-a23*sin;
							t3 = a31*cos-a33*sin;
							a23 = a21*sin+a23*cos;
							a33 = a31*sin+a33*cos;
							a43 = a41*sin+a43*cos;
							a11 = t1;
							a21 = t2;
							a31 = t3;
						}
						//rotationZ
						angle = Math.atan2(a21, a11);
						tm.rotation = angle * _RAD2DEG;
						if (angle) {
							cos = Math.cos(-angle);
							sin = Math.sin(-angle);
							a11 = a11*cos+a12*sin;
							t2 = a21*cos+a22*sin;
							a22 = a21*-sin+a22*cos;
							a32 = a31*-sin+a32*cos;
							a21 = t2;
						}

						if (tm.rotationX && Math.abs(tm.rotationX) + Math.abs(tm.rotation) > 359.9) { //when rotationY is set, it will often be parsed as 180 degrees different than it should be, and rotationX and rotation both being 180 (it looks the same), so we adjust for that here.
							tm.rotationX = tm.rotation = 0;
							tm.rotationY = 180 - tm.rotationY;
						}

						tm.scaleX = ((Math.sqrt(a11 * a11 + a21 * a21) * rnd + 0.5) | 0) / rnd;
						tm.scaleY = ((Math.sqrt(a22 * a22 + a23 * a23) * rnd + 0.5) | 0) / rnd;
						tm.scaleZ = ((Math.sqrt(a32 * a32 + a33 * a33) * rnd + 0.5) | 0) / rnd;
						if (tm.rotationX || tm.rotationY) {
							tm.skewX = 0;
						} else {
							tm.skewX = (a12 || a22) ? Math.atan2(a12, a22) * _RAD2DEG + tm.rotation : tm.skewX || 0;
							if (Math.abs(tm.skewX) > 90 && Math.abs(tm.skewX) < 270) {
								if (invX) {
									tm.scaleX *= -1;
									tm.skewX += (tm.rotation <= 0) ? 180 : -180;
									tm.rotation += (tm.rotation <= 0) ? 180 : -180;
								} else {
									tm.scaleY *= -1;
									tm.skewX += (tm.skewX <= 0) ? 180 : -180;
								}
							}
						}
						tm.perspective = a43 ? 1 / ((a43 < 0) ? -a43 : a43) : 0;
						tm.x = a14;
						tm.y = a24;
						tm.z = a34;
						if (tm.svg) {
							tm.x -= tm.xOrigin - (tm.xOrigin * a11 - tm.yOrigin * a12);
							tm.y -= tm.yOrigin - (tm.yOrigin * a21 - tm.xOrigin * a22);
						}

					} else if ((!_supports3D || parse || !m.length || tm.x !== m[4] || tm.y !== m[5] || (!tm.rotationX && !tm.rotationY))) { //sometimes a 6-element matrix is returned even when we performed 3D transforms, like if rotationX and rotationY are 180. In cases like this, we still need to honor the 3D transforms. If we just rely on the 2D info, it could affect how the data is interpreted, like scaleY might get set to -1 or rotation could get offset by 180 degrees. For example, do a TweenLite.to(element, 1, {css:{rotationX:180, rotationY:180}}) and then later, TweenLite.to(element, 1, {css:{rotationX:0}}) and without this conditional logic in place, it'd jump to a state of being unrotated when the 2nd tween starts. Then again, we need to honor the fact that the user COULD alter the transforms outside of CSSPlugin, like by manually applying new css, so we try to sense that by looking at x and y because if those changed, we know the changes were made outside CSSPlugin and we force a reinterpretation of the matrix values. Also, in Webkit browsers, if the element's "display" is "none", its calculated style value will always return empty, so if we've already recorded the values in the _gsTransform object, we'll just rely on those.
						var k = (m.length >= 6),
							a = k ? m[0] : 1,
							b = m[1] || 0,
							c = m[2] || 0,
							d = k ? m[3] : 1;
						tm.x = m[4] || 0;
						tm.y = m[5] || 0;
						scaleX = Math.sqrt(a * a + b * b);
						scaleY = Math.sqrt(d * d + c * c);
						rotation = (a || b) ? Math.atan2(b, a) * _RAD2DEG : tm.rotation || 0; //note: if scaleX is 0, we cannot accurately measure rotation. Same for skewX with a scaleY of 0. Therefore, we default to the previously recorded value (or zero if that doesn't exist).
						skewX = (c || d) ? Math.atan2(c, d) * _RAD2DEG + rotation : tm.skewX || 0;
						if (Math.abs(skewX) > 90 && Math.abs(skewX) < 270) {
							if (invX) {
								scaleX *= -1;
								skewX += (rotation <= 0) ? 180 : -180;
								rotation += (rotation <= 0) ? 180 : -180;
							} else {
								scaleY *= -1;
								skewX += (skewX <= 0) ? 180 : -180;
							}
						}
						tm.scaleX = scaleX;
						tm.scaleY = scaleY;
						tm.rotation = rotation;
						tm.skewX = skewX;
						if (_supports3D) {
							tm.rotationX = tm.rotationY = tm.z = 0;
							tm.perspective = defaultTransformPerspective;
							tm.scaleZ = 1;
						}
						if (tm.svg) {
							tm.x -= tm.xOrigin - (tm.xOrigin * a + tm.yOrigin * c);
							tm.y -= tm.yOrigin - (tm.xOrigin * b + tm.yOrigin * d);
						}
					}
					tm.zOrigin = zOrigin;
					//some browsers have a hard time with very small values like 2.4492935982947064e-16 (notice the "e-" towards the end) and would render the object slightly off. So we round to 0 in these cases. The conditional logic here is faster than calling Math.abs(). Also, browsers tend to render a SLIGHTLY rotated object in a fuzzy way, so we need to snap to exactly 0 when appropriate.
					for (i in tm) {
						if (tm[i] < min) if (tm[i] > -min) {
							tm[i] = 0;
						}
					}
				}
				//DEBUG: _log("parsed rotation of " + t.getAttribute("id")+": "+(tm.rotationX)+", "+(tm.rotationY)+", "+(tm.rotation)+", scale: "+tm.scaleX+", "+tm.scaleY+", "+tm.scaleZ+", position: "+tm.x+", "+tm.y+", "+tm.z+", perspective: "+tm.perspective+ ", origin: "+ tm.xOrigin+ ","+ tm.yOrigin);
				if (rec) {
					t._gsTransform = tm; //record to the object's _gsTransform which we use so that tweens can control individual properties independently (we need all the properties to accurately recompose the matrix in the setRatio() method)
					if (tm.svg) { //if we're supposed to apply transforms to the SVG element's "transform" attribute, make sure there aren't any CSS transforms applied or they'll override the attribute ones. Also clear the transform attribute if we're using CSS, just to be clean.
						if (_useSVGTransformAttr && t.style[_transformProp]) {
							TweenLite.delayedCall(0.001, function(){ //if we apply this right away (before anything has rendered), we risk there being no transforms for a brief moment and it also interferes with adjusting the transformOrigin in a tween with immediateRender:true (it'd try reading the matrix and it wouldn't have the appropriate data in place because we just removed it).
								_removeProp(t.style, _transformProp);
							});
						} else if (!_useSVGTransformAttr && t.getAttribute("transform")) {
							TweenLite.delayedCall(0.001, function(){
								t.removeAttribute("transform");
							});
						}
					}
				}
				return tm;
			},

			//for setting 2D transforms in IE6, IE7, and IE8 (must use a "filter" to emulate the behavior of modern day browser transforms)
			_setIETransformRatio = function(v) {
				var t = this.data, //refers to the element's _gsTransform object
					ang = -t.rotation * _DEG2RAD,
					skew = ang + t.skewX * _DEG2RAD,
					rnd = 100000,
					a = ((Math.cos(ang) * t.scaleX * rnd) | 0) / rnd,
					b = ((Math.sin(ang) * t.scaleX * rnd) | 0) / rnd,
					c = ((Math.sin(skew) * -t.scaleY * rnd) | 0) / rnd,
					d = ((Math.cos(skew) * t.scaleY * rnd) | 0) / rnd,
					style = this.t.style,
					cs = this.t.currentStyle,
					filters, val;
				if (!cs) {
					return;
				}
				val = b; //just for swapping the variables an inverting them (reused "val" to avoid creating another variable in memory). IE's filter matrix uses a non-standard matrix configuration (angle goes the opposite way, and b and c are reversed and inverted)
				b = -c;
				c = -val;
				filters = cs.filter;
				style.filter = ""; //remove filters so that we can accurately measure offsetWidth/offsetHeight
				var w = this.t.offsetWidth,
					h = this.t.offsetHeight,
					clip = (cs.position !== "absolute"),
					m = "progid:DXImageTransform.Microsoft.Matrix(M11=" + a + ", M12=" + b + ", M21=" + c + ", M22=" + d,
					ox = t.x + (w * t.xPercent / 100),
					oy = t.y + (h * t.yPercent / 100),
					dx, dy;

				//if transformOrigin is being used, adjust the offset x and y
				if (t.ox != null) {
					dx = ((t.oxp) ? w * t.ox * 0.01 : t.ox) - w / 2;
					dy = ((t.oyp) ? h * t.oy * 0.01 : t.oy) - h / 2;
					ox += dx - (dx * a + dy * b);
					oy += dy - (dx * c + dy * d);
				}

				if (!clip) {
					m += ", sizingMethod='auto expand')";
				} else {
					dx = (w / 2);
					dy = (h / 2);
					//translate to ensure that transformations occur around the correct origin (default is center).
					m += ", Dx=" + (dx - (dx * a + dy * b) + ox) + ", Dy=" + (dy - (dx * c + dy * d) + oy) + ")";
				}
				if (filters.indexOf("DXImageTransform.Microsoft.Matrix(") !== -1) {
					style.filter = filters.replace(_ieSetMatrixExp, m);
				} else {
					style.filter = m + " " + filters; //we must always put the transform/matrix FIRST (before alpha(opacity=xx)) to avoid an IE bug that slices part of the object when rotation is applied with alpha.
				}

				//at the end or beginning of the tween, if the matrix is normal (1, 0, 0, 1) and opacity is 100 (or doesn't exist), remove the filter to improve browser performance.
				if (v === 0 || v === 1) if (a === 1) if (b === 0) if (c === 0) if (d === 1) if (!clip || m.indexOf("Dx=0, Dy=0") !== -1) if (!_opacityExp.test(filters) || parseFloat(RegExp.$1) === 100) if (filters.indexOf("gradient(" && filters.indexOf("Alpha")) === -1) {
					style.removeAttribute("filter");
				}

				//we must set the margins AFTER applying the filter in order to avoid some bugs in IE8 that could (in rare scenarios) cause them to be ignored intermittently (vibration).
				if (!clip) {
					var mult = (_ieVers < 8) ? 1 : -1, //in Internet Explorer 7 and before, the box model is broken, causing the browser to treat the width/height of the actual rotated filtered image as the width/height of the box itself, but Microsoft corrected that in IE8. We must use a negative offset in IE8 on the right/bottom
						marg, prop, dif;
					dx = t.ieOffsetX || 0;
					dy = t.ieOffsetY || 0;
					t.ieOffsetX = Math.round((w - ((a < 0 ? -a : a) * w + (b < 0 ? -b : b) * h)) / 2 + ox);
					t.ieOffsetY = Math.round((h - ((d < 0 ? -d : d) * h + (c < 0 ? -c : c) * w)) / 2 + oy);
					for (i = 0; i < 4; i++) {
						prop = _margins[i];
						marg = cs[prop];
						//we need to get the current margin in case it is being tweened separately (we want to respect that tween's changes)
						val = (marg.indexOf("px") !== -1) ? parseFloat(marg) : _convertToPixels(this.t, prop, parseFloat(marg), marg.replace(_suffixExp, "")) || 0;
						if (val !== t[prop]) {
							dif = (i < 2) ? -t.ieOffsetX : -t.ieOffsetY; //if another tween is controlling a margin, we cannot only apply the difference in the ieOffsets, so we essentially zero-out the dx and dy here in that case. We record the margin(s) later so that we can keep comparing them, making this code very flexible.
						} else {
							dif = (i < 2) ? dx - t.ieOffsetX : dy - t.ieOffsetY;
						}
						style[prop] = (t[prop] = Math.round( val - dif * ((i === 0 || i === 2) ? 1 : mult) )) + "px";
					}
				}
			},

			/* translates a super small decimal to a string WITHOUT scientific notation
			_safeDecimal = function(n) {
				var s = (n < 0 ? -n : n) + "",
					a = s.split("e-");
				return (n < 0 ? "-0." : "0.") + new Array(parseInt(a[1], 10) || 0).join("0") + a[0].split(".").join("");
			},
			*/

			_setTransformRatio = _internals.set3DTransformRatio = _internals.setTransformRatio = function(v) {
				var t = this.data, //refers to the element's _gsTransform object
					style = this.t.style,
					angle = t.rotation,
					rotationX = t.rotationX,
					rotationY = t.rotationY,
					sx = t.scaleX,
					sy = t.scaleY,
					sz = t.scaleZ,
					x = t.x,
					y = t.y,
					z = t.z,
					isSVG = t.svg,
					perspective = t.perspective,
					force3D = t.force3D,
					skewY = t.skewY,
					skewX = t.skewX,
					t1,	a11, a12, a13, a21, a22, a23, a31, a32, a33, a41, a42, a43,
					zOrigin, min, cos, sin, t2, transform, comma, zero, skew, rnd;
				if (skewY) { //for performance reasons, we combine all skewing into the skewX and rotation values. Remember, a skewY of 10 degrees looks the same as a rotation of 10 degrees plus a skewX of 10 degrees.
					skewX += skewY;
					angle += skewY;
				}

				//check to see if we should render as 2D (and SVGs must use 2D when _useSVGTransformAttr is true)
				if (((((v === 1 || v === 0) && force3D === "auto" && (this.tween._totalTime === this.tween._totalDuration || !this.tween._totalTime)) || !force3D) && !z && !perspective && !rotationY && !rotationX && sz === 1) || (_useSVGTransformAttr && isSVG) || !_supports3D) { //on the final render (which could be 0 for a from tween), if there are no 3D aspects, render in 2D to free up memory and improve performance especially on mobile devices. Check the tween's totalTime/totalDuration too in order to make sure it doesn't happen between repeats if it's a repeating tween.

					//2D
					if (angle || skewX || isSVG) {
						angle *= _DEG2RAD;
						skew = skewX * _DEG2RAD;
						rnd = 100000;
						a11 = Math.cos(angle) * sx;
						a21 = Math.sin(angle) * sx;
						a12 = Math.sin(angle - skew) * -sy;
						a22 = Math.cos(angle - skew) * sy;
						if (skew && t.skewType === "simple") { //by default, we compensate skewing on the other axis to make it look more natural, but you can set the skewType to "simple" to use the uncompensated skewing that CSS does
							t1 = Math.tan(skew - skewY * _DEG2RAD);
							t1 = Math.sqrt(1 + t1 * t1);
							a12 *= t1;
							a22 *= t1;
							if (skewY) {
								t1 = Math.tan(skewY * _DEG2RAD);
								t1 = Math.sqrt(1 + t1 * t1);
								a11 *= t1;
								a21 *= t1;
							}
						}
						if (isSVG) {
							x += t.xOrigin - (t.xOrigin * a11 + t.yOrigin * a12) + t.xOffset;
							y += t.yOrigin - (t.xOrigin * a21 + t.yOrigin * a22) + t.yOffset;
							if (_useSVGTransformAttr && (t.xPercent || t.yPercent)) { //The SVG spec doesn't support percentage-based translation in the "transform" attribute, so we merge it into the matrix to simulate it.
								min = this.t.getBBox();
								x += t.xPercent * 0.01 * min.width;
								y += t.yPercent * 0.01 * min.height;
							}
							min = 0.000001;
							if (x < min) if (x > -min) {
								x = 0;
							}
							if (y < min) if (y > -min) {
								y = 0;
							}
						}
						transform = (((a11 * rnd) | 0) / rnd) + "," + (((a21 * rnd) | 0) / rnd) + "," + (((a12 * rnd) | 0) / rnd) + "," + (((a22 * rnd) | 0) / rnd) + "," + x + "," + y + ")";
						if (isSVG && _useSVGTransformAttr) {
							this.t.setAttribute("transform", "matrix(" + transform);
						} else {
							//some browsers have a hard time with very small values like 2.4492935982947064e-16 (notice the "e-" towards the end) and would render the object slightly off. So we round to 5 decimal places.
							style[_transformProp] = ((t.xPercent || t.yPercent) ? "translate(" + t.xPercent + "%," + t.yPercent + "%) matrix(" : "matrix(") + transform;
						}
					} else {
						style[_transformProp] = ((t.xPercent || t.yPercent) ? "translate(" + t.xPercent + "%," + t.yPercent + "%) matrix(" : "matrix(") + sx + ",0,0," + sy + "," + x + "," + y + ")";
					}
					return;

				}
				if (_isFirefox) { //Firefox has a bug (at least in v25) that causes it to render the transparent part of 32-bit PNG images as black when displayed inside an iframe and the 3D scale is very small and doesn't change sufficiently enough between renders (like if you use a Power4.easeInOut to scale from 0 to 1 where the beginning values only change a tiny amount to begin the tween before accelerating). In this case, we force the scale to be 0.00002 instead which is visually the same but works around the Firefox issue.
					min = 0.0001;
					if (sx < min && sx > -min) {
						sx = sz = 0.00002;
					}
					if (sy < min && sy > -min) {
						sy = sz = 0.00002;
					}
					if (perspective && !t.z && !t.rotationX && !t.rotationY) { //Firefox has a bug that causes elements to have an odd super-thin, broken/dotted black border on elements that have a perspective set but aren't utilizing 3D space (no rotationX, rotationY, or z).
						perspective = 0;
					}
				}
				if (angle || skewX) {
					angle *= _DEG2RAD;
					cos = a11 = Math.cos(angle);
					sin = a21 = Math.sin(angle);
					if (skewX) {
						angle -= skewX * _DEG2RAD;
						cos = Math.cos(angle);
						sin = Math.sin(angle);
						if (t.skewType === "simple") { //by default, we compensate skewing on the other axis to make it look more natural, but you can set the skewType to "simple" to use the uncompensated skewing that CSS does
							t1 = Math.tan((skewX - skewY) * _DEG2RAD);
							t1 = Math.sqrt(1 + t1 * t1);
							cos *= t1;
							sin *= t1;
							if (t.skewY) {
								t1 = Math.tan(skewY * _DEG2RAD);
								t1 = Math.sqrt(1 + t1 * t1);
								a11 *= t1;
								a21 *= t1;
							}
						}
					}
					a12 = -sin;
					a22 = cos;

				} else if (!rotationY && !rotationX && sz === 1 && !perspective && !isSVG) { //if we're only translating and/or 2D scaling, this is faster...
					style[_transformProp] = ((t.xPercent || t.yPercent) ? "translate(" + t.xPercent + "%," + t.yPercent + "%) translate3d(" : "translate3d(") + x + "px," + y + "px," + z +"px)" + ((sx !== 1 || sy !== 1) ? " scale(" + sx + "," + sy + ")" : "");
					return;
				} else {
					a11 = a22 = 1;
					a12 = a21 = 0;
				}
				// KEY  INDEX   AFFECTS
				// a11  0       rotation, rotationY, scaleX
				// a21  1       rotation, rotationY, scaleX
				// a31  2       rotationY, scaleX
				// a41  3       rotationY, scaleX
				// a12  4       rotation, skewX, rotationX, scaleY
				// a22  5       rotation, skewX, rotationX, scaleY
				// a32  6       rotationX, scaleY
				// a42  7       rotationX, scaleY
				// a13  8       rotationY, rotationX, scaleZ
				// a23  9       rotationY, rotationX, scaleZ
				// a33  10      rotationY, rotationX, scaleZ
				// a43  11      rotationY, rotationX, perspective, scaleZ
				// a14  12      x, zOrigin, svgOrigin
				// a24  13      y, zOrigin, svgOrigin
				// a34  14      z, zOrigin
				// a44  15
				// rotation: Math.atan2(a21, a11)
				// rotationY: Math.atan2(a13, a33) (or Math.atan2(a13, a11))
				// rotationX: Math.atan2(a32, a33)
				a33 = 1;
				a13 = a23 = a31 = a32 = a41 = a42 = 0;
				a43 = (perspective) ? -1 / perspective : 0;
				zOrigin = t.zOrigin;
				min = 0.000001; //threshold below which browsers use scientific notation which won't work.
				comma = ",";
				zero = "0";
				angle = rotationY * _DEG2RAD;
				if (angle) {
					cos = Math.cos(angle);
					sin = Math.sin(angle);
					a31 = -sin;
					a41 = a43*-sin;
					a13 = a11*sin;
					a23 = a21*sin;
					a33 = cos;
					a43 *= cos;
					a11 *= cos;
					a21 *= cos;
				}
				angle = rotationX * _DEG2RAD;
				if (angle) {
					cos = Math.cos(angle);
					sin = Math.sin(angle);
					t1 = a12*cos+a13*sin;
					t2 = a22*cos+a23*sin;
					a32 = a33*sin;
					a42 = a43*sin;
					a13 = a12*-sin+a13*cos;
					a23 = a22*-sin+a23*cos;
					a33 = a33*cos;
					a43 = a43*cos;
					a12 = t1;
					a22 = t2;
				}
				if (sz !== 1) {
					a13*=sz;
					a23*=sz;
					a33*=sz;
					a43*=sz;
				}
				if (sy !== 1) {
					a12*=sy;
					a22*=sy;
					a32*=sy;
					a42*=sy;
				}
				if (sx !== 1) {
					a11*=sx;
					a21*=sx;
					a31*=sx;
					a41*=sx;
				}

				if (zOrigin || isSVG) {
					if (zOrigin) {
						x += a13*-zOrigin;
						y += a23*-zOrigin;
						z += a33*-zOrigin+zOrigin;
					}
					if (isSVG) { //due to bugs in some browsers, we need to manage the transform-origin of SVG manually
						x += t.xOrigin - (t.xOrigin * a11 + t.yOrigin * a12) + t.xOffset;
						y += t.yOrigin - (t.xOrigin * a21 + t.yOrigin * a22) + t.yOffset;
					}
					if (x < min && x > -min) {
						x = zero;
					}
					if (y < min && y > -min) {
						y = zero;
					}
					if (z < min && z > -min) {
						z = 0; //don't use string because we calculate perspective later and need the number.
					}
				}

				//optimized way of concatenating all the values into a string. If we do it all in one shot, it's slower because of the way browsers have to create temp strings and the way it affects memory. If we do it piece-by-piece with +=, it's a bit slower too. We found that doing it in these sized chunks works best overall:
				transform = ((t.xPercent || t.yPercent) ? "translate(" + t.xPercent + "%," + t.yPercent + "%) matrix3d(" : "matrix3d(");
				transform += ((a11 < min && a11 > -min) ? zero : a11) + comma + ((a21 < min && a21 > -min) ? zero : a21) + comma + ((a31 < min && a31 > -min) ? zero : a31);
				transform += comma + ((a41 < min && a41 > -min) ? zero : a41) + comma + ((a12 < min && a12 > -min) ? zero : a12) + comma + ((a22 < min && a22 > -min) ? zero : a22);
				if (rotationX || rotationY || sz !== 1) { //performance optimization (often there's no rotationX or rotationY, so we can skip these calculations)
					transform += comma + ((a32 < min && a32 > -min) ? zero : a32) + comma + ((a42 < min && a42 > -min) ? zero : a42) + comma + ((a13 < min && a13 > -min) ? zero : a13);
					transform += comma + ((a23 < min && a23 > -min) ? zero : a23) + comma + ((a33 < min && a33 > -min) ? zero : a33) + comma + ((a43 < min && a43 > -min) ? zero : a43) + comma;
				} else {
					transform += ",0,0,0,0,1,0,";
				}
				transform += x + comma + y + comma + z + comma + (perspective ? (1 + (-z / perspective)) : 1) + ")";

				style[_transformProp] = transform;
			};

		p = Transform.prototype;
		p.x = p.y = p.z = p.skewX = p.skewY = p.rotation = p.rotationX = p.rotationY = p.zOrigin = p.xPercent = p.yPercent = p.xOffset = p.yOffset = 0;
		p.scaleX = p.scaleY = p.scaleZ = 1;

		_registerComplexSpecialProp("transform,scale,scaleX,scaleY,scaleZ,x,y,z,rotation,rotationX,rotationY,rotationZ,skewX,skewY,shortRotation,shortRotationX,shortRotationY,shortRotationZ,transformOrigin,svgOrigin,transformPerspective,directionalRotation,parseTransform,force3D,skewType,xPercent,yPercent,smoothOrigin", {parser:function(t, e, parsingProp, cssp, pt, plugin, vars) {
			if (cssp._lastParsedTransform === vars) { return pt; } //only need to parse the transform once, and only if the browser supports it.
			cssp._lastParsedTransform = vars;
			var scaleFunc = (vars.scale && typeof(vars.scale) === "function") ? vars.scale : 0, //if there's a function-based "scale" value, swap in the resulting numeric value temporarily. Otherwise, if it's called for both scaleX and scaleY independently, they may not match (like if the function uses Math.random()).
				swapFunc;
			if (typeof(vars[parsingProp]) === "function") { //whatever property triggers the initial parsing might be a function-based value in which case it already got called in parse(), thus we don't want to call it again in here. The most efficient way to avoid this is to temporarily swap the value directly into the vars object, and then after we do all our parsing in this function, we'll swap it back again.
				swapFunc = vars[parsingProp];
				vars[parsingProp] = e;
			}
			if (scaleFunc) {
				vars.scale = scaleFunc(_index, t);
			}
			var originalGSTransform = t._gsTransform,
				style = t.style,
				min = 0.000001,
				i = _transformProps.length,
				v = vars,
				endRotations = {},
				transformOriginString = "transformOrigin",
				m1 = _getTransform(t, _cs, true, v.parseTransform),
				orig = v.transform && ((typeof(v.transform) === "function") ? v.transform(_index, _target) : v.transform),
				m2, copy, has3D, hasChange, dr, x, y, matrix, p;
			cssp._transform = m1;
			if (orig && typeof(orig) === "string" && _transformProp) { //for values like transform:"rotate(60deg) scale(0.5, 0.8)"
				copy = _tempDiv.style; //don't use the original target because it might be SVG in which case some browsers don't report computed style correctly.
				copy[_transformProp] = orig;
				copy.display = "block"; //if display is "none", the browser often refuses to report the transform properties correctly.
				copy.position = "absolute";
				_doc.body.appendChild(_tempDiv);
				m2 = _getTransform(_tempDiv, null, false);
				if (m1.svg) { //if it's an SVG element, x/y part of the matrix will be affected by whatever we use as the origin and the offsets, so compensate here...
					x = m1.xOrigin;
					y = m1.yOrigin;
					m2.x -= m1.xOffset;
					m2.y -= m1.yOffset;
					if (v.transformOrigin || v.svgOrigin) { //if this tween is altering the origin, we must factor that in here. The actual work of recording the transformOrigin values and setting up the PropTween is done later (still inside this function) so we cannot leave the changes intact here - we only want to update the x/y accordingly.
						orig = {};
						_parseSVGOrigin(t, _parsePosition(v.transformOrigin), orig, v.svgOrigin, v.smoothOrigin, true);
						x = orig.xOrigin;
						y = orig.yOrigin;
						m2.x -= orig.xOffset - m1.xOffset;
						m2.y -= orig.yOffset - m1.yOffset;
					}
					if (x || y) {
						matrix = _getMatrix(_tempDiv, true);
						m2.x -= x - (x * matrix[0] + y * matrix[2]);
						m2.y -= y - (x * matrix[1] + y * matrix[3]);
					}
				}
				_doc.body.removeChild(_tempDiv);
				if (!m2.perspective) {
					m2.perspective = m1.perspective; //tweening to no perspective gives very unintuitive results - just keep the same perspective in that case.
				}
				if (v.xPercent != null) {
					m2.xPercent = _parseVal(v.xPercent, m1.xPercent);
				}
				if (v.yPercent != null) {
					m2.yPercent = _parseVal(v.yPercent, m1.yPercent);
				}
			} else if (typeof(v) === "object") { //for values like scaleX, scaleY, rotation, x, y, skewX, and skewY or transform:{...} (object)
				m2 = {scaleX:_parseVal((v.scaleX != null) ? v.scaleX : v.scale, m1.scaleX),
					scaleY:_parseVal((v.scaleY != null) ? v.scaleY : v.scale, m1.scaleY),
					scaleZ:_parseVal(v.scaleZ, m1.scaleZ),
					x:_parseVal(v.x, m1.x),
					y:_parseVal(v.y, m1.y),
					z:_parseVal(v.z, m1.z),
					xPercent:_parseVal(v.xPercent, m1.xPercent),
					yPercent:_parseVal(v.yPercent, m1.yPercent),
					perspective:_parseVal(v.transformPerspective, m1.perspective)};
				dr = v.directionalRotation;
				if (dr != null) {
					if (typeof(dr) === "object") {
						for (copy in dr) {
							v[copy] = dr[copy];
						}
					} else {
						v.rotation = dr;
					}
				}
				if (typeof(v.x) === "string" && v.x.indexOf("%") !== -1) {
					m2.x = 0;
					m2.xPercent = _parseVal(v.x, m1.xPercent);
				}
				if (typeof(v.y) === "string" && v.y.indexOf("%") !== -1) {
					m2.y = 0;
					m2.yPercent = _parseVal(v.y, m1.yPercent);
				}

				m2.rotation = _parseAngle(("rotation" in v) ? v.rotation : ("shortRotation" in v) ? v.shortRotation + "_short" : ("rotationZ" in v) ? v.rotationZ : m1.rotation, m1.rotation, "rotation", endRotations);
				if (_supports3D) {
					m2.rotationX = _parseAngle(("rotationX" in v) ? v.rotationX : ("shortRotationX" in v) ? v.shortRotationX + "_short" : m1.rotationX || 0, m1.rotationX, "rotationX", endRotations);
					m2.rotationY = _parseAngle(("rotationY" in v) ? v.rotationY : ("shortRotationY" in v) ? v.shortRotationY + "_short" : m1.rotationY || 0, m1.rotationY, "rotationY", endRotations);
				}
				m2.skewX = _parseAngle(v.skewX, m1.skewX);
				m2.skewY = _parseAngle(v.skewY, m1.skewY);
			}
			if (_supports3D && v.force3D != null) {
				m1.force3D = v.force3D;
				hasChange = true;
			}

			m1.skewType = v.skewType || m1.skewType || CSSPlugin.defaultSkewType;

			has3D = (m1.force3D || m1.z || m1.rotationX || m1.rotationY || m2.z || m2.rotationX || m2.rotationY || m2.perspective);
			if (!has3D && v.scale != null) {
				m2.scaleZ = 1; //no need to tween scaleZ.
			}

			while (--i > -1) {
				p = _transformProps[i];
				orig = m2[p] - m1[p];
				if (orig > min || orig < -min || v[p] != null || _forcePT[p] != null) {
					hasChange = true;
					pt = new CSSPropTween(m1, p, m1[p], orig, pt);
					if (p in endRotations) {
						pt.e = endRotations[p]; //directional rotations typically have compensated values during the tween, but we need to make sure they end at exactly what the user requested
					}
					pt.xs0 = 0; //ensures the value stays numeric in setRatio()
					pt.plugin = plugin;
					cssp._overwriteProps.push(pt.n);
				}
			}

			orig = v.transformOrigin;
			if (m1.svg && (orig || v.svgOrigin)) {
				x = m1.xOffset; //when we change the origin, in order to prevent things from jumping we adjust the x/y so we must record those here so that we can create PropTweens for them and flip them at the same time as the origin
				y = m1.yOffset;
				_parseSVGOrigin(t, _parsePosition(orig), m2, v.svgOrigin, v.smoothOrigin);
				pt = _addNonTweeningNumericPT(m1, "xOrigin", (originalGSTransform ? m1 : m2).xOrigin, m2.xOrigin, pt, transformOriginString); //note: if there wasn't a transformOrigin defined yet, just start with the destination one; it's wasteful otherwise, and it causes problems with fromTo() tweens. For example, TweenLite.to("#wheel", 3, {rotation:180, transformOrigin:"50% 50%", delay:1}); TweenLite.fromTo("#wheel", 3, {scale:0.5, transformOrigin:"50% 50%"}, {scale:1, delay:2}); would cause a jump when the from values revert at the beginning of the 2nd tween.
				pt = _addNonTweeningNumericPT(m1, "yOrigin", (originalGSTransform ? m1 : m2).yOrigin, m2.yOrigin, pt, transformOriginString);
				if (x !== m1.xOffset || y !== m1.yOffset) {
					pt = _addNonTweeningNumericPT(m1, "xOffset", (originalGSTransform ? x : m1.xOffset), m1.xOffset, pt, transformOriginString);
					pt = _addNonTweeningNumericPT(m1, "yOffset", (originalGSTransform ? y : m1.yOffset), m1.yOffset, pt, transformOriginString);
				}
				orig = "0px 0px"; //certain browsers (like firefox) completely botch transform-origin, so we must remove it to prevent it from contaminating transforms. We manage it ourselves with xOrigin and yOrigin
			}
			if (orig || (_supports3D && has3D && m1.zOrigin)) { //if anything 3D is happening and there's a transformOrigin with a z component that's non-zero, we must ensure that the transformOrigin's z-component is set to 0 so that we can manually do those calculations to get around Safari bugs. Even if the user didn't specifically define a "transformOrigin" in this particular tween (maybe they did it via css directly).
				if (_transformProp) {
					hasChange = true;
					p = _transformOriginProp;
					orig = (orig || _getStyle(t, p, _cs, false, "50% 50%")) + ""; //cast as string to avoid errors
					pt = new CSSPropTween(style, p, 0, 0, pt, -1, transformOriginString);
					pt.b = style[p];
					pt.plugin = plugin;
					if (_supports3D) {
						copy = m1.zOrigin;
						orig = orig.split(" ");
						m1.zOrigin = ((orig.length > 2 && !(copy !== 0 && orig[2] === "0px")) ? parseFloat(orig[2]) : copy) || 0; //Safari doesn't handle the z part of transformOrigin correctly, so we'll manually handle it in the _set3DTransformRatio() method.
						pt.xs0 = pt.e = orig[0] + " " + (orig[1] || "50%") + " 0px"; //we must define a z value of 0px specifically otherwise iOS 5 Safari will stick with the old one (if one was defined)!
						pt = new CSSPropTween(m1, "zOrigin", 0, 0, pt, -1, pt.n); //we must create a CSSPropTween for the _gsTransform.zOrigin so that it gets reset properly at the beginning if the tween runs backward (as opposed to just setting m1.zOrigin here)
						pt.b = copy;
						pt.xs0 = pt.e = m1.zOrigin;
					} else {
						pt.xs0 = pt.e = orig;
					}

					//for older versions of IE (6-8), we need to manually calculate things inside the setRatio() function. We record origin x and y (ox and oy) and whether or not the values are percentages (oxp and oyp).
				} else {
					_parsePosition(orig + "", m1);
				}
			}
			if (hasChange) {
				cssp._transformType = (!(m1.svg && _useSVGTransformAttr) && (has3D || this._transformType === 3)) ? 3 : 2; //quicker than calling cssp._enableTransforms();
			}
			if (swapFunc) {
				vars[parsingProp] = swapFunc;
			}
			if (scaleFunc) {
				vars.scale = scaleFunc;
			}
			return pt;
		}, prefix:true});

		_registerComplexSpecialProp("boxShadow", {defaultValue:"0px 0px 0px 0px #999", prefix:true, color:true, multi:true, keyword:"inset"});

		_registerComplexSpecialProp("borderRadius", {defaultValue:"0px", parser:function(t, e, p, cssp, pt, plugin) {
			e = this.format(e);
			var props = ["borderTopLeftRadius","borderTopRightRadius","borderBottomRightRadius","borderBottomLeftRadius"],
				style = t.style,
				ea1, i, es2, bs2, bs, es, bn, en, w, h, esfx, bsfx, rel, hn, vn, em;
			w = parseFloat(t.offsetWidth);
			h = parseFloat(t.offsetHeight);
			ea1 = e.split(" ");
			for (i = 0; i < props.length; i++) { //if we're dealing with percentages, we must convert things separately for the horizontal and vertical axis!
				if (this.p.indexOf("border")) { //older browsers used a prefix
					props[i] = _checkPropPrefix(props[i]);
				}
				bs = bs2 = _getStyle(t, props[i], _cs, false, "0px");
				if (bs.indexOf(" ") !== -1) {
					bs2 = bs.split(" ");
					bs = bs2[0];
					bs2 = bs2[1];
				}
				es = es2 = ea1[i];
				bn = parseFloat(bs);
				bsfx = bs.substr((bn + "").length);
				rel = (es.charAt(1) === "=");
				if (rel) {
					en = parseInt(es.charAt(0)+"1", 10);
					es = es.substr(2);
					en *= parseFloat(es);
					esfx = es.substr((en + "").length - (en < 0 ? 1 : 0)) || "";
				} else {
					en = parseFloat(es);
					esfx = es.substr((en + "").length);
				}
				if (esfx === "") {
					esfx = _suffixMap[p] || bsfx;
				}
				if (esfx !== bsfx) {
					hn = _convertToPixels(t, "borderLeft", bn, bsfx); //horizontal number (we use a bogus "borderLeft" property just because the _convertToPixels() method searches for the keywords "Left", "Right", "Top", and "Bottom" to determine of it's a horizontal or vertical property, and we need "border" in the name so that it knows it should measure relative to the element itself, not its parent.
					vn = _convertToPixels(t, "borderTop", bn, bsfx); //vertical number
					if (esfx === "%") {
						bs = (hn / w * 100) + "%";
						bs2 = (vn / h * 100) + "%";
					} else if (esfx === "em") {
						em = _convertToPixels(t, "borderLeft", 1, "em");
						bs = (hn / em) + "em";
						bs2 = (vn / em) + "em";
					} else {
						bs = hn + "px";
						bs2 = vn + "px";
					}
					if (rel) {
						es = (parseFloat(bs) + en) + esfx;
						es2 = (parseFloat(bs2) + en) + esfx;
					}
				}
				pt = _parseComplex(style, props[i], bs + " " + bs2, es + " " + es2, false, "0px", pt);
			}
			return pt;
		}, prefix:true, formatter:_getFormatter("0px 0px 0px 0px", false, true)});
		_registerComplexSpecialProp("borderBottomLeftRadius,borderBottomRightRadius,borderTopLeftRadius,borderTopRightRadius", {defaultValue:"0px", parser:function(t, e, p, cssp, pt, plugin) {
			return _parseComplex(t.style, p, this.format(_getStyle(t, p, _cs, false, "0px 0px")), this.format(e), false, "0px", pt);
		}, prefix:true, formatter:_getFormatter("0px 0px", false, true)});
		_registerComplexSpecialProp("backgroundPosition", {defaultValue:"0 0", parser:function(t, e, p, cssp, pt, plugin) {
			var bp = "background-position",
				cs = (_cs || _getComputedStyle(t, null)),
				bs = this.format( ((cs) ? _ieVers ? cs.getPropertyValue(bp + "-x") + " " + cs.getPropertyValue(bp + "-y") : cs.getPropertyValue(bp) : t.currentStyle.backgroundPositionX + " " + t.currentStyle.backgroundPositionY) || "0 0"), //Internet Explorer doesn't report background-position correctly - we must query background-position-x and background-position-y and combine them (even in IE10). Before IE9, we must do the same with the currentStyle object and use camelCase
				es = this.format(e),
				ba, ea, i, pct, overlap, src;
			if ((bs.indexOf("%") !== -1) !== (es.indexOf("%") !== -1) && es.split(",").length < 2) {
				src = _getStyle(t, "backgroundImage").replace(_urlExp, "");
				if (src && src !== "none") {
					ba = bs.split(" ");
					ea = es.split(" ");
					_tempImg.setAttribute("src", src); //set the temp IMG's src to the background-image so that we can measure its width/height
					i = 2;
					while (--i > -1) {
						bs = ba[i];
						pct = (bs.indexOf("%") !== -1);
						if (pct !== (ea[i].indexOf("%") !== -1)) {
							overlap = (i === 0) ? t.offsetWidth - _tempImg.width : t.offsetHeight - _tempImg.height;
							ba[i] = pct ? (parseFloat(bs) / 100 * overlap) + "px" : (parseFloat(bs) / overlap * 100) + "%";
						}
					}
					bs = ba.join(" ");
				}
			}
			return this.parseComplex(t.style, bs, es, pt, plugin);
		}, formatter:_parsePosition});
		_registerComplexSpecialProp("backgroundSize", {defaultValue:"0 0", formatter:function(v) {
			v += ""; //ensure it's a string
			return _parsePosition(v.indexOf(" ") === -1 ? v + " " + v : v); //if set to something like "100% 100%", Safari typically reports the computed style as just "100%" (no 2nd value), but we should ensure that there are two values, so copy the first one. Otherwise, it'd be interpreted as "100% 0" (wrong).
		}});
		_registerComplexSpecialProp("perspective", {defaultValue:"0px", prefix:true});
		_registerComplexSpecialProp("perspectiveOrigin", {defaultValue:"50% 50%", prefix:true});
		_registerComplexSpecialProp("transformStyle", {prefix:true});
		_registerComplexSpecialProp("backfaceVisibility", {prefix:true});
		_registerComplexSpecialProp("userSelect", {prefix:true});
		_registerComplexSpecialProp("margin", {parser:_getEdgeParser("marginTop,marginRight,marginBottom,marginLeft")});
		_registerComplexSpecialProp("padding", {parser:_getEdgeParser("paddingTop,paddingRight,paddingBottom,paddingLeft")});
		_registerComplexSpecialProp("clip", {defaultValue:"rect(0px,0px,0px,0px)", parser:function(t, e, p, cssp, pt, plugin){
			var b, cs, delim;
			if (_ieVers < 9) { //IE8 and earlier don't report a "clip" value in the currentStyle - instead, the values are split apart into clipTop, clipRight, clipBottom, and clipLeft. Also, in IE7 and earlier, the values inside rect() are space-delimited, not comma-delimited.
				cs = t.currentStyle;
				delim = _ieVers < 8 ? " " : ",";
				b = "rect(" + cs.clipTop + delim + cs.clipRight + delim + cs.clipBottom + delim + cs.clipLeft + ")";
				e = this.format(e).split(",").join(delim);
			} else {
				b = this.format(_getStyle(t, this.p, _cs, false, this.dflt));
				e = this.format(e);
			}
			return this.parseComplex(t.style, b, e, pt, plugin);
		}});
		_registerComplexSpecialProp("textShadow", {defaultValue:"0px 0px 0px #999", color:true, multi:true});
		_registerComplexSpecialProp("autoRound,strictUnits", {parser:function(t, e, p, cssp, pt) {return pt;}}); //just so that we can ignore these properties (not tween them)
		_registerComplexSpecialProp("border", {defaultValue:"0px solid #000", parser:function(t, e, p, cssp, pt, plugin) {
			var bw = _getStyle(t, "borderTopWidth", _cs, false, "0px"),
				end = this.format(e).split(" "),
				esfx = end[0].replace(_suffixExp, "");
			if (esfx !== "px") { //if we're animating to a non-px value, we need to convert the beginning width to that unit.
				bw = (parseFloat(bw) / _convertToPixels(t, "borderTopWidth", 1, esfx)) + esfx;
			}
			return this.parseComplex(t.style, this.format(bw + " " + _getStyle(t, "borderTopStyle", _cs, false, "solid") + " " + _getStyle(t, "borderTopColor", _cs, false, "#000")), end.join(" "), pt, plugin);
			}, color:true, formatter:function(v) {
				var a = v.split(" ");
				return a[0] + " " + (a[1] || "solid") + " " + (v.match(_colorExp) || ["#000"])[0];
			}});
		_registerComplexSpecialProp("borderWidth", {parser:_getEdgeParser("borderTopWidth,borderRightWidth,borderBottomWidth,borderLeftWidth")}); //Firefox doesn't pick up on borderWidth set in style sheets (only inline).
		_registerComplexSpecialProp("float,cssFloat,styleFloat", {parser:function(t, e, p, cssp, pt, plugin) {
			var s = t.style,
				prop = ("cssFloat" in s) ? "cssFloat" : "styleFloat";
			return new CSSPropTween(s, prop, 0, 0, pt, -1, p, false, 0, s[prop], e);
		}});

		//opacity-related
		var _setIEOpacityRatio = function(v) {
				var t = this.t, //refers to the element's style property
					filters = t.filter || _getStyle(this.data, "filter") || "",
					val = (this.s + this.c * v) | 0,
					skip;
				if (val === 100) { //for older versions of IE that need to use a filter to apply opacity, we should remove the filter if opacity hits 1 in order to improve performance, but make sure there isn't a transform (matrix) or gradient in the filters.
					if (filters.indexOf("atrix(") === -1 && filters.indexOf("radient(") === -1 && filters.indexOf("oader(") === -1) {
						t.removeAttribute("filter");
						skip = (!_getStyle(this.data, "filter")); //if a class is applied that has an alpha filter, it will take effect (we don't want that), so re-apply our alpha filter in that case. We must first remove it and then check.
					} else {
						t.filter = filters.replace(_alphaFilterExp, "");
						skip = true;
					}
				}
				if (!skip) {
					if (this.xn1) {
						t.filter = filters = filters || ("alpha(opacity=" + val + ")"); //works around bug in IE7/8 that prevents changes to "visibility" from being applied properly if the filter is changed to a different alpha on the same frame.
					}
					if (filters.indexOf("pacity") === -1) { //only used if browser doesn't support the standard opacity style property (IE 7 and 8). We omit the "O" to avoid case-sensitivity issues
						if (val !== 0 || !this.xn1) { //bugs in IE7/8 won't render the filter properly if opacity is ADDED on the same frame/render as "visibility" changes (this.xn1 is 1 if this tween is an "autoAlpha" tween)
							t.filter = filters + " alpha(opacity=" + val + ")"; //we round the value because otherwise, bugs in IE7/8 can prevent "visibility" changes from being applied properly.
						}
					} else {
						t.filter = filters.replace(_opacityExp, "opacity=" + val);
					}
				}
			};
		_registerComplexSpecialProp("opacity,alpha,autoAlpha", {defaultValue:"1", parser:function(t, e, p, cssp, pt, plugin) {
			var b = parseFloat(_getStyle(t, "opacity", _cs, false, "1")),
				style = t.style,
				isAutoAlpha = (p === "autoAlpha");
			if (typeof(e) === "string" && e.charAt(1) === "=") {
				e = ((e.charAt(0) === "-") ? -1 : 1) * parseFloat(e.substr(2)) + b;
			}
			if (isAutoAlpha && b === 1 && _getStyle(t, "visibility", _cs) === "hidden" && e !== 0) { //if visibility is initially set to "hidden", we should interpret that as intent to make opacity 0 (a convenience)
				b = 0;
			}
			if (_supportsOpacity) {
				pt = new CSSPropTween(style, "opacity", b, e - b, pt);
			} else {
				pt = new CSSPropTween(style, "opacity", b * 100, (e - b) * 100, pt);
				pt.xn1 = isAutoAlpha ? 1 : 0; //we need to record whether or not this is an autoAlpha so that in the setRatio(), we know to duplicate the setting of the alpha in order to work around a bug in IE7 and IE8 that prevents changes to "visibility" from taking effect if the filter is changed to a different alpha(opacity) at the same time. Setting it to the SAME value first, then the new value works around the IE7/8 bug.
				style.zoom = 1; //helps correct an IE issue.
				pt.type = 2;
				pt.b = "alpha(opacity=" + pt.s + ")";
				pt.e = "alpha(opacity=" + (pt.s + pt.c) + ")";
				pt.data = t;
				pt.plugin = plugin;
				pt.setRatio = _setIEOpacityRatio;
			}
			if (isAutoAlpha) { //we have to create the "visibility" PropTween after the opacity one in the linked list so that they run in the order that works properly in IE8 and earlier
				pt = new CSSPropTween(style, "visibility", 0, 0, pt, -1, null, false, 0, ((b !== 0) ? "inherit" : "hidden"), ((e === 0) ? "hidden" : "inherit"));
				pt.xs0 = "inherit";
				cssp._overwriteProps.push(pt.n);
				cssp._overwriteProps.push(p);
			}
			return pt;
		}});


		var _removeProp = function(s, p) {
				if (p) {
					if (s.removeProperty) {
						if (p.substr(0,2) === "ms" || p.substr(0,6) === "webkit") { //Microsoft and some Webkit browsers don't conform to the standard of capitalizing the first prefix character, so we adjust so that when we prefix the caps with a dash, it's correct (otherwise it'd be "ms-transform" instead of "-ms-transform" for IE9, for example)
							p = "-" + p;
						}
						s.removeProperty(p.replace(_capsExp, "-$1").toLowerCase());
					} else { //note: old versions of IE use "removeAttribute()" instead of "removeProperty()"
						s.removeAttribute(p);
					}
				}
			},
			_setClassNameRatio = function(v) {
				this.t._gsClassPT = this;
				if (v === 1 || v === 0) {
					this.t.setAttribute("class", (v === 0) ? this.b : this.e);
					var mpt = this.data, //first MiniPropTween
						s = this.t.style;
					while (mpt) {
						if (!mpt.v) {
							_removeProp(s, mpt.p);
						} else {
							s[mpt.p] = mpt.v;
						}
						mpt = mpt._next;
					}
					if (v === 1 && this.t._gsClassPT === this) {
						this.t._gsClassPT = null;
					}
				} else if (this.t.getAttribute("class") !== this.e) {
					this.t.setAttribute("class", this.e);
				}
			};
		_registerComplexSpecialProp("className", {parser:function(t, e, p, cssp, pt, plugin, vars) {
			var b = t.getAttribute("class") || "", //don't use t.className because it doesn't work consistently on SVG elements; getAttribute("class") and setAttribute("class", value") is more reliable.
				cssText = t.style.cssText,
				difData, bs, cnpt, cnptLookup, mpt;
			pt = cssp._classNamePT = new CSSPropTween(t, p, 0, 0, pt, 2);
			pt.setRatio = _setClassNameRatio;
			pt.pr = -11;
			_hasPriority = true;
			pt.b = b;
			bs = _getAllStyles(t, _cs);
			//if there's a className tween already operating on the target, force it to its end so that the necessary inline styles are removed and the class name is applied before we determine the end state (we don't want inline styles interfering that were there just for class-specific values)
			cnpt = t._gsClassPT;
			if (cnpt) {
				cnptLookup = {};
				mpt = cnpt.data; //first MiniPropTween which stores the inline styles - we need to force these so that the inline styles don't contaminate things. Otherwise, there's a small chance that a tween could start and the inline values match the destination values and they never get cleaned.
				while (mpt) {
					cnptLookup[mpt.p] = 1;
					mpt = mpt._next;
				}
				cnpt.setRatio(1);
			}
			t._gsClassPT = pt;
			pt.e = (e.charAt(1) !== "=") ? e : b.replace(new RegExp("(?:\\s|^)" + e.substr(2) + "(?![\\w-])"), "") + ((e.charAt(0) === "+") ? " " + e.substr(2) : "");
			t.setAttribute("class", pt.e);
			difData = _cssDif(t, bs, _getAllStyles(t), vars, cnptLookup);
			t.setAttribute("class", b);
			pt.data = difData.firstMPT;
			t.style.cssText = cssText; //we recorded cssText before we swapped classes and ran _getAllStyles() because in cases when a className tween is overwritten, we remove all the related tweening properties from that class change (otherwise class-specific stuff can't override properties we've directly set on the target's style object due to specificity).
			pt = pt.xfirst = cssp.parse(t, difData.difs, pt, plugin); //we record the CSSPropTween as the xfirst so that we can handle overwriting propertly (if "className" gets overwritten, we must kill all the properties associated with the className part of the tween, so we can loop through from xfirst to the pt itself)
			return pt;
		}});


		var _setClearPropsRatio = function(v) {
			if (v === 1 || v === 0) if (this.data._totalTime === this.data._totalDuration && this.data.data !== "isFromStart") { //this.data refers to the tween. Only clear at the END of the tween (remember, from() tweens make the ratio go from 1 to 0, so we can't just check that and if the tween is the zero-duration one that's created internally to render the starting values in a from() tween, ignore that because otherwise, for example, from(...{height:100, clearProps:"height", delay:1}) would wipe the height at the beginning of the tween and after 1 second, it'd kick back in).
				var s = this.t.style,
					transformParse = _specialProps.transform.parse,
					a, p, i, clearTransform, transform;
				if (this.e === "all") {
					s.cssText = "";
					clearTransform = true;
				} else {
					a = this.e.split(" ").join("").split(",");
					i = a.length;
					while (--i > -1) {
						p = a[i];
						if (_specialProps[p]) {
							if (_specialProps[p].parse === transformParse) {
								clearTransform = true;
							} else {
								p = (p === "transformOrigin") ? _transformOriginProp : _specialProps[p].p; //ensures that special properties use the proper browser-specific property name, like "scaleX" might be "-webkit-transform" or "boxShadow" might be "-moz-box-shadow"
							}
						}
						_removeProp(s, p);
					}
				}
				if (clearTransform) {
					_removeProp(s, _transformProp);
					transform = this.t._gsTransform;
					if (transform) {
						if (transform.svg) {
							this.t.removeAttribute("data-svg-origin");
							this.t.removeAttribute("transform");
						}
						delete this.t._gsTransform;
					}
				}

			}
		};
		_registerComplexSpecialProp("clearProps", {parser:function(t, e, p, cssp, pt) {
			pt = new CSSPropTween(t, p, 0, 0, pt, 2);
			pt.setRatio = _setClearPropsRatio;
			pt.e = e;
			pt.pr = -10;
			pt.data = cssp._tween;
			_hasPriority = true;
			return pt;
		}});

		p = "bezier,throwProps,physicsProps,physics2D".split(",");
		i = p.length;
		while (i--) {
			_registerPluginProp(p[i]);
		}








		p = CSSPlugin.prototype;
		p._firstPT = p._lastParsedTransform = p._transform = null;

		//gets called when the tween renders for the first time. This kicks everything off, recording start/end values, etc.
		p._onInitTween = function(target, vars, tween, index) {
			if (!target.nodeType) { //css is only for dom elements
				return false;
			}
			this._target = _target = target;
			this._tween = tween;
			this._vars = vars;
			_index = index;
			_autoRound = vars.autoRound;
			_hasPriority = false;
			_suffixMap = vars.suffixMap || CSSPlugin.suffixMap;
			_cs = _getComputedStyle(target, "");
			_overwriteProps = this._overwriteProps;
			var style = target.style,
				v, pt, pt2, first, last, next, zIndex, tpt, threeD;
			if (_reqSafariFix) if (style.zIndex === "") {
				v = _getStyle(target, "zIndex", _cs);
				if (v === "auto" || v === "") {
					//corrects a bug in [non-Android] Safari that prevents it from repainting elements in their new positions if they don't have a zIndex set. We also can't just apply this inside _parseTransform() because anything that's moved in any way (like using "left" or "top" instead of transforms like "x" and "y") can be affected, so it is best to ensure that anything that's tweening has a z-index. Setting "WebkitPerspective" to a non-zero value worked too except that on iOS Safari things would flicker randomly. Plus zIndex is less memory-intensive.
					this._addLazySet(style, "zIndex", 0);
				}
			}

			if (typeof(vars) === "string") {
				first = style.cssText;
				v = _getAllStyles(target, _cs);
				style.cssText = first + ";" + vars;
				v = _cssDif(target, v, _getAllStyles(target)).difs;
				if (!_supportsOpacity && _opacityValExp.test(vars)) {
					v.opacity = parseFloat( RegExp.$1 );
				}
				vars = v;
				style.cssText = first;
			}

			if (vars.className) { //className tweens will combine any differences they find in the css with the vars that are passed in, so {className:"myClass", scale:0.5, left:20} would work.
				this._firstPT = pt = _specialProps.className.parse(target, vars.className, "className", this, null, null, vars);
			} else {
				this._firstPT = pt = this.parse(target, vars, null);
			}

			if (this._transformType) {
				threeD = (this._transformType === 3);
				if (!_transformProp) {
					style.zoom = 1; //helps correct an IE issue.
				} else if (_isSafari) {
					_reqSafariFix = true;
					//if zIndex isn't set, iOS Safari doesn't repaint things correctly sometimes (seemingly at random).
					if (style.zIndex === "") {
						zIndex = _getStyle(target, "zIndex", _cs);
						if (zIndex === "auto" || zIndex === "") {
							this._addLazySet(style, "zIndex", 0);
						}
					}
					//Setting WebkitBackfaceVisibility corrects 3 bugs:
					// 1) [non-Android] Safari skips rendering changes to "top" and "left" that are made on the same frame/render as a transform update.
					// 2) iOS Safari sometimes neglects to repaint elements in their new positions. Setting "WebkitPerspective" to a non-zero value worked too except that on iOS Safari things would flicker randomly.
					// 3) Safari sometimes displayed odd artifacts when tweening the transform (or WebkitTransform) property, like ghosts of the edges of the element remained. Definitely a browser bug.
					//Note: we allow the user to override the auto-setting by defining WebkitBackfaceVisibility in the vars of the tween.
					if (_isSafariLT6) {
						this._addLazySet(style, "WebkitBackfaceVisibility", this._vars.WebkitBackfaceVisibility || (threeD ? "visible" : "hidden"));
					}
				}
				pt2 = pt;
				while (pt2 && pt2._next) {
					pt2 = pt2._next;
				}
				tpt = new CSSPropTween(target, "transform", 0, 0, null, 2);
				this._linkCSSP(tpt, null, pt2);
				tpt.setRatio = _transformProp ? _setTransformRatio : _setIETransformRatio;
				tpt.data = this._transform || _getTransform(target, _cs, true);
				tpt.tween = tween;
				tpt.pr = -1; //ensures that the transforms get applied after the components are updated.
				_overwriteProps.pop(); //we don't want to force the overwrite of all "transform" tweens of the target - we only care about individual transform properties like scaleX, rotation, etc. The CSSPropTween constructor automatically adds the property to _overwriteProps which is why we need to pop() here.
			}

			if (_hasPriority) {
				//reorders the linked list in order of pr (priority)
				while (pt) {
					next = pt._next;
					pt2 = first;
					while (pt2 && pt2.pr > pt.pr) {
						pt2 = pt2._next;
					}
					if ((pt._prev = pt2 ? pt2._prev : last)) {
						pt._prev._next = pt;
					} else {
						first = pt;
					}
					if ((pt._next = pt2)) {
						pt2._prev = pt;
					} else {
						last = pt;
					}
					pt = next;
				}
				this._firstPT = first;
			}
			return true;
		};


		p.parse = function(target, vars, pt, plugin) {
			var style = target.style,
				p, sp, bn, en, bs, es, bsfx, esfx, isStr, rel;
			for (p in vars) {
				es = vars[p]; //ending value string
				if (typeof(es) === "function") {
					es = es(_index, _target);
				}
				sp = _specialProps[p]; //SpecialProp lookup.
				if (sp) {
					pt = sp.parse(target, es, p, this, pt, plugin, vars);

				} else {
					bs = _getStyle(target, p, _cs) + "";
					isStr = (typeof(es) === "string");
					if (p === "color" || p === "fill" || p === "stroke" || p.indexOf("Color") !== -1 || (isStr && _rgbhslExp.test(es))) { //Opera uses background: to define color sometimes in addition to backgroundColor:
						if (!isStr) {
							es = _parseColor(es);
							es = ((es.length > 3) ? "rgba(" : "rgb(") + es.join(",") + ")";
						}
						pt = _parseComplex(style, p, bs, es, true, "transparent", pt, 0, plugin);

					} else if (isStr && _complexExp.test(es)) {
						pt = _parseComplex(style, p, bs, es, true, null, pt, 0, plugin);

					} else {
						bn = parseFloat(bs);
						bsfx = (bn || bn === 0) ? bs.substr((bn + "").length) : ""; //remember, bs could be non-numeric like "normal" for fontWeight, so we should default to a blank suffix in that case.

						if (bs === "" || bs === "auto") {
							if (p === "width" || p === "height") {
								bn = _getDimension(target, p, _cs);
								bsfx = "px";
							} else if (p === "left" || p === "top") {
								bn = _calculateOffset(target, p, _cs);
								bsfx = "px";
							} else {
								bn = (p !== "opacity") ? 0 : 1;
								bsfx = "";
							}
						}

						rel = (isStr && es.charAt(1) === "=");
						if (rel) {
							en = parseInt(es.charAt(0) + "1", 10);
							es = es.substr(2);
							en *= parseFloat(es);
							esfx = es.replace(_suffixExp, "");
						} else {
							en = parseFloat(es);
							esfx = isStr ? es.replace(_suffixExp, "") : "";
						}

						if (esfx === "") {
							esfx = (p in _suffixMap) ? _suffixMap[p] : bsfx; //populate the end suffix, prioritizing the map, then if none is found, use the beginning suffix.
						}

						es = (en || en === 0) ? (rel ? en + bn : en) + esfx : vars[p]; //ensures that any += or -= prefixes are taken care of. Record the end value before normalizing the suffix because we always want to end the tween on exactly what they intended even if it doesn't match the beginning value's suffix.

						//if the beginning/ending suffixes don't match, normalize them...
						if (bsfx !== esfx) if (esfx !== "") if (en || en === 0) if (bn) { //note: if the beginning value (bn) is 0, we don't need to convert units!
							bn = _convertToPixels(target, p, bn, bsfx);
							if (esfx === "%") {
								bn /= _convertToPixels(target, p, 100, "%") / 100;
								if (vars.strictUnits !== true) { //some browsers report only "px" values instead of allowing "%" with getComputedStyle(), so we assume that if we're tweening to a %, we should start there too unless strictUnits:true is defined. This approach is particularly useful for responsive designs that use from() tweens.
									bs = bn + "%";
								}

							} else if (esfx === "em" || esfx === "rem" || esfx === "vw" || esfx === "vh") {
								bn /= _convertToPixels(target, p, 1, esfx);

							//otherwise convert to pixels.
							} else if (esfx !== "px") {
								en = _convertToPixels(target, p, en, esfx);
								esfx = "px"; //we don't use bsfx after this, so we don't need to set it to px too.
							}
							if (rel) if (en || en === 0) {
								es = (en + bn) + esfx; //the changes we made affect relative calculations, so adjust the end value here.
							}
						}

						if (rel) {
							en += bn;
						}

						if ((bn || bn === 0) && (en || en === 0)) { //faster than isNaN(). Also, previously we required en !== bn but that doesn't really gain much performance and it prevents _parseToProxy() from working properly if beginning and ending values match but need to get tweened by an external plugin anyway. For example, a bezier tween where the target starts at left:0 and has these points: [{left:50},{left:0}] wouldn't work properly because when parsing the last point, it'd match the first (current) one and a non-tweening CSSPropTween would be recorded when we actually need a normal tween (type:0) so that things get updated during the tween properly.
							pt = new CSSPropTween(style, p, bn, en - bn, pt, 0, p, (_autoRound !== false && (esfx === "px" || p === "zIndex")), 0, bs, es);
							pt.xs0 = esfx;
							//DEBUG: _log("tween "+p+" from "+pt.b+" ("+bn+esfx+") to "+pt.e+" with suffix: "+pt.xs0);
						} else if (style[p] === undefined || !es && (es + "" === "NaN" || es == null)) {
							_log("invalid " + p + " tween value: " + vars[p]);
						} else {
							pt = new CSSPropTween(style, p, en || bn || 0, 0, pt, -1, p, false, 0, bs, es);
							pt.xs0 = (es === "none" && (p === "display" || p.indexOf("Style") !== -1)) ? bs : es; //intermediate value should typically be set immediately (end value) except for "display" or things like borderTopStyle, borderBottomStyle, etc. which should use the beginning value during the tween.
							//DEBUG: _log("non-tweening value "+p+": "+pt.xs0);
						}
					}
				}
				if (plugin) if (pt && !pt.plugin) {
					pt.plugin = plugin;
				}
			}
			return pt;
		};


		//gets called every time the tween updates, passing the new ratio (typically a value between 0 and 1, but not always (for example, if an Elastic.easeOut is used, the value can jump above 1 mid-tween). It will always start and 0 and end at 1.
		p.setRatio = function(v) {
			var pt = this._firstPT,
				min = 0.000001,
				val, str, i;
			//at the end of the tween, we set the values to exactly what we received in order to make sure non-tweening values (like "position" or "float" or whatever) are set and so that if the beginning/ending suffixes (units) didn't match and we normalized to px, the value that the user passed in is used here. We check to see if the tween is at its beginning in case it's a from() tween in which case the ratio will actually go from 1 to 0 over the course of the tween (backwards).
			if (v === 1 && (this._tween._time === this._tween._duration || this._tween._time === 0)) {
				while (pt) {
					if (pt.type !== 2) {
						if (pt.r && pt.type !== -1) {
							val = Math.round(pt.s + pt.c);
							if (!pt.type) {
								pt.t[pt.p] = val + pt.xs0;
							} else if (pt.type === 1) { //complex value (one that typically has multiple numbers inside a string, like "rect(5px,10px,20px,25px)"
								i = pt.l;
								str = pt.xs0 + val + pt.xs1;
								for (i = 1; i < pt.l; i++) {
									str += pt["xn"+i] + pt["xs"+(i+1)];
								}
								pt.t[pt.p] = str;
							}
						} else {
							pt.t[pt.p] = pt.e;
						}
					} else {
						pt.setRatio(v);
					}
					pt = pt._next;
				}

			} else if (v || !(this._tween._time === this._tween._duration || this._tween._time === 0) || this._tween._rawPrevTime === -0.000001) {
				while (pt) {
					val = pt.c * v + pt.s;
					if (pt.r) {
						val = Math.round(val);
					} else if (val < min) if (val > -min) {
						val = 0;
					}
					if (!pt.type) {
						pt.t[pt.p] = val + pt.xs0;
					} else if (pt.type === 1) { //complex value (one that typically has multiple numbers inside a string, like "rect(5px,10px,20px,25px)"
						i = pt.l;
						if (i === 2) {
							pt.t[pt.p] = pt.xs0 + val + pt.xs1 + pt.xn1 + pt.xs2;
						} else if (i === 3) {
							pt.t[pt.p] = pt.xs0 + val + pt.xs1 + pt.xn1 + pt.xs2 + pt.xn2 + pt.xs3;
						} else if (i === 4) {
							pt.t[pt.p] = pt.xs0 + val + pt.xs1 + pt.xn1 + pt.xs2 + pt.xn2 + pt.xs3 + pt.xn3 + pt.xs4;
						} else if (i === 5) {
							pt.t[pt.p] = pt.xs0 + val + pt.xs1 + pt.xn1 + pt.xs2 + pt.xn2 + pt.xs3 + pt.xn3 + pt.xs4 + pt.xn4 + pt.xs5;
						} else {
							str = pt.xs0 + val + pt.xs1;
							for (i = 1; i < pt.l; i++) {
								str += pt["xn"+i] + pt["xs"+(i+1)];
							}
							pt.t[pt.p] = str;
						}

					} else if (pt.type === -1) { //non-tweening value
						pt.t[pt.p] = pt.xs0;

					} else if (pt.setRatio) { //custom setRatio() for things like SpecialProps, external plugins, etc.
						pt.setRatio(v);
					}
					pt = pt._next;
				}

			//if the tween is reversed all the way back to the beginning, we need to restore the original values which may have different units (like % instead of px or em or whatever).
			} else {
				while (pt) {
					if (pt.type !== 2) {
						pt.t[pt.p] = pt.b;
					} else {
						pt.setRatio(v);
					}
					pt = pt._next;
				}
			}
		};

		/**
		 * @private
		 * Forces rendering of the target's transforms (rotation, scale, etc.) whenever the CSSPlugin's setRatio() is called.
		 * Basically, this tells the CSSPlugin to create a CSSPropTween (type 2) after instantiation that runs last in the linked
		 * list and calls the appropriate (3D or 2D) rendering function. We separate this into its own method so that we can call
		 * it from other plugins like BezierPlugin if, for example, it needs to apply an autoRotation and this CSSPlugin
		 * doesn't have any transform-related properties of its own. You can call this method as many times as you
		 * want and it won't create duplicate CSSPropTweens.
		 *
		 * @param {boolean} threeD if true, it should apply 3D tweens (otherwise, just 2D ones are fine and typically faster)
		 */
		p._enableTransforms = function(threeD) {
			this._transform = this._transform || _getTransform(this._target, _cs, true); //ensures that the element has a _gsTransform property with the appropriate values.
			this._transformType = (!(this._transform.svg && _useSVGTransformAttr) && (threeD || this._transformType === 3)) ? 3 : 2;
		};

		var lazySet = function(v) {
			this.t[this.p] = this.e;
			this.data._linkCSSP(this, this._next, null, true); //we purposefully keep this._next even though it'd make sense to null it, but this is a performance optimization, as this happens during the while (pt) {} loop in setRatio() at the bottom of which it sets pt = pt._next, so if we null it, the linked list will be broken in that loop.
		};
		/** @private Gives us a way to set a value on the first render (and only the first render). **/
		p._addLazySet = function(t, p, v) {
			var pt = this._firstPT = new CSSPropTween(t, p, 0, 0, this._firstPT, 2);
			pt.e = v;
			pt.setRatio = lazySet;
			pt.data = this;
		};

		/** @private **/
		p._linkCSSP = function(pt, next, prev, remove) {
			if (pt) {
				if (next) {
					next._prev = pt;
				}
				if (pt._next) {
					pt._next._prev = pt._prev;
				}
				if (pt._prev) {
					pt._prev._next = pt._next;
				} else if (this._firstPT === pt) {
					this._firstPT = pt._next;
					remove = true; //just to prevent resetting this._firstPT 5 lines down in case pt._next is null. (optimized for speed)
				}
				if (prev) {
					prev._next = pt;
				} else if (!remove && this._firstPT === null) {
					this._firstPT = pt;
				}
				pt._next = next;
				pt._prev = prev;
			}
			return pt;
		};

		p._mod = function(lookup) {
			var pt = this._firstPT;
			while (pt) {
				if (typeof(lookup[pt.p]) === "function" && lookup[pt.p] === Math.round) { //only gets called by RoundPropsPlugin (ModifyPlugin manages all the rendering internally for CSSPlugin properties that need modification). Remember, we handle rounding a bit differently in this plugin for performance reasons, leveraging "r" as an indicator that the value should be rounded internally..
					pt.r = 1;
				}
				pt = pt._next;
			}
		};

		//we need to make sure that if alpha or autoAlpha is killed, opacity is too. And autoAlpha affects the "visibility" property.
		p._kill = function(lookup) {
			var copy = lookup,
				pt, p, xfirst;
			if (lookup.autoAlpha || lookup.alpha) {
				copy = {};
				for (p in lookup) { //copy the lookup so that we're not changing the original which may be passed elsewhere.
					copy[p] = lookup[p];
				}
				copy.opacity = 1;
				if (copy.autoAlpha) {
					copy.visibility = 1;
				}
			}
			if (lookup.className && (pt = this._classNamePT)) { //for className tweens, we need to kill any associated CSSPropTweens too; a linked list starts at the className's "xfirst".
				xfirst = pt.xfirst;
				if (xfirst && xfirst._prev) {
					this._linkCSSP(xfirst._prev, pt._next, xfirst._prev._prev); //break off the prev
				} else if (xfirst === this._firstPT) {
					this._firstPT = pt._next;
				}
				if (pt._next) {
					this._linkCSSP(pt._next, pt._next._next, xfirst._prev);
				}
				this._classNamePT = null;
			}
			pt = this._firstPT;
			while (pt) {
				if (pt.plugin && pt.plugin !== p && pt.plugin._kill) { //for plugins that are registered with CSSPlugin, we should notify them of the kill.
					pt.plugin._kill(lookup);
					p = pt.plugin;
				}
				pt = pt._next;
			}
			return TweenPlugin.prototype._kill.call(this, copy);
		};



		//used by cascadeTo() for gathering all the style properties of each child element into an array for comparison.
		var _getChildStyles = function(e, props, targets) {
				var children, i, child, type;
				if (e.slice) {
					i = e.length;
					while (--i > -1) {
						_getChildStyles(e[i], props, targets);
					}
					return;
				}
				children = e.childNodes;
				i = children.length;
				while (--i > -1) {
					child = children[i];
					type = child.type;
					if (child.style) {
						props.push(_getAllStyles(child));
						if (targets) {
							targets.push(child);
						}
					}
					if ((type === 1 || type === 9 || type === 11) && child.childNodes.length) {
						_getChildStyles(child, props, targets);
					}
				}
			};

		/**
		 * Typically only useful for className tweens that may affect child elements, this method creates a TweenLite
		 * and then compares the style properties of all the target's child elements at the tween's start and end, and
		 * if any are different, it also creates tweens for those and returns an array containing ALL of the resulting
		 * tweens (so that you can easily add() them to a TimelineLite, for example). The reason this functionality is
		 * wrapped into a separate static method of CSSPlugin instead of being integrated into all regular className tweens
		 * is because it creates entirely new tweens that may have completely different targets than the original tween,
		 * so if they were all lumped into the original tween instance, it would be inconsistent with the rest of the API
		 * and it would create other problems. For example:
		 *  - If I create a tween of elementA, that tween instance may suddenly change its target to include 50 other elements (unintuitive if I specifically defined the target I wanted)
		 *  - We can't just create new independent tweens because otherwise, what happens if the original/parent tween is reversed or pause or dropped into a TimelineLite for tight control? You'd expect that tween's behavior to affect all the others.
		 *  - Analyzing every style property of every child before and after the tween is an expensive operation when there are many children, so this behavior shouldn't be imposed on all className tweens by default, especially since it's probably rare that this extra functionality is needed.
		 *
		 * @param {Object} target object to be tweened
		 * @param {number} Duration in seconds (or frames for frames-based tweens)
		 * @param {Object} Object containing the end values, like {className:"newClass", ease:Linear.easeNone}
		 * @return {Array} An array of TweenLite instances
		 */
		CSSPlugin.cascadeTo = function(target, duration, vars) {
			var tween = TweenLite.to(target, duration, vars),
				results = [tween],
				b = [],
				e = [],
				targets = [],
				_reservedProps = TweenLite._internals.reservedProps,
				i, difs, p, from;
			target = tween._targets || tween.target;
			_getChildStyles(target, b, targets);
			tween.render(duration, true, true);
			_getChildStyles(target, e);
			tween.render(0, true, true);
			tween._enabled(true);
			i = targets.length;
			while (--i > -1) {
				difs = _cssDif(targets[i], b[i], e[i]);
				if (difs.firstMPT) {
					difs = difs.difs;
					for (p in vars) {
						if (_reservedProps[p]) {
							difs[p] = vars[p];
						}
					}
					from = {};
					for (p in difs) {
						from[p] = b[i][p];
					}
					results.push(TweenLite.fromTo(targets[i], duration, from, difs));
				}
			}
			return results;
		};

		TweenPlugin.activate([CSSPlugin]);
		return CSSPlugin;

	}, true);

	
	
	
	
	
	
	
	
	
	
/*
 * ----------------------------------------------------------------
 * RoundPropsPlugin
 * ----------------------------------------------------------------
 */
	(function() {

		var RoundPropsPlugin = _gsScope._gsDefine.plugin({
				propName: "roundProps",
				version: "1.6.0",
				priority: -1,
				API: 2,

				//called when the tween renders for the first time. This is where initial values should be recorded and any setup routines should run.
				init: function(target, value, tween) {
					this._tween = tween;
					return true;
				}

			}),
			_roundLinkedList = function(node) {
				while (node) {
					if (!node.f && !node.blob) {
						node.m = Math.round;
					}
					node = node._next;
				}
			},
			p = RoundPropsPlugin.prototype;

		p._onInitAllProps = function() {
			var tween = this._tween,
				rp = (tween.vars.roundProps.join) ? tween.vars.roundProps : tween.vars.roundProps.split(","),
				i = rp.length,
				lookup = {},
				rpt = tween._propLookup.roundProps,
				prop, pt, next;
			while (--i > -1) {
				lookup[rp[i]] = Math.round;
			}
			i = rp.length;
			while (--i > -1) {
				prop = rp[i];
				pt = tween._firstPT;
				while (pt) {
					next = pt._next; //record here, because it may get removed
					if (pt.pg) {
						pt.t._mod(lookup);
					} else if (pt.n === prop) {
						if (pt.f === 2 && pt.t) { //a blob (text containing multiple numeric values)
							_roundLinkedList(pt.t._firstPT);
						} else {
							this._add(pt.t, prop, pt.s, pt.c);
							//remove from linked list
							if (next) {
								next._prev = pt._prev;
							}
							if (pt._prev) {
								pt._prev._next = next;
							} else if (tween._firstPT === pt) {
								tween._firstPT = next;
							}
							pt._next = pt._prev = null;
							tween._propLookup[prop] = rpt;
						}
					}
					pt = next;
				}
			}
			return false;
		};

		p._add = function(target, p, s, c) {
			this._addTween(target, p, s, s + c, p, Math.round);
			this._overwriteProps.push(p);
		};

	}());










/*
 * ----------------------------------------------------------------
 * AttrPlugin
 * ----------------------------------------------------------------
 */

	(function() {

		_gsScope._gsDefine.plugin({
			propName: "attr",
			API: 2,
			version: "0.6.0",

			//called when the tween renders for the first time. This is where initial values should be recorded and any setup routines should run.
			init: function(target, value, tween, index) {
				var p, end;
				if (typeof(target.setAttribute) !== "function") {
					return false;
				}
				for (p in value) {
					end = value[p];
					if (typeof(end) === "function") {
						end = end(index, target);
					}
					this._addTween(target, "setAttribute", target.getAttribute(p) + "", end + "", p, false, p);
					this._overwriteProps.push(p);
				}
				return true;
			}

		});

	}());










/*
 * ----------------------------------------------------------------
 * DirectionalRotationPlugin
 * ----------------------------------------------------------------
 */
	_gsScope._gsDefine.plugin({
		propName: "directionalRotation",
		version: "0.3.0",
		API: 2,

		//called when the tween renders for the first time. This is where initial values should be recorded and any setup routines should run.
		init: function(target, value, tween, index) {
			if (typeof(value) !== "object") {
				value = {rotation:value};
			}
			this.finals = {};
			var cap = (value.useRadians === true) ? Math.PI * 2 : 360,
				min = 0.000001,
				p, v, start, end, dif, split;
			for (p in value) {
				if (p !== "useRadians") {
					end = value[p];
					if (typeof(end) === "function") {
						end = end(index, target);
					}
					split = (end + "").split("_");
					v = split[0];
					start = parseFloat( (typeof(target[p]) !== "function") ? target[p] : target[ ((p.indexOf("set") || typeof(target["get" + p.substr(3)]) !== "function") ? p : "get" + p.substr(3)) ]() );
					end = this.finals[p] = (typeof(v) === "string" && v.charAt(1) === "=") ? start + parseInt(v.charAt(0) + "1", 10) * Number(v.substr(2)) : Number(v) || 0;
					dif = end - start;
					if (split.length) {
						v = split.join("_");
						if (v.indexOf("short") !== -1) {
							dif = dif % cap;
							if (dif !== dif % (cap / 2)) {
								dif = (dif < 0) ? dif + cap : dif - cap;
							}
						}
						if (v.indexOf("_cw") !== -1 && dif < 0) {
							dif = ((dif + cap * 9999999999) % cap) - ((dif / cap) | 0) * cap;
						} else if (v.indexOf("ccw") !== -1 && dif > 0) {
							dif = ((dif - cap * 9999999999) % cap) - ((dif / cap) | 0) * cap;
						}
					}
					if (dif > min || dif < -min) {
						this._addTween(target, p, start, start + dif, p);
						this._overwriteProps.push(p);
					}
				}
			}
			return true;
		},

		//called each time the values should be updated, and the ratio gets passed as the only parameter (typically it's a value between 0 and 1, but it can exceed those when using an ease like Elastic.easeOut or Back.easeOut, etc.)
		set: function(ratio) {
			var pt;
			if (ratio !== 1) {
				this._super.setRatio.call(this, ratio);
			} else {
				pt = this._firstPT;
				while (pt) {
					if (pt.f) {
						pt.t[pt.p](this.finals[pt.p]);
					} else {
						pt.t[pt.p] = this.finals[pt.p];
					}
					pt = pt._next;
				}
			}
		}

	})._autoCSS = true;







	
	
	
	
/*
 * ----------------------------------------------------------------
 * EasePack
 * ----------------------------------------------------------------
 */
	_gsScope._gsDefine("easing.Back", ["easing.Ease"], function(Ease) {
		
		var w = (_gsScope.GreenSockGlobals || _gsScope),
			gs = w.com.greensock,
			_2PI = Math.PI * 2,
			_HALF_PI = Math.PI / 2,
			_class = gs._class,
			_create = function(n, f) {
				var C = _class("easing." + n, function(){}, true),
					p = C.prototype = new Ease();
				p.constructor = C;
				p.getRatio = f;
				return C;
			},
			_easeReg = Ease.register || function(){}, //put an empty function in place just as a safety measure in case someone loads an OLD version of TweenLite.js where Ease.register doesn't exist.
			_wrap = function(name, EaseOut, EaseIn, EaseInOut, aliases) {
				var C = _class("easing."+name, {
					easeOut:new EaseOut(),
					easeIn:new EaseIn(),
					easeInOut:new EaseInOut()
				}, true);
				_easeReg(C, name);
				return C;
			},
			EasePoint = function(time, value, next) {
				this.t = time;
				this.v = value;
				if (next) {
					this.next = next;
					next.prev = this;
					this.c = next.v - value;
					this.gap = next.t - time;
				}
			},

			//Back
			_createBack = function(n, f) {
				var C = _class("easing." + n, function(overshoot) {
						this._p1 = (overshoot || overshoot === 0) ? overshoot : 1.70158;
						this._p2 = this._p1 * 1.525;
					}, true),
					p = C.prototype = new Ease();
				p.constructor = C;
				p.getRatio = f;
				p.config = function(overshoot) {
					return new C(overshoot);
				};
				return C;
			},

			Back = _wrap("Back",
				_createBack("BackOut", function(p) {
					return ((p = p - 1) * p * ((this._p1 + 1) * p + this._p1) + 1);
				}),
				_createBack("BackIn", function(p) {
					return p * p * ((this._p1 + 1) * p - this._p1);
				}),
				_createBack("BackInOut", function(p) {
					return ((p *= 2) < 1) ? 0.5 * p * p * ((this._p2 + 1) * p - this._p2) : 0.5 * ((p -= 2) * p * ((this._p2 + 1) * p + this._p2) + 2);
				})
			),


			//SlowMo
			SlowMo = _class("easing.SlowMo", function(linearRatio, power, yoyoMode) {
				power = (power || power === 0) ? power : 0.7;
				if (linearRatio == null) {
					linearRatio = 0.7;
				} else if (linearRatio > 1) {
					linearRatio = 1;
				}
				this._p = (linearRatio !== 1) ? power : 0;
				this._p1 = (1 - linearRatio) / 2;
				this._p2 = linearRatio;
				this._p3 = this._p1 + this._p2;
				this._calcEnd = (yoyoMode === true);
			}, true),
			p = SlowMo.prototype = new Ease(),
			SteppedEase, RoughEase, _createElastic;

		p.constructor = SlowMo;
		p.getRatio = function(p) {
			var r = p + (0.5 - p) * this._p;
			if (p < this._p1) {
				return this._calcEnd ? 1 - ((p = 1 - (p / this._p1)) * p) : r - ((p = 1 - (p / this._p1)) * p * p * p * r);
			} else if (p > this._p3) {
				return this._calcEnd ? 1 - (p = (p - this._p3) / this._p1) * p : r + ((p - r) * (p = (p - this._p3) / this._p1) * p * p * p);
			}
			return this._calcEnd ? 1 : r;
		};
		SlowMo.ease = new SlowMo(0.7, 0.7);

		p.config = SlowMo.config = function(linearRatio, power, yoyoMode) {
			return new SlowMo(linearRatio, power, yoyoMode);
		};


		//SteppedEase
		SteppedEase = _class("easing.SteppedEase", function(steps) {
				steps = steps || 1;
				this._p1 = 1 / steps;
				this._p2 = steps + 1;
			}, true);
		p = SteppedEase.prototype = new Ease();
		p.constructor = SteppedEase;
		p.getRatio = function(p) {
			if (p < 0) {
				p = 0;
			} else if (p >= 1) {
				p = 0.999999999;
			}
			return ((this._p2 * p) >> 0) * this._p1;
		};
		p.config = SteppedEase.config = function(steps) {
			return new SteppedEase(steps);
		};


		//RoughEase
		RoughEase = _class("easing.RoughEase", function(vars) {
			vars = vars || {};
			var taper = vars.taper || "none",
				a = [],
				cnt = 0,
				points = (vars.points || 20) | 0,
				i = points,
				randomize = (vars.randomize !== false),
				clamp = (vars.clamp === true),
				template = (vars.template instanceof Ease) ? vars.template : null,
				strength = (typeof(vars.strength) === "number") ? vars.strength * 0.4 : 0.4,
				x, y, bump, invX, obj, pnt;
			while (--i > -1) {
				x = randomize ? Math.random() : (1 / points) * i;
				y = template ? template.getRatio(x) : x;
				if (taper === "none") {
					bump = strength;
				} else if (taper === "out") {
					invX = 1 - x;
					bump = invX * invX * strength;
				} else if (taper === "in") {
					bump = x * x * strength;
				} else if (x < 0.5) {  //"both" (start)
					invX = x * 2;
					bump = invX * invX * 0.5 * strength;
				} else {				//"both" (end)
					invX = (1 - x) * 2;
					bump = invX * invX * 0.5 * strength;
				}
				if (randomize) {
					y += (Math.random() * bump) - (bump * 0.5);
				} else if (i % 2) {
					y += bump * 0.5;
				} else {
					y -= bump * 0.5;
				}
				if (clamp) {
					if (y > 1) {
						y = 1;
					} else if (y < 0) {
						y = 0;
					}
				}
				a[cnt++] = {x:x, y:y};
			}
			a.sort(function(a, b) {
				return a.x - b.x;
			});

			pnt = new EasePoint(1, 1, null);
			i = points;
			while (--i > -1) {
				obj = a[i];
				pnt = new EasePoint(obj.x, obj.y, pnt);
			}

			this._prev = new EasePoint(0, 0, (pnt.t !== 0) ? pnt : pnt.next);
		}, true);
		p = RoughEase.prototype = new Ease();
		p.constructor = RoughEase;
		p.getRatio = function(p) {
			var pnt = this._prev;
			if (p > pnt.t) {
				while (pnt.next && p >= pnt.t) {
					pnt = pnt.next;
				}
				pnt = pnt.prev;
			} else {
				while (pnt.prev && p <= pnt.t) {
					pnt = pnt.prev;
				}
			}
			this._prev = pnt;
			return (pnt.v + ((p - pnt.t) / pnt.gap) * pnt.c);
		};
		p.config = function(vars) {
			return new RoughEase(vars);
		};
		RoughEase.ease = new RoughEase();


		//Bounce
		_wrap("Bounce",
			_create("BounceOut", function(p) {
				if (p < 1 / 2.75) {
					return 7.5625 * p * p;
				} else if (p < 2 / 2.75) {
					return 7.5625 * (p -= 1.5 / 2.75) * p + 0.75;
				} else if (p < 2.5 / 2.75) {
					return 7.5625 * (p -= 2.25 / 2.75) * p + 0.9375;
				}
				return 7.5625 * (p -= 2.625 / 2.75) * p + 0.984375;
			}),
			_create("BounceIn", function(p) {
				if ((p = 1 - p) < 1 / 2.75) {
					return 1 - (7.5625 * p * p);
				} else if (p < 2 / 2.75) {
					return 1 - (7.5625 * (p -= 1.5 / 2.75) * p + 0.75);
				} else if (p < 2.5 / 2.75) {
					return 1 - (7.5625 * (p -= 2.25 / 2.75) * p + 0.9375);
				}
				return 1 - (7.5625 * (p -= 2.625 / 2.75) * p + 0.984375);
			}),
			_create("BounceInOut", function(p) {
				var invert = (p < 0.5);
				if (invert) {
					p = 1 - (p * 2);
				} else {
					p = (p * 2) - 1;
				}
				if (p < 1 / 2.75) {
					p = 7.5625 * p * p;
				} else if (p < 2 / 2.75) {
					p = 7.5625 * (p -= 1.5 / 2.75) * p + 0.75;
				} else if (p < 2.5 / 2.75) {
					p = 7.5625 * (p -= 2.25 / 2.75) * p + 0.9375;
				} else {
					p = 7.5625 * (p -= 2.625 / 2.75) * p + 0.984375;
				}
				return invert ? (1 - p) * 0.5 : p * 0.5 + 0.5;
			})
		);


		//CIRC
		_wrap("Circ",
			_create("CircOut", function(p) {
				return Math.sqrt(1 - (p = p - 1) * p);
			}),
			_create("CircIn", function(p) {
				return -(Math.sqrt(1 - (p * p)) - 1);
			}),
			_create("CircInOut", function(p) {
				return ((p*=2) < 1) ? -0.5 * (Math.sqrt(1 - p * p) - 1) : 0.5 * (Math.sqrt(1 - (p -= 2) * p) + 1);
			})
		);


		//Elastic
		_createElastic = function(n, f, def) {
			var C = _class("easing." + n, function(amplitude, period) {
					this._p1 = (amplitude >= 1) ? amplitude : 1; //note: if amplitude is < 1, we simply adjust the period for a more natural feel. Otherwise the math doesn't work right and the curve starts at 1.
					this._p2 = (period || def) / (amplitude < 1 ? amplitude : 1);
					this._p3 = this._p2 / _2PI * (Math.asin(1 / this._p1) || 0);
					this._p2 = _2PI / this._p2; //precalculate to optimize
				}, true),
				p = C.prototype = new Ease();
			p.constructor = C;
			p.getRatio = f;
			p.config = function(amplitude, period) {
				return new C(amplitude, period);
			};
			return C;
		};
		_wrap("Elastic",
			_createElastic("ElasticOut", function(p) {
				return this._p1 * Math.pow(2, -10 * p) * Math.sin( (p - this._p3) * this._p2 ) + 1;
			}, 0.3),
			_createElastic("ElasticIn", function(p) {
				return -(this._p1 * Math.pow(2, 10 * (p -= 1)) * Math.sin( (p - this._p3) * this._p2 ));
			}, 0.3),
			_createElastic("ElasticInOut", function(p) {
				return ((p *= 2) < 1) ? -0.5 * (this._p1 * Math.pow(2, 10 * (p -= 1)) * Math.sin( (p - this._p3) * this._p2)) : this._p1 * Math.pow(2, -10 *(p -= 1)) * Math.sin( (p - this._p3) * this._p2 ) * 0.5 + 1;
			}, 0.45)
		);


		//Expo
		_wrap("Expo",
			_create("ExpoOut", function(p) {
				return 1 - Math.pow(2, -10 * p);
			}),
			_create("ExpoIn", function(p) {
				return Math.pow(2, 10 * (p - 1)) - 0.001;
			}),
			_create("ExpoInOut", function(p) {
				return ((p *= 2) < 1) ? 0.5 * Math.pow(2, 10 * (p - 1)) : 0.5 * (2 - Math.pow(2, -10 * (p - 1)));
			})
		);


		//Sine
		_wrap("Sine",
			_create("SineOut", function(p) {
				return Math.sin(p * _HALF_PI);
			}),
			_create("SineIn", function(p) {
				return -Math.cos(p * _HALF_PI) + 1;
			}),
			_create("SineInOut", function(p) {
				return -0.5 * (Math.cos(Math.PI * p) - 1);
			})
		);

		_class("easing.EaseLookup", {
				find:function(s) {
					return Ease.map[s];
				}
			}, true);

		//register the non-standard eases
		_easeReg(w.SlowMo, "SlowMo", "ease,");
		_easeReg(RoughEase, "RoughEase", "ease,");
		_easeReg(SteppedEase, "SteppedEase", "ease,");

		return Back;
		
	}, true);


});

if (_gsScope._gsDefine) { _gsScope._gsQueue.pop()(); } //necessary in case TweenLite was already loaded separately.











/*
 * ----------------------------------------------------------------
 * Base classes like TweenLite, SimpleTimeline, Ease, Ticker, etc.
 * ----------------------------------------------------------------
 */
(function(window, moduleName) {

		"use strict";
		var _exports = {},
			_doc = window.document,
			_globals = window.GreenSockGlobals = window.GreenSockGlobals || window;
		if (_globals.TweenLite) {
			return; //in case the core set of classes is already loaded, don't instantiate twice.
		}
		var _namespace = function(ns) {
				var a = ns.split("."),
					p = _globals, i;
				for (i = 0; i < a.length; i++) {
					p[a[i]] = p = p[a[i]] || {};
				}
				return p;
			},
			gs = _namespace("com.greensock"),
			_tinyNum = 0.0000000001,
			_slice = function(a) { //don't use Array.prototype.slice.call(target, 0) because that doesn't work in IE8 with a NodeList that's returned by querySelectorAll()
				var b = [],
					l = a.length,
					i;
				for (i = 0; i !== l; b.push(a[i++])) {}
				return b;
			},
			_emptyFunc = function() {},
			_isArray = (function() { //works around issues in iframe environments where the Array global isn't shared, thus if the object originates in a different window/iframe, "(obj instanceof Array)" will evaluate false. We added some speed optimizations to avoid Object.prototype.toString.call() unless it's absolutely necessary because it's VERY slow (like 20x slower)
				var toString = Object.prototype.toString,
					array = toString.call([]);
				return function(obj) {
					return obj != null && (obj instanceof Array || (typeof(obj) === "object" && !!obj.push && toString.call(obj) === array));
				};
			}()),
			a, i, p, _ticker, _tickerActive,
			_defLookup = {},

			/**
			 * @constructor
			 * Defines a GreenSock class, optionally with an array of dependencies that must be instantiated first and passed into the definition.
			 * This allows users to load GreenSock JS files in any order even if they have interdependencies (like CSSPlugin extends TweenPlugin which is
			 * inside TweenLite.js, but if CSSPlugin is loaded first, it should wait to run its code until TweenLite.js loads and instantiates TweenPlugin
			 * and then pass TweenPlugin to CSSPlugin's definition). This is all done automatically and internally.
			 *
			 * Every definition will be added to a "com.greensock" global object (typically window, but if a window.GreenSockGlobals object is found,
			 * it will go there as of v1.7). For example, TweenLite will be found at window.com.greensock.TweenLite and since it's a global class that should be available anywhere,
			 * it is ALSO referenced at window.TweenLite. However some classes aren't considered global, like the base com.greensock.core.Animation class, so
			 * those will only be at the package like window.com.greensock.core.Animation. Again, if you define a GreenSockGlobals object on the window, everything
			 * gets tucked neatly inside there instead of on the window directly. This allows you to do advanced things like load multiple versions of GreenSock
			 * files and put them into distinct objects (imagine a banner ad uses a newer version but the main site uses an older one). In that case, you could
			 * sandbox the banner one like:
			 *
			 * <script>
			 *     var gs = window.GreenSockGlobals = {}; //the newer version we're about to load could now be referenced in a "gs" object, like gs.TweenLite.to(...). Use whatever alias you want as long as it's unique, "gs" or "banner" or whatever.
			 * </script>
			 * <script src="js/greensock/v1.7/TweenMax.js"></script>
			 * <script>
			 *     window.GreenSockGlobals = window._gsQueue = window._gsDefine = null; //reset it back to null (along with the special _gsQueue variable) so that the next load of TweenMax affects the window and we can reference things directly like TweenLite.to(...)
			 * </script>
			 * <script src="js/greensock/v1.6/TweenMax.js"></script>
			 * <script>
			 *     gs.TweenLite.to(...); //would use v1.7
			 *     TweenLite.to(...); //would use v1.6
			 * </script>
			 *
			 * @param {!string} ns The namespace of the class definition, leaving off "com.greensock." as that's assumed. For example, "TweenLite" or "plugins.CSSPlugin" or "easing.Back".
			 * @param {!Array.<string>} dependencies An array of dependencies (described as their namespaces minus "com.greensock." prefix). For example ["TweenLite","plugins.TweenPlugin","core.Animation"]
			 * @param {!function():Object} func The function that should be called and passed the resolved dependencies which will return the actual class for this definition.
			 * @param {boolean=} global If true, the class will be added to the global scope (typically window unless you define a window.GreenSockGlobals object)
			 */
			Definition = function(ns, dependencies, func, global) {
				this.sc = (_defLookup[ns]) ? _defLookup[ns].sc : []; //subclasses
				_defLookup[ns] = this;
				this.gsClass = null;
				this.func = func;
				var _classes = [];
				this.check = function(init) {
					var i = dependencies.length,
						missing = i,
						cur, a, n, cl, hasModule;
					while (--i > -1) {
						if ((cur = _defLookup[dependencies[i]] || new Definition(dependencies[i], [])).gsClass) {
							_classes[i] = cur.gsClass;
							missing--;
						} else if (init) {
							cur.sc.push(this);
						}
					}
					if (missing === 0 && func) {
						a = ("com.greensock." + ns).split(".");
						n = a.pop();
						cl = _namespace(a.join("."))[n] = this.gsClass = func.apply(func, _classes);

						//exports to multiple environments
						if (global) {
							_globals[n] = _exports[n] = cl; //provides a way to avoid global namespace pollution. By default, the main classes like TweenLite, Power1, Strong, etc. are added to window unless a GreenSockGlobals is defined. So if you want to have things added to a custom object instead, just do something like window.GreenSockGlobals = {} before loading any GreenSock files. You can even set up an alias like window.GreenSockGlobals = windows.gs = {} so that you can access everything like gs.TweenLite. Also remember that ALL classes are added to the window.com.greensock object (in their respective packages, like com.greensock.easing.Power1, com.greensock.TweenLite, etc.)
							hasModule = (typeof(module) !== "undefined" && module.exports);
							if (!hasModule && typeof(define) === "function" && define.amd){ //AMD
								define((window.GreenSockAMDPath ? window.GreenSockAMDPath + "/" : "") + ns.split(".").pop(), [], function() { return cl; });
							} else if (hasModule){ //node
								if (ns === moduleName) {
									module.exports = _exports[moduleName] = cl;
									for (i in _exports) {
										cl[i] = _exports[i];
									}
								} else if (_exports[moduleName]) {
									_exports[moduleName][n] = cl;
								}
							}
						}
						for (i = 0; i < this.sc.length; i++) {
							this.sc[i].check();
						}
					}
				};
				this.check(true);
			},

			//used to create Definition instances (which basically registers a class that has dependencies).
			_gsDefine = window._gsDefine = function(ns, dependencies, func, global) {
				return new Definition(ns, dependencies, func, global);
			},

			//a quick way to create a class that doesn't have any dependencies. Returns the class, but first registers it in the GreenSock namespace so that other classes can grab it (other classes might be dependent on the class).
			_class = gs._class = function(ns, func, global) {
				func = func || function() {};
				_gsDefine(ns, [], function(){ return func; }, global);
				return func;
			};

		_gsDefine.globals = _globals;



/*
 * ----------------------------------------------------------------
 * Ease
 * ----------------------------------------------------------------
 */
		var _baseParams = [0, 0, 1, 1],
			_blankArray = [],
			Ease = _class("easing.Ease", function(func, extraParams, type, power) {
				this._func = func;
				this._type = type || 0;
				this._power = power || 0;
				this._params = extraParams ? _baseParams.concat(extraParams) : _baseParams;
			}, true),
			_easeMap = Ease.map = {},
			_easeReg = Ease.register = function(ease, names, types, create) {
				var na = names.split(","),
					i = na.length,
					ta = (types || "easeIn,easeOut,easeInOut").split(","),
					e, name, j, type;
				while (--i > -1) {
					name = na[i];
					e = create ? _class("easing."+name, null, true) : gs.easing[name] || {};
					j = ta.length;
					while (--j > -1) {
						type = ta[j];
						_easeMap[name + "." + type] = _easeMap[type + name] = e[type] = ease.getRatio ? ease : ease[type] || new ease();
					}
				}
			};

		p = Ease.prototype;
		p._calcEnd = false;
		p.getRatio = function(p) {
			if (this._func) {
				this._params[0] = p;
				return this._func.apply(null, this._params);
			}
			var t = this._type,
				pw = this._power,
				r = (t === 1) ? 1 - p : (t === 2) ? p : (p < 0.5) ? p * 2 : (1 - p) * 2;
			if (pw === 1) {
				r *= r;
			} else if (pw === 2) {
				r *= r * r;
			} else if (pw === 3) {
				r *= r * r * r;
			} else if (pw === 4) {
				r *= r * r * r * r;
			}
			return (t === 1) ? 1 - r : (t === 2) ? r : (p < 0.5) ? r / 2 : 1 - (r / 2);
		};

		//create all the standard eases like Linear, Quad, Cubic, Quart, Quint, Strong, Power0, Power1, Power2, Power3, and Power4 (each with easeIn, easeOut, and easeInOut)
		a = ["Linear","Quad","Cubic","Quart","Quint,Strong"];
		i = a.length;
		while (--i > -1) {
			p = a[i]+",Power"+i;
			_easeReg(new Ease(null,null,1,i), p, "easeOut", true);
			_easeReg(new Ease(null,null,2,i), p, "easeIn" + ((i === 0) ? ",easeNone" : ""));
			_easeReg(new Ease(null,null,3,i), p, "easeInOut");
		}
		_easeMap.linear = gs.easing.Linear.easeIn;
		_easeMap.swing = gs.easing.Quad.easeInOut; //for jQuery folks


/*
 * ----------------------------------------------------------------
 * EventDispatcher
 * ----------------------------------------------------------------
 */
		var EventDispatcher = _class("events.EventDispatcher", function(target) {
			this._listeners = {};
			this._eventTarget = target || this;
		});
		p = EventDispatcher.prototype;

		p.addEventListener = function(type, callback, scope, useParam, priority) {
			priority = priority || 0;
			var list = this._listeners[type],
				index = 0,
				listener, i;
			if (this === _ticker && !_tickerActive) {
				_ticker.wake();
			}
			if (list == null) {
				this._listeners[type] = list = [];
			}
			i = list.length;
			while (--i > -1) {
				listener = list[i];
				if (listener.c === callback && listener.s === scope) {
					list.splice(i, 1);
				} else if (index === 0 && listener.pr < priority) {
					index = i + 1;
				}
			}
			list.splice(index, 0, {c:callback, s:scope, up:useParam, pr:priority});
		};

		p.removeEventListener = function(type, callback) {
			var list = this._listeners[type], i;
			if (list) {
				i = list.length;
				while (--i > -1) {
					if (list[i].c === callback) {
						list.splice(i, 1);
						return;
					}
				}
			}
		};

		p.dispatchEvent = function(type) {
			var list = this._listeners[type],
				i, t, listener;
			if (list) {
				i = list.length;
				if (i > 1) {
					list = list.slice(0); //in case addEventListener() is called from within a listener/callback (otherwise the index could change, resulting in a skip)
				}
				t = this._eventTarget;
				while (--i > -1) {
					listener = list[i];
					if (listener) {
						if (listener.up) {
							listener.c.call(listener.s || t, {type:type, target:t});
						} else {
							listener.c.call(listener.s || t);
						}
					}
				}
			}
		};


/*
 * ----------------------------------------------------------------
 * Ticker
 * ----------------------------------------------------------------
 */
 		var _reqAnimFrame = window.requestAnimationFrame,
			_cancelAnimFrame = window.cancelAnimationFrame,
			_getTime = Date.now || function() {return new Date().getTime();},
			_lastUpdate = _getTime();

		//now try to determine the requestAnimationFrame and cancelAnimationFrame functions and if none are found, we'll use a setTimeout()/clearTimeout() polyfill.
		a = ["ms","moz","webkit","o"];
		i = a.length;
		while (--i > -1 && !_reqAnimFrame) {
			_reqAnimFrame = window[a[i] + "RequestAnimationFrame"];
			_cancelAnimFrame = window[a[i] + "CancelAnimationFrame"] || window[a[i] + "CancelRequestAnimationFrame"];
		}

		_class("Ticker", function(fps, useRAF) {
			var _self = this,
				_startTime = _getTime(),
				_useRAF = (useRAF !== false && _reqAnimFrame) ? "auto" : false,
				_lagThreshold = 500,
				_adjustedLag = 33,
				_tickWord = "tick", //helps reduce gc burden
				_fps, _req, _id, _gap, _nextTime,
				_tick = function(manual) {
					var elapsed = _getTime() - _lastUpdate,
						overlap, dispatch;
					if (elapsed > _lagThreshold) {
						_startTime += elapsed - _adjustedLag;
					}
					_lastUpdate += elapsed;
					_self.time = (_lastUpdate - _startTime) / 1000;
					overlap = _self.time - _nextTime;
					if (!_fps || overlap > 0 || manual === true) {
						_self.frame++;
						_nextTime += overlap + (overlap >= _gap ? 0.004 : _gap - overlap);
						dispatch = true;
					}
					if (manual !== true) { //make sure the request is made before we dispatch the "tick" event so that timing is maintained. Otherwise, if processing the "tick" requires a bunch of time (like 15ms) and we're using a setTimeout() that's based on 16.7ms, it'd technically take 31.7ms between frames otherwise.
						_id = _req(_tick);
					}
					if (dispatch) {
						_self.dispatchEvent(_tickWord);
					}
				};

			EventDispatcher.call(_self);
			_self.time = _self.frame = 0;
			_self.tick = function() {
				_tick(true);
			};

			_self.lagSmoothing = function(threshold, adjustedLag) {
				_lagThreshold = threshold || (1 / _tinyNum); //zero should be interpreted as basically unlimited
				_adjustedLag = Math.min(adjustedLag, _lagThreshold, 0);
			};

			_self.sleep = function() {
				if (_id == null) {
					return;
				}
				if (!_useRAF || !_cancelAnimFrame) {
					clearTimeout(_id);
				} else {
					_cancelAnimFrame(_id);
				}
				_req = _emptyFunc;
				_id = null;
				if (_self === _ticker) {
					_tickerActive = false;
				}
			};

			_self.wake = function(seamless) {
				if (_id !== null) {
					_self.sleep();
				} else if (seamless) {
					_startTime += -_lastUpdate + (_lastUpdate = _getTime());
				} else if (_self.frame > 10) { //don't trigger lagSmoothing if we're just waking up, and make sure that at least 10 frames have elapsed because of the iOS bug that we work around below with the 1.5-second setTimout().
					_lastUpdate = _getTime() - _lagThreshold + 5;
				}
				_req = (_fps === 0) ? _emptyFunc : (!_useRAF || !_reqAnimFrame) ? function(f) { return setTimeout(f, ((_nextTime - _self.time) * 1000 + 1) | 0); } : _reqAnimFrame;
				if (_self === _ticker) {
					_tickerActive = true;
				}
				_tick(2);
			};

			_self.fps = function(value) {
				if (!arguments.length) {
					return _fps;
				}
				_fps = value;
				_gap = 1 / (_fps || 60);
				_nextTime = this.time + _gap;
				_self.wake();
			};

			_self.useRAF = function(value) {
				if (!arguments.length) {
					return _useRAF;
				}
				_self.sleep();
				_useRAF = value;
				_self.fps(_fps);
			};
			_self.fps(fps);

			//a bug in iOS 6 Safari occasionally prevents the requestAnimationFrame from working initially, so we use a 1.5-second timeout that automatically falls back to setTimeout() if it senses this condition.
			setTimeout(function() {
				if (_useRAF === "auto" && _self.frame < 5 && _doc.visibilityState !== "hidden") {
					_self.useRAF(false);
				}
			}, 1500);
		});

		p = gs.Ticker.prototype = new gs.events.EventDispatcher();
		p.constructor = gs.Ticker;


/*
 * ----------------------------------------------------------------
 * Animation
 * ----------------------------------------------------------------
 */
		var Animation = _class("core.Animation", function(duration, vars) {
				this.vars = vars = vars || {};
				this._duration = this._totalDuration = duration || 0;
				this._delay = Number(vars.delay) || 0;
				this._timeScale = 1;
				this._active = (vars.immediateRender === true);
				this.data = vars.data;
				this._reversed = (vars.reversed === true);

				if (!_rootTimeline) {
					return;
				}
				if (!_tickerActive) { //some browsers (like iOS 6 Safari) shut down JavaScript execution when the tab is disabled and they [occasionally] neglect to start up requestAnimationFrame again when returning - this code ensures that the engine starts up again properly.
					_ticker.wake();
				}

				var tl = this.vars.useFrames ? _rootFramesTimeline : _rootTimeline;
				tl.add(this, tl._time);

				if (this.vars.paused) {
					this.paused(true);
				}
			});

		_ticker = Animation.ticker = new gs.Ticker();
		p = Animation.prototype;
		p._dirty = p._gc = p._initted = p._paused = false;
		p._totalTime = p._time = 0;
		p._rawPrevTime = -1;
		p._next = p._last = p._onUpdate = p._timeline = p.timeline = null;
		p._paused = false;


		//some browsers (like iOS) occasionally drop the requestAnimationFrame event when the user switches to a different tab and then comes back again, so we use a 2-second setTimeout() to sense if/when that condition occurs and then wake() the ticker.
		var _checkTimeout = function() {
				if (_tickerActive && _getTime() - _lastUpdate > 2000) {
					_ticker.wake();
				}
				setTimeout(_checkTimeout, 2000);
			};
		_checkTimeout();


		p.play = function(from, suppressEvents) {
			if (from != null) {
				this.seek(from, suppressEvents);
			}
			return this.reversed(false).paused(false);
		};

		p.pause = function(atTime, suppressEvents) {
			if (atTime != null) {
				this.seek(atTime, suppressEvents);
			}
			return this.paused(true);
		};

		p.resume = function(from, suppressEvents) {
			if (from != null) {
				this.seek(from, suppressEvents);
			}
			return this.paused(false);
		};

		p.seek = function(time, suppressEvents) {
			return this.totalTime(Number(time), suppressEvents !== false);
		};

		p.restart = function(includeDelay, suppressEvents) {
			return this.reversed(false).paused(false).totalTime(includeDelay ? -this._delay : 0, (suppressEvents !== false), true);
		};

		p.reverse = function(from, suppressEvents) {
			if (from != null) {
				this.seek((from || this.totalDuration()), suppressEvents);
			}
			return this.reversed(true).paused(false);
		};

		p.render = function(time, suppressEvents, force) {
			//stub - we override this method in subclasses.
		};

		p.invalidate = function() {
			this._time = this._totalTime = 0;
			this._initted = this._gc = false;
			this._rawPrevTime = -1;
			if (this._gc || !this.timeline) {
				this._enabled(true);
			}
			return this;
		};

		p.isActive = function() {
			var tl = this._timeline, //the 2 root timelines won't have a _timeline; they're always active.
				startTime = this._startTime,
				rawTime;
			return (!tl || (!this._gc && !this._paused && tl.isActive() && (rawTime = tl.rawTime(true)) >= startTime && rawTime < startTime + this.totalDuration() / this._timeScale));
		};

		p._enabled = function (enabled, ignoreTimeline) {
			if (!_tickerActive) {
				_ticker.wake();
			}
			this._gc = !enabled;
			this._active = this.isActive();
			if (ignoreTimeline !== true) {
				if (enabled && !this.timeline) {
					this._timeline.add(this, this._startTime - this._delay);
				} else if (!enabled && this.timeline) {
					this._timeline._remove(this, true);
				}
			}
			return false;
		};


		p._kill = function(vars, target) {
			return this._enabled(false, false);
		};

		p.kill = function(vars, target) {
			this._kill(vars, target);
			return this;
		};

		p._uncache = function(includeSelf) {
			var tween = includeSelf ? this : this.timeline;
			while (tween) {
				tween._dirty = true;
				tween = tween.timeline;
			}
			return this;
		};

		p._swapSelfInParams = function(params) {
			var i = params.length,
				copy = params.concat();
			while (--i > -1) {
				if (params[i] === "{self}") {
					copy[i] = this;
				}
			}
			return copy;
		};

		p._callback = function(type) {
			var v = this.vars,
				callback = v[type],
				params = v[type + "Params"],
				scope = v[type + "Scope"] || v.callbackScope || this,
				l = params ? params.length : 0;
			switch (l) { //speed optimization; call() is faster than apply() so use it when there are only a few parameters (which is by far most common). Previously we simply did var v = this.vars; v[type].apply(v[type + "Scope"] || v.callbackScope || this, v[type + "Params"] || _blankArray);
				case 0: callback.call(scope); break;
				case 1: callback.call(scope, params[0]); break;
				case 2: callback.call(scope, params[0], params[1]); break;
				default: callback.apply(scope, params);
			}
		};

//----Animation getters/setters --------------------------------------------------------

		p.eventCallback = function(type, callback, params, scope) {
			if ((type || "").substr(0,2) === "on") {
				var v = this.vars;
				if (arguments.length === 1) {
					return v[type];
				}
				if (callback == null) {
					delete v[type];
				} else {
					v[type] = callback;
					v[type + "Params"] = (_isArray(params) && params.join("").indexOf("{self}") !== -1) ? this._swapSelfInParams(params) : params;
					v[type + "Scope"] = scope;
				}
				if (type === "onUpdate") {
					this._onUpdate = callback;
				}
			}
			return this;
		};

		p.delay = function(value) {
			if (!arguments.length) {
				return this._delay;
			}
			if (this._timeline.smoothChildTiming) {
				this.startTime( this._startTime + value - this._delay );
			}
			this._delay = value;
			return this;
		};

		p.duration = function(value) {
			if (!arguments.length) {
				this._dirty = false;
				return this._duration;
			}
			this._duration = this._totalDuration = value;
			this._uncache(true); //true in case it's a TweenMax or TimelineMax that has a repeat - we'll need to refresh the totalDuration.
			if (this._timeline.smoothChildTiming) if (this._time > 0) if (this._time < this._duration) if (value !== 0) {
				this.totalTime(this._totalTime * (value / this._duration), true);
			}
			return this;
		};

		p.totalDuration = function(value) {
			this._dirty = false;
			return (!arguments.length) ? this._totalDuration : this.duration(value);
		};

		p.time = function(value, suppressEvents) {
			if (!arguments.length) {
				return this._time;
			}
			if (this._dirty) {
				this.totalDuration();
			}
			return this.totalTime((value > this._duration) ? this._duration : value, suppressEvents);
		};

		p.totalTime = function(time, suppressEvents, uncapped) {
			if (!_tickerActive) {
				_ticker.wake();
			}
			if (!arguments.length) {
				return this._totalTime;
			}
			if (this._timeline) {
				if (time < 0 && !uncapped) {
					time += this.totalDuration();
				}
				if (this._timeline.smoothChildTiming) {
					if (this._dirty) {
						this.totalDuration();
					}
					var totalDuration = this._totalDuration,
						tl = this._timeline;
					if (time > totalDuration && !uncapped) {
						time = totalDuration;
					}
					this._startTime = (this._paused ? this._pauseTime : tl._time) - ((!this._reversed ? time : totalDuration - time) / this._timeScale);
					if (!tl._dirty) { //for performance improvement. If the parent's cache is already dirty, it already took care of marking the ancestors as dirty too, so skip the function call here.
						this._uncache(false);
					}
					//in case any of the ancestor timelines had completed but should now be enabled, we should reset their totalTime() which will also ensure that they're lined up properly and enabled. Skip for animations that are on the root (wasteful). Example: a TimelineLite.exportRoot() is performed when there's a paused tween on the root, the export will not complete until that tween is unpaused, but imagine a child gets restarted later, after all [unpaused] tweens have completed. The startTime of that child would get pushed out, but one of the ancestors may have completed.
					if (tl._timeline) {
						while (tl._timeline) {
							if (tl._timeline._time !== (tl._startTime + tl._totalTime) / tl._timeScale) {
								tl.totalTime(tl._totalTime, true);
							}
							tl = tl._timeline;
						}
					}
				}
				if (this._gc) {
					this._enabled(true, false);
				}
				if (this._totalTime !== time || this._duration === 0) {
					if (_lazyTweens.length) {
						_lazyRender();
					}
					this.render(time, suppressEvents, false);
					if (_lazyTweens.length) { //in case rendering caused any tweens to lazy-init, we should render them because typically when someone calls seek() or time() or progress(), they expect an immediate render.
						_lazyRender();
					}
				}
			}
			return this;
		};

		p.progress = p.totalProgress = function(value, suppressEvents) {
			var duration = this.duration();
			return (!arguments.length) ? (duration ? this._time / duration : this.ratio) : this.totalTime(duration * value, suppressEvents);
		};

		p.startTime = function(value) {
			if (!arguments.length) {
				return this._startTime;
			}
			if (value !== this._startTime) {
				this._startTime = value;
				if (this.timeline) if (this.timeline._sortChildren) {
					this.timeline.add(this, value - this._delay); //ensures that any necessary re-sequencing of Animations in the timeline occurs to make sure the rendering order is correct.
				}
			}
			return this;
		};

		p.endTime = function(includeRepeats) {
			return this._startTime + ((includeRepeats != false) ? this.totalDuration() : this.duration()) / this._timeScale;
		};

		p.timeScale = function(value) {
			if (!arguments.length) {
				return this._timeScale;
			}
			value = value || _tinyNum; //can't allow zero because it'll throw the math off
			if (this._timeline && this._timeline.smoothChildTiming) {
				var pauseTime = this._pauseTime,
					t = (pauseTime || pauseTime === 0) ? pauseTime : this._timeline.totalTime();
				this._startTime = t - ((t - this._startTime) * this._timeScale / value);
			}
			this._timeScale = value;
			return this._uncache(false);
		};

		p.reversed = function(value) {
			if (!arguments.length) {
				return this._reversed;
			}
			if (value != this._reversed) {
				this._reversed = value;
				this.totalTime(((this._timeline && !this._timeline.smoothChildTiming) ? this.totalDuration() - this._totalTime : this._totalTime), true);
			}
			return this;
		};

		p.paused = function(value) {
			if (!arguments.length) {
				return this._paused;
			}
			var tl = this._timeline,
				raw, elapsed;
			if (value != this._paused) if (tl) {
				if (!_tickerActive && !value) {
					_ticker.wake();
				}
				raw = tl.rawTime();
				elapsed = raw - this._pauseTime;
				if (!value && tl.smoothChildTiming) {
					this._startTime += elapsed;
					this._uncache(false);
				}
				this._pauseTime = value ? raw : null;
				this._paused = value;
				this._active = this.isActive();
				if (!value && elapsed !== 0 && this._initted && this.duration()) {
					raw = tl.smoothChildTiming ? this._totalTime : (raw - this._startTime) / this._timeScale;
					this.render(raw, (raw === this._totalTime), true); //in case the target's properties changed via some other tween or manual update by the user, we should force a render.
				}
			}
			if (this._gc && !value) {
				this._enabled(true, false);
			}
			return this;
		};


/*
 * ----------------------------------------------------------------
 * SimpleTimeline
 * ----------------------------------------------------------------
 */
		var SimpleTimeline = _class("core.SimpleTimeline", function(vars) {
			Animation.call(this, 0, vars);
			this.autoRemoveChildren = this.smoothChildTiming = true;
		});

		p = SimpleTimeline.prototype = new Animation();
		p.constructor = SimpleTimeline;
		p.kill()._gc = false;
		p._first = p._last = p._recent = null;
		p._sortChildren = false;

		p.add = p.insert = function(child, position, align, stagger) {
			var prevTween, st;
			child._startTime = Number(position || 0) + child._delay;
			if (child._paused) if (this !== child._timeline) { //we only adjust the _pauseTime if it wasn't in this timeline already. Remember, sometimes a tween will be inserted again into the same timeline when its startTime is changed so that the tweens in the TimelineLite/Max are re-ordered properly in the linked list (so everything renders in the proper order).
				child._pauseTime = child._startTime + ((this.rawTime() - child._startTime) / child._timeScale);
			}
			if (child.timeline) {
				child.timeline._remove(child, true); //removes from existing timeline so that it can be properly added to this one.
			}
			child.timeline = child._timeline = this;
			if (child._gc) {
				child._enabled(true, true);
			}
			prevTween = this._last;
			if (this._sortChildren) {
				st = child._startTime;
				while (prevTween && prevTween._startTime > st) {
					prevTween = prevTween._prev;
				}
			}
			if (prevTween) {
				child._next = prevTween._next;
				prevTween._next = child;
			} else {
				child._next = this._first;
				this._first = child;
			}
			if (child._next) {
				child._next._prev = child;
			} else {
				this._last = child;
			}
			child._prev = prevTween;
			this._recent = child;
			if (this._timeline) {
				this._uncache(true);
			}
			return this;
		};

		p._remove = function(tween, skipDisable) {
			if (tween.timeline === this) {
				if (!skipDisable) {
					tween._enabled(false, true);
				}

				if (tween._prev) {
					tween._prev._next = tween._next;
				} else if (this._first === tween) {
					this._first = tween._next;
				}
				if (tween._next) {
					tween._next._prev = tween._prev;
				} else if (this._last === tween) {
					this._last = tween._prev;
				}
				tween._next = tween._prev = tween.timeline = null;
				if (tween === this._recent) {
					this._recent = this._last;
				}

				if (this._timeline) {
					this._uncache(true);
				}
			}
			return this;
		};

		p.render = function(time, suppressEvents, force) {
			var tween = this._first,
				next;
			this._totalTime = this._time = this._rawPrevTime = time;
			while (tween) {
				next = tween._next; //record it here because the value could change after rendering...
				if (tween._active || (time >= tween._startTime && !tween._paused)) {
					if (!tween._reversed) {
						tween.render((time - tween._startTime) * tween._timeScale, suppressEvents, force);
					} else {
						tween.render(((!tween._dirty) ? tween._totalDuration : tween.totalDuration()) - ((time - tween._startTime) * tween._timeScale), suppressEvents, force);
					}
				}
				tween = next;
			}
		};

		p.rawTime = function() {
			if (!_tickerActive) {
				_ticker.wake();
			}
			return this._totalTime;
		};

/*
 * ----------------------------------------------------------------
 * TweenLite
 * ----------------------------------------------------------------
 */
		var TweenLite = _class("TweenLite", function(target, duration, vars) {
				Animation.call(this, duration, vars);
				this.render = TweenLite.prototype.render; //speed optimization (avoid prototype lookup on this "hot" method)

				if (target == null) {
					throw "Cannot tween a null target.";
				}

				this.target = target = (typeof(target) !== "string") ? target : TweenLite.selector(target) || target;

				var isSelector = (target.jquery || (target.length && target !== window && target[0] && (target[0] === window || (target[0].nodeType && target[0].style && !target.nodeType)))),
					overwrite = this.vars.overwrite,
					i, targ, targets;

				this._overwrite = overwrite = (overwrite == null) ? _overwriteLookup[TweenLite.defaultOverwrite] : (typeof(overwrite) === "number") ? overwrite >> 0 : _overwriteLookup[overwrite];

				if ((isSelector || target instanceof Array || (target.push && _isArray(target))) && typeof(target[0]) !== "number") {
					this._targets = targets = _slice(target);  //don't use Array.prototype.slice.call(target, 0) because that doesn't work in IE8 with a NodeList that's returned by querySelectorAll()
					this._propLookup = [];
					this._siblings = [];
					for (i = 0; i < targets.length; i++) {
						targ = targets[i];
						if (!targ) {
							targets.splice(i--, 1);
							continue;
						} else if (typeof(targ) === "string") {
							targ = targets[i--] = TweenLite.selector(targ); //in case it's an array of strings
							if (typeof(targ) === "string") {
								targets.splice(i+1, 1); //to avoid an endless loop (can't imagine why the selector would return a string, but just in case)
							}
							continue;
						} else if (targ.length && targ !== window && targ[0] && (targ[0] === window || (targ[0].nodeType && targ[0].style && !targ.nodeType))) { //in case the user is passing in an array of selector objects (like jQuery objects), we need to check one more level and pull things out if necessary. Also note that <select> elements pass all the criteria regarding length and the first child having style, so we must also check to ensure the target isn't an HTML node itself.
							targets.splice(i--, 1);
							this._targets = targets = targets.concat(_slice(targ));
							continue;
						}
						this._siblings[i] = _register(targ, this, false);
						if (overwrite === 1) if (this._siblings[i].length > 1) {
							_applyOverwrite(targ, this, null, 1, this._siblings[i]);
						}
					}

				} else {
					this._propLookup = {};
					this._siblings = _register(target, this, false);
					if (overwrite === 1) if (this._siblings.length > 1) {
						_applyOverwrite(target, this, null, 1, this._siblings);
					}
				}
				if (this.vars.immediateRender || (duration === 0 && this._delay === 0 && this.vars.immediateRender !== false)) {
					this._time = -_tinyNum; //forces a render without having to set the render() "force" parameter to true because we want to allow lazying by default (using the "force" parameter always forces an immediate full render)
					this.render(Math.min(0, -this._delay)); //in case delay is negative
				}
			}, true),
			_isSelector = function(v) {
				return (v && v.length && v !== window && v[0] && (v[0] === window || (v[0].nodeType && v[0].style && !v.nodeType))); //we cannot check "nodeType" if the target is window from within an iframe, otherwise it will trigger a security error in some browsers like Firefox.
			},
			_autoCSS = function(vars, target) {
				var css = {},
					p;
				for (p in vars) {
					if (!_reservedProps[p] && (!(p in target) || p === "transform" || p === "x" || p === "y" || p === "width" || p === "height" || p === "className" || p === "border") && (!_plugins[p] || (_plugins[p] && _plugins[p]._autoCSS))) { //note: <img> elements contain read-only "x" and "y" properties. We should also prioritize editing css width/height rather than the element's properties.
						css[p] = vars[p];
						delete vars[p];
					}
				}
				vars.css = css;
			};

		p = TweenLite.prototype = new Animation();
		p.constructor = TweenLite;
		p.kill()._gc = false;

//----TweenLite defaults, overwrite management, and root updates ----------------------------------------------------

		p.ratio = 0;
		p._firstPT = p._targets = p._overwrittenProps = p._startAt = null;
		p._notifyPluginsOfEnabled = p._lazy = false;

		TweenLite.version = "1.19.1";
		TweenLite.defaultEase = p._ease = new Ease(null, null, 1, 1);
		TweenLite.defaultOverwrite = "auto";
		TweenLite.ticker = _ticker;
		TweenLite.autoSleep = 120;
		TweenLite.lagSmoothing = function(threshold, adjustedLag) {
			_ticker.lagSmoothing(threshold, adjustedLag);
		};

		TweenLite.selector = window.$ || window.jQuery || function(e) {
			var selector = window.$ || window.jQuery;
			if (selector) {
				TweenLite.selector = selector;
				return selector(e);
			}
			return (typeof(_doc) === "undefined") ? e : (_doc.querySelectorAll ? _doc.querySelectorAll(e) : _doc.getElementById((e.charAt(0) === "#") ? e.substr(1) : e));
		};

		var _lazyTweens = [],
			_lazyLookup = {},
			_numbersExp = /(?:(-|-=|\+=)?\d*\.?\d*(?:e[\-+]?\d+)?)[0-9]/ig,
			//_nonNumbersExp = /(?:([\-+](?!(\d|=)))|[^\d\-+=e]|(e(?![\-+][\d])))+/ig,
			_setRatio = function(v) {
				var pt = this._firstPT,
					min = 0.000001,
					val;
				while (pt) {
					val = !pt.blob ? pt.c * v + pt.s : (v === 1) ? this.end : v ? this.join("") : this.start;
					if (pt.m) {
						val = pt.m(val, this._target || pt.t);
					} else if (val < min) if (val > -min && !pt.blob) { //prevents issues with converting very small numbers to strings in the browser
						val = 0;
					}
					if (!pt.f) {
						pt.t[pt.p] = val;
					} else if (pt.fp) {
						pt.t[pt.p](pt.fp, val);
					} else {
						pt.t[pt.p](val);
					}
					pt = pt._next;
				}
			},
			//compares two strings (start/end), finds the numbers that are different and spits back an array representing the whole value but with the changing values isolated as elements. For example, "rgb(0,0,0)" and "rgb(100,50,0)" would become ["rgb(", 0, ",", 50, ",0)"]. Notice it merges the parts that are identical (performance optimization). The array also has a linked list of PropTweens attached starting with _firstPT that contain the tweening data (t, p, s, c, f, etc.). It also stores the starting value as a "start" property so that we can revert to it if/when necessary, like when a tween rewinds fully. If the quantity of numbers differs between the start and end, it will always prioritize the end value(s). The pt parameter is optional - it's for a PropTween that will be appended to the end of the linked list and is typically for actually setting the value after all of the elements have been updated (with array.join("")).
			_blobDif = function(start, end, filter, pt) {
				var a = [],
					charIndex = 0,
					s = "",
					color = 0,
					startNums, endNums, num, i, l, nonNumbers, currentNum;
				a.start = start;
				a.end = end;
				start = a[0] = start + ""; //ensure values are strings
				end = a[1] = end + "";
				if (filter) {
					filter(a); //pass an array with the starting and ending values and let the filter do whatever it needs to the values.
					start = a[0];
					end = a[1];
				}
				a.length = 0;
				startNums = start.match(_numbersExp) || [];
				endNums = end.match(_numbersExp) || [];
				if (pt) {
					pt._next = null;
					pt.blob = 1;
					a._firstPT = a._applyPT = pt; //apply last in the linked list (which means inserting it first)
				}
				l = endNums.length;
				for (i = 0; i < l; i++) {
					currentNum = endNums[i];
					nonNumbers = end.substr(charIndex, end.indexOf(currentNum, charIndex)-charIndex);
					s += (nonNumbers || !i) ? nonNumbers : ","; //note: SVG spec allows omission of comma/space when a negative sign is wedged between two numbers, like 2.5-5.3 instead of 2.5,-5.3 but when tweening, the negative value may switch to positive, so we insert the comma just in case.
					charIndex += nonNumbers.length;
					if (color) { //sense rgba() values and round them.
						color = (color + 1) % 5;
					} else if (nonNumbers.substr(-5) === "rgba(") {
						color = 1;
					}
					if (currentNum === startNums[i] || startNums.length <= i) {
						s += currentNum;
					} else {
						if (s) {
							a.push(s);
							s = "";
						}
						num = parseFloat(startNums[i]);
						a.push(num);
						a._firstPT = {_next: a._firstPT, t:a, p: a.length-1, s:num, c:((currentNum.charAt(1) === "=") ? parseInt(currentNum.charAt(0) + "1", 10) * parseFloat(currentNum.substr(2)) : (parseFloat(currentNum) - num)) || 0, f:0, m:(color && color < 4) ? Math.round : 0};
						//note: we don't set _prev because we'll never need to remove individual PropTweens from this list.
					}
					charIndex += currentNum.length;
				}
				s += end.substr(charIndex);
				if (s) {
					a.push(s);
				}
				a.setRatio = _setRatio;
				return a;
			},
			//note: "funcParam" is only necessary for function-based getters/setters that require an extra parameter like getAttribute("width") and setAttribute("width", value). In this example, funcParam would be "width". Used by AttrPlugin for example.
			_addPropTween = function(target, prop, start, end, overwriteProp, mod, funcParam, stringFilter, index) {
				if (typeof(end) === "function") {
					end = end(index || 0, target);
				}
				var type = typeof(target[prop]),
					getterName = (type !== "function") ? "" : ((prop.indexOf("set") || typeof(target["get" + prop.substr(3)]) !== "function") ? prop : "get" + prop.substr(3)),
					s = (start !== "get") ? start : !getterName ? target[prop] : funcParam ? target[getterName](funcParam) : target[getterName](),
					isRelative = (typeof(end) === "string" && end.charAt(1) === "="),
					pt = {t:target, p:prop, s:s, f:(type === "function"), pg:0, n:overwriteProp || prop, m:(!mod ? 0 : (typeof(mod) === "function") ? mod : Math.round), pr:0, c:isRelative ? parseInt(end.charAt(0) + "1", 10) * parseFloat(end.substr(2)) : (parseFloat(end) - s) || 0},
					blob;

				if (typeof(s) !== "number" || (typeof(end) !== "number" && !isRelative)) {
					if (funcParam || isNaN(s) || (!isRelative && isNaN(end)) || typeof(s) === "boolean" || typeof(end) === "boolean") {
						//a blob (string that has multiple numbers in it)
						pt.fp = funcParam;
						blob = _blobDif(s, (isRelative ? pt.s + pt.c : end), stringFilter || TweenLite.defaultStringFilter, pt);
						pt = {t: blob, p: "setRatio", s: 0, c: 1, f: 2, pg: 0, n: overwriteProp || prop, pr: 0, m: 0}; //"2" indicates it's a Blob property tween. Needed for RoundPropsPlugin for example.
					} else {
						pt.s = parseFloat(s);
						if (!isRelative) {
							pt.c = (parseFloat(end) - pt.s) || 0;
						}
					}
				}
				if (pt.c) { //only add it to the linked list if there's a change.
					if ((pt._next = this._firstPT)) {
						pt._next._prev = pt;
					}
					this._firstPT = pt;
					return pt;
				}
			},
			_internals = TweenLite._internals = {isArray:_isArray, isSelector:_isSelector, lazyTweens:_lazyTweens, blobDif:_blobDif}, //gives us a way to expose certain private values to other GreenSock classes without contaminating tha main TweenLite object.
			_plugins = TweenLite._plugins = {},
			_tweenLookup = _internals.tweenLookup = {},
			_tweenLookupNum = 0,
			_reservedProps = _internals.reservedProps = {ease:1, delay:1, overwrite:1, onComplete:1, onCompleteParams:1, onCompleteScope:1, useFrames:1, runBackwards:1, startAt:1, onUpdate:1, onUpdateParams:1, onUpdateScope:1, onStart:1, onStartParams:1, onStartScope:1, onReverseComplete:1, onReverseCompleteParams:1, onReverseCompleteScope:1, onRepeat:1, onRepeatParams:1, onRepeatScope:1, easeParams:1, yoyo:1, immediateRender:1, repeat:1, repeatDelay:1, data:1, paused:1, reversed:1, autoCSS:1, lazy:1, onOverwrite:1, callbackScope:1, stringFilter:1, id:1},
			_overwriteLookup = {none:0, all:1, auto:2, concurrent:3, allOnStart:4, preexisting:5, "true":1, "false":0},
			_rootFramesTimeline = Animation._rootFramesTimeline = new SimpleTimeline(),
			_rootTimeline = Animation._rootTimeline = new SimpleTimeline(),
			_nextGCFrame = 30,
			_lazyRender = _internals.lazyRender = function() {
				var i = _lazyTweens.length,
					tween;
				_lazyLookup = {};
				while (--i > -1) {
					tween = _lazyTweens[i];
					if (tween && tween._lazy !== false) {
						tween.render(tween._lazy[0], tween._lazy[1], true);
						tween._lazy = false;
					}
				}
				_lazyTweens.length = 0;
			};

		_rootTimeline._startTime = _ticker.time;
		_rootFramesTimeline._startTime = _ticker.frame;
		_rootTimeline._active = _rootFramesTimeline._active = true;
		setTimeout(_lazyRender, 1); //on some mobile devices, there isn't a "tick" before code runs which means any lazy renders wouldn't run before the next official "tick".

		Animation._updateRoot = TweenLite.render = function() {
				var i, a, p;
				if (_lazyTweens.length) { //if code is run outside of the requestAnimationFrame loop, there may be tweens queued AFTER the engine refreshed, so we need to ensure any pending renders occur before we refresh again.
					_lazyRender();
				}
				_rootTimeline.render((_ticker.time - _rootTimeline._startTime) * _rootTimeline._timeScale, false, false);
				_rootFramesTimeline.render((_ticker.frame - _rootFramesTimeline._startTime) * _rootFramesTimeline._timeScale, false, false);
				if (_lazyTweens.length) {
					_lazyRender();
				}
				if (_ticker.frame >= _nextGCFrame) { //dump garbage every 120 frames or whatever the user sets TweenLite.autoSleep to
					_nextGCFrame = _ticker.frame + (parseInt(TweenLite.autoSleep, 10) || 120);
					for (p in _tweenLookup) {
						a = _tweenLookup[p].tweens;
						i = a.length;
						while (--i > -1) {
							if (a[i]._gc) {
								a.splice(i, 1);
							}
						}
						if (a.length === 0) {
							delete _tweenLookup[p];
						}
					}
					//if there are no more tweens in the root timelines, or if they're all paused, make the _timer sleep to reduce load on the CPU slightly
					p = _rootTimeline._first;
					if (!p || p._paused) if (TweenLite.autoSleep && !_rootFramesTimeline._first && _ticker._listeners.tick.length === 1) {
						while (p && p._paused) {
							p = p._next;
						}
						if (!p) {
							_ticker.sleep();
						}
					}
				}
			};

		_ticker.addEventListener("tick", Animation._updateRoot);

		var _register = function(target, tween, scrub) {
				var id = target._gsTweenID, a, i;
				if (!_tweenLookup[id || (target._gsTweenID = id = "t" + (_tweenLookupNum++))]) {
					_tweenLookup[id] = {target:target, tweens:[]};
				}
				if (tween) {
					a = _tweenLookup[id].tweens;
					a[(i = a.length)] = tween;
					if (scrub) {
						while (--i > -1) {
							if (a[i] === tween) {
								a.splice(i, 1);
							}
						}
					}
				}
				return _tweenLookup[id].tweens;
			},
			_onOverwrite = function(overwrittenTween, overwritingTween, target, killedProps) {
				var func = overwrittenTween.vars.onOverwrite, r1, r2;
				if (func) {
					r1 = func(overwrittenTween, overwritingTween, target, killedProps);
				}
				func = TweenLite.onOverwrite;
				if (func) {
					r2 = func(overwrittenTween, overwritingTween, target, killedProps);
				}
				return (r1 !== false && r2 !== false);
			},
			_applyOverwrite = function(target, tween, props, mode, siblings) {
				var i, changed, curTween, l;
				if (mode === 1 || mode >= 4) {
					l = siblings.length;
					for (i = 0; i < l; i++) {
						if ((curTween = siblings[i]) !== tween) {
							if (!curTween._gc) {
								if (curTween._kill(null, target, tween)) {
									changed = true;
								}
							}
						} else if (mode === 5) {
							break;
						}
					}
					return changed;
				}
				//NOTE: Add 0.0000000001 to overcome floating point errors that can cause the startTime to be VERY slightly off (when a tween's time() is set for example)
				var startTime = tween._startTime + _tinyNum,
					overlaps = [],
					oCount = 0,
					zeroDur = (tween._duration === 0),
					globalStart;
				i = siblings.length;
				while (--i > -1) {
					if ((curTween = siblings[i]) === tween || curTween._gc || curTween._paused) {
						//ignore
					} else if (curTween._timeline !== tween._timeline) {
						globalStart = globalStart || _checkOverlap(tween, 0, zeroDur);
						if (_checkOverlap(curTween, globalStart, zeroDur) === 0) {
							overlaps[oCount++] = curTween;
						}
					} else if (curTween._startTime <= startTime) if (curTween._startTime + curTween.totalDuration() / curTween._timeScale > startTime) if (!((zeroDur || !curTween._initted) && startTime - curTween._startTime <= 0.0000000002)) {
						overlaps[oCount++] = curTween;
					}
				}

				i = oCount;
				while (--i > -1) {
					curTween = overlaps[i];
					if (mode === 2) if (curTween._kill(props, target, tween)) {
						changed = true;
					}
					if (mode !== 2 || (!curTween._firstPT && curTween._initted)) {
						if (mode !== 2 && !_onOverwrite(curTween, tween)) {
							continue;
						}
						if (curTween._enabled(false, false)) { //if all property tweens have been overwritten, kill the tween.
							changed = true;
						}
					}
				}
				return changed;
			},
			_checkOverlap = function(tween, reference, zeroDur) {
				var tl = tween._timeline,
					ts = tl._timeScale,
					t = tween._startTime;
				while (tl._timeline) {
					t += tl._startTime;
					ts *= tl._timeScale;
					if (tl._paused) {
						return -100;
					}
					tl = tl._timeline;
				}
				t /= ts;
				return (t > reference) ? t - reference : ((zeroDur && t === reference) || (!tween._initted && t - reference < 2 * _tinyNum)) ? _tinyNum : ((t += tween.totalDuration() / tween._timeScale / ts) > reference + _tinyNum) ? 0 : t - reference - _tinyNum;
			};


//---- TweenLite instance methods -----------------------------------------------------------------------------

		p._init = function() {
			var v = this.vars,
				op = this._overwrittenProps,
				dur = this._duration,
				immediate = !!v.immediateRender,
				ease = v.ease,
				i, initPlugins, pt, p, startVars, l;
			if (v.startAt) {
				if (this._startAt) {
					this._startAt.render(-1, true); //if we've run a startAt previously (when the tween instantiated), we should revert it so that the values re-instantiate correctly particularly for relative tweens. Without this, a TweenLite.fromTo(obj, 1, {x:"+=100"}, {x:"-=100"}), for example, would actually jump to +=200 because the startAt would run twice, doubling the relative change.
					this._startAt.kill();
				}
				startVars = {};
				for (p in v.startAt) { //copy the properties/values into a new object to avoid collisions, like var to = {x:0}, from = {x:500}; timeline.fromTo(e, 1, from, to).fromTo(e, 1, to, from);
					startVars[p] = v.startAt[p];
				}
				startVars.overwrite = false;
				startVars.immediateRender = true;
				startVars.lazy = (immediate && v.lazy !== false);
				startVars.startAt = startVars.delay = null; //no nesting of startAt objects allowed (otherwise it could cause an infinite loop).
				this._startAt = TweenLite.to(this.target, 0, startVars);
				if (immediate) {
					if (this._time > 0) {
						this._startAt = null; //tweens that render immediately (like most from() and fromTo() tweens) shouldn't revert when their parent timeline's playhead goes backward past the startTime because the initial render could have happened anytime and it shouldn't be directly correlated to this tween's startTime. Imagine setting up a complex animation where the beginning states of various objects are rendered immediately but the tween doesn't happen for quite some time - if we revert to the starting values as soon as the playhead goes backward past the tween's startTime, it will throw things off visually. Reversion should only happen in TimelineLite/Max instances where immediateRender was false (which is the default in the convenience methods like from()).
					} else if (dur !== 0) {
						return; //we skip initialization here so that overwriting doesn't occur until the tween actually begins. Otherwise, if you create several immediateRender:true tweens of the same target/properties to drop into a TimelineLite or TimelineMax, the last one created would overwrite the first ones because they didn't get placed into the timeline yet before the first render occurs and kicks in overwriting.
					}
				}
			} else if (v.runBackwards && dur !== 0) {
				//from() tweens must be handled uniquely: their beginning values must be rendered but we don't want overwriting to occur yet (when time is still 0). Wait until the tween actually begins before doing all the routines like overwriting. At that time, we should render at the END of the tween to ensure that things initialize correctly (remember, from() tweens go backwards)
				if (this._startAt) {
					this._startAt.render(-1, true);
					this._startAt.kill();
					this._startAt = null;
				} else {
					if (this._time !== 0) { //in rare cases (like if a from() tween runs and then is invalidate()-ed), immediateRender could be true but the initial forced-render gets skipped, so there's no need to force the render in this context when the _time is greater than 0
						immediate = false;
					}
					pt = {};
					for (p in v) { //copy props into a new object and skip any reserved props, otherwise onComplete or onUpdate or onStart could fire. We should, however, permit autoCSS to go through.
						if (!_reservedProps[p] || p === "autoCSS") {
							pt[p] = v[p];
						}
					}
					pt.overwrite = 0;
					pt.data = "isFromStart"; //we tag the tween with as "isFromStart" so that if [inside a plugin] we need to only do something at the very END of a tween, we have a way of identifying this tween as merely the one that's setting the beginning values for a "from()" tween. For example, clearProps in CSSPlugin should only get applied at the very END of a tween and without this tag, from(...{height:100, clearProps:"height", delay:1}) would wipe the height at the beginning of the tween and after 1 second, it'd kick back in.
					pt.lazy = (immediate && v.lazy !== false);
					pt.immediateRender = immediate; //zero-duration tweens render immediately by default, but if we're not specifically instructed to render this tween immediately, we should skip this and merely _init() to record the starting values (rendering them immediately would push them to completion which is wasteful in that case - we'd have to render(-1) immediately after)
					this._startAt = TweenLite.to(this.target, 0, pt);
					if (!immediate) {
						this._startAt._init(); //ensures that the initial values are recorded
						this._startAt._enabled(false); //no need to have the tween render on the next cycle. Disable it because we'll always manually control the renders of the _startAt tween.
						if (this.vars.immediateRender) {
							this._startAt = null;
						}
					} else if (this._time === 0) {
						return;
					}
				}
			}
			this._ease = ease = (!ease) ? TweenLite.defaultEase : (ease instanceof Ease) ? ease : (typeof(ease) === "function") ? new Ease(ease, v.easeParams) : _easeMap[ease] || TweenLite.defaultEase;
			if (v.easeParams instanceof Array && ease.config) {
				this._ease = ease.config.apply(ease, v.easeParams);
			}
			this._easeType = this._ease._type;
			this._easePower = this._ease._power;
			this._firstPT = null;

			if (this._targets) {
				l = this._targets.length;
				for (i = 0; i < l; i++) {
					if ( this._initProps( this._targets[i], (this._propLookup[i] = {}), this._siblings[i], (op ? op[i] : null), i) ) {
						initPlugins = true;
					}
				}
			} else {
				initPlugins = this._initProps(this.target, this._propLookup, this._siblings, op, 0);
			}

			if (initPlugins) {
				TweenLite._onPluginEvent("_onInitAllProps", this); //reorders the array in order of priority. Uses a static TweenPlugin method in order to minimize file size in TweenLite
			}
			if (op) if (!this._firstPT) if (typeof(this.target) !== "function") { //if all tweening properties have been overwritten, kill the tween. If the target is a function, it's probably a delayedCall so let it live.
				this._enabled(false, false);
			}
			if (v.runBackwards) {
				pt = this._firstPT;
				while (pt) {
					pt.s += pt.c;
					pt.c = -pt.c;
					pt = pt._next;
				}
			}
			this._onUpdate = v.onUpdate;
			this._initted = true;
		};

		p._initProps = function(target, propLookup, siblings, overwrittenProps, index) {
			var p, i, initPlugins, plugin, pt, v;
			if (target == null) {
				return false;
			}

			if (_lazyLookup[target._gsTweenID]) {
				_lazyRender(); //if other tweens of the same target have recently initted but haven't rendered yet, we've got to force the render so that the starting values are correct (imagine populating a timeline with a bunch of sequential tweens and then jumping to the end)
			}

			if (!this.vars.css) if (target.style) if (target !== window && target.nodeType) if (_plugins.css) if (this.vars.autoCSS !== false) { //it's so common to use TweenLite/Max to animate the css of DOM elements, we assume that if the target is a DOM element, that's what is intended (a convenience so that users don't have to wrap things in css:{}, although we still recommend it for a slight performance boost and better specificity). Note: we cannot check "nodeType" on the window inside an iframe.
				_autoCSS(this.vars, target);
			}
			for (p in this.vars) {
				v = this.vars[p];
				if (_reservedProps[p]) {
					if (v) if ((v instanceof Array) || (v.push && _isArray(v))) if (v.join("").indexOf("{self}") !== -1) {
						this.vars[p] = v = this._swapSelfInParams(v, this);
					}

				} else if (_plugins[p] && (plugin = new _plugins[p]())._onInitTween(target, this.vars[p], this, index)) {

					//t - target 		[object]
					//p - property 		[string]
					//s - start			[number]
					//c - change		[number]
					//f - isFunction	[boolean]
					//n - name			[string]
					//pg - isPlugin 	[boolean]
					//pr - priority		[number]
					//m - mod           [function | 0]
					this._firstPT = pt = {_next:this._firstPT, t:plugin, p:"setRatio", s:0, c:1, f:1, n:p, pg:1, pr:plugin._priority, m:0};
					i = plugin._overwriteProps.length;
					while (--i > -1) {
						propLookup[plugin._overwriteProps[i]] = this._firstPT;
					}
					if (plugin._priority || plugin._onInitAllProps) {
						initPlugins = true;
					}
					if (plugin._onDisable || plugin._onEnable) {
						this._notifyPluginsOfEnabled = true;
					}
					if (pt._next) {
						pt._next._prev = pt;
					}

				} else {
					propLookup[p] = _addPropTween.call(this, target, p, "get", v, p, 0, null, this.vars.stringFilter, index);
				}
			}

			if (overwrittenProps) if (this._kill(overwrittenProps, target)) { //another tween may have tried to overwrite properties of this tween before init() was called (like if two tweens start at the same time, the one created second will run first)
				return this._initProps(target, propLookup, siblings, overwrittenProps, index);
			}
			if (this._overwrite > 1) if (this._firstPT) if (siblings.length > 1) if (_applyOverwrite(target, this, propLookup, this._overwrite, siblings)) {
				this._kill(propLookup, target);
				return this._initProps(target, propLookup, siblings, overwrittenProps, index);
			}
			if (this._firstPT) if ((this.vars.lazy !== false && this._duration) || (this.vars.lazy && !this._duration)) { //zero duration tweens don't lazy render by default; everything else does.
				_lazyLookup[target._gsTweenID] = true;
			}
			return initPlugins;
		};

		p.render = function(time, suppressEvents, force) {
			var prevTime = this._time,
				duration = this._duration,
				prevRawPrevTime = this._rawPrevTime,
				isComplete, callback, pt, rawPrevTime;
			if (time >= duration - 0.0000001 && time >= 0) { //to work around occasional floating point math artifacts.
				this._totalTime = this._time = duration;
				this.ratio = this._ease._calcEnd ? this._ease.getRatio(1) : 1;
				if (!this._reversed ) {
					isComplete = true;
					callback = "onComplete";
					force = (force || this._timeline.autoRemoveChildren); //otherwise, if the animation is unpaused/activated after it's already finished, it doesn't get removed from the parent timeline.
				}
				if (duration === 0) if (this._initted || !this.vars.lazy || force) { //zero-duration tweens are tricky because we must discern the momentum/direction of time in order to determine whether the starting values should be rendered or the ending values. If the "playhead" of its timeline goes past the zero-duration tween in the forward direction or lands directly on it, the end values should be rendered, but if the timeline's "playhead" moves past it in the backward direction (from a postitive time to a negative time), the starting values must be rendered.
					if (this._startTime === this._timeline._duration) { //if a zero-duration tween is at the VERY end of a timeline and that timeline renders at its end, it will typically add a tiny bit of cushion to the render time to prevent rounding errors from getting in the way of tweens rendering their VERY end. If we then reverse() that timeline, the zero-duration tween will trigger its onReverseComplete even though technically the playhead didn't pass over it again. It's a very specific edge case we must accommodate.
						time = 0;
					}
					if (prevRawPrevTime < 0 || (time <= 0 && time >= -0.0000001) || (prevRawPrevTime === _tinyNum && this.data !== "isPause")) if (prevRawPrevTime !== time) { //note: when this.data is "isPause", it's a callback added by addPause() on a timeline that we should not be triggered when LEAVING its exact start time. In other words, tl.addPause(1).play(1) shouldn't pause.
						force = true;
						if (prevRawPrevTime > _tinyNum) {
							callback = "onReverseComplete";
						}
					}
					this._rawPrevTime = rawPrevTime = (!suppressEvents || time || prevRawPrevTime === time) ? time : _tinyNum; //when the playhead arrives at EXACTLY time 0 (right on top) of a zero-duration tween, we need to discern if events are suppressed so that when the playhead moves again (next time), it'll trigger the callback. If events are NOT suppressed, obviously the callback would be triggered in this render. Basically, the callback should fire either when the playhead ARRIVES or LEAVES this exact spot, not both. Imagine doing a timeline.seek(0) and there's a callback that sits at 0. Since events are suppressed on that seek() by default, nothing will fire, but when the playhead moves off of that position, the callback should fire. This behavior is what people intuitively expect. We set the _rawPrevTime to be a precise tiny number to indicate this scenario rather than using another property/variable which would increase memory usage. This technique is less readable, but more efficient.
				}

			} else if (time < 0.0000001) { //to work around occasional floating point math artifacts, round super small values to 0.
				this._totalTime = this._time = 0;
				this.ratio = this._ease._calcEnd ? this._ease.getRatio(0) : 0;
				if (prevTime !== 0 || (duration === 0 && prevRawPrevTime > 0)) {
					callback = "onReverseComplete";
					isComplete = this._reversed;
				}
				if (time < 0) {
					this._active = false;
					if (duration === 0) if (this._initted || !this.vars.lazy || force) { //zero-duration tweens are tricky because we must discern the momentum/direction of time in order to determine whether the starting values should be rendered or the ending values. If the "playhead" of its timeline goes past the zero-duration tween in the forward direction or lands directly on it, the end values should be rendered, but if the timeline's "playhead" moves past it in the backward direction (from a postitive time to a negative time), the starting values must be rendered.
						if (prevRawPrevTime >= 0 && !(prevRawPrevTime === _tinyNum && this.data === "isPause")) {
							force = true;
						}
						this._rawPrevTime = rawPrevTime = (!suppressEvents || time || prevRawPrevTime === time) ? time : _tinyNum; //when the playhead arrives at EXACTLY time 0 (right on top) of a zero-duration tween, we need to discern if events are suppressed so that when the playhead moves again (next time), it'll trigger the callback. If events are NOT suppressed, obviously the callback would be triggered in this render. Basically, the callback should fire either when the playhead ARRIVES or LEAVES this exact spot, not both. Imagine doing a timeline.seek(0) and there's a callback that sits at 0. Since events are suppressed on that seek() by default, nothing will fire, but when the playhead moves off of that position, the callback should fire. This behavior is what people intuitively expect. We set the _rawPrevTime to be a precise tiny number to indicate this scenario rather than using another property/variable which would increase memory usage. This technique is less readable, but more efficient.
					}
				}
				if (!this._initted) { //if we render the very beginning (time == 0) of a fromTo(), we must force the render (normal tweens wouldn't need to render at a time of 0 when the prevTime was also 0). This is also mandatory to make sure overwriting kicks in immediately.
					force = true;
				}
			} else {
				this._totalTime = this._time = time;

				if (this._easeType) {
					var r = time / duration, type = this._easeType, pow = this._easePower;
					if (type === 1 || (type === 3 && r >= 0.5)) {
						r = 1 - r;
					}
					if (type === 3) {
						r *= 2;
					}
					if (pow === 1) {
						r *= r;
					} else if (pow === 2) {
						r *= r * r;
					} else if (pow === 3) {
						r *= r * r * r;
					} else if (pow === 4) {
						r *= r * r * r * r;
					}

					if (type === 1) {
						this.ratio = 1 - r;
					} else if (type === 2) {
						this.ratio = r;
					} else if (time / duration < 0.5) {
						this.ratio = r / 2;
					} else {
						this.ratio = 1 - (r / 2);
					}

				} else {
					this.ratio = this._ease.getRatio(time / duration);
				}
			}

			if (this._time === prevTime && !force) {
				return;
			} else if (!this._initted) {
				this._init();
				if (!this._initted || this._gc) { //immediateRender tweens typically won't initialize until the playhead advances (_time is greater than 0) in order to ensure that overwriting occurs properly. Also, if all of the tweening properties have been overwritten (which would cause _gc to be true, as set in _init()), we shouldn't continue otherwise an onStart callback could be called for example.
					return;
				} else if (!force && this._firstPT && ((this.vars.lazy !== false && this._duration) || (this.vars.lazy && !this._duration))) {
					this._time = this._totalTime = prevTime;
					this._rawPrevTime = prevRawPrevTime;
					_lazyTweens.push(this);
					this._lazy = [time, suppressEvents];
					return;
				}
				//_ease is initially set to defaultEase, so now that init() has run, _ease is set properly and we need to recalculate the ratio. Overall this is faster than using conditional logic earlier in the method to avoid having to set ratio twice because we only init() once but renderTime() gets called VERY frequently.
				if (this._time && !isComplete) {
					this.ratio = this._ease.getRatio(this._time / duration);
				} else if (isComplete && this._ease._calcEnd) {
					this.ratio = this._ease.getRatio((this._time === 0) ? 0 : 1);
				}
			}
			if (this._lazy !== false) { //in case a lazy render is pending, we should flush it because the new render is occurring now (imagine a lazy tween instantiating and then immediately the user calls tween.seek(tween.duration()), skipping to the end - the end render would be forced, and then if we didn't flush the lazy render, it'd fire AFTER the seek(), rendering it at the wrong time.
				this._lazy = false;
			}
			if (!this._active) if (!this._paused && this._time !== prevTime && time >= 0) {
				this._active = true;  //so that if the user renders a tween (as opposed to the timeline rendering it), the timeline is forced to re-render and align it with the proper time/frame on the next rendering cycle. Maybe the tween already finished but the user manually re-renders it as halfway done.
			}
			if (prevTime === 0) {
				if (this._startAt) {
					if (time >= 0) {
						this._startAt.render(time, suppressEvents, force);
					} else if (!callback) {
						callback = "_dummyGS"; //if no callback is defined, use a dummy value just so that the condition at the end evaluates as true because _startAt should render AFTER the normal render loop when the time is negative. We could handle this in a more intuitive way, of course, but the render loop is the MOST important thing to optimize, so this technique allows us to avoid adding extra conditional logic in a high-frequency area.
					}
				}
				if (this.vars.onStart) if (this._time !== 0 || duration === 0) if (!suppressEvents) {
					this._callback("onStart");
				}
			}
			pt = this._firstPT;
			while (pt) {
				if (pt.f) {
					pt.t[pt.p](pt.c * this.ratio + pt.s);
				} else {
					pt.t[pt.p] = pt.c * this.ratio + pt.s;
				}
				pt = pt._next;
			}

			if (this._onUpdate) {
				if (time < 0) if (this._startAt && time !== -0.0001) { //if the tween is positioned at the VERY beginning (_startTime 0) of its parent timeline, it's illegal for the playhead to go back further, so we should not render the recorded startAt values.
					this._startAt.render(time, suppressEvents, force); //note: for performance reasons, we tuck this conditional logic inside less traveled areas (most tweens don't have an onUpdate). We'd just have it at the end before the onComplete, but the values should be updated before any onUpdate is called, so we ALSO put it here and then if it's not called, we do so later near the onComplete.
				}
				if (!suppressEvents) if (this._time !== prevTime || isComplete || force) {
					this._callback("onUpdate");
				}
			}
			if (callback) if (!this._gc || force) { //check _gc because there's a chance that kill() could be called in an onUpdate
				if (time < 0 && this._startAt && !this._onUpdate && time !== -0.0001) { //-0.0001 is a special value that we use when looping back to the beginning of a repeated TimelineMax, in which case we shouldn't render the _startAt values.
					this._startAt.render(time, suppressEvents, force);
				}
				if (isComplete) {
					if (this._timeline.autoRemoveChildren) {
						this._enabled(false, false);
					}
					this._active = false;
				}
				if (!suppressEvents && this.vars[callback]) {
					this._callback(callback);
				}
				if (duration === 0 && this._rawPrevTime === _tinyNum && rawPrevTime !== _tinyNum) { //the onComplete or onReverseComplete could trigger movement of the playhead and for zero-duration tweens (which must discern direction) that land directly back on their start time, we don't want to fire again on the next render. Think of several addPause()'s in a timeline that forces the playhead to a certain spot, but what if it's already paused and another tween is tweening the "time" of the timeline? Each time it moves [forward] past that spot, it would move back, and since suppressEvents is true, it'd reset _rawPrevTime to _tinyNum so that when it begins again, the callback would fire (so ultimately it could bounce back and forth during that tween). Again, this is a very uncommon scenario, but possible nonetheless.
					this._rawPrevTime = 0;
				}
			}
		};

		p._kill = function(vars, target, overwritingTween) {
			if (vars === "all") {
				vars = null;
			}
			if (vars == null) if (target == null || target === this.target) {
				this._lazy = false;
				return this._enabled(false, false);
			}
			target = (typeof(target) !== "string") ? (target || this._targets || this.target) : TweenLite.selector(target) || target;
			var simultaneousOverwrite = (overwritingTween && this._time && overwritingTween._startTime === this._startTime && this._timeline === overwritingTween._timeline),
				i, overwrittenProps, p, pt, propLookup, changed, killProps, record, killed;
			if ((_isArray(target) || _isSelector(target)) && typeof(target[0]) !== "number") {
				i = target.length;
				while (--i > -1) {
					if (this._kill(vars, target[i], overwritingTween)) {
						changed = true;
					}
				}
			} else {
				if (this._targets) {
					i = this._targets.length;
					while (--i > -1) {
						if (target === this._targets[i]) {
							propLookup = this._propLookup[i] || {};
							this._overwrittenProps = this._overwrittenProps || [];
							overwrittenProps = this._overwrittenProps[i] = vars ? this._overwrittenProps[i] || {} : "all";
							break;
						}
					}
				} else if (target !== this.target) {
					return false;
				} else {
					propLookup = this._propLookup;
					overwrittenProps = this._overwrittenProps = vars ? this._overwrittenProps || {} : "all";
				}

				if (propLookup) {
					killProps = vars || propLookup;
					record = (vars !== overwrittenProps && overwrittenProps !== "all" && vars !== propLookup && (typeof(vars) !== "object" || !vars._tempKill)); //_tempKill is a super-secret way to delete a particular tweening property but NOT have it remembered as an official overwritten property (like in BezierPlugin)
					if (overwritingTween && (TweenLite.onOverwrite || this.vars.onOverwrite)) {
						for (p in killProps) {
							if (propLookup[p]) {
								if (!killed) {
									killed = [];
								}
								killed.push(p);
							}
						}
						if ((killed || !vars) && !_onOverwrite(this, overwritingTween, target, killed)) { //if the onOverwrite returned false, that means the user wants to override the overwriting (cancel it).
							return false;
						}
					}

					for (p in killProps) {
						if ((pt = propLookup[p])) {
							if (simultaneousOverwrite) { //if another tween overwrites this one and they both start at exactly the same time, yet this tween has already rendered once (for example, at 0.001) because it's first in the queue, we should revert the values to where they were at 0 so that the starting values aren't contaminated on the overwriting tween.
								if (pt.f) {
									pt.t[pt.p](pt.s);
								} else {
									pt.t[pt.p] = pt.s;
								}
								changed = true;
							}
							if (pt.pg && pt.t._kill(killProps)) {
								changed = true; //some plugins need to be notified so they can perform cleanup tasks first
							}
							if (!pt.pg || pt.t._overwriteProps.length === 0) {
								if (pt._prev) {
									pt._prev._next = pt._next;
								} else if (pt === this._firstPT) {
									this._firstPT = pt._next;
								}
								if (pt._next) {
									pt._next._prev = pt._prev;
								}
								pt._next = pt._prev = null;
							}
							delete propLookup[p];
						}
						if (record) {
							overwrittenProps[p] = 1;
						}
					}
					if (!this._firstPT && this._initted) { //if all tweening properties are killed, kill the tween. Without this line, if there's a tween with multiple targets and then you killTweensOf() each target individually, the tween would technically still remain active and fire its onComplete even though there aren't any more properties tweening.
						this._enabled(false, false);
					}
				}
			}
			return changed;
		};

		p.invalidate = function() {
			if (this._notifyPluginsOfEnabled) {
				TweenLite._onPluginEvent("_onDisable", this);
			}
			this._firstPT = this._overwrittenProps = this._startAt = this._onUpdate = null;
			this._notifyPluginsOfEnabled = this._active = this._lazy = false;
			this._propLookup = (this._targets) ? {} : [];
			Animation.prototype.invalidate.call(this);
			if (this.vars.immediateRender) {
				this._time = -_tinyNum; //forces a render without having to set the render() "force" parameter to true because we want to allow lazying by default (using the "force" parameter always forces an immediate full render)
				this.render(Math.min(0, -this._delay)); //in case delay is negative.
			}
			return this;
		};

		p._enabled = function(enabled, ignoreTimeline) {
			if (!_tickerActive) {
				_ticker.wake();
			}
			if (enabled && this._gc) {
				var targets = this._targets,
					i;
				if (targets) {
					i = targets.length;
					while (--i > -1) {
						this._siblings[i] = _register(targets[i], this, true);
					}
				} else {
					this._siblings = _register(this.target, this, true);
				}
			}
			Animation.prototype._enabled.call(this, enabled, ignoreTimeline);
			if (this._notifyPluginsOfEnabled) if (this._firstPT) {
				return TweenLite._onPluginEvent((enabled ? "_onEnable" : "_onDisable"), this);
			}
			return false;
		};


//----TweenLite static methods -----------------------------------------------------

		TweenLite.to = function(target, duration, vars) {
			return new TweenLite(target, duration, vars);
		};

		TweenLite.from = function(target, duration, vars) {
			vars.runBackwards = true;
			vars.immediateRender = (vars.immediateRender != false);
			return new TweenLite(target, duration, vars);
		};

		TweenLite.fromTo = function(target, duration, fromVars, toVars) {
			toVars.startAt = fromVars;
			toVars.immediateRender = (toVars.immediateRender != false && fromVars.immediateRender != false);
			return new TweenLite(target, duration, toVars);
		};

		TweenLite.delayedCall = function(delay, callback, params, scope, useFrames) {
			return new TweenLite(callback, 0, {delay:delay, onComplete:callback, onCompleteParams:params, callbackScope:scope, onReverseComplete:callback, onReverseCompleteParams:params, immediateRender:false, lazy:false, useFrames:useFrames, overwrite:0});
		};

		TweenLite.set = function(target, vars) {
			return new TweenLite(target, 0, vars);
		};

		TweenLite.getTweensOf = function(target, onlyActive) {
			if (target == null) { return []; }
			target = (typeof(target) !== "string") ? target : TweenLite.selector(target) || target;
			var i, a, j, t;
			if ((_isArray(target) || _isSelector(target)) && typeof(target[0]) !== "number") {
				i = target.length;
				a = [];
				while (--i > -1) {
					a = a.concat(TweenLite.getTweensOf(target[i], onlyActive));
				}
				i = a.length;
				//now get rid of any duplicates (tweens of arrays of objects could cause duplicates)
				while (--i > -1) {
					t = a[i];
					j = i;
					while (--j > -1) {
						if (t === a[j]) {
							a.splice(i, 1);
						}
					}
				}
			} else {
				a = _register(target).concat();
				i = a.length;
				while (--i > -1) {
					if (a[i]._gc || (onlyActive && !a[i].isActive())) {
						a.splice(i, 1);
					}
				}
			}
			return a;
		};

		TweenLite.killTweensOf = TweenLite.killDelayedCallsTo = function(target, onlyActive, vars) {
			if (typeof(onlyActive) === "object") {
				vars = onlyActive; //for backwards compatibility (before "onlyActive" parameter was inserted)
				onlyActive = false;
			}
			var a = TweenLite.getTweensOf(target, onlyActive),
				i = a.length;
			while (--i > -1) {
				a[i]._kill(vars, target);
			}
		};



/*
 * ----------------------------------------------------------------
 * TweenPlugin   (could easily be split out as a separate file/class, but included for ease of use (so that people don't need to include another script call before loading plugins which is easy to forget)
 * ----------------------------------------------------------------
 */
		var TweenPlugin = _class("plugins.TweenPlugin", function(props, priority) {
					this._overwriteProps = (props || "").split(",");
					this._propName = this._overwriteProps[0];
					this._priority = priority || 0;
					this._super = TweenPlugin.prototype;
				}, true);

		p = TweenPlugin.prototype;
		TweenPlugin.version = "1.19.0";
		TweenPlugin.API = 2;
		p._firstPT = null;
		p._addTween = _addPropTween;
		p.setRatio = _setRatio;

		p._kill = function(lookup) {
			var a = this._overwriteProps,
				pt = this._firstPT,
				i;
			if (lookup[this._propName] != null) {
				this._overwriteProps = [];
			} else {
				i = a.length;
				while (--i > -1) {
					if (lookup[a[i]] != null) {
						a.splice(i, 1);
					}
				}
			}
			while (pt) {
				if (lookup[pt.n] != null) {
					if (pt._next) {
						pt._next._prev = pt._prev;
					}
					if (pt._prev) {
						pt._prev._next = pt._next;
						pt._prev = null;
					} else if (this._firstPT === pt) {
						this._firstPT = pt._next;
					}
				}
				pt = pt._next;
			}
			return false;
		};

		p._mod = p._roundProps = function(lookup) {
			var pt = this._firstPT,
				val;
			while (pt) {
				val = lookup[this._propName] || (pt.n != null && lookup[ pt.n.split(this._propName + "_").join("") ]);
				if (val && typeof(val) === "function") { //some properties that are very plugin-specific add a prefix named after the _propName plus an underscore, so we need to ignore that extra stuff here.
					if (pt.f === 2) {
						pt.t._applyPT.m = val;
					} else {
						pt.m = val;
					}
				}
				pt = pt._next;
			}
		};

		TweenLite._onPluginEvent = function(type, tween) {
			var pt = tween._firstPT,
				changed, pt2, first, last, next;
			if (type === "_onInitAllProps") {
				//sorts the PropTween linked list in order of priority because some plugins need to render earlier/later than others, like MotionBlurPlugin applies its effects after all x/y/alpha tweens have rendered on each frame.
				while (pt) {
					next = pt._next;
					pt2 = first;
					while (pt2 && pt2.pr > pt.pr) {
						pt2 = pt2._next;
					}
					if ((pt._prev = pt2 ? pt2._prev : last)) {
						pt._prev._next = pt;
					} else {
						first = pt;
					}
					if ((pt._next = pt2)) {
						pt2._prev = pt;
					} else {
						last = pt;
					}
					pt = next;
				}
				pt = tween._firstPT = first;
			}
			while (pt) {
				if (pt.pg) if (typeof(pt.t[type]) === "function") if (pt.t[type]()) {
					changed = true;
				}
				pt = pt._next;
			}
			return changed;
		};

		TweenPlugin.activate = function(plugins) {
			var i = plugins.length;
			while (--i > -1) {
				if (plugins[i].API === TweenPlugin.API) {
					_plugins[(new plugins[i]())._propName] = plugins[i];
				}
			}
			return true;
		};

		//provides a more concise way to define plugins that have no dependencies besides TweenPlugin and TweenLite, wrapping common boilerplate stuff into one function (added in 1.9.0). You don't NEED to use this to define a plugin - the old way still works and can be useful in certain (rare) situations.
		_gsDefine.plugin = function(config) {
			if (!config || !config.propName || !config.init || !config.API) { throw "illegal plugin definition."; }
			var propName = config.propName,
				priority = config.priority || 0,
				overwriteProps = config.overwriteProps,
				map = {init:"_onInitTween", set:"setRatio", kill:"_kill", round:"_mod", mod:"_mod", initAll:"_onInitAllProps"},
				Plugin = _class("plugins." + propName.charAt(0).toUpperCase() + propName.substr(1) + "Plugin",
					function() {
						TweenPlugin.call(this, propName, priority);
						this._overwriteProps = overwriteProps || [];
					}, (config.global === true)),
				p = Plugin.prototype = new TweenPlugin(propName),
				prop;
			p.constructor = Plugin;
			Plugin.API = config.API;
			for (prop in map) {
				if (typeof(config[prop]) === "function") {
					p[map[prop]] = config[prop];
				}
			}
			Plugin.version = config.version;
			TweenPlugin.activate([Plugin]);
			return Plugin;
		};


		//now run through all the dependencies discovered and if any are missing, log that to the console as a warning. This is why it's best to have TweenLite load last - it can check all the dependencies for you.
		a = window._gsQueue;
		if (a) {
			for (i = 0; i < a.length; i++) {
				a[i]();
			}
			for (p in _defLookup) {
				if (!_defLookup[p].func) {
					window.console.log("GSAP encountered missing dependency: " + p);
				}
			}
		}

		_tickerActive = false; //ensures that the first official animation forces a ticker.tick() to update the time when it is instantiated

})((typeof(module) !== "undefined" && module.exports && typeof(global) !== "undefined") ? global : this || window, "TweenMax");
/*!
* PreloadJS
* Visit http://createjs.com/ for documentation, updates and examples.
*
* Copyright (c) 2010 gskinner.com, inc.
*
* 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.
*/


//##############################################################################
// version.js
//##############################################################################

this.createjs = this.createjs || {};

(function () {
	"use strict";

	/**
	 * Static class holding library specific information such as the version and buildDate of the library.
	 * @class PreloadJS
	 **/
	var s = createjs.PreloadJS = createjs.PreloadJS || {};

	/**
	 * The version string for this release.
	 * @property version
	 * @type {String}
	 * @static
	 **/
	s.version = /*=version*/"0.6.2"; // injected by build process

	/**
	 * The build date for this release in UTC format.
	 * @property buildDate
	 * @type {String}
	 * @static
	 **/
	s.buildDate = /*=date*/"Thu, 26 Nov 2015 20:44:31 GMT"; // injected by build process

})();

//##############################################################################
// extend.js
//##############################################################################

this.createjs = this.createjs||{};

/**
 * @class Utility Methods
 */

/**
 * Sets up the prototype chain and constructor property for a new class.
 *
 * This should be called right after creating the class constructor.
 *
 * 	function MySubClass() {}
 * 	createjs.extend(MySubClass, MySuperClass);
 * 	MySubClass.prototype.doSomething = function() { }
 *
 * 	var foo = new MySubClass();
 * 	console.log(foo instanceof MySuperClass); // true
 * 	console.log(foo.prototype.constructor === MySubClass); // true
 *
 * @method extend
 * @param {Function} subclass The subclass.
 * @param {Function} superclass The superclass to extend.
 * @return {Function} Returns the subclass's new prototype.
 */
createjs.extend = function(subclass, superclass) {
	"use strict";

	function o() { this.constructor = subclass; }
	o.prototype = superclass.prototype;
	return (subclass.prototype = new o());
};

//##############################################################################
// promote.js
//##############################################################################

this.createjs = this.createjs||{};

/**
 * @class Utility Methods
 */

/**
 * Promotes any methods on the super class that were overridden, by creating an alias in the format `prefix_methodName`.
 * It is recommended to use the super class's name as the prefix.
 * An alias to the super class's constructor is always added in the format `prefix_constructor`.
 * This allows the subclass to call super class methods without using `function.call`, providing better performance.
 *
 * For example, if `MySubClass` extends `MySuperClass`, and both define a `draw` method, then calling `promote(MySubClass, "MySuperClass")`
 * would add a `MySuperClass_constructor` method to MySubClass and promote the `draw` method on `MySuperClass` to the
 * prototype of `MySubClass` as `MySuperClass_draw`.
 *
 * This should be called after the class's prototype is fully defined.
 *
 * 	function ClassA(name) {
 * 		this.name = name;
 * 	}
 * 	ClassA.prototype.greet = function() {
 * 		return "Hello "+this.name;
 * 	}
 *
 * 	function ClassB(name, punctuation) {
 * 		this.ClassA_constructor(name);
 * 		this.punctuation = punctuation;
 * 	}
 * 	createjs.extend(ClassB, ClassA);
 * 	ClassB.prototype.greet = function() {
 * 		return this.ClassA_greet()+this.punctuation;
 * 	}
 * 	createjs.promote(ClassB, "ClassA");
 *
 * 	var foo = new ClassB("World", "!?!");
 * 	console.log(foo.greet()); // Hello World!?!
 *
 * @method promote
 * @param {Function} subclass The class to promote super class methods on.
 * @param {String} prefix The prefix to add to the promoted method names. Usually the name of the superclass.
 * @return {Function} Returns the subclass.
 */
createjs.promote = function(subclass, prefix) {
	"use strict";

	var subP = subclass.prototype, supP = (Object.getPrototypeOf&&Object.getPrototypeOf(subP))||subP.__proto__;
	if (supP) {
		subP[(prefix+="_") + "constructor"] = supP.constructor; // constructor is not always innumerable
		for (var n in supP) {
			if (subP.hasOwnProperty(n) && (typeof supP[n] == "function")) { subP[prefix + n] = supP[n]; }
		}
	}
	return subclass;
};

//##############################################################################
// proxy.js
//##############################################################################

this.createjs = this.createjs||{};

/**
 * Various utilities that the CreateJS Suite uses. Utilities are created as separate files, and will be available on the
 * createjs namespace directly.
 *
 * <h4>Example</h4>
 *
 *      myObject.addEventListener("change", createjs.proxy(myMethod, scope));
 *
 * @class Utility Methods
 * @main Utility Methods
 */

(function() {
	"use strict";

	/**
	 * A function proxy for methods. By default, JavaScript methods do not maintain scope, so passing a method as a
	 * callback will result in the method getting called in the scope of the caller. Using a proxy ensures that the
	 * method gets called in the correct scope.
	 *
	 * Additional arguments can be passed that will be applied to the function when it is called.
	 *
	 * <h4>Example</h4>
	 *
	 *      myObject.addEventListener("event", createjs.proxy(myHandler, this, arg1, arg2));
	 *
	 *      function myHandler(arg1, arg2) {
	 *           // This gets called when myObject.myCallback is executed.
	 *      }
	 *
	 * @method proxy
	 * @param {Function} method The function to call
	 * @param {Object} scope The scope to call the method name on
	 * @param {mixed} [arg] * Arguments that are appended to the callback for additional params.
	 * @public
	 * @static
	 */
	createjs.proxy = function (method, scope) {
		var aArgs = Array.prototype.slice.call(arguments, 2);
		return function () {
			return method.apply(scope, Array.prototype.slice.call(arguments, 0).concat(aArgs));
		};
	}

}());

//##############################################################################
// indexOf.js
//##############################################################################

this.createjs = this.createjs||{};

/**
 * @class Utility Methods
 */

/**
 * Finds the first occurrence of a specified value searchElement in the passed in array, and returns the index of
 * that value.  Returns -1 if value is not found.
 *
 *      var i = createjs.indexOf(myArray, myElementToFind);
 *
 * @method indexOf
 * @param {Array} array Array to search for searchElement
 * @param searchElement Element to find in array.
 * @return {Number} The first index of searchElement in array.
 */
createjs.indexOf = function (array, searchElement){
	"use strict";

	for (var i = 0,l=array.length; i < l; i++) {
		if (searchElement === array[i]) {
			return i;
		}
	}
	return -1;
};

//##############################################################################
// Event.js
//##############################################################################

this.createjs = this.createjs||{};

(function() {
	"use strict";

// constructor:
	/**
	 * Contains properties and methods shared by all events for use with
	 * {{#crossLink "EventDispatcher"}}{{/crossLink}}.
	 * 
	 * Note that Event objects are often reused, so you should never
	 * rely on an event object's state outside of the call stack it was received in.
	 * @class Event
	 * @param {String} type The event type.
	 * @param {Boolean} bubbles Indicates whether the event will bubble through the display list.
	 * @param {Boolean} cancelable Indicates whether the default behaviour of this event can be cancelled.
	 * @constructor
	 **/
	function Event(type, bubbles, cancelable) {
		
	
	// public properties:
		/**
		 * The type of event.
		 * @property type
		 * @type String
		 **/
		this.type = type;
	
		/**
		 * The object that generated an event.
		 * @property target
		 * @type Object
		 * @default null
		 * @readonly
		*/
		this.target = null;
	
		/**
		 * The current target that a bubbling event is being dispatched from. For non-bubbling events, this will
		 * always be the same as target. For example, if childObj.parent = parentObj, and a bubbling event
		 * is generated from childObj, then a listener on parentObj would receive the event with
		 * target=childObj (the original target) and currentTarget=parentObj (where the listener was added).
		 * @property currentTarget
		 * @type Object
		 * @default null
		 * @readonly
		*/
		this.currentTarget = null;
	
		/**
		 * For bubbling events, this indicates the current event phase:<OL>
		 * 	<LI> capture phase: starting from the top parent to the target</LI>
		 * 	<LI> at target phase: currently being dispatched from the target</LI>
		 * 	<LI> bubbling phase: from the target to the top parent</LI>
		 * </OL>
		 * @property eventPhase
		 * @type Number
		 * @default 0
		 * @readonly
		*/
		this.eventPhase = 0;
	
		/**
		 * Indicates whether the event will bubble through the display list.
		 * @property bubbles
		 * @type Boolean
		 * @default false
		 * @readonly
		*/
		this.bubbles = !!bubbles;
	
		/**
		 * Indicates whether the default behaviour of this event can be cancelled via
		 * {{#crossLink "Event/preventDefault"}}{{/crossLink}}. This is set via the Event constructor.
		 * @property cancelable
		 * @type Boolean
		 * @default false
		 * @readonly
		*/
		this.cancelable = !!cancelable;
	
		/**
		 * The epoch time at which this event was created.
		 * @property timeStamp
		 * @type Number
		 * @default 0
		 * @readonly
		*/
		this.timeStamp = (new Date()).getTime();
	
		/**
		 * Indicates if {{#crossLink "Event/preventDefault"}}{{/crossLink}} has been called
		 * on this event.
		 * @property defaultPrevented
		 * @type Boolean
		 * @default false
		 * @readonly
		*/
		this.defaultPrevented = false;
	
		/**
		 * Indicates if {{#crossLink "Event/stopPropagation"}}{{/crossLink}} or
		 * {{#crossLink "Event/stopImmediatePropagation"}}{{/crossLink}} has been called on this event.
		 * @property propagationStopped
		 * @type Boolean
		 * @default false
		 * @readonly
		*/
		this.propagationStopped = false;
	
		/**
		 * Indicates if {{#crossLink "Event/stopImmediatePropagation"}}{{/crossLink}} has been called
		 * on this event.
		 * @property immediatePropagationStopped
		 * @type Boolean
		 * @default false
		 * @readonly
		*/
		this.immediatePropagationStopped = false;
		
		/**
		 * Indicates if {{#crossLink "Event/remove"}}{{/crossLink}} has been called on this event.
		 * @property removed
		 * @type Boolean
		 * @default false
		 * @readonly
		*/
		this.removed = false;
	}
	var p = Event.prototype;

	/**
	 * <strong>REMOVED</strong>. Removed in favor of using `MySuperClass_constructor`.
	 * See {{#crossLink "Utility Methods/extend"}}{{/crossLink}} and {{#crossLink "Utility Methods/promote"}}{{/crossLink}}
	 * for details.
	 *
	 * There is an inheritance tutorial distributed with EaselJS in /tutorials/Inheritance.
	 *
	 * @method initialize
	 * @protected
	 * @deprecated
	 */
	// p.initialize = function() {}; // searchable for devs wondering where it is.

// public methods:
	/**
	 * Sets {{#crossLink "Event/defaultPrevented"}}{{/crossLink}} to true if the event is cancelable.
	 * Mirrors the DOM level 2 event standard. In general, cancelable events that have `preventDefault()` called will
	 * cancel the default behaviour associated with the event.
	 * @method preventDefault
	 **/
	p.preventDefault = function() {
		this.defaultPrevented = this.cancelable&&true;
	};

	/**
	 * Sets {{#crossLink "Event/propagationStopped"}}{{/crossLink}} to true.
	 * Mirrors the DOM event standard.
	 * @method stopPropagation
	 **/
	p.stopPropagation = function() {
		this.propagationStopped = true;
	};

	/**
	 * Sets {{#crossLink "Event/propagationStopped"}}{{/crossLink}} and
	 * {{#crossLink "Event/immediatePropagationStopped"}}{{/crossLink}} to true.
	 * Mirrors the DOM event standard.
	 * @method stopImmediatePropagation
	 **/
	p.stopImmediatePropagation = function() {
		this.immediatePropagationStopped = this.propagationStopped = true;
	};
	
	/**
	 * Causes the active listener to be removed via removeEventListener();
	 * 
	 * 		myBtn.addEventListener("click", function(evt) {
	 * 			// do stuff...
	 * 			evt.remove(); // removes this listener.
	 * 		});
	 * 
	 * @method remove
	 **/
	p.remove = function() {
		this.removed = true;
	};
	
	/**
	 * Returns a clone of the Event instance.
	 * @method clone
	 * @return {Event} a clone of the Event instance.
	 **/
	p.clone = function() {
		return new Event(this.type, this.bubbles, this.cancelable);
	};
	
	/**
	 * Provides a chainable shortcut method for setting a number of properties on the instance.
	 *
	 * @method set
	 * @param {Object} props A generic object containing properties to copy to the instance.
	 * @return {Event} Returns the instance the method is called on (useful for chaining calls.)
	 * @chainable
	*/
	p.set = function(props) {
		for (var n in props) { this[n] = props[n]; }
		return this;
	};

	/**
	 * Returns a string representation of this object.
	 * @method toString
	 * @return {String} a string representation of the instance.
	 **/
	p.toString = function() {
		return "[Event (type="+this.type+")]";
	};

	createjs.Event = Event;
}());

//##############################################################################
// ErrorEvent.js
//##############################################################################

this.createjs = this.createjs||{};

(function() {
	"use strict";

	/**
	 * A general error {{#crossLink "Event"}}{{/crossLink}}, that describes an error that occurred, as well as any details.
	 * @class ErrorEvent
	 * @param {String} [title] The error title
	 * @param {String} [message] The error description
	 * @param {Object} [data] Additional error data
	 * @constructor
	 */
	function ErrorEvent(title, message, data) {
		this.Event_constructor("error");

		/**
		 * The short error title, which indicates the type of error that occurred.
		 * @property title
		 * @type String
		 */
		this.title = title;

		/**
		 * The verbose error message, containing details about the error.
		 * @property message
		 * @type String
		 */
		this.message = message;

		/**
		 * Additional data attached to an error.
		 * @property data
		 * @type {Object}
		 */
		this.data = data;
	}

	var p = createjs.extend(ErrorEvent, createjs.Event);

	p.clone = function() {
		return new createjs.ErrorEvent(this.title, this.message, this.data);
	};

	createjs.ErrorEvent = createjs.promote(ErrorEvent, "Event");

}());

//##############################################################################
// EventDispatcher.js
//##############################################################################

this.createjs = this.createjs||{};

(function() {
	"use strict";


// constructor:
	/**
	 * EventDispatcher provides methods for managing queues of event listeners and dispatching events.
	 *
	 * You can either extend EventDispatcher or mix its methods into an existing prototype or instance by using the
	 * EventDispatcher {{#crossLink "EventDispatcher/initialize"}}{{/crossLink}} method.
	 * 
	 * Together with the CreateJS Event class, EventDispatcher provides an extended event model that is based on the
	 * DOM Level 2 event model, including addEventListener, removeEventListener, and dispatchEvent. It supports
	 * bubbling / capture, preventDefault, stopPropagation, stopImmediatePropagation, and handleEvent.
	 * 
	 * EventDispatcher also exposes a {{#crossLink "EventDispatcher/on"}}{{/crossLink}} method, which makes it easier
	 * to create scoped listeners, listeners that only run once, and listeners with associated arbitrary data. The 
	 * {{#crossLink "EventDispatcher/off"}}{{/crossLink}} method is merely an alias to
	 * {{#crossLink "EventDispatcher/removeEventListener"}}{{/crossLink}}.
	 * 
	 * Another addition to the DOM Level 2 model is the {{#crossLink "EventDispatcher/removeAllEventListeners"}}{{/crossLink}}
	 * method, which can be used to listeners for all events, or listeners for a specific event. The Event object also 
	 * includes a {{#crossLink "Event/remove"}}{{/crossLink}} method which removes the active listener.
	 *
	 * <h4>Example</h4>
	 * Add EventDispatcher capabilities to the "MyClass" class.
	 *
	 *      EventDispatcher.initialize(MyClass.prototype);
	 *
	 * Add an event (see {{#crossLink "EventDispatcher/addEventListener"}}{{/crossLink}}).
	 *
	 *      instance.addEventListener("eventName", handlerMethod);
	 *      function handlerMethod(event) {
	 *          console.log(event.target + " Was Clicked");
	 *      }
	 *
	 * <b>Maintaining proper scope</b><br />
	 * Scope (ie. "this") can be be a challenge with events. Using the {{#crossLink "EventDispatcher/on"}}{{/crossLink}}
	 * method to subscribe to events simplifies this.
	 *
	 *      instance.addEventListener("click", function(event) {
	 *          console.log(instance == this); // false, scope is ambiguous.
	 *      });
	 *      
	 *      instance.on("click", function(event) {
	 *          console.log(instance == this); // true, "on" uses dispatcher scope by default.
	 *      });
	 * 
	 * If you want to use addEventListener instead, you may want to use function.bind() or a similar proxy to manage
	 * scope.
	 *
	 * <b>Browser support</b>
	 * The event model in CreateJS can be used separately from the suite in any project, however the inheritance model
	 * requires modern browsers (IE9+).
	 *      
	 *
	 * @class EventDispatcher
	 * @constructor
	 **/
	function EventDispatcher() {
	
	
	// private properties:
		/**
		 * @protected
		 * @property _listeners
		 * @type Object
		 **/
		this._listeners = null;
		
		/**
		 * @protected
		 * @property _captureListeners
		 * @type Object
		 **/
		this._captureListeners = null;
	}
	var p = EventDispatcher.prototype;

	/**
	 * <strong>REMOVED</strong>. Removed in favor of using `MySuperClass_constructor`.
	 * See {{#crossLink "Utility Methods/extend"}}{{/crossLink}} and {{#crossLink "Utility Methods/promote"}}{{/crossLink}}
	 * for details.
	 *
	 * There is an inheritance tutorial distributed with EaselJS in /tutorials/Inheritance.
	 *
	 * @method initialize
	 * @protected
	 * @deprecated
	 */
	// p.initialize = function() {}; // searchable for devs wondering where it is.


// static public methods:
	/**
	 * Static initializer to mix EventDispatcher methods into a target object or prototype.
	 * 
	 * 		EventDispatcher.initialize(MyClass.prototype); // add to the prototype of the class
	 * 		EventDispatcher.initialize(myObject); // add to a specific instance
	 * 
	 * @method initialize
	 * @static
	 * @param {Object} target The target object to inject EventDispatcher methods into. This can be an instance or a
	 * prototype.
	 **/
	EventDispatcher.initialize = function(target) {
		target.addEventListener = p.addEventListener;
		target.on = p.on;
		target.removeEventListener = target.off =  p.removeEventListener;
		target.removeAllEventListeners = p.removeAllEventListeners;
		target.hasEventListener = p.hasEventListener;
		target.dispatchEvent = p.dispatchEvent;
		target._dispatchEvent = p._dispatchEvent;
		target.willTrigger = p.willTrigger;
	};
	

// public methods:
	/**
	 * Adds the specified event listener. Note that adding multiple listeners to the same function will result in
	 * multiple callbacks getting fired.
	 *
	 * <h4>Example</h4>
	 *
	 *      displayObject.addEventListener("click", handleClick);
	 *      function handleClick(event) {
	 *         // Click happened.
	 *      }
	 *
	 * @method addEventListener
	 * @param {String} type The string type of the event.
	 * @param {Function | Object} listener An object with a handleEvent method, or a function that will be called when
	 * the event is dispatched.
	 * @param {Boolean} [useCapture] For events that bubble, indicates whether to listen for the event in the capture or bubbling/target phase.
	 * @return {Function | Object} Returns the listener for chaining or assignment.
	 **/
	p.addEventListener = function(type, listener, useCapture) {
		var listeners;
		if (useCapture) {
			listeners = this._captureListeners = this._captureListeners||{};
		} else {
			listeners = this._listeners = this._listeners||{};
		}
		var arr = listeners[type];
		if (arr) { this.removeEventListener(type, listener, useCapture); }
		arr = listeners[type]; // remove may have deleted the array
		if (!arr) { listeners[type] = [listener];  }
		else { arr.push(listener); }
		return listener;
	};
	
	/**
	 * A shortcut method for using addEventListener that makes it easier to specify an execution scope, have a listener
	 * only run once, associate arbitrary data with the listener, and remove the listener.
	 * 
	 * This method works by creating an anonymous wrapper function and subscribing it with addEventListener.
	 * The wrapper function is returned for use with `removeEventListener` (or `off`).
	 * 
	 * <b>IMPORTANT:</b> To remove a listener added with `on`, you must pass in the returned wrapper function as the listener, or use
	 * {{#crossLink "Event/remove"}}{{/crossLink}}. Likewise, each time you call `on` a NEW wrapper function is subscribed, so multiple calls
	 * to `on` with the same params will create multiple listeners.
	 * 
	 * <h4>Example</h4>
	 * 
	 * 		var listener = myBtn.on("click", handleClick, null, false, {count:3});
	 * 		function handleClick(evt, data) {
	 * 			data.count -= 1;
	 * 			console.log(this == myBtn); // true - scope defaults to the dispatcher
	 * 			if (data.count == 0) {
	 * 				alert("clicked 3 times!");
	 * 				myBtn.off("click", listener);
	 * 				// alternately: evt.remove();
	 * 			}
	 * 		}
	 * 
	 * @method on
	 * @param {String} type The string type of the event.
	 * @param {Function | Object} listener An object with a handleEvent method, or a function that will be called when
	 * the event is dispatched.
	 * @param {Object} [scope] The scope to execute the listener in. Defaults to the dispatcher/currentTarget for function listeners, and to the listener itself for object listeners (ie. using handleEvent).
	 * @param {Boolean} [once=false] If true, the listener will remove itself after the first time it is triggered.
	 * @param {*} [data] Arbitrary data that will be included as the second parameter when the listener is called.
	 * @param {Boolean} [useCapture=false] For events that bubble, indicates whether to listen for the event in the capture or bubbling/target phase.
	 * @return {Function} Returns the anonymous function that was created and assigned as the listener. This is needed to remove the listener later using .removeEventListener.
	 **/
	p.on = function(type, listener, scope, once, data, useCapture) {
		if (listener.handleEvent) {
			scope = scope||listener;
			listener = listener.handleEvent;
		}
		scope = scope||this;
		return this.addEventListener(type, function(evt) {
				listener.call(scope, evt, data);
				once&&evt.remove();
			}, useCapture);
	};

	/**
	 * Removes the specified event listener.
	 *
	 * <b>Important Note:</b> that you must pass the exact function reference used when the event was added. If a proxy
	 * function, or function closure is used as the callback, the proxy/closure reference must be used - a new proxy or
	 * closure will not work.
	 *
	 * <h4>Example</h4>
	 *
	 *      displayObject.removeEventListener("click", handleClick);
	 *
	 * @method removeEventListener
	 * @param {String} type The string type of the event.
	 * @param {Function | Object} listener The listener function or object.
	 * @param {Boolean} [useCapture] For events that bubble, indicates whether to listen for the event in the capture or bubbling/target phase.
	 **/
	p.removeEventListener = function(type, listener, useCapture) {
		var listeners = useCapture ? this._captureListeners : this._listeners;
		if (!listeners) { return; }
		var arr = listeners[type];
		if (!arr) { return; }
		for (var i=0,l=arr.length; i<l; i++) {
			if (arr[i] == listener) {
				if (l==1) { delete(listeners[type]); } // allows for faster checks.
				else { arr.splice(i,1); }
				break;
			}
		}
	};
	
	/**
	 * A shortcut to the removeEventListener method, with the same parameters and return value. This is a companion to the
	 * .on method.
	 * 
	 * <b>IMPORTANT:</b> To remove a listener added with `on`, you must pass in the returned wrapper function as the listener. See 
	 * {{#crossLink "EventDispatcher/on"}}{{/crossLink}} for an example.
	 *
	 * @method off
	 * @param {String} type The string type of the event.
	 * @param {Function | Object} listener The listener function or object.
	 * @param {Boolean} [useCapture] For events that bubble, indicates whether to listen for the event in the capture or bubbling/target phase.
	 **/
	p.off = p.removeEventListener;

	/**
	 * Removes all listeners for the specified type, or all listeners of all types.
	 *
	 * <h4>Example</h4>
	 *
	 *      // Remove all listeners
	 *      displayObject.removeAllEventListeners();
	 *
	 *      // Remove all click listeners
	 *      displayObject.removeAllEventListeners("click");
	 *
	 * @method removeAllEventListeners
	 * @param {String} [type] The string type of the event. If omitted, all listeners for all types will be removed.
	 **/
	p.removeAllEventListeners = function(type) {
		if (!type) { this._listeners = this._captureListeners = null; }
		else {
			if (this._listeners) { delete(this._listeners[type]); }
			if (this._captureListeners) { delete(this._captureListeners[type]); }
		}
	};

	/**
	 * Dispatches the specified event to all listeners.
	 *
	 * <h4>Example</h4>
	 *
	 *      // Use a string event
	 *      this.dispatchEvent("complete");
	 *
	 *      // Use an Event instance
	 *      var event = new createjs.Event("progress");
	 *      this.dispatchEvent(event);
	 *
	 * @method dispatchEvent
	 * @param {Object | String | Event} eventObj An object with a "type" property, or a string type.
	 * While a generic object will work, it is recommended to use a CreateJS Event instance. If a string is used,
	 * dispatchEvent will construct an Event instance if necessary with the specified type. This latter approach can
	 * be used to avoid event object instantiation for non-bubbling events that may not have any listeners.
	 * @param {Boolean} [bubbles] Specifies the `bubbles` value when a string was passed to eventObj.
	 * @param {Boolean} [cancelable] Specifies the `cancelable` value when a string was passed to eventObj.
	 * @return {Boolean} Returns false if `preventDefault()` was called on a cancelable event, true otherwise.
	 **/
	p.dispatchEvent = function(eventObj, bubbles, cancelable) {
		if (typeof eventObj == "string") {
			// skip everything if there's no listeners and it doesn't bubble:
			var listeners = this._listeners;
			if (!bubbles && (!listeners || !listeners[eventObj])) { return true; }
			eventObj = new createjs.Event(eventObj, bubbles, cancelable);
		} else if (eventObj.target && eventObj.clone) {
			// redispatching an active event object, so clone it:
			eventObj = eventObj.clone();
		}
		
		// TODO: it would be nice to eliminate this. Maybe in favour of evtObj instanceof Event? Or !!evtObj.createEvent
		try { eventObj.target = this; } catch (e) {} // try/catch allows redispatching of native events

		if (!eventObj.bubbles || !this.parent) {
			this._dispatchEvent(eventObj, 2);
		} else {
			var top=this, list=[top];
			while (top.parent) { list.push(top = top.parent); }
			var i, l=list.length;

			// capture & atTarget
			for (i=l-1; i>=0 && !eventObj.propagationStopped; i--) {
				list[i]._dispatchEvent(eventObj, 1+(i==0));
			}
			// bubbling
			for (i=1; i<l && !eventObj.propagationStopped; i++) {
				list[i]._dispatchEvent(eventObj, 3);
			}
		}
		return !eventObj.defaultPrevented;
	};

	/**
	 * Indicates whether there is at least one listener for the specified event type.
	 * @method hasEventListener
	 * @param {String} type The string type of the event.
	 * @return {Boolean} Returns true if there is at least one listener for the specified event.
	 **/
	p.hasEventListener = function(type) {
		var listeners = this._listeners, captureListeners = this._captureListeners;
		return !!((listeners && listeners[type]) || (captureListeners && captureListeners[type]));
	};
	
	/**
	 * Indicates whether there is at least one listener for the specified event type on this object or any of its
	 * ancestors (parent, parent's parent, etc). A return value of true indicates that if a bubbling event of the
	 * specified type is dispatched from this object, it will trigger at least one listener.
	 * 
	 * This is similar to {{#crossLink "EventDispatcher/hasEventListener"}}{{/crossLink}}, but it searches the entire
	 * event flow for a listener, not just this object.
	 * @method willTrigger
	 * @param {String} type The string type of the event.
	 * @return {Boolean} Returns `true` if there is at least one listener for the specified event.
	 **/
	p.willTrigger = function(type) {
		var o = this;
		while (o) {
			if (o.hasEventListener(type)) { return true; }
			o = o.parent;
		}
		return false;
	};

	/**
	 * @method toString
	 * @return {String} a string representation of the instance.
	 **/
	p.toString = function() {
		return "[EventDispatcher]";
	};


// private methods:
	/**
	 * @method _dispatchEvent
	 * @param {Object | String | Event} eventObj
	 * @param {Object} eventPhase
	 * @protected
	 **/
	p._dispatchEvent = function(eventObj, eventPhase) {
		var l, listeners = (eventPhase==1) ? this._captureListeners : this._listeners;
		if (eventObj && listeners) {
			var arr = listeners[eventObj.type];
			if (!arr||!(l=arr.length)) { return; }
			try { eventObj.currentTarget = this; } catch (e) {}
			try { eventObj.eventPhase = eventPhase; } catch (e) {}
			eventObj.removed = false;
			
			arr = arr.slice(); // to avoid issues with items being removed or added during the dispatch
			for (var i=0; i<l && !eventObj.immediatePropagationStopped; i++) {
				var o = arr[i];
				if (o.handleEvent) { o.handleEvent(eventObj); }
				else { o(eventObj); }
				if (eventObj.removed) {
					this.off(eventObj.type, o, eventPhase==1);
					eventObj.removed = false;
				}
			}
		}
	};


	createjs.EventDispatcher = EventDispatcher;
}());

//##############################################################################
// ProgressEvent.js
//##############################################################################

this.createjs = this.createjs || {};

(function (scope) {
	"use strict";

	// constructor
	/**
	 * A CreateJS {{#crossLink "Event"}}{{/crossLink}} that is dispatched when progress changes.
	 * @class ProgressEvent
	 * @param {Number} loaded The amount that has been loaded. This can be any number relative to the total.
	 * @param {Number} [total=1] The total amount that will load. This will default to 1, so if the `loaded` value is
	 * a percentage (between 0 and 1), it can be omitted.
	 * @todo Consider having this event be a "fileprogress" event as well
	 * @constructor
	 */
	function ProgressEvent(loaded, total) {
		this.Event_constructor("progress");

		/**
		 * The amount that has been loaded (out of a total amount)
		 * @property loaded
		 * @type {Number}
		 */
		this.loaded = loaded;

		/**
		 * The total "size" of the load.
		 * @property total
		 * @type {Number}
		 * @default 1
		 */
		this.total = (total == null) ? 1 : total;

		/**
		 * The percentage (out of 1) that the load has been completed. This is calculated using `loaded/total`.
		 * @property progress
		 * @type {Number}
		 * @default 0
		 */
		this.progress = (total == 0) ? 0 : this.loaded / this.total;
	};

	var p = createjs.extend(ProgressEvent, createjs.Event);

	/**
	 * Returns a clone of the ProgressEvent instance.
	 * @method clone
	 * @return {ProgressEvent} a clone of the Event instance.
	 **/
	p.clone = function() {
		return new createjs.ProgressEvent(this.loaded, this.total);
	};

	createjs.ProgressEvent = createjs.promote(ProgressEvent, "Event");

}(window));

//##############################################################################
// json3.js
//##############################################################################

/*! JSON v3.3.2 | http://bestiejs.github.io/json3 | Copyright 2012-2014, Kit Cambridge | http://kit.mit-license.org */
;(function () {
  // Detect the `define` function exposed by asynchronous module loaders. The
  // strict `define` check is necessary for compatibility with `r.js`.
  var isLoader = typeof define === "function" && define.amd;

  // A set of types used to distinguish objects from primitives.
  var objectTypes = {
    "function": true,
    "object": true
  };

  // Detect the `exports` object exposed by CommonJS implementations.
  var freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports;

  // Use the `global` object exposed by Node (including Browserify via
  // `insert-module-globals`), Narwhal, and Ringo as the default context,
  // and the `window` object in browsers. Rhino exports a `global` function
  // instead.
  var root = objectTypes[typeof window] && window || this,
      freeGlobal = freeExports && objectTypes[typeof module] && module && !module.nodeType && typeof global == "object" && global;

  if (freeGlobal && (freeGlobal["global"] === freeGlobal || freeGlobal["window"] === freeGlobal || freeGlobal["self"] === freeGlobal)) {
    root = freeGlobal;
  }

  // Public: Initializes JSON 3 using the given `context` object, attaching the
  // `stringify` and `parse` functions to the specified `exports` object.
  function runInContext(context, exports) {
    context || (context = root["Object"]());
    exports || (exports = root["Object"]());

    // Native constructor aliases.
    var Number = context["Number"] || root["Number"],
        String = context["String"] || root["String"],
        Object = context["Object"] || root["Object"],
        Date = context["Date"] || root["Date"],
        SyntaxError = context["SyntaxError"] || root["SyntaxError"],
        TypeError = context["TypeError"] || root["TypeError"],
        Math = context["Math"] || root["Math"],
        nativeJSON = context["JSON"] || root["JSON"];

    // Delegate to the native `stringify` and `parse` implementations.
    if (typeof nativeJSON == "object" && nativeJSON) {
      exports.stringify = nativeJSON.stringify;
      exports.parse = nativeJSON.parse;
    }

    // Convenience aliases.
    var objectProto = Object.prototype,
        getClass = objectProto.toString,
        isProperty, forEach, undef;

    // Test the `Date#getUTC*` methods. Based on work by @Yaffle.
    var isExtended = new Date(-3509827334573292);
    try {
      // The `getUTCFullYear`, `Month`, and `Date` methods return nonsensical
      // results for certain dates in Opera >= 10.53.
      isExtended = isExtended.getUTCFullYear() == -109252 && isExtended.getUTCMonth() === 0 && isExtended.getUTCDate() === 1 &&
        // Safari < 2.0.2 stores the internal millisecond time value correctly,
        // but clips the values returned by the date methods to the range of
        // signed 32-bit integers ([-2 ** 31, 2 ** 31 - 1]).
        isExtended.getUTCHours() == 10 && isExtended.getUTCMinutes() == 37 && isExtended.getUTCSeconds() == 6 && isExtended.getUTCMilliseconds() == 708;
    } catch (exception) {}

    // Internal: Determines whether the native `JSON.stringify` and `parse`
    // implementations are spec-compliant. Based on work by Ken Snyder.
    function has(name) {
      if (has[name] !== undef) {
        // Return cached feature test result.
        return has[name];
      }
      var isSupported;
      if (name == "bug-string-char-index") {
        // IE <= 7 doesn't support accessing string characters using square
        // bracket notation. IE 8 only supports this for primitives.
        isSupported = "a"[0] != "a";
      } else if (name == "json") {
        // Indicates whether both `JSON.stringify` and `JSON.parse` are
        // supported.
        isSupported = has("json-stringify") && has("json-parse");
      } else {
        var value, serialized = '{"a":[1,true,false,null,"\\u0000\\b\\n\\f\\r\\t"]}';
        // Test `JSON.stringify`.
        if (name == "json-stringify") {
          var stringify = exports.stringify, stringifySupported = typeof stringify == "function" && isExtended;
          if (stringifySupported) {
            // A test function object with a custom `toJSON` method.
            (value = function () {
              return 1;
            }).toJSON = value;
            try {
              stringifySupported =
                // Firefox 3.1b1 and b2 serialize string, number, and boolean
                // primitives as object literals.
                stringify(0) === "0" &&
                // FF 3.1b1, b2, and JSON 2 serialize wrapped primitives as object
                // literals.
                stringify(new Number()) === "0" &&
                stringify(new String()) == '""' &&
                // FF 3.1b1, 2 throw an error if the value is `null`, `undefined`, or
                // does not define a canonical JSON representation (this applies to
                // objects with `toJSON` properties as well, *unless* they are nested
                // within an object or array).
                stringify(getClass) === undef &&
                // IE 8 serializes `undefined` as `"undefined"`. Safari <= 5.1.7 and
                // FF 3.1b3 pass this test.
                stringify(undef) === undef &&
                // Safari <= 5.1.7 and FF 3.1b3 throw `Error`s and `TypeError`s,
                // respectively, if the value is omitted entirely.
                stringify() === undef &&
                // FF 3.1b1, 2 throw an error if the given value is not a number,
                // string, array, object, Boolean, or `null` literal. This applies to
                // objects with custom `toJSON` methods as well, unless they are nested
                // inside object or array literals. YUI 3.0.0b1 ignores custom `toJSON`
                // methods entirely.
                stringify(value) === "1" &&
                stringify([value]) == "[1]" &&
                // Prototype <= 1.6.1 serializes `[undefined]` as `"[]"` instead of
                // `"[null]"`.
                stringify([undef]) == "[null]" &&
                // YUI 3.0.0b1 fails to serialize `null` literals.
                stringify(null) == "null" &&
                // FF 3.1b1, 2 halts serialization if an array contains a function:
                // `[1, true, getClass, 1]` serializes as "[1,true,],". FF 3.1b3
                // elides non-JSON values from objects and arrays, unless they
                // define custom `toJSON` methods.
                stringify([undef, getClass, null]) == "[null,null,null]" &&
                // Simple serialization test. FF 3.1b1 uses Unicode escape sequences
                // where character escape codes are expected (e.g., `\b` => `\u0008`).
                stringify({ "a": [value, true, false, null, "\x00\b\n\f\r\t"] }) == serialized &&
                // FF 3.1b1 and b2 ignore the `filter` and `width` arguments.
                stringify(null, value) === "1" &&
                stringify([1, 2], null, 1) == "[\n 1,\n 2\n]" &&
                // JSON 2, Prototype <= 1.7, and older WebKit builds incorrectly
                // serialize extended years.
                stringify(new Date(-8.64e15)) == '"-271821-04-20T00:00:00.000Z"' &&
                // The milliseconds are optional in ES 5, but required in 5.1.
                stringify(new Date(8.64e15)) == '"+275760-09-13T00:00:00.000Z"' &&
                // Firefox <= 11.0 incorrectly serializes years prior to 0 as negative
                // four-digit years instead of six-digit years. Credits: @Yaffle.
                stringify(new Date(-621987552e5)) == '"-000001-01-01T00:00:00.000Z"' &&
                // Safari <= 5.1.5 and Opera >= 10.53 incorrectly serialize millisecond
                // values less than 1000. Credits: @Yaffle.
                stringify(new Date(-1)) == '"1969-12-31T23:59:59.999Z"';
            } catch (exception) {
              stringifySupported = false;
            }
          }
          isSupported = stringifySupported;
        }
        // Test `JSON.parse`.
        if (name == "json-parse") {
          var parse = exports.parse;
          if (typeof parse == "function") {
            try {
              // FF 3.1b1, b2 will throw an exception if a bare literal is provided.
              // Conforming implementations should also coerce the initial argument to
              // a string prior to parsing.
              if (parse("0") === 0 && !parse(false)) {
                // Simple parsing test.
                value = parse(serialized);
                var parseSupported = value["a"].length == 5 && value["a"][0] === 1;
                if (parseSupported) {
                  try {
                    // Safari <= 5.1.2 and FF 3.1b1 allow unescaped tabs in strings.
                    parseSupported = !parse('"\t"');
                  } catch (exception) {}
                  if (parseSupported) {
                    try {
                      // FF 4.0 and 4.0.1 allow leading `+` signs and leading
                      // decimal points. FF 4.0, 4.0.1, and IE 9-10 also allow
                      // certain octal literals.
                      parseSupported = parse("01") !== 1;
                    } catch (exception) {}
                  }
                  if (parseSupported) {
                    try {
                      // FF 4.0, 4.0.1, and Rhino 1.7R3-R4 allow trailing decimal
                      // points. These environments, along with FF 3.1b1 and 2,
                      // also allow trailing commas in JSON objects and arrays.
                      parseSupported = parse("1.") !== 1;
                    } catch (exception) {}
                  }
                }
              }
            } catch (exception) {
              parseSupported = false;
            }
          }
          isSupported = parseSupported;
        }
      }
      return has[name] = !!isSupported;
    }

    if (!has("json")) {
      // Common `[[Class]]` name aliases.
      var functionClass = "[object Function]",
          dateClass = "[object Date]",
          numberClass = "[object Number]",
          stringClass = "[object String]",
          arrayClass = "[object Array]",
          booleanClass = "[object Boolean]";

      // Detect incomplete support for accessing string characters by index.
      var charIndexBuggy = has("bug-string-char-index");

      // Define additional utility methods if the `Date` methods are buggy.
      if (!isExtended) {
        var floor = Math.floor;
        // A mapping between the months of the year and the number of days between
        // January 1st and the first of the respective month.
        var Months = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
        // Internal: Calculates the number of days between the Unix epoch and the
        // first day of the given month.
        var getDay = function (year, month) {
          return Months[month] + 365 * (year - 1970) + floor((year - 1969 + (month = +(month > 1))) / 4) - floor((year - 1901 + month) / 100) + floor((year - 1601 + month) / 400);
        };
      }

      // Internal: Determines if a property is a direct property of the given
      // object. Delegates to the native `Object#hasOwnProperty` method.
      if (!(isProperty = objectProto.hasOwnProperty)) {
        isProperty = function (property) {
          var members = {}, constructor;
          if ((members.__proto__ = null, members.__proto__ = {
            // The *proto* property cannot be set multiple times in recent
            // versions of Firefox and SeaMonkey.
            "toString": 1
          }, members).toString != getClass) {
            // Safari <= 2.0.3 doesn't implement `Object#hasOwnProperty`, but
            // supports the mutable *proto* property.
            isProperty = function (property) {
              // Capture and break the object's prototype chain (see section 8.6.2
              // of the ES 5.1 spec). The parenthesized expression prevents an
              // unsafe transformation by the Closure Compiler.
              var original = this.__proto__, result = property in (this.__proto__ = null, this);
              // Restore the original prototype chain.
              this.__proto__ = original;
              return result;
            };
          } else {
            // Capture a reference to the top-level `Object` constructor.
            constructor = members.constructor;
            // Use the `constructor` property to simulate `Object#hasOwnProperty` in
            // other environments.
            isProperty = function (property) {
              var parent = (this.constructor || constructor).prototype;
              return property in this && !(property in parent && this[property] === parent[property]);
            };
          }
          members = null;
          return isProperty.call(this, property);
        };
      }

      // Internal: Normalizes the `for...in` iteration algorithm across
      // environments. Each enumerated key is yielded to a `callback` function.
      forEach = function (object, callback) {
        var size = 0, Properties, members, property;

        // Tests for bugs in the current environment's `for...in` algorithm. The
        // `valueOf` property inherits the non-enumerable flag from
        // `Object.prototype` in older versions of IE, Netscape, and Mozilla.
        (Properties = function () {
          this.valueOf = 0;
        }).prototype.valueOf = 0;

        // Iterate over a new instance of the `Properties` class.
        members = new Properties();
        for (property in members) {
          // Ignore all properties inherited from `Object.prototype`.
          if (isProperty.call(members, property)) {
            size++;
          }
        }
        Properties = members = null;

        // Normalize the iteration algorithm.
        if (!size) {
          // A list of non-enumerable properties inherited from `Object.prototype`.
          members = ["valueOf", "toString", "toLocaleString", "propertyIsEnumerable", "isPrototypeOf", "hasOwnProperty", "constructor"];
          // IE <= 8, Mozilla 1.0, and Netscape 6.2 ignore shadowed non-enumerable
          // properties.
          forEach = function (object, callback) {
            var isFunction = getClass.call(object) == functionClass, property, length;
            var hasProperty = !isFunction && typeof object.constructor != "function" && objectTypes[typeof object.hasOwnProperty] && object.hasOwnProperty || isProperty;
            for (property in object) {
              // Gecko <= 1.0 enumerates the `prototype` property of functions under
              // certain conditions; IE does not.
              if (!(isFunction && property == "prototype") && hasProperty.call(object, property)) {
                callback(property);
              }
            }
            // Manually invoke the callback for each non-enumerable property.
            for (length = members.length; property = members[--length]; hasProperty.call(object, property) && callback(property));
          };
        } else if (size == 2) {
          // Safari <= 2.0.4 enumerates shadowed properties twice.
          forEach = function (object, callback) {
            // Create a set of iterated properties.
            var members = {}, isFunction = getClass.call(object) == functionClass, property;
            for (property in object) {
              // Store each property name to prevent double enumeration. The
              // `prototype` property of functions is not enumerated due to cross-
              // environment inconsistencies.
              if (!(isFunction && property == "prototype") && !isProperty.call(members, property) && (members[property] = 1) && isProperty.call(object, property)) {
                callback(property);
              }
            }
          };
        } else {
          // No bugs detected; use the standard `for...in` algorithm.
          forEach = function (object, callback) {
            var isFunction = getClass.call(object) == functionClass, property, isConstructor;
            for (property in object) {
              if (!(isFunction && property == "prototype") && isProperty.call(object, property) && !(isConstructor = property === "constructor")) {
                callback(property);
              }
            }
            // Manually invoke the callback for the `constructor` property due to
            // cross-environment inconsistencies.
            if (isConstructor || isProperty.call(object, (property = "constructor"))) {
              callback(property);
            }
          };
        }
        return forEach(object, callback);
      };

      // Public: Serializes a JavaScript `value` as a JSON string. The optional
      // `filter` argument may specify either a function that alters how object and
      // array members are serialized, or an array of strings and numbers that
      // indicates which properties should be serialized. The optional `width`
      // argument may be either a string or number that specifies the indentation
      // level of the output.
      if (!has("json-stringify")) {
        // Internal: A map of control characters and their escaped equivalents.
        var Escapes = {
          92: "\\\\",
          34: '\\"',
          8: "\\b",
          12: "\\f",
          10: "\\n",
          13: "\\r",
          9: "\\t"
        };

        // Internal: Converts `value` into a zero-padded string such that its
        // length is at least equal to `width`. The `width` must be <= 6.
        var leadingZeroes = "000000";
        var toPaddedString = function (width, value) {
          // The `|| 0` expression is necessary to work around a bug in
          // Opera <= 7.54u2 where `0 == -0`, but `String(-0) !== "0"`.
          return (leadingZeroes + (value || 0)).slice(-width);
        };

        // Internal: Double-quotes a string `value`, replacing all ASCII control
        // characters (characters with code unit values between 0 and 31) with
        // their escaped equivalents. This is an implementation of the
        // `Quote(value)` operation defined in ES 5.1 section 15.12.3.
        var unicodePrefix = "\\u00";
        var quote = function (value) {
          var result = '"', index = 0, length = value.length, useCharIndex = !charIndexBuggy || length > 10;
          var symbols = useCharIndex && (charIndexBuggy ? value.split("") : value);
          for (; index < length; index++) {
            var charCode = value.charCodeAt(index);
            // If the character is a control character, append its Unicode or
            // shorthand escape sequence; otherwise, append the character as-is.
            switch (charCode) {
              case 8: case 9: case 10: case 12: case 13: case 34: case 92:
                result += Escapes[charCode];
                break;
              default:
                if (charCode < 32) {
                  result += unicodePrefix + toPaddedString(2, charCode.toString(16));
                  break;
                }
                result += useCharIndex ? symbols[index] : value.charAt(index);
            }
          }
          return result + '"';
        };

        // Internal: Recursively serializes an object. Implements the
        // `Str(key, holder)`, `JO(value)`, and `JA(value)` operations.
        var serialize = function (property, object, callback, properties, whitespace, indentation, stack) {
          var value, className, year, month, date, time, hours, minutes, seconds, milliseconds, results, element, index, length, prefix, result;
          try {
            // Necessary for host object support.
            value = object[property];
          } catch (exception) {}
          if (typeof value == "object" && value) {
            className = getClass.call(value);
            if (className == dateClass && !isProperty.call(value, "toJSON")) {
              if (value > -1 / 0 && value < 1 / 0) {
                // Dates are serialized according to the `Date#toJSON` method
                // specified in ES 5.1 section 15.9.5.44. See section 15.9.1.15
                // for the ISO 8601 date time string format.
                if (getDay) {
                  // Manually compute the year, month, date, hours, minutes,
                  // seconds, and milliseconds if the `getUTC*` methods are
                  // buggy. Adapted from @Yaffle's `date-shim` project.
                  date = floor(value / 864e5);
                  for (year = floor(date / 365.2425) + 1970 - 1; getDay(year + 1, 0) <= date; year++);
                  for (month = floor((date - getDay(year, 0)) / 30.42); getDay(year, month + 1) <= date; month++);
                  date = 1 + date - getDay(year, month);
                  // The `time` value specifies the time within the day (see ES
                  // 5.1 section 15.9.1.2). The formula `(A % B + B) % B` is used
                  // to compute `A modulo B`, as the `%` operator does not
                  // correspond to the `modulo` operation for negative numbers.
                  time = (value % 864e5 + 864e5) % 864e5;
                  // The hours, minutes, seconds, and milliseconds are obtained by
                  // decomposing the time within the day. See section 15.9.1.10.
                  hours = floor(time / 36e5) % 24;
                  minutes = floor(time / 6e4) % 60;
                  seconds = floor(time / 1e3) % 60;
                  milliseconds = time % 1e3;
                } else {
                  year = value.getUTCFullYear();
                  month = value.getUTCMonth();
                  date = value.getUTCDate();
                  hours = value.getUTCHours();
                  minutes = value.getUTCMinutes();
                  seconds = value.getUTCSeconds();
                  milliseconds = value.getUTCMilliseconds();
                }
                // Serialize extended years correctly.
                value = (year <= 0 || year >= 1e4 ? (year < 0 ? "-" : "+") + toPaddedString(6, year < 0 ? -year : year) : toPaddedString(4, year)) +
                  "-" + toPaddedString(2, month + 1) + "-" + toPaddedString(2, date) +
                  // Months, dates, hours, minutes, and seconds should have two
                  // digits; milliseconds should have three.
                  "T" + toPaddedString(2, hours) + ":" + toPaddedString(2, minutes) + ":" + toPaddedString(2, seconds) +
                  // Milliseconds are optional in ES 5.0, but required in 5.1.
                  "." + toPaddedString(3, milliseconds) + "Z";
              } else {
                value = null;
              }
            } else if (typeof value.toJSON == "function" && ((className != numberClass && className != stringClass && className != arrayClass) || isProperty.call(value, "toJSON"))) {
              // Prototype <= 1.6.1 adds non-standard `toJSON` methods to the
              // `Number`, `String`, `Date`, and `Array` prototypes. JSON 3
              // ignores all `toJSON` methods on these objects unless they are
              // defined directly on an instance.
              value = value.toJSON(property);
            }
          }
          if (callback) {
            // If a replacement function was provided, call it to obtain the value
            // for serialization.
            value = callback.call(object, property, value);
          }
          if (value === null) {
            return "null";
          }
          className = getClass.call(value);
          if (className == booleanClass) {
            // Booleans are represented literally.
            return "" + value;
          } else if (className == numberClass) {
            // JSON numbers must be finite. `Infinity` and `NaN` are serialized as
            // `"null"`.
            return value > -1 / 0 && value < 1 / 0 ? "" + value : "null";
          } else if (className == stringClass) {
            // Strings are double-quoted and escaped.
            return quote("" + value);
          }
          // Recursively serialize objects and arrays.
          if (typeof value == "object") {
            // Check for cyclic structures. This is a linear search; performance
            // is inversely proportional to the number of unique nested objects.
            for (length = stack.length; length--;) {
              if (stack[length] === value) {
                // Cyclic structures cannot be serialized by `JSON.stringify`.
                throw TypeError();
              }
            }
            // Add the object to the stack of traversed objects.
            stack.push(value);
            results = [];
            // Save the current indentation level and indent one additional level.
            prefix = indentation;
            indentation += whitespace;
            if (className == arrayClass) {
              // Recursively serialize array elements.
              for (index = 0, length = value.length; index < length; index++) {
                element = serialize(index, value, callback, properties, whitespace, indentation, stack);
                results.push(element === undef ? "null" : element);
              }
              result = results.length ? (whitespace ? "[\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "]" : ("[" + results.join(",") + "]")) : "[]";
            } else {
              // Recursively serialize object members. Members are selected from
              // either a user-specified list of property names, or the object
              // itself.
              forEach(properties || value, function (property) {
                var element = serialize(property, value, callback, properties, whitespace, indentation, stack);
                if (element !== undef) {
                  // According to ES 5.1 section 15.12.3: "If `gap` {whitespace}
                  // is not the empty string, let `member` {quote(property) + ":"}
                  // be the concatenation of `member` and the `space` character."
                  // The "`space` character" refers to the literal space
                  // character, not the `space` {width} argument provided to
                  // `JSON.stringify`.
                  results.push(quote(property) + ":" + (whitespace ? " " : "") + element);
                }
              });
              result = results.length ? (whitespace ? "{\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "}" : ("{" + results.join(",") + "}")) : "{}";
            }
            // Remove the object from the traversed object stack.
            stack.pop();
            return result;
          }
        };

        // Public: `JSON.stringify`. See ES 5.1 section 15.12.3.
        exports.stringify = function (source, filter, width) {
          var whitespace, callback, properties, className;
          if (objectTypes[typeof filter] && filter) {
            if ((className = getClass.call(filter)) == functionClass) {
              callback = filter;
            } else if (className == arrayClass) {
              // Convert the property names array into a makeshift set.
              properties = {};
              for (var index = 0, length = filter.length, value; index < length; value = filter[index++], ((className = getClass.call(value)), className == stringClass || className == numberClass) && (properties[value] = 1));
            }
          }
          if (width) {
            if ((className = getClass.call(width)) == numberClass) {
              // Convert the `width` to an integer and create a string containing
              // `width` number of space characters.
              if ((width -= width % 1) > 0) {
                for (whitespace = "", width > 10 && (width = 10); whitespace.length < width; whitespace += " ");
              }
            } else if (className == stringClass) {
              whitespace = width.length <= 10 ? width : width.slice(0, 10);
            }
          }
          // Opera <= 7.54u2 discards the values associated with empty string keys
          // (`""`) only if they are used directly within an object member list
          // (e.g., `!("" in { "": 1})`).
          return serialize("", (value = {}, value[""] = source, value), callback, properties, whitespace, "", []);
        };
      }

      // Public: Parses a JSON source string.
      if (!has("json-parse")) {
        var fromCharCode = String.fromCharCode;

        // Internal: A map of escaped control characters and their unescaped
        // equivalents.
        var Unescapes = {
          92: "\\",
          34: '"',
          47: "/",
          98: "\b",
          116: "\t",
          110: "\n",
          102: "\f",
          114: "\r"
        };

        // Internal: Stores the parser state.
        var Index, Source;

        // Internal: Resets the parser state and throws a `SyntaxError`.
        var abort = function () {
          Index = Source = null;
          throw SyntaxError();
        };

        // Internal: Returns the next token, or `"$"` if the parser has reached
        // the end of the source string. A token may be a string, number, `null`
        // literal, or Boolean literal.
        var lex = function () {
          var source = Source, length = source.length, value, begin, position, isSigned, charCode;
          while (Index < length) {
            charCode = source.charCodeAt(Index);
            switch (charCode) {
              case 9: case 10: case 13: case 32:
                // Skip whitespace tokens, including tabs, carriage returns, line
                // feeds, and space characters.
                Index++;
                break;
              case 123: case 125: case 91: case 93: case 58: case 44:
                // Parse a punctuator token (`{`, `}`, `[`, `]`, `:`, or `,`) at
                // the current position.
                value = charIndexBuggy ? source.charAt(Index) : source[Index];
                Index++;
                return value;
              case 34:
                // `"` delimits a JSON string; advance to the next character and
                // begin parsing the string. String tokens are prefixed with the
                // sentinel `@` character to distinguish them from punctuators and
                // end-of-string tokens.
                for (value = "@", Index++; Index < length;) {
                  charCode = source.charCodeAt(Index);
                  if (charCode < 32) {
                    // Unescaped ASCII control characters (those with a code unit
                    // less than the space character) are not permitted.
                    abort();
                  } else if (charCode == 92) {
                    // A reverse solidus (`\`) marks the beginning of an escaped
                    // control character (including `"`, `\`, and `/`) or Unicode
                    // escape sequence.
                    charCode = source.charCodeAt(++Index);
                    switch (charCode) {
                      case 92: case 34: case 47: case 98: case 116: case 110: case 102: case 114:
                        // Revive escaped control characters.
                        value += Unescapes[charCode];
                        Index++;
                        break;
                      case 117:
                        // `\u` marks the beginning of a Unicode escape sequence.
                        // Advance to the first character and validate the
                        // four-digit code point.
                        begin = ++Index;
                        for (position = Index + 4; Index < position; Index++) {
                          charCode = source.charCodeAt(Index);
                          // A valid sequence comprises four hexdigits (case-
                          // insensitive) that form a single hexadecimal value.
                          if (!(charCode >= 48 && charCode <= 57 || charCode >= 97 && charCode <= 102 || charCode >= 65 && charCode <= 70)) {
                            // Invalid Unicode escape sequence.
                            abort();
                          }
                        }
                        // Revive the escaped character.
                        value += fromCharCode("0x" + source.slice(begin, Index));
                        break;
                      default:
                        // Invalid escape sequence.
                        abort();
                    }
                  } else {
                    if (charCode == 34) {
                      // An unescaped double-quote character marks the end of the
                      // string.
                      break;
                    }
                    charCode = source.charCodeAt(Index);
                    begin = Index;
                    // Optimize for the common case where a string is valid.
                    while (charCode >= 32 && charCode != 92 && charCode != 34) {
                      charCode = source.charCodeAt(++Index);
                    }
                    // Append the string as-is.
                    value += source.slice(begin, Index);
                  }
                }
                if (source.charCodeAt(Index) == 34) {
                  // Advance to the next character and return the revived string.
                  Index++;
                  return value;
                }
                // Unterminated string.
                abort();
              default:
                // Parse numbers and literals.
                begin = Index;
                // Advance past the negative sign, if one is specified.
                if (charCode == 45) {
                  isSigned = true;
                  charCode = source.charCodeAt(++Index);
                }
                // Parse an integer or floating-point value.
                if (charCode >= 48 && charCode <= 57) {
                  // Leading zeroes are interpreted as octal literals.
                  if (charCode == 48 && ((charCode = source.charCodeAt(Index + 1)), charCode >= 48 && charCode <= 57)) {
                    // Illegal octal literal.
                    abort();
                  }
                  isSigned = false;
                  // Parse the integer component.
                  for (; Index < length && ((charCode = source.charCodeAt(Index)), charCode >= 48 && charCode <= 57); Index++);
                  // Floats cannot contain a leading decimal point; however, this
                  // case is already accounted for by the parser.
                  if (source.charCodeAt(Index) == 46) {
                    position = ++Index;
                    // Parse the decimal component.
                    for (; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++);
                    if (position == Index) {
                      // Illegal trailing decimal.
                      abort();
                    }
                    Index = position;
                  }
                  // Parse exponents. The `e` denoting the exponent is
                  // case-insensitive.
                  charCode = source.charCodeAt(Index);
                  if (charCode == 101 || charCode == 69) {
                    charCode = source.charCodeAt(++Index);
                    // Skip past the sign following the exponent, if one is
                    // specified.
                    if (charCode == 43 || charCode == 45) {
                      Index++;
                    }
                    // Parse the exponential component.
                    for (position = Index; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++);
                    if (position == Index) {
                      // Illegal empty exponent.
                      abort();
                    }
                    Index = position;
                  }
                  // Coerce the parsed value to a JavaScript number.
                  return +source.slice(begin, Index);
                }
                // A negative sign may only precede numbers.
                if (isSigned) {
                  abort();
                }
                // `true`, `false`, and `null` literals.
                if (source.slice(Index, Index + 4) == "true") {
                  Index += 4;
                  return true;
                } else if (source.slice(Index, Index + 5) == "false") {
                  Index += 5;
                  return false;
                } else if (source.slice(Index, Index + 4) == "null") {
                  Index += 4;
                  return null;
                }
                // Unrecognized token.
                abort();
            }
          }
          // Return the sentinel `$` character if the parser has reached the end
          // of the source string.
          return "$";
        };

        // Internal: Parses a JSON `value` token.
        var get = function (value) {
          var results, hasMembers;
          if (value == "$") {
            // Unexpected end of input.
            abort();
          }
          if (typeof value == "string") {
            if ((charIndexBuggy ? value.charAt(0) : value[0]) == "@") {
              // Remove the sentinel `@` character.
              return value.slice(1);
            }
            // Parse object and array literals.
            if (value == "[") {
              // Parses a JSON array, returning a new JavaScript array.
              results = [];
              for (;; hasMembers || (hasMembers = true)) {
                value = lex();
                // A closing square bracket marks the end of the array literal.
                if (value == "]") {
                  break;
                }
                // If the array literal contains elements, the current token
                // should be a comma separating the previous element from the
                // next.
                if (hasMembers) {
                  if (value == ",") {
                    value = lex();
                    if (value == "]") {
                      // Unexpected trailing `,` in array literal.
                      abort();
                    }
                  } else {
                    // A `,` must separate each array element.
                    abort();
                  }
                }
                // Elisions and leading commas are not permitted.
                if (value == ",") {
                  abort();
                }
                results.push(get(value));
              }
              return results;
            } else if (value == "{") {
              // Parses a JSON object, returning a new JavaScript object.
              results = {};
              for (;; hasMembers || (hasMembers = true)) {
                value = lex();
                // A closing curly brace marks the end of the object literal.
                if (value == "}") {
                  break;
                }
                // If the object literal contains members, the current token
                // should be a comma separator.
                if (hasMembers) {
                  if (value == ",") {
                    value = lex();
                    if (value == "}") {
                      // Unexpected trailing `,` in object literal.
                      abort();
                    }
                  } else {
                    // A `,` must separate each object member.
                    abort();
                  }
                }
                // Leading commas are not permitted, object property names must be
                // double-quoted strings, and a `:` must separate each property
                // name and value.
                if (value == "," || typeof value != "string" || (charIndexBuggy ? value.charAt(0) : value[0]) != "@" || lex() != ":") {
                  abort();
                }
                results[value.slice(1)] = get(lex());
              }
              return results;
            }
            // Unexpected token encountered.
            abort();
          }
          return value;
        };

        // Internal: Updates a traversed object member.
        var update = function (source, property, callback) {
          var element = walk(source, property, callback);
          if (element === undef) {
            delete source[property];
          } else {
            source[property] = element;
          }
        };

        // Internal: Recursively traverses a parsed JSON object, invoking the
        // `callback` function for each value. This is an implementation of the
        // `Walk(holder, name)` operation defined in ES 5.1 section 15.12.2.
        var walk = function (source, property, callback) {
          var value = source[property], length;
          if (typeof value == "object" && value) {
            // `forEach` can't be used to traverse an array in Opera <= 8.54
            // because its `Object#hasOwnProperty` implementation returns `false`
            // for array indices (e.g., `![1, 2, 3].hasOwnProperty("0")`).
            if (getClass.call(value) == arrayClass) {
              for (length = value.length; length--;) {
                update(value, length, callback);
              }
            } else {
              forEach(value, function (property) {
                update(value, property, callback);
              });
            }
          }
          return callback.call(source, property, value);
        };

        // Public: `JSON.parse`. See ES 5.1 section 15.12.2.
        exports.parse = function (source, callback) {
          var result, value;
          Index = 0;
          Source = "" + source;
          result = get(lex());
          // If a JSON string contains multiple tokens, it is invalid.
          if (lex() != "$") {
            abort();
          }
          // Reset the parser state.
          Index = Source = null;
          return callback && getClass.call(callback) == functionClass ? walk((value = {}, value[""] = result, value), "", callback) : result;
        };
      }
    }

    exports["runInContext"] = runInContext;
    return exports;
  }

  if (freeExports && !isLoader) {
    // Export for CommonJS environments.
    runInContext(root, freeExports);
  } else {
    // Export for web browsers and JavaScript engines.
    var nativeJSON = root.JSON,
        previousJSON = root["JSON3"],
        isRestored = false;

    var JSON3 = runInContext(root, (root["JSON3"] = {
      // Public: Restores the original value of the global `JSON` object and
      // returns a reference to the `JSON3` object.
      "noConflict": function () {
        if (!isRestored) {
          isRestored = true;
          root.JSON = nativeJSON;
          root["JSON3"] = previousJSON;
          nativeJSON = previousJSON = null;
        }
        return JSON3;
      }
    }));

    root.JSON = {
      "parse": JSON3.parse,
      "stringify": JSON3.stringify
    };
  }

  // Export for asynchronous module loaders.
  if (isLoader) {
    define(function () {
      return JSON3;
    });
  }
}).call(this);

//##############################################################################
// DomUtils.js
//##############################################################################

(function () {

	/**
	 * A few utilities for interacting with the dom.
	 * @class DomUtils
	 */
	var s = {};

	s.appendToHead = function (el) {
		s.getHead().appendChild(el)
	}

	s.getHead = function () {
		return document.head || document.getElementsByTagName("head")[0];
	}

	s.getBody = function () {
		return document.body || document.getElementsByTagName("body")[0];
	}

	createjs.DomUtils = s;

}());

//##############################################################################
// DataUtils.js
//##############################################################################

(function () {

	/**
	 * A few data utilities for formatting different data types.
	 * @class DataUtils
	 */
	var s = {};

	// static methods
	/**
	 * Parse XML using the DOM. This is required when preloading XML or SVG.
	 * @method parseXML
	 * @param {String} text The raw text or XML that is loaded by XHR.
	 * @param {String} type The mime type of the XML. Use "text/xml" for XML, and  "image/svg+xml" for SVG parsing.
	 * @return {XML} An XML document
	 * @static
	 */
	s.parseXML = function (text, type) {
		var xml = null;
		// CocoonJS does not support XML parsing with either method.

		// Most browsers will use DOMParser
		// IE fails on certain SVG files, so we have a fallback below.
		try {
			if (window.DOMParser) {
				var parser = new DOMParser();
				xml = parser.parseFromString(text, type);
			}
		} catch (e) {
		}

		// Fallback for IE support.
		if (!xml) {
			try {
				xml = new ActiveXObject("Microsoft.XMLDOM");
				xml.async = false;
				xml.loadXML(text);
			} catch (e) {
				xml = null;
			}
		}

		return xml;
	};

	/**
	 * Parse a string into an Object.
	 * @method parseJSON
	 * @param {String} value The loaded JSON string
	 * @returns {Object} A JavaScript object.
	 */
	s.parseJSON = function (value) {
		if (value == null) {
			return null;
		}

		try {
			return JSON.parse(value);
		} catch (e) {
			// TODO; Handle this with a custom error?
			throw e;
		}
	};

	createjs.DataUtils = s;

}());

//##############################################################################
// LoadItem.js
//##############################################################################

this.createjs = this.createjs || {};

(function () {
	"use strict";

	/**
	 * All loaders accept an item containing the properties defined in this class. If a raw object is passed instead,
	 * it will not be affected, but it must contain at least a {{#crossLink "src:property"}}{{/crossLink}} property. A
	 * string path or HTML tag is also acceptable, but it will be automatically converted to a LoadItem using the
	 * {{#crossLink "create"}}{{/crossLink}} method by {{#crossLink "AbstractLoader"}}{{/crossLink}}
	 * @class LoadItem
	 * @constructor
	 * @since 0.6.0
	 */
	function LoadItem() {
		/**
		 * The source of the file that is being loaded. This property is <b>required</b>. The source can either be a
		 * string (recommended), or an HTML tag.
		 * This can also be an object, but in that case it has to include a type and be handled by a plugin.
		 * @property src
		 * @type {String}
		 * @default null
		 */
		this.src = null;

		/**
		 * The type file that is being loaded. The type of the file is usually inferred by the extension, but can also
		 * be set manually. This is helpful in cases where a file does not have an extension.
		 * @property type
		 * @type {String}
		 * @default null
		 */
		this.type = null;

		/**
		 * A string identifier which can be used to reference the loaded object. If none is provided, this will be
		 * automatically set to the {{#crossLink "src:property"}}{{/crossLink}}.
		 * @property id
		 * @type {String}
		 * @default null
		 */
		this.id = null;

		/**
		 * Determines if a manifest will maintain the order of this item, in relation to other items in the manifest
		 * that have also set the `maintainOrder` property to `true`. This only applies when the max connections has
		 * been set above 1 (using {{#crossLink "LoadQueue/setMaxConnections"}}{{/crossLink}}). Everything with this
		 * property set to `false` will finish as it is loaded. Ordered items are combined with script tags loading in
		 * order when {{#crossLink "LoadQueue/maintainScriptOrder:property"}}{{/crossLink}} is set to `true`.
		 * @property maintainOrder
		 * @type {Boolean}
		 * @default false
		 */
		this.maintainOrder = false;

		/**
		 * A callback used by JSONP requests that defines what global method to call when the JSONP content is loaded.
		 * @property callback
		 * @type {String}
		 * @default null
		 */
		this.callback = null;

		/**
		 * An arbitrary data object, which is included with the loaded object.
		 * @property data
		 * @type {Object}
		 * @default null
		 */
		this.data = null;

		/**
		 * The request method used for HTTP calls. Both {{#crossLink "AbstractLoader/GET:property"}}{{/crossLink}} or
		 * {{#crossLink "AbstractLoader/POST:property"}}{{/crossLink}} request types are supported, and are defined as
		 * constants on {{#crossLink "AbstractLoader"}}{{/crossLink}}.
		 * @property method
		 * @type {String}
		 * @default get
		 */
		this.method = createjs.LoadItem.GET;

		/**
		 * An object hash of name/value pairs to send to the server.
		 * @property values
		 * @type {Object}
		 * @default null
		 */
		this.values = null;

		/**
		 * An object hash of headers to attach to an XHR request. PreloadJS will automatically attach some default
		 * headers when required, including "Origin", "Content-Type", and "X-Requested-With". You may override the
		 * default headers by including them in your headers object.
		 * @property headers
		 * @type {Object}
		 * @default null
		 */
		this.headers = null;

		/**
		 * Enable credentials for XHR requests.
		 * @property withCredentials
		 * @type {Boolean}
		 * @default false
		 */
		this.withCredentials = false;

		/**
		 * Set the mime type of XHR-based requests. This is automatically set to "text/plain; charset=utf-8" for text
		 * based files (json, xml, text, css, js).
		 * @property mimeType
		 * @type {String}
		 * @default null
		 */
		this.mimeType = null;

		/**
		 * Sets the crossOrigin attribute for CORS-enabled images loading cross-domain.
		 * @property crossOrigin
		 * @type {boolean}
		 * @default Anonymous
		 */
		this.crossOrigin = null;

		/**
		 * The duration in milliseconds to wait before a request times out. This only applies to tag-based and and XHR
		 * (level one) loading, as XHR (level 2) provides its own timeout event.
		 * @property loadTimeout
		 * @type {Number}
		 * @default 8000 (8 seconds)
		 */
		this.loadTimeout = s.LOAD_TIMEOUT_DEFAULT;
	};

	var p = LoadItem.prototype = {};
	var s = LoadItem;

	/**
	 * Default duration in milliseconds to wait before a request times out. This only applies to tag-based and and XHR
	 * (level one) loading, as XHR (level 2) provides its own timeout event.
	 * @property LOAD_TIMEOUT_DEFAULT
	 * @type {number}
	 * @static
	 */
	s.LOAD_TIMEOUT_DEFAULT = 8000;

	/**
	 * Create a LoadItem.
	 * <ul>
	 *     <li>String-based items are converted to a LoadItem with a populated {{#crossLink "src:property"}}{{/crossLink}}.</li>
	 *     <li>LoadItem instances are returned as-is</li>
	 *     <li>Objects are returned with any needed properties added</li>
	 * </ul>
	 * @method create
	 * @param {LoadItem|String|Object} value The load item value
	 * @returns {LoadItem|Object}
	 * @static
	 */
	s.create = function (value) {
		if (typeof value == "string") {
			var item = new LoadItem();
			item.src = value;
			return item;
		} else if (value instanceof s) {
			return value;
		} else if (value instanceof Object && value.src) {
			if (value.loadTimeout == null) {
				value.loadTimeout = s.LOAD_TIMEOUT_DEFAULT;
			}
			return value;
		} else {
			throw new Error("Type not recognized.");
		}
	};

	/**
	 * Provides a chainable shortcut method for setting a number of properties on the instance.
	 *
	 * <h4>Example</h4>
	 *
	 *      var loadItem = new createjs.LoadItem().set({src:"image.png", maintainOrder:true});
	 *
	 * @method set
	 * @param {Object} props A generic object containing properties to copy to the LoadItem instance.
	 * @return {LoadItem} Returns the instance the method is called on (useful for chaining calls.)
	*/
	p.set = function(props) {
		for (var n in props) { this[n] = props[n]; }
		return this;
	};

	createjs.LoadItem = s;

}());

//##############################################################################
// RequestUtils.js
//##############################################################################

(function () {

	/**
	 * Utilities that assist with parsing load items, and determining file types, etc.
	 * @class RequestUtils
	 */
	var s = {};

	/**
	 * The Regular Expression used to test file URLS for an absolute path.
	 * @property ABSOLUTE_PATH
	 * @type {RegExp}
	 * @static
	 */
	s.ABSOLUTE_PATT = /^(?:\w+:)?\/{2}/i;

	/**
	 * The Regular Expression used to test file URLS for a relative path.
	 * @property RELATIVE_PATH
	 * @type {RegExp}
	 * @static
	 */
	s.RELATIVE_PATT = (/^[./]*?\//i);

	/**
	 * The Regular Expression used to test file URLS for an extension. Note that URIs must already have the query string
	 * removed.
	 * @property EXTENSION_PATT
	 * @type {RegExp}
	 * @static
	 */
	s.EXTENSION_PATT = /\/?[^/]+\.(\w{1,5})$/i;

	/**
	 * Parse a file path to determine the information we need to work with it. Currently, PreloadJS needs to know:
	 * <ul>
	 *     <li>If the path is absolute. Absolute paths start with a protocol (such as `http://`, `file://`, or
	 *     `//networkPath`)</li>
	 *     <li>If the path is relative. Relative paths start with `../` or `/path` (or similar)</li>
	 *     <li>The file extension. This is determined by the filename with an extension. Query strings are dropped, and
	 *     the file path is expected to follow the format `name.ext`.</li>
	 * </ul>
	 * @method parseURI
	 * @param {String} path
	 * @returns {Object} An Object with an `absolute` and `relative` Boolean values, as well as an optional 'extension`
	 * property, which is the lowercase extension.
	 * @static
	 */
	s.parseURI = function (path) {
		var info = {absolute: false, relative: false};
		if (path == null) { return info; }

		// Drop the query string
		var queryIndex = path.indexOf("?");
		if (queryIndex > -1) {
			path = path.substr(0, queryIndex);
		}

		// Absolute
		var match;
		if (s.ABSOLUTE_PATT.test(path)) {
			info.absolute = true;

			// Relative
		} else if (s.RELATIVE_PATT.test(path)) {
			info.relative = true;
		}

		// Extension
		if (match = path.match(s.EXTENSION_PATT)) {
			info.extension = match[1].toLowerCase();
		}
		return info;
	};

	/**
	 * Formats an object into a query string for either a POST or GET request.
	 * @method formatQueryString
	 * @param {Object} data The data to convert to a query string.
	 * @param {Array} [query] Existing name/value pairs to append on to this query.
	 * @static
	 */
	s.formatQueryString = function (data, query) {
		if (data == null) {
			throw new Error('You must specify data.');
		}
		var params = [];
		for (var n in data) {
			params.push(n + '=' + escape(data[n]));
		}
		if (query) {
			params = params.concat(query);
		}
		return params.join('&');
	};

	/**
	 * A utility method that builds a file path using a source and a data object, and formats it into a new path.
	 * @method buildPath
	 * @param {String} src The source path to add values to.
	 * @param {Object} [data] Object used to append values to this request as a query string. Existing parameters on the
	 * path will be preserved.
	 * @returns {string} A formatted string that contains the path and the supplied parameters.
	 * @static
	 */
	s.buildPath = function (src, data) {
		if (data == null) {
			return src;
		}

		var query = [];
		var idx = src.indexOf('?');

		if (idx != -1) {
			var q = src.slice(idx + 1);
			query = query.concat(q.split('&'));
		}

		if (idx != -1) {
			return src.slice(0, idx) + '?' + this.formatQueryString(data, query);
		} else {
			return src + '?' + this.formatQueryString(data, query);
		}
	};

	/**
	 * @method isCrossDomain
	 * @param {LoadItem|Object} item A load item with a `src` property.
	 * @return {Boolean} If the load item is loading from a different domain than the current location.
	 * @static
	 */
	s.isCrossDomain = function (item) {
		var target = document.createElement("a");
		target.href = item.src;

		var host = document.createElement("a");
		host.href = location.href;

		var crossdomain = (target.hostname != "") &&
						  (target.port != host.port ||
						   target.protocol != host.protocol ||
						   target.hostname != host.hostname);
		return crossdomain;
	};

	/**
	 * @method isLocal
	 * @param {LoadItem|Object} item A load item with a `src` property
	 * @return {Boolean} If the load item is loading from the "file:" protocol. Assume that the host must be local as
	 * well.
	 * @static
	 */
	s.isLocal = function (item) {
		var target = document.createElement("a");
		target.href = item.src;
		return target.hostname == "" && target.protocol == "file:";
	};

	/**
	 * Determine if a specific type should be loaded as a binary file. Currently, only images and items marked
	 * specifically as "binary" are loaded as binary. Note that audio is <b>not</b> a binary type, as we can not play
	 * back using an audio tag if it is loaded as binary. Plugins can change the item type to binary to ensure they get
	 * a binary result to work with. Binary files are loaded using XHR2. Types are defined as static constants on
	 * {{#crossLink "AbstractLoader"}}{{/crossLink}}.
	 * @method isBinary
	 * @param {String} type The item type.
	 * @return {Boolean} If the specified type is binary.
	 * @static
	 */
	s.isBinary = function (type) {
		switch (type) {
			case createjs.AbstractLoader.IMAGE:
			case createjs.AbstractLoader.BINARY:
				return true;
			default:
				return false;
		}
	};

	/**
	 * Check if item is a valid HTMLImageElement
	 * @method isImageTag
	 * @param {Object} item
	 * @returns {Boolean}
	 * @static
	 */
	s.isImageTag = function(item) {
		return item instanceof HTMLImageElement;
	};

	/**
	 * Check if item is a valid HTMLAudioElement
	 * @method isAudioTag
	 * @param {Object} item
	 * @returns {Boolean}
	 * @static
	 */
	s.isAudioTag = function(item) {
		if (window.HTMLAudioElement) {
			return item instanceof HTMLAudioElement;
		} else {
			return false;
		}
	};

	/**
	 * Check if item is a valid HTMLVideoElement
	 * @method isVideoTag
	 * @param {Object} item
	 * @returns {Boolean}
	 * @static
	 */
	s.isVideoTag = function(item) {
		if (window.HTMLVideoElement) {
			return item instanceof HTMLVideoElement;
		} else {
			return false;
		}
	};

	/**
	 * Determine if a specific type is a text-based asset, and should be loaded as UTF-8.
	 * @method isText
	 * @param {String} type The item type.
	 * @return {Boolean} If the specified type is text.
	 * @static
	 */
	s.isText = function (type) {
		switch (type) {
			case createjs.AbstractLoader.TEXT:
			case createjs.AbstractLoader.JSON:
			case createjs.AbstractLoader.MANIFEST:
			case createjs.AbstractLoader.XML:
			case createjs.AbstractLoader.CSS:
			case createjs.AbstractLoader.SVG:
			case createjs.AbstractLoader.JAVASCRIPT:
			case createjs.AbstractLoader.SPRITESHEET:
				return true;
			default:
				return false;
		}
	};

	/**
	 * Determine the type of the object using common extensions. Note that the type can be passed in with the load item
	 * if it is an unusual extension.
	 * @method getTypeByExtension
	 * @param {String} extension The file extension to use to determine the load type.
	 * @return {String} The determined load type (for example, <code>AbstractLoader.IMAGE</code>). Will return `null` if
	 * the type can not be determined by the extension.
	 * @static
	 */
	s.getTypeByExtension = function (extension) {
		if (extension == null) {
			return createjs.AbstractLoader.TEXT;
		}

		switch (extension.toLowerCase()) {
			case "jpeg":
			case "jpg":
			case "gif":
			case "png":
			case "webp":
			case "bmp":
				return createjs.AbstractLoader.IMAGE;
			case "ogg":
			case "mp3":
			case "webm":
				return createjs.AbstractLoader.SOUND;
			case "mp4":
			case "webm":
			case "ts":
				return createjs.AbstractLoader.VIDEO;
			case "json":
				return createjs.AbstractLoader.JSON;
			case "xml":
				return createjs.AbstractLoader.XML;
			case "css":
				return createjs.AbstractLoader.CSS;
			case "js":
				return createjs.AbstractLoader.JAVASCRIPT;
			case 'svg':
				return createjs.AbstractLoader.SVG;
			default:
				return createjs.AbstractLoader.TEXT;
		}
	};

	createjs.RequestUtils = s;

}());

//##############################################################################
// AbstractLoader.js
//##############################################################################

this.createjs = this.createjs || {};

(function () {
	"use strict";

// constructor
	/**
	 * The base loader, which defines all the generic methods, properties, and events. All loaders extend this class,
	 * including the {{#crossLink "LoadQueue"}}{{/crossLink}}.
	 * @class AbstractLoader
	 * @param {LoadItem|object|string} loadItem The item to be loaded.
	 * @param {Boolean} [preferXHR] Determines if the LoadItem should <em>try</em> and load using XHR, or take a
	 * tag-based approach, which can be better in cross-domain situations. Not all loaders can load using one or the
	 * other, so this is a suggested directive.
	 * @param {String} [type] The type of loader. Loader types are defined as constants on the AbstractLoader class,
	 * such as {{#crossLink "IMAGE:property"}}{{/crossLink}}, {{#crossLink "CSS:property"}}{{/crossLink}}, etc.
	 * @extends EventDispatcher
	 */
	function AbstractLoader(loadItem, preferXHR, type) {
		this.EventDispatcher_constructor();

		// public properties
		/**
		 * If the loader has completed loading. This provides a quick check, but also ensures that the different approaches
		 * used for loading do not pile up resulting in more than one `complete` {{#crossLink "Event"}}{{/crossLink}}.
		 * @property loaded
		 * @type {Boolean}
		 * @default false
		 */
		this.loaded = false;

		/**
		 * Determine if the loader was canceled. Canceled loads will not fire complete events. Note that this property
		 * is readonly, so {{#crossLink "LoadQueue"}}{{/crossLink}} queues should be closed using {{#crossLink "LoadQueue/close"}}{{/crossLink}}
		 * instead.
		 * @property canceled
		 * @type {Boolean}
		 * @default false
		 * @readonly
		 */
		this.canceled = false;

		/**
		 * The current load progress (percentage) for this item. This will be a number between 0 and 1.
		 *
		 * <h4>Example</h4>
		 *
		 *     var queue = new createjs.LoadQueue();
		 *     queue.loadFile("largeImage.png");
		 *     queue.on("progress", function() {
		 *         console.log("Progress:", queue.progress, event.progress);
		 *     });
		 *
		 * @property progress
		 * @type {Number}
		 * @default 0
		 */
		this.progress = 0;

		/**
		 * The type of item this loader will load. See {{#crossLink "AbstractLoader"}}{{/crossLink}} for a full list of
		 * supported types.
		 * @property type
		 * @type {String}
		 */
		this.type = type;

		/**
		 * A formatter function that converts the loaded raw result into the final result. For example, the JSONLoader
		 * converts a string of text into a JavaScript object. Not all loaders have a resultFormatter, and this property
		 * can be overridden to provide custom formatting.
		 *
		 * Optionally, a resultFormatter can return a callback function in cases where the formatting needs to be
		 * asynchronous, such as creating a new image. The callback function is passed 2 parameters, which are callbacks
		 * to handle success and error conditions in the resultFormatter. Note that the resultFormatter method is
		 * called in the current scope, as well as the success and error callbacks.
		 *
		 * <h4>Example asynchronous resultFormatter</h4>
		 *
		 * 	function _formatResult(loader) {
		 * 		return function(success, error) {
		 * 			if (errorCondition) { error(errorDetailEvent); }
		 * 			success(result);
		 * 		}
		 * 	}
		 * @property resultFormatter
		 * @type {Function}
		 * @default null
		 */
		this.resultFormatter = null;

		// protected properties
		/**
		 * The {{#crossLink "LoadItem"}}{{/crossLink}} this loader represents. Note that this is null in a {{#crossLink "LoadQueue"}}{{/crossLink}},
		 * but will be available on loaders such as {{#crossLink "XMLLoader"}}{{/crossLink}} and {{#crossLink "ImageLoader"}}{{/crossLink}}.
		 * @property _item
		 * @type {LoadItem|Object}
		 * @private
		 */
		if (loadItem) {
			this._item = createjs.LoadItem.create(loadItem);
		} else {
			this._item = null;
		}

		/**
		 * Whether the loader will try and load content using XHR (true) or HTML tags (false).
		 * @property _preferXHR
		 * @type {Boolean}
		 * @private
		 */
		this._preferXHR = preferXHR;

		/**
		 * The loaded result after it is formatted by an optional {{#crossLink "resultFormatter"}}{{/crossLink}}. For
		 * items that are not formatted, this will be the same as the {{#crossLink "_rawResult:property"}}{{/crossLink}}.
		 * The result is accessed using the {{#crossLink "getResult"}}{{/crossLink}} method.
		 * @property _result
		 * @type {Object|String}
		 * @private
		 */
		this._result = null;

		/**
		 * The loaded result before it is formatted. The rawResult is accessed using the {{#crossLink "getResult"}}{{/crossLink}}
		 * method, and passing `true`.
		 * @property _rawResult
		 * @type {Object|String}
		 * @private
		 */
		this._rawResult = null;

		/**
		 * A list of items that loaders load behind the scenes. This does not include the main item the loader is
		 * responsible for loading. Examples of loaders that have sub-items include the {{#crossLink "SpriteSheetLoader"}}{{/crossLink}} and
		 * {{#crossLink "ManifestLoader"}}{{/crossLink}}.
		 * @property _loadItems
		 * @type {null}
		 * @protected
		 */
		this._loadedItems = null;

		/**
		 * The attribute the items loaded using tags use for the source.
		 * @type {string}
		 * @default null
		 * @private
		 */
		this._tagSrcAttribute = null;

		/**
		 * An HTML tag (or similar) that a loader may use to load HTML content, such as images, scripts, etc.
		 * @property _tag
		 * @type {Object}
		 * @private
		 */
		this._tag = null;
	};

	var p = createjs.extend(AbstractLoader, createjs.EventDispatcher);
	var s = AbstractLoader;

	// TODO: deprecated
	// p.initialize = function() {}; // searchable for devs wondering where it is. REMOVED. See docs for details.


	/**
	 * Defines a POST request, use for a method value when loading data.
	 * @property POST
	 * @type {string}
	 * @default post
	 * @static
	 */
	s.POST = "POST";

	/**
	 * Defines a GET request, use for a method value when loading data.
	 * @property GET
	 * @type {string}
	 * @default get
	 * @static
	 */
	s.GET = "GET";

	/**
	 * The preload type for generic binary types. Note that images are loaded as binary files when using XHR.
	 * @property BINARY
	 * @type {String}
	 * @default binary
	 * @static
	 * @since 0.6.0
	 */
	s.BINARY = "binary";

	/**
	 * The preload type for css files. CSS files are loaded using a &lt;link&gt; when loaded with XHR, or a
	 * &lt;style&gt; tag when loaded with tags.
	 * @property CSS
	 * @type {String}
	 * @default css
	 * @static
	 * @since 0.6.0
	 */
	s.CSS = "css";

	/**
	 * The preload type for image files, usually png, gif, or jpg/jpeg. Images are loaded into an &lt;image&gt; tag.
	 * @property IMAGE
	 * @type {String}
	 * @default image
	 * @static
	 * @since 0.6.0
	 */
	s.IMAGE = "image";

	/**
	 * The preload type for javascript files, usually with the "js" file extension. JavaScript files are loaded into a
	 * &lt;script&gt; tag.
	 *
	 * Since version 0.4.1+, due to how tag-loaded scripts work, all JavaScript files are automatically injected into
	 * the body of the document to maintain parity between XHR and tag-loaded scripts. In version 0.4.0 and earlier,
	 * only tag-loaded scripts are injected.
	 * @property JAVASCRIPT
	 * @type {String}
	 * @default javascript
	 * @static
	 * @since 0.6.0
	 */
	s.JAVASCRIPT = "javascript";

	/**
	 * The preload type for json files, usually with the "json" file extension. JSON data is loaded and parsed into a
	 * JavaScript object. Note that if a `callback` is present on the load item, the file will be loaded with JSONP,
	 * no matter what the {{#crossLink "LoadQueue/preferXHR:property"}}{{/crossLink}} property is set to, and the JSON
	 * must contain a matching wrapper function.
	 * @property JSON
	 * @type {String}
	 * @default json
	 * @static
	 * @since 0.6.0
	 */
	s.JSON = "json";

	/**
	 * The preload type for jsonp files, usually with the "json" file extension. JSON data is loaded and parsed into a
	 * JavaScript object. You are required to pass a callback parameter that matches the function wrapper in the JSON.
	 * Note that JSONP will always be used if there is a callback present, no matter what the {{#crossLink "LoadQueue/preferXHR:property"}}{{/crossLink}}
	 * property is set to.
	 * @property JSONP
	 * @type {String}
	 * @default jsonp
	 * @static
	 * @since 0.6.0
	 */
	s.JSONP = "jsonp";

	/**
	 * The preload type for json-based manifest files, usually with the "json" file extension. The JSON data is loaded
	 * and parsed into a JavaScript object. PreloadJS will then look for a "manifest" property in the JSON, which is an
	 * Array of files to load, following the same format as the {{#crossLink "LoadQueue/loadManifest"}}{{/crossLink}}
	 * method. If a "callback" is specified on the manifest object, then it will be loaded using JSONP instead,
	 * regardless of what the {{#crossLink "LoadQueue/preferXHR:property"}}{{/crossLink}} property is set to.
	 * @property MANIFEST
	 * @type {String}
	 * @default manifest
	 * @static
	 * @since 0.6.0
	 */
	s.MANIFEST = "manifest";

	/**
	 * The preload type for sound files, usually mp3, ogg, or wav. When loading via tags, audio is loaded into an
	 * &lt;audio&gt; tag.
	 * @property SOUND
	 * @type {String}
	 * @default sound
	 * @static
	 * @since 0.6.0
	 */
	s.SOUND = "sound";

	/**
	 * The preload type for video files, usually mp4, ts, or ogg. When loading via tags, video is loaded into an
	 * &lt;video&gt; tag.
	 * @property VIDEO
	 * @type {String}
	 * @default video
	 * @static
	 * @since 0.6.0
	 */
	s.VIDEO = "video";

	/**
	 * The preload type for SpriteSheet files. SpriteSheet files are JSON files that contain string image paths.
	 * @property SPRITESHEET
	 * @type {String}
	 * @default spritesheet
	 * @static
	 * @since 0.6.0
	 */
	s.SPRITESHEET = "spritesheet";

	/**
	 * The preload type for SVG files.
	 * @property SVG
	 * @type {String}
	 * @default svg
	 * @static
	 * @since 0.6.0
	 */
	s.SVG = "svg";

	/**
	 * The preload type for text files, which is also the default file type if the type can not be determined. Text is
	 * loaded as raw text.
	 * @property TEXT
	 * @type {String}
	 * @default text
	 * @static
	 * @since 0.6.0
	 */
	s.TEXT = "text";

	/**
	 * The preload type for xml files. XML is loaded into an XML document.
	 * @property XML
	 * @type {String}
	 * @default xml
	 * @static
	 * @since 0.6.0
	 */
	s.XML = "xml";

// Events
	/**
	 * The {{#crossLink "ProgressEvent"}}{{/crossLink}} that is fired when the overall progress changes. Prior to
	 * version 0.6.0, this was just a regular {{#crossLink "Event"}}{{/crossLink}}.
	 * @event progress
	 * @since 0.3.0
	 */

	/**
	 * The {{#crossLink "Event"}}{{/crossLink}} that is fired when a load starts.
	 * @event loadstart
	 * @param {Object} target The object that dispatched the event.
	 * @param {String} type The event type.
	 * @since 0.3.1
	 */

	/**
	 * The {{#crossLink "Event"}}{{/crossLink}} that is fired when the entire queue has been loaded.
	 * @event complete
	 * @param {Object} target The object that dispatched the event.
	 * @param {String} type The event type.
	 * @since 0.3.0
	 */

	/**
	 * The {{#crossLink "ErrorEvent"}}{{/crossLink}} that is fired when the loader encounters an error. If the error was
	 * encountered by a file, the event will contain the item that caused the error. Prior to version 0.6.0, this was
	 * just a regular {{#crossLink "Event"}}{{/crossLink}}.
	 * @event error
	 * @since 0.3.0
	 */

	/**
	 * The {{#crossLink "Event"}}{{/crossLink}} that is fired when the loader encounters an internal file load error.
	 * This enables loaders to maintain internal queues, and surface file load errors.
	 * @event fileerror
	 * @param {Object} target The object that dispatched the event.
	 * @param {String} type The even type ("fileerror")
	 * @param {LoadItem|object} The item that encountered the error
	 * @since 0.6.0
	 */

	/**
	 * The {{#crossLink "Event"}}{{/crossLink}} that is fired when a loader internally loads a file. This enables
	 * loaders such as {{#crossLink "ManifestLoader"}}{{/crossLink}} to maintain internal {{#crossLink "LoadQueue"}}{{/crossLink}}s
	 * and notify when they have loaded a file. The {{#crossLink "LoadQueue"}}{{/crossLink}} class dispatches a
	 * slightly different {{#crossLink "LoadQueue/fileload:event"}}{{/crossLink}} event.
	 * @event fileload
	 * @param {Object} target The object that dispatched the event.
	 * @param {String} type The event type ("fileload")
	 * @param {Object} item The file item which was specified in the {{#crossLink "LoadQueue/loadFile"}}{{/crossLink}}
	 * or {{#crossLink "LoadQueue/loadManifest"}}{{/crossLink}} call. If only a string path or tag was specified, the
	 * object will contain that value as a `src` property.
	 * @param {Object} result The HTML tag or parsed result of the loaded item.
	 * @param {Object} rawResult The unprocessed result, usually the raw text or binary data before it is converted
	 * to a usable object.
	 * @since 0.6.0
	 */

	/**
	 * The {{#crossLink "Event"}}{{/crossLink}} that is fired after the internal request is created, but before a load.
	 * This allows updates to the loader for specific loading needs, such as binary or XHR image loading.
	 * @event initialize
	 * @param {Object} target The object that dispatched the event.
	 * @param {String} type The event type ("initialize")
	 * @param {AbstractLoader} loader The loader that has been initialized.
	 */


	/**
	 * Get a reference to the manifest item that is loaded by this loader. In some cases this will be the value that was
	 * passed into {{#crossLink "LoadQueue"}}{{/crossLink}} using {{#crossLink "LoadQueue/loadFile"}}{{/crossLink}} or
	 * {{#crossLink "LoadQueue/loadManifest"}}{{/crossLink}}. However if only a String path was passed in, then it will
	 * be a {{#crossLink "LoadItem"}}{{/crossLink}}.
	 * @method getItem
	 * @return {Object} The manifest item that this loader is responsible for loading.
	 * @since 0.6.0
	 */
	p.getItem = function () {
		return this._item;
	};

	/**
	 * Get a reference to the content that was loaded by the loader (only available after the {{#crossLink "complete:event"}}{{/crossLink}}
	 * event is dispatched.
	 * @method getResult
	 * @param {Boolean} [raw=false] Determines if the returned result will be the formatted content, or the raw loaded
	 * data (if it exists).
	 * @return {Object}
	 * @since 0.6.0
	 */
	p.getResult = function (raw) {
		return raw ? this._rawResult : this._result;
	};

	/**
	 * Return the `tag` this object creates or uses for loading.
	 * @method getTag
	 * @return {Object} The tag instance
	 * @since 0.6.0
	 */
	p.getTag = function () {
		return this._tag;
	};

	/**
	 * Set the `tag` this item uses for loading.
	 * @method setTag
	 * @param {Object} tag The tag instance
	 * @since 0.6.0
	 */
	p.setTag = function(tag) {
	  this._tag = tag;
	};

	/**
	 * Begin loading the item. This method is required when using a loader by itself.
	 *
	 * <h4>Example</h4>
	 *
	 *      var queue = new createjs.LoadQueue();
	 *      queue.on("complete", handleComplete);
	 *      queue.loadManifest(fileArray, false); // Note the 2nd argument that tells the queue not to start loading yet
	 *      queue.load();
	 *
	 * @method load
	 */
	p.load = function () {
		this._createRequest();

		this._request.on("complete", this, this);
		this._request.on("progress", this, this);
		this._request.on("loadStart", this, this);
		this._request.on("abort", this, this);
		this._request.on("timeout", this, this);
		this._request.on("error", this, this);

		var evt = new createjs.Event("initialize");
		evt.loader = this._request;
		this.dispatchEvent(evt);

		this._request.load();
	};

	/**
	 * Close the the item. This will stop any open requests (although downloads using HTML tags may still continue in
	 * the background), but events will not longer be dispatched.
	 * @method cancel
	 */
	p.cancel = function () {
		this.canceled = true;
		this.destroy();
	};

	/**
	 * Clean up the loader.
	 * @method destroy
	 */
	p.destroy = function() {
		if (this._request) {
			this._request.removeAllEventListeners();
			this._request.destroy();
		}

		this._request = null;

		this._item = null;
		this._rawResult = null;
		this._result = null;

		this._loadItems = null;

		this.removeAllEventListeners();
	};

	/**
	 * Get any items loaded internally by the loader. The enables loaders such as {{#crossLink "ManifestLoader"}}{{/crossLink}}
	 * to expose items it loads internally.
	 * @method getLoadedItems
	 * @return {Array} A list of the items loaded by the loader.
	 * @since 0.6.0
	 */
	p.getLoadedItems = function () {
		return this._loadedItems;
	};


	// Private methods
	/**
	 * Create an internal request used for loading. By default, an {{#crossLink "XHRRequest"}}{{/crossLink}} or
	 * {{#crossLink "TagRequest"}}{{/crossLink}} is created, depending on the value of {{#crossLink "preferXHR:property"}}{{/crossLink}}.
	 * Other loaders may override this to use different request types, such as {{#crossLink "ManifestLoader"}}{{/crossLink}},
	 * which uses {{#crossLink "JSONLoader"}}{{/crossLink}} or {{#crossLink "JSONPLoader"}}{{/crossLink}} under the hood.
	 * @method _createRequest
	 * @protected
	 */
	p._createRequest = function() {
		if (!this._preferXHR) {
			this._request = new createjs.TagRequest(this._item, this._tag || this._createTag(), this._tagSrcAttribute);
		} else {
			this._request = new createjs.XHRRequest(this._item);
		}
	};

	/**
	 * Create the HTML tag used for loading. This method does nothing by default, and needs to be implemented
	 * by loaders that require tag loading.
	 * @method _createTag
	 * @param {String} src The tag source
	 * @return {HTMLElement} The tag that was created
	 * @protected
	 */
	p._createTag = function(src) { return null; };

	/**
	 * Dispatch a loadstart {{#crossLink "Event"}}{{/crossLink}}. Please see the {{#crossLink "AbstractLoader/loadstart:event"}}{{/crossLink}}
	 * event for details on the event payload.
	 * @method _sendLoadStart
	 * @protected
	 */
	p._sendLoadStart = function () {
		if (this._isCanceled()) { return; }
		this.dispatchEvent("loadstart");
	};

	/**
	 * Dispatch a {{#crossLink "ProgressEvent"}}{{/crossLink}}.
	 * @method _sendProgress
	 * @param {Number | Object} value The progress of the loaded item, or an object containing <code>loaded</code>
	 * and <code>total</code> properties.
	 * @protected
	 */
	p._sendProgress = function (value) {
		if (this._isCanceled()) { return; }
		var event = null;
		if (typeof(value) == "number") {
			this.progress = value;
			event = new createjs.ProgressEvent(this.progress);
		} else {
			event = value;
			this.progress = value.loaded / value.total;
			event.progress = this.progress;
			if (isNaN(this.progress) || this.progress == Infinity) { this.progress = 0; }
		}
		this.hasEventListener("progress") && this.dispatchEvent(event);
	};

	/**
	 * Dispatch a complete {{#crossLink "Event"}}{{/crossLink}}. Please see the {{#crossLink "AbstractLoader/complete:event"}}{{/crossLink}} event
	 * @method _sendComplete
	 * @protected
	 */
	p._sendComplete = function () {
		if (this._isCanceled()) { return; }

		this.loaded = true;

		var event = new createjs.Event("complete");
		event.rawResult = this._rawResult;

		if (this._result != null) {
			event.result = this._result;
		}

		this.dispatchEvent(event);
	};

	/**
	 * Dispatch an error {{#crossLink "Event"}}{{/crossLink}}. Please see the {{#crossLink "AbstractLoader/error:event"}}{{/crossLink}}
	 * event for details on the event payload.
	 * @method _sendError
	 * @param {ErrorEvent} event The event object containing specific error properties.
	 * @protected
	 */
	p._sendError = function (event) {
		if (this._isCanceled() || !this.hasEventListener("error")) { return; }
		if (event == null) {
			event = new createjs.ErrorEvent("PRELOAD_ERROR_EMPTY"); // TODO: Populate error
		}
		this.dispatchEvent(event);
	};

	/**
	 * Determine if the load has been canceled. This is important to ensure that method calls or asynchronous events
	 * do not cause issues after the queue has been cleaned up.
	 * @method _isCanceled
	 * @return {Boolean} If the loader has been canceled.
	 * @protected
	 */
	p._isCanceled = function () {
		if (window.createjs == null || this.canceled) {
			return true;
		}
		return false;
	};

	/**
	 * A custom result formatter function, which is called just before a request dispatches its complete event. Most
	 * loader types already have an internal formatter, but this can be user-overridden for custom formatting. The
	 * formatted result will be available on Loaders using {{#crossLink "getResult"}}{{/crossLink}}, and passing `true`.
	 * @property resultFormatter
	 * @type Function
	 * @return {Object} The formatted result
	 * @since 0.6.0
	 */
	p.resultFormatter = null;

	/**
	 * Handle events from internal requests. By default, loaders will handle, and redispatch the necessary events, but
	 * this method can be overridden for custom behaviours.
	 * @method handleEvent
	 * @param {Event} event The event that the internal request dispatches.
	 * @protected
	 * @since 0.6.0
	 */
	p.handleEvent = function (event) {
		switch (event.type) {
			case "complete":
				this._rawResult = event.target._response;
				var result = this.resultFormatter && this.resultFormatter(this);
				if (result instanceof Function) {
					result.call(this,
							createjs.proxy(this._resultFormatSuccess, this),
							createjs.proxy(this._resultFormatFailed, this)
					);
				} else {
					this._result =  result || this._rawResult;
					this._sendComplete();
				}
				break;
			case "progress":
				this._sendProgress(event);
				break;
			case "error":
				this._sendError(event);
				break;
			case "loadstart":
				this._sendLoadStart();
				break;
			case "abort":
			case "timeout":
				if (!this._isCanceled()) {
					this.dispatchEvent(new createjs.ErrorEvent("PRELOAD_" + event.type.toUpperCase() + "_ERROR"));
				}
				break;
		}
	};

	/**
	 * The "success" callback passed to {{#crossLink "AbstractLoader/resultFormatter"}}{{/crossLink}} asynchronous
	 * functions.
	 * @method _resultFormatSuccess
	 * @param {Object} result The formatted result
	 * @private
	 */
	p._resultFormatSuccess = function (result) {
		this._result = result;
		this._sendComplete();
	};

	/**
	 * The "error" callback passed to {{#crossLink "AbstractLoader/resultFormatter"}}{{/crossLink}} asynchronous
	 * functions.
	 * @method _resultFormatSuccess
	 * @param {Object} error The error event
	 * @private
	 */
	p._resultFormatFailed = function (event) {
		this._sendError(event);
	};

	/**
	 * @method buildPath
	 * @protected
	 * @deprecated Use the {{#crossLink "RequestUtils"}}{{/crossLink}} method {{#crossLink "RequestUtils/buildPath"}}{{/crossLink}}
	 * instead.
	 */
	p.buildPath = function (src, data) {
		return createjs.RequestUtils.buildPath(src, data);
	};

	/**
	 * @method toString
	 * @return {String} a string representation of the instance.
	 */
	p.toString = function () {
		return "[PreloadJS AbstractLoader]";
	};

	createjs.AbstractLoader = createjs.promote(AbstractLoader, "EventDispatcher");

}());

//##############################################################################
// AbstractMediaLoader.js
//##############################################################################

this.createjs = this.createjs || {};

(function () {
	"use strict";

	// constructor
	/**
	 * The AbstractMediaLoader is a base class that handles some of the shared methods and properties of loaders that
	 * handle HTML media elements, such as Video and Audio.
	 * @class AbstractMediaLoader
	 * @param {LoadItem|Object} loadItem
	 * @param {Boolean} preferXHR
	 * @param {String} type The type of media to load. Usually "video" or "audio".
	 * @extends AbstractLoader
	 * @constructor
	 */
	function AbstractMediaLoader(loadItem, preferXHR, type) {
		this.AbstractLoader_constructor(loadItem, preferXHR, type);

		// public properties
		this.resultFormatter = this._formatResult;

		// protected properties
		this._tagSrcAttribute = "src";

        this.on("initialize", this._updateXHR, this);
	};

	var p = createjs.extend(AbstractMediaLoader, createjs.AbstractLoader);

	// static properties
	// public methods
	p.load = function () {
		// TagRequest will handle most of this, but Sound / Video need a few custom properties, so just handle them here.
		if (!this._tag) {
			this._tag = this._createTag(this._item.src);
		}

		this._tag.preload = "auto";
		this._tag.load();

		this.AbstractLoader_load();
	};

	// protected methods
	/**
	 * Creates a new tag for loading if it doesn't exist yet.
	 * @method _createTag
	 * @private
	 */
	p._createTag = function () {};


	p._createRequest = function() {
		if (!this._preferXHR) {
			this._request = new createjs.MediaTagRequest(this._item, this._tag || this._createTag(), this._tagSrcAttribute);
		} else {
			this._request = new createjs.XHRRequest(this._item);
		}
	};

    // protected methods
    /**
     * Before the item loads, set its mimeType and responseType.
     * @property _updateXHR
     * @param {Event} event
     * @private
     */
    p._updateXHR = function (event) {
        // Only exists for XHR
        if (event.loader.setResponseType) {
            event.loader.setResponseType("blob");
        }
    };

	/**
	 * The result formatter for media files.
	 * @method _formatResult
	 * @param {AbstractLoader} loader
	 * @returns {HTMLVideoElement|HTMLAudioElement}
	 * @private
	 */
	p._formatResult = function (loader) {
		this._tag.removeEventListener && this._tag.removeEventListener("canplaythrough", this._loadedHandler);
		this._tag.onstalled = null;
		if (this._preferXHR) {
            var URL = window.URL || window.webkitURL;
            var result = loader.getResult(true);

			loader.getTag().src = URL.createObjectURL(result);
		}
		return loader.getTag();
	};

	createjs.AbstractMediaLoader = createjs.promote(AbstractMediaLoader, "AbstractLoader");

}());

//##############################################################################
// AbstractRequest.js
//##############################################################################

this.createjs = this.createjs || {};

(function () {
	"use strict";

	/**
	 * A base class for actual data requests, such as {{#crossLink "XHRRequest"}}{{/crossLink}}, {{#crossLink "TagRequest"}}{{/crossLink}},
	 * and {{#crossLink "MediaRequest"}}{{/crossLink}}. PreloadJS loaders will typically use a data loader under the
	 * hood to get data.
	 * @class AbstractRequest
	 * @param {LoadItem} item
	 * @constructor
	 */
	var AbstractRequest = function (item) {
		this._item = item;
	};

	var p = createjs.extend(AbstractRequest, createjs.EventDispatcher);

	// public methods
	/**
	 * Begin a load.
	 * @method load
	 */
	p.load =  function() {};

	/**
	 * Clean up a request.
	 * @method destroy
	 */
	p.destroy = function() {};

	/**
	 * Cancel an in-progress request.
	 * @method cancel
	 */
	p.cancel = function() {};

	createjs.AbstractRequest = createjs.promote(AbstractRequest, "EventDispatcher");

}());

//##############################################################################
// TagRequest.js
//##############################################################################

this.createjs = this.createjs || {};

(function () {
	"use strict";

	// constructor
	/**
	 * An {{#crossLink "AbstractRequest"}}{{/crossLink}} that loads HTML tags, such as images and scripts.
	 * @class TagRequest
	 * @param {LoadItem} loadItem
	 * @param {HTMLElement} tag
	 * @param {String} srcAttribute The tag attribute that specifies the source, such as "src", "href", etc.
	 */
	function TagRequest(loadItem, tag, srcAttribute) {
		this.AbstractRequest_constructor(loadItem);

		// protected properties
		/**
		 * The HTML tag instance that is used to load.
		 * @property _tag
		 * @type {HTMLElement}
		 * @protected
		 */
		this._tag = tag;

		/**
		 * The tag attribute that specifies the source, such as "src", "href", etc.
		 * @property _tagSrcAttribute
		 * @type {String}
		 * @protected
		 */
		this._tagSrcAttribute = srcAttribute;

		/**
		 * A method closure used for handling the tag load event.
		 * @property _loadedHandler
		 * @type {Function}
		 * @private
		 */
		this._loadedHandler = createjs.proxy(this._handleTagComplete, this);

		/**
		 * Determines if the element was added to the DOM automatically by PreloadJS, so it can be cleaned up after.
		 * @property _addedToDOM
		 * @type {Boolean}
		 * @private
		 */
		this._addedToDOM = false;

		/**
		 * Determines what the tags initial style.visibility was, so we can set it correctly after a load.
		 *
		 * @type {null}
		 * @private
		 */
		this._startTagVisibility = null;
	};

	var p = createjs.extend(TagRequest, createjs.AbstractRequest);

	// public methods
	p.load = function () {
		this._tag.onload = createjs.proxy(this._handleTagComplete, this);
		this._tag.onreadystatechange = createjs.proxy(this._handleReadyStateChange, this);
		this._tag.onerror = createjs.proxy(this._handleError, this);

		var evt = new createjs.Event("initialize");
		evt.loader = this._tag;

		this.dispatchEvent(evt);

		this._hideTag();

		this._loadTimeout = setTimeout(createjs.proxy(this._handleTimeout, this), this._item.loadTimeout);

		this._tag[this._tagSrcAttribute] = this._item.src;

		// wdg:: Append the tag AFTER setting the src, or SVG loading on iOS will fail.
		if (this._tag.parentNode == null) {
			window.document.body.appendChild(this._tag);
			this._addedToDOM = true;
		}
	};

	p.destroy = function() {
		this._clean();
		this._tag = null;

		this.AbstractRequest_destroy();
	};

	// private methods
	/**
	 * Handle the readyStateChange event from a tag. We need this in place of the `onload` callback (mainly SCRIPT
	 * and LINK tags), but other cases may exist.
	 * @method _handleReadyStateChange
	 * @private
	 */
	p._handleReadyStateChange = function () {
		clearTimeout(this._loadTimeout);
		// This is strictly for tags in browsers that do not support onload.
		var tag = this._tag;

		// Complete is for old IE support.
		if (tag.readyState == "loaded" || tag.readyState == "complete") {
			this._handleTagComplete();
		}
	};

	/**
	 * Handle any error events from the tag.
	 * @method _handleError
	 * @protected
	 */
	p._handleError = function() {
		this._clean();
		this.dispatchEvent("error");
	};

	/**
	 * Handle the tag's onload callback.
	 * @method _handleTagComplete
	 * @private
	 */
	p._handleTagComplete = function () {
		this._rawResult = this._tag;
		this._result = this.resultFormatter && this.resultFormatter(this) || this._rawResult;

		this._clean();
		this._showTag();

		this.dispatchEvent("complete");
	};

	/**
	 * The tag request has not loaded within the time specified in loadTimeout.
	 * @method _handleError
	 * @param {Object} event The XHR error event.
	 * @private
	 */
	p._handleTimeout = function () {
		this._clean();
		this.dispatchEvent(new createjs.Event("timeout"));
	};

	/**
	 * Remove event listeners, but don't destroy the request object
	 * @method _clean
	 * @private
	 */
	p._clean = function() {
		this._tag.onload = null;
		this._tag.onreadystatechange = null;
		this._tag.onerror = null;
		if (this._addedToDOM && this._tag.parentNode != null) {
			this._tag.parentNode.removeChild(this._tag);
		}
		clearTimeout(this._loadTimeout);
	};

	p._hideTag = function() {
		this._startTagVisibility = this._tag.style.visibility;
		this._tag.style.visibility = "hidden";
	};

	p._showTag = function() {
		this._tag.style.visibility = this._startTagVisibility;
	};

	/**
	 * Handle a stalled audio event. The main place this happens is with HTMLAudio in Chrome when playing back audio
	 * that is already in a load, but not complete.
	 * @method _handleStalled
	 * @private
	 */
	p._handleStalled = function () {
		//Ignore, let the timeout take care of it. Sometimes its not really stopped.
	};

	createjs.TagRequest = createjs.promote(TagRequest, "AbstractRequest");

}());

//##############################################################################
// MediaTagRequest.js
//##############################################################################

this.createjs = this.createjs || {};

(function () {
	"use strict";

	// constructor
	/**
	 * An {{#crossLink "TagRequest"}}{{/crossLink}} that loads HTML tags for video and audio.
	 * @class MediaTagRequest
	 * @param {LoadItem} loadItem
	 * @param {HTMLAudioElement|HTMLVideoElement} tag
	 * @param {String} srcAttribute The tag attribute that specifies the source, such as "src", "href", etc.
	 * @constructor
	 */
	function MediaTagRequest(loadItem, tag, srcAttribute) {
		this.AbstractRequest_constructor(loadItem);

		// protected properties
		this._tag = tag;
		this._tagSrcAttribute = srcAttribute;
		this._loadedHandler = createjs.proxy(this._handleTagComplete, this);
	};

	var p = createjs.extend(MediaTagRequest, createjs.TagRequest);
	var s = MediaTagRequest;

	// public methods
	p.load = function () {
		var sc = createjs.proxy(this._handleStalled, this);
		this._stalledCallback = sc;

		var pc = createjs.proxy(this._handleProgress, this);
		this._handleProgress = pc;

		this._tag.addEventListener("stalled", sc);
		this._tag.addEventListener("progress", pc);

		// This will tell us when audio is buffered enough to play through, but not when its loaded.
		// The tag doesn't keep loading in Chrome once enough has buffered, and we have decided that behaviour is sufficient.
		this._tag.addEventListener && this._tag.addEventListener("canplaythrough", this._loadedHandler, false); // canplaythrough callback doesn't work in Chrome, so we use an event.

		this.TagRequest_load();
	};

	// private methods
	p._handleReadyStateChange = function () {
		clearTimeout(this._loadTimeout);
		// This is strictly for tags in browsers that do not support onload.
		var tag = this._tag;

		// Complete is for old IE support.
		if (tag.readyState == "loaded" || tag.readyState == "complete") {
			this._handleTagComplete();
		}
	};

	p._handleStalled = function () {
		//Ignore, let the timeout take care of it. Sometimes its not really stopped.
	};

	/**
	 * An XHR request has reported progress.
	 * @method _handleProgress
	 * @param {Object} event The XHR progress event.
	 * @private
	 */
	p._handleProgress = function (event) {
		if (!event || event.loaded > 0 && event.total == 0) {
			return; // Sometimes we get no "total", so just ignore the progress event.
		}

		var newEvent = new createjs.ProgressEvent(event.loaded, event.total);
		this.dispatchEvent(newEvent);
	};

	// protected methods
	p._clean = function () {
		this._tag.removeEventListener && this._tag.removeEventListener("canplaythrough", this._loadedHandler);
		this._tag.removeEventListener("stalled", this._stalledCallback);
		this._tag.removeEventListener("progress", this._progressCallback);

		this.TagRequest__clean();
	};

	createjs.MediaTagRequest = createjs.promote(MediaTagRequest, "TagRequest");

}());

//##############################################################################
// XHRRequest.js
//##############################################################################

this.createjs = this.createjs || {};

(function () {
	"use strict";

// constructor
	/**
	 * A preloader that loads items using XHR requests, usually XMLHttpRequest. However XDomainRequests will be used
	 * for cross-domain requests if possible, and older versions of IE fall back on to ActiveX objects when necessary.
	 * XHR requests load the content as text or binary data, provide progress and consistent completion events, and
	 * can be canceled during load. Note that XHR is not supported in IE 6 or earlier, and is not recommended for
	 * cross-domain loading.
	 * @class XHRRequest
	 * @constructor
	 * @param {Object} item The object that defines the file to load. Please see the {{#crossLink "LoadQueue/loadFile"}}{{/crossLink}}
	 * for an overview of supported file properties.
	 * @extends AbstractLoader
	 */
	function XHRRequest (item) {
		this.AbstractRequest_constructor(item);

		// protected properties
		/**
		 * A reference to the XHR request used to load the content.
		 * @property _request
		 * @type {XMLHttpRequest | XDomainRequest | ActiveX.XMLHTTP}
		 * @private
		 */
		this._request = null;

		/**
		 * A manual load timeout that is used for browsers that do not support the onTimeout event on XHR (XHR level 1,
		 * typically IE9).
		 * @property _loadTimeout
		 * @type {Number}
		 * @private
		 */
		this._loadTimeout = null;

		/**
		 * The browser's XHR (XMLHTTPRequest) version. Supported versions are 1 and 2. There is no official way to detect
		 * the version, so we use capabilities to make a best guess.
		 * @property _xhrLevel
		 * @type {Number}
		 * @default 1
		 * @private
		 */
		this._xhrLevel = 1;

		/**
		 * The response of a loaded file. This is set because it is expensive to look up constantly. This property will be
		 * null until the file is loaded.
		 * @property _response
		 * @type {mixed}
		 * @private
		 */
		this._response = null;

		/**
		 * The response of the loaded file before it is modified. In most cases, content is converted from raw text to
		 * an HTML tag or a formatted object which is set to the <code>result</code> property, but the developer may still
		 * want to access the raw content as it was loaded.
		 * @property _rawResponse
		 * @type {String|Object}
		 * @private
		 */
		this._rawResponse = null;

		this._canceled = false;

		// Setup our event handlers now.
		this._handleLoadStartProxy = createjs.proxy(this._handleLoadStart, this);
		this._handleProgressProxy = createjs.proxy(this._handleProgress, this);
		this._handleAbortProxy = createjs.proxy(this._handleAbort, this);
		this._handleErrorProxy = createjs.proxy(this._handleError, this);
		this._handleTimeoutProxy = createjs.proxy(this._handleTimeout, this);
		this._handleLoadProxy = createjs.proxy(this._handleLoad, this);
		this._handleReadyStateChangeProxy = createjs.proxy(this._handleReadyStateChange, this);

		if (!this._createXHR(item)) {
			//TODO: Throw error?
		}
	};

	var p = createjs.extend(XHRRequest, createjs.AbstractRequest);

// static properties
	/**
	 * A list of XMLHTTP object IDs to try when building an ActiveX object for XHR requests in earlier versions of IE.
	 * @property ACTIVEX_VERSIONS
	 * @type {Array}
	 * @since 0.4.2
	 * @private
	 */
	XHRRequest.ACTIVEX_VERSIONS = [
		"Msxml2.XMLHTTP.6.0",
		"Msxml2.XMLHTTP.5.0",
		"Msxml2.XMLHTTP.4.0",
		"MSXML2.XMLHTTP.3.0",
		"MSXML2.XMLHTTP",
		"Microsoft.XMLHTTP"
	];

// Public methods
	/**
	 * Look up the loaded result.
	 * @method getResult
	 * @param {Boolean} [raw=false] Return a raw result instead of a formatted result. This applies to content
	 * loaded via XHR such as scripts, XML, CSS, and Images. If there is no raw result, the formatted result will be
	 * returned instead.
	 * @return {Object} A result object containing the content that was loaded, such as:
	 * <ul>
	 *      <li>An image tag (&lt;image /&gt;) for images</li>
	 *      <li>A script tag for JavaScript (&lt;script /&gt;). Note that scripts loaded with tags may be added to the
	 *      HTML head.</li>
	 *      <li>A style tag for CSS (&lt;style /&gt;)</li>
	 *      <li>Raw text for TEXT</li>
	 *      <li>A formatted JavaScript object defined by JSON</li>
	 *      <li>An XML document</li>
	 *      <li>An binary arraybuffer loaded by XHR</li>
	 * </ul>
	 * Note that if a raw result is requested, but not found, the result will be returned instead.
	 */
	p.getResult = function (raw) {
		if (raw && this._rawResponse) {
			return this._rawResponse;
		}
		return this._response;
	};

	// Overrides abstract method in AbstractRequest
	p.cancel = function () {
		this.canceled = true;
		this._clean();
		this._request.abort();
	};

	// Overrides abstract method in AbstractLoader
	p.load = function () {
		if (this._request == null) {
			this._handleError();
			return;
		}

		//Events
		if (this._request.addEventListener != null) {
			this._request.addEventListener("loadstart", this._handleLoadStartProxy, false);
			this._request.addEventListener("progress", this._handleProgressProxy, false);
			this._request.addEventListener("abort", this._handleAbortProxy, false);
			this._request.addEventListener("error", this._handleErrorProxy, false);
			this._request.addEventListener("timeout", this._handleTimeoutProxy, false);

			// Note: We don't get onload in all browsers (earlier FF and IE). onReadyStateChange handles these.
			this._request.addEventListener("load", this._handleLoadProxy, false);
			this._request.addEventListener("readystatechange", this._handleReadyStateChangeProxy, false);
		} else {
			// IE9 support
			this._request.onloadstart = this._handleLoadStartProxy;
			this._request.onprogress = this._handleProgressProxy;
			this._request.onabort = this._handleAbortProxy;
			this._request.onerror = this._handleErrorProxy;
			this._request.ontimeout = this._handleTimeoutProxy;

			// Note: We don't get onload in all browsers (earlier FF and IE). onReadyStateChange handles these.
			this._request.onload = this._handleLoadProxy;
			this._request.onreadystatechange = this._handleReadyStateChangeProxy;
		}

		// Set up a timeout if we don't have XHR2
		if (this._xhrLevel == 1) {
			this._loadTimeout = setTimeout(createjs.proxy(this._handleTimeout, this), this._item.loadTimeout);
		}

		// Sometimes we get back 404s immediately, particularly when there is a cross origin request.  // note this does not catch in Chrome
		try {
			if (!this._item.values || this._item.method == createjs.AbstractLoader.GET) {
				this._request.send();
			} else if (this._item.method == createjs.AbstractLoader.POST) {
				this._request.send(createjs.RequestUtils.formatQueryString(this._item.values));
			}
		} catch (error) {
			this.dispatchEvent(new createjs.ErrorEvent("XHR_SEND", null, error));
		}
	};

	p.setResponseType = function (type) {
		// Some old browsers doesn't support blob, so we convert arraybuffer to blob after response is downloaded
		if (type === 'blob') {
			type = window.URL ? 'blob' : 'arraybuffer';
			this._responseType = type;
		}
		this._request.responseType = type;
	};

	/**
	 * Get all the response headers from the XmlHttpRequest.
	 *
	 * <strong>From the docs:</strong> Return all the HTTP headers, excluding headers that are a case-insensitive match
	 * for Set-Cookie or Set-Cookie2, as a single string, with each header line separated by a U+000D CR U+000A LF pair,
	 * excluding the status line, and with each header name and header value separated by a U+003A COLON U+0020 SPACE
	 * pair.
	 * @method getAllResponseHeaders
	 * @return {String}
	 * @since 0.4.1
	 */
	p.getAllResponseHeaders = function () {
		if (this._request.getAllResponseHeaders instanceof Function) {
			return this._request.getAllResponseHeaders();
		} else {
			return null;
		}
	};

	/**
	 * Get a specific response header from the XmlHttpRequest.
	 *
	 * <strong>From the docs:</strong> Returns the header field value from the response of which the field name matches
	 * header, unless the field name is Set-Cookie or Set-Cookie2.
	 * @method getResponseHeader
	 * @param {String} header The header name to retrieve.
	 * @return {String}
	 * @since 0.4.1
	 */
	p.getResponseHeader = function (header) {
		if (this._request.getResponseHeader instanceof Function) {
			return this._request.getResponseHeader(header);
		} else {
			return null;
		}
	};

// protected methods
	/**
	 * The XHR request has reported progress.
	 * @method _handleProgress
	 * @param {Object} event The XHR progress event.
	 * @private
	 */
	p._handleProgress = function (event) {
		if (!event || event.loaded > 0 && event.total == 0) {
			return; // Sometimes we get no "total", so just ignore the progress event.
		}

		var newEvent = new createjs.ProgressEvent(event.loaded, event.total);
		this.dispatchEvent(newEvent);
	};

	/**
	 * The XHR request has reported a load start.
	 * @method _handleLoadStart
	 * @param {Object} event The XHR loadStart event.
	 * @private
	 */
	p._handleLoadStart = function (event) {
		clearTimeout(this._loadTimeout);
		this.dispatchEvent("loadstart");
	};

	/**
	 * The XHR request has reported an abort event.
	 * @method handleAbort
	 * @param {Object} event The XHR abort event.
	 * @private
	 */
	p._handleAbort = function (event) {
		this._clean();
		this.dispatchEvent(new createjs.ErrorEvent("XHR_ABORTED", null, event));
	};

	/**
	 * The XHR request has reported an error event.
	 * @method _handleError
	 * @param {Object} event The XHR error event.
	 * @private
	 */
	p._handleError = function (event) {
		this._clean();
		this.dispatchEvent(new createjs.ErrorEvent(event.message));
	};

	/**
	 * The XHR request has reported a readyState change. Note that older browsers (IE 7 & 8) do not provide an onload
	 * event, so we must monitor the readyStateChange to determine if the file is loaded.
	 * @method _handleReadyStateChange
	 * @param {Object} event The XHR readyStateChange event.
	 * @private
	 */
	p._handleReadyStateChange = function (event) {
		if (this._request.readyState == 4) {
			this._handleLoad();
		}
	};

	/**
	 * The XHR request has completed. This is called by the XHR request directly, or by a readyStateChange that has
	 * <code>request.readyState == 4</code>. Only the first call to this method will be processed.
	 * @method _handleLoad
	 * @param {Object} event The XHR load event.
	 * @private
	 */
	p._handleLoad = function (event) {
		if (this.loaded) {
			return;
		}
		this.loaded = true;

		var error = this._checkError();
		if (error) {
			this._handleError(error);
			return;
		}

		this._response = this._getResponse();
		// Convert arraybuffer back to blob
		if (this._responseType === 'arraybuffer') {
			try {
				this._response = new Blob([this._response]);
			} catch (e) {
				// Fallback to use BlobBuilder if Blob constructor is not supported
				// Tested on Android 2.3 ~ 4.2 and iOS5 safari
				window.BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder;
				if (e.name === 'TypeError' && window.BlobBuilder) {
					var builder = new BlobBuilder();
					builder.append(this._response);
					this._response = builder.getBlob();
				}
			}
		}
		this._clean();

		this.dispatchEvent(new createjs.Event("complete"));
	};

	/**
	 * The XHR request has timed out. This is called by the XHR request directly, or via a <code>setTimeout</code>
	 * callback.
	 * @method _handleTimeout
	 * @param {Object} [event] The XHR timeout event. This is occasionally null when called by the backup setTimeout.
	 * @private
	 */
	p._handleTimeout = function (event) {
		this._clean();

		this.dispatchEvent(new createjs.ErrorEvent("PRELOAD_TIMEOUT", null, event));
	};

// Protected
	/**
	 * Determine if there is an error in the current load. This checks the status of the request for problem codes. Note
	 * that this does not check for an actual response. Currently, it only checks for 404 or 0 error code.
	 * @method _checkError
	 * @return {int} If the request status returns an error code.
	 * @private
	 */
	p._checkError = function () {
		//LM: Probably need additional handlers here, maybe 501
		var status = parseInt(this._request.status);

		switch (status) {
			case 404:   // Not Found
			case 0:     // Not Loaded
				return new Error(status);
		}
		return null;
	};

	/**
	 * Validate the response. Different browsers have different approaches, some of which throw errors when accessed
	 * in other browsers. If there is no response, the <code>_response</code> property will remain null.
	 * @method _getResponse
	 * @private
	 */
	p._getResponse = function () {
		if (this._response != null) {
			return this._response;
		}

		if (this._request.response != null) {
			return this._request.response;
		}

		// Android 2.2 uses .responseText
		try {
			if (this._request.responseText != null) {
				return this._request.responseText;
			}
		} catch (e) {
		}

		// When loading XML, IE9 does not return .response, instead it returns responseXML.xml
		try {
			if (this._request.responseXML != null) {
				return this._request.responseXML;
			}
		} catch (e) {
		}

		return null;
	};

	/**
	 * Create an XHR request. Depending on a number of factors, we get totally different results.
	 * <ol><li>Some browsers get an <code>XDomainRequest</code> when loading cross-domain.</li>
	 *      <li>XMLHttpRequest are created when available.</li>
	 *      <li>ActiveX.XMLHTTP objects are used in older IE browsers.</li>
	 *      <li>Text requests override the mime type if possible</li>
	 *      <li>Origin headers are sent for crossdomain requests in some browsers.</li>
	 *      <li>Binary loads set the response type to "arraybuffer"</li></ol>
	 * @method _createXHR
	 * @param {Object} item The requested item that is being loaded.
	 * @return {Boolean} If an XHR request or equivalent was successfully created.
	 * @private
	 */
	p._createXHR = function (item) {
		// Check for cross-domain loads. We can't fully support them, but we can try.
		var crossdomain = createjs.RequestUtils.isCrossDomain(item);
		var headers = {};

		// Create the request. Fallback to whatever support we have.
		var req = null;
		if (window.XMLHttpRequest) {
			req = new XMLHttpRequest();
			// This is 8 or 9, so use XDomainRequest instead.
			if (crossdomain && req.withCredentials === undefined && window.XDomainRequest) {
				req = new XDomainRequest();
			}
		} else { // Old IE versions use a different approach
			for (var i = 0, l = s.ACTIVEX_VERSIONS.length; i < l; i++) {
				var axVersion = s.ACTIVEX_VERSIONS[i];
				try {
					req = new ActiveXObject(axVersion);
					break;
				} catch (e) {
				}
			}
			if (req == null) {
				return false;
			}
		}

		// Default to utf-8 for Text requests.
		if (item.mimeType == null && createjs.RequestUtils.isText(item.type)) {
			item.mimeType = "text/plain; charset=utf-8";
		}

		// IE9 doesn't support overrideMimeType(), so we need to check for it.
		if (item.mimeType && req.overrideMimeType) {
			req.overrideMimeType(item.mimeType);
		}

		// Determine the XHR level
		this._xhrLevel = (typeof req.responseType === "string") ? 2 : 1;

		var src = null;
		if (item.method == createjs.AbstractLoader.GET) {
			src = createjs.RequestUtils.buildPath(item.src, item.values);
		} else {
			src = item.src;
		}

		// Open the request.  Set cross-domain flags if it is supported (XHR level 1 only)
		req.open(item.method || createjs.AbstractLoader.GET, src, true);

		if (crossdomain && req instanceof XMLHttpRequest && this._xhrLevel == 1) {
			headers["Origin"] = location.origin;
		}

		// To send data we need to set the Content-type header)
		if (item.values && item.method == createjs.AbstractLoader.POST) {
			headers["Content-Type"] = "application/x-www-form-urlencoded";
		}

		if (!crossdomain && !headers["X-Requested-With"]) {
			headers["X-Requested-With"] = "XMLHttpRequest";
		}

		if (item.headers) {
			for (var n in item.headers) {
				headers[n] = item.headers[n];
			}
		}

		for (n in headers) {
			req.setRequestHeader(n, headers[n])
		}

		if (req instanceof XMLHttpRequest && item.withCredentials !== undefined) {
			req.withCredentials = item.withCredentials;
		}

		this._request = req;

		return true;
	};

	/**
	 * A request has completed (or failed or canceled), and needs to be disposed.
	 * @method _clean
	 * @private
	 */
	p._clean = function () {
		clearTimeout(this._loadTimeout);

		if (this._request.removeEventListener != null) {
			this._request.removeEventListener("loadstart", this._handleLoadStartProxy);
			this._request.removeEventListener("progress", this._handleProgressProxy);
			this._request.removeEventListener("abort", this._handleAbortProxy);
			this._request.removeEventListener("error", this._handleErrorProxy);
			this._request.removeEventListener("timeout", this._handleTimeoutProxy);
			this._request.removeEventListener("load", this._handleLoadProxy);
			this._request.removeEventListener("readystatechange", this._handleReadyStateChangeProxy);
		} else {
			this._request.onloadstart = null;
			this._request.onprogress = null;
			this._request.onabort = null;
			this._request.onerror = null;
			this._request.ontimeout = null;
			this._request.onload = null;
			this._request.onreadystatechange = null;
		}
	};

	p.toString = function () {
		return "[PreloadJS XHRRequest]";
	};

	createjs.XHRRequest = createjs.promote(XHRRequest, "AbstractRequest");

}());

//##############################################################################
// LoadQueue.js
//##############################################################################

this.createjs = this.createjs || {};

/*
 TODO: WINDOWS ISSUES
 * No error for HTML audio in IE 678
 * SVG no failure error in IE 67 (maybe 8) TAGS AND XHR
 * No script complete handler in IE 67 TAGS (XHR is fine)
 * No XML/JSON in IE6 TAGS
 * Need to hide loading SVG in Opera TAGS
 * No CSS onload/readystatechange in Safari or Android TAGS (requires rule checking)
 * SVG no load or failure in Opera XHR
 * Reported issues with IE7/8
 */

(function () {
	"use strict";

// constructor
	/**
	 * The LoadQueue class is the main API for preloading content. LoadQueue is a load manager, which can preload either
	 * a single file, or queue of files.
	 *
	 * <b>Creating a Queue</b><br />
	 * To use LoadQueue, create a LoadQueue instance. If you want to force tag loading where possible, set the preferXHR
	 * argument to false.
	 *
	 *      var queue = new createjs.LoadQueue(true);
	 *
	 * <b>Listening for Events</b><br />
	 * Add any listeners you want to the queue. Since PreloadJS 0.3.0, the {{#crossLink "EventDispatcher"}}{{/crossLink}}
	 * lets you add as many listeners as you want for events. You can subscribe to the following events:<ul>
	 *     <li>{{#crossLink "AbstractLoader/complete:event"}}{{/crossLink}}: fired when a queue completes loading all
	 *     files</li>
	 *     <li>{{#crossLink "AbstractLoader/error:event"}}{{/crossLink}}: fired when the queue encounters an error with
	 *     any file.</li>
	 *     <li>{{#crossLink "AbstractLoader/progress:event"}}{{/crossLink}}: Progress for the entire queue has
	 *     changed.</li>
	 *     <li>{{#crossLink "LoadQueue/fileload:event"}}{{/crossLink}}: A single file has completed loading.</li>
	 *     <li>{{#crossLink "LoadQueue/fileprogress:event"}}{{/crossLink}}: Progress for a single file has changes. Note
	 *     that only files loaded with XHR (or possibly by plugins) will fire progress events other than 0 or 100%.</li>
	 * </ul>
	 *
	 *      queue.on("fileload", handleFileLoad, this);
	 *      queue.on("complete", handleComplete, this);
	 *
	 * <b>Adding files and manifests</b><br />
	 * Add files you want to load using {{#crossLink "LoadQueue/loadFile"}}{{/crossLink}} or add multiple files at a
	 * time using a list or a manifest definition using {{#crossLink "LoadQueue/loadManifest"}}{{/crossLink}}. Files are
	 * appended to the end of the active queue, so you can use these methods as many times as you like, whenever you
	 * like.
	 *
	 *      queue.loadFile("filePath/file.jpg");
	 *      queue.loadFile({id:"image", src:"filePath/file.jpg"});
	 *      queue.loadManifest(["filePath/file.jpg", {id:"image", src:"filePath/file.jpg"}]);
	 *
	 *      // Use an external manifest
	 *      queue.loadManifest("path/to/manifest.json");
	 *      queue.loadManifest({src:"manifest.json", type:"manifest"});
	 *
	 * If you pass `false` as the `loadNow` parameter, the queue will not kick of the load of the files, but it will not
	 * stop if it has already been started. Call the {{#crossLink "AbstractLoader/load"}}{{/crossLink}} method to begin
	 * a paused queue. Note that a paused queue will automatically resume when new files are added to it with a
	 * `loadNow` argument of `true`.
	 *
	 *      queue.load();
	 *
	 * <b>File Types</b><br />
	 * The file type of a manifest item is auto-determined by the file extension. The pattern matching in PreloadJS
	 * should handle the majority of standard file and url formats, and works with common file extensions. If you have
	 * either a non-standard file extension, or are serving the file using a proxy script, then you can pass in a
	 * <code>type</code> property with any manifest item.
	 *
	 *      queue.loadFile({src:"path/to/myFile.mp3x", type:createjs.AbstractLoader.SOUND});
	 *
	 *      // Note that PreloadJS will not read a file extension from the query string
	 *      queue.loadFile({src:"http://server.com/proxy?file=image.jpg", type:createjs.AbstractLoader.IMAGE});
	 *
	 * Supported types are defined on the {{#crossLink "AbstractLoader"}}{{/crossLink}} class, and include:
	 * <ul>
	 *     <li>{{#crossLink "AbstractLoader/BINARY:property"}}{{/crossLink}}: Raw binary data via XHR</li>
	 *     <li>{{#crossLink "AbstractLoader/CSS:property"}}{{/crossLink}}: CSS files</li>
	 *     <li>{{#crossLink "AbstractLoader/IMAGE:property"}}{{/crossLink}}: Common image formats</li>
	 *     <li>{{#crossLink "AbstractLoader/JAVASCRIPT:property"}}{{/crossLink}}: JavaScript files</li>
	 *     <li>{{#crossLink "AbstractLoader/JSON:property"}}{{/crossLink}}: JSON data</li>
	 *     <li>{{#crossLink "AbstractLoader/JSONP:property"}}{{/crossLink}}: JSON files cross-domain</li>
	 *     <li>{{#crossLink "AbstractLoader/MANIFEST:property"}}{{/crossLink}}: A list of files to load in JSON format, see
	 *     {{#crossLink "AbstractLoader/loadManifest"}}{{/crossLink}}</li>
	 *     <li>{{#crossLink "AbstractLoader/SOUND:property"}}{{/crossLink}}: Audio file formats</li>
	 *     <li>{{#crossLink "AbstractLoader/SPRITESHEET:property"}}{{/crossLink}}: JSON SpriteSheet definitions. This
	 *     will also load sub-images, and provide a {{#crossLink "SpriteSheet"}}{{/crossLink}} instance.</li>
	 *     <li>{{#crossLink "AbstractLoader/SVG:property"}}{{/crossLink}}: SVG files</li>
	 *     <li>{{#crossLink "AbstractLoader/TEXT:property"}}{{/crossLink}}: Text files - XHR only</li>
     *     <li>{{#crossLink "AbstractLoader/VIDEO:property"}}{{/crossLink}}: Video objects</li>
	 *     <li>{{#crossLink "AbstractLoader/XML:property"}}{{/crossLink}}: XML data</li>
	 * </ul>
	 *
	 * <em>Note: Loader types used to be defined on LoadQueue, but have been moved to AbstractLoader for better
	 * portability of loader classes, which can be used individually now. The properties on LoadQueue still exist, but
	 * are deprecated.</em>
	 *
	 * <b>Handling Results</b><br />
	 * When a file is finished downloading, a {{#crossLink "LoadQueue/fileload:event"}}{{/crossLink}} event is
	 * dispatched. In an example above, there is an event listener snippet for fileload. Loaded files are usually a
	 * formatted object that can be used immediately, including:
	 * <ul>
	 *     <li>Binary: The binary loaded result</li>
	 *     <li>CSS: A &lt;link /&gt; tag</li>
	 *     <li>Image: An &lt;img /&gt; tag</li>
	 *     <li>JavaScript: A &lt;script /&gt; tag</li>
	 *     <li>JSON/JSONP: A formatted JavaScript Object</li>
	 *     <li>Manifest: A JavaScript object.
	 *     <li>Sound: An &lt;audio /&gt; tag</a>
	 *     <li>SpriteSheet: A {{#crossLink "SpriteSheet"}}{{/crossLink}} instance, containing loaded images.
	 *     <li>SVG: An &lt;object /&gt; tag</li>
	 *     <li>Text: Raw text</li>
     *     <li>Video: A Video DOM node</li>
	 *     <li>XML: An XML DOM node</li>
	 * </ul>
	 *
	 *      function handleFileLoad(event) {
	 *          var item = event.item; // A reference to the item that was passed in to the LoadQueue
	 *          var type = item.type;
	 *
	 *          // Add any images to the page body.
	 *          if (type == createjs.LoadQueue.IMAGE) {
	 *              document.body.appendChild(event.result);
	 *          }
	 *      }
	 *
	 * At any time after the file has been loaded (usually after the queue has completed), any result can be looked up
	 * via its "id" using {{#crossLink "LoadQueue/getResult"}}{{/crossLink}}. If no id was provided, then the
	 * "src" or file path can be used instead, including the `path` defined by a manifest, but <strong>not including</strong>
	 * a base path defined on the LoadQueue. It is recommended to always pass an id if you want to look up content.
	 *
	 *      var image = queue.getResult("image");
	 *      document.body.appendChild(image);
	 *
	 * Raw loaded content can be accessed using the <code>rawResult</code> property of the {{#crossLink "LoadQueue/fileload:event"}}{{/crossLink}}
	 * event, or can be looked up using {{#crossLink "LoadQueue/getResult"}}{{/crossLink}}, passing `true` as the 2nd
	 * argument. This is only applicable for content that has been parsed for the browser, specifically: JavaScript,
	 * CSS, XML, SVG, and JSON objects, or anything loaded with XHR.
	 *
	 *      var image = queue.getResult("image", true); // load the binary image data loaded with XHR.
	 *
	 * <b>Plugins</b><br />
	 * LoadQueue has a simple plugin architecture to help process and preload content. For example, to preload audio,
	 * make sure to install the <a href="http://soundjs.com">SoundJS</a> Sound class, which will help load HTML audio,
	 * Flash audio, and WebAudio files. This should be installed <strong>before</strong> loading any audio files.
	 *
	 *      queue.installPlugin(createjs.Sound);
	 *
	 * <h4>Known Browser Issues</h4>
	 * <ul>
	 *     <li>Browsers without audio support can not load audio files.</li>
	 *     <li>Safari on Mac OS X can only play HTML audio if QuickTime is installed</li>
	 *     <li>HTML Audio tags will only download until their <code>canPlayThrough</code> event is fired. Browsers other
	 *     than Chrome will continue to download in the background.</li>
	 *     <li>When loading scripts using tags, they are automatically added to the document.</li>
	 *     <li>Scripts loaded via XHR may not be properly inspectable with browser tools.</li>
	 *     <li>IE6 and IE7 (and some other browsers) may not be able to load XML, Text, or JSON, since they require
	 *     XHR to work.</li>
	 *     <li>Content loaded via tags will not show progress, and will continue to download in the background when
	 *     canceled, although no events will be dispatched.</li>
	 * </ul>
	 *
	 * @class LoadQueue
	 * @param {Boolean} [preferXHR=true] Determines whether the preload instance will favor loading with XHR (XML HTTP
	 * Requests), or HTML tags. When this is `false`, the queue will use tag loading when possible, and fall back on XHR
	 * when necessary.
	 * @param {String} [basePath=""] A path that will be prepended on to the source parameter of all items in the queue
	 * before they are loaded.  Sources beginning with a protocol such as `http://` or a relative path such as `../`
	 * will not receive a base path.
	 * @param {String|Boolean} [crossOrigin=""] An optional flag to support images loaded from a CORS-enabled server. To
	 * use it, set this value to `true`, which will default the crossOrigin property on images to "Anonymous". Any
	 * string value will be passed through, but only "" and "Anonymous" are recommended. <strong>Note: The crossOrigin
	 * parameter is deprecated. Use LoadItem.crossOrigin instead</strong>
	 *
	 * @constructor
	 * @extends AbstractLoader
	 */
	function LoadQueue (preferXHR, basePath, crossOrigin) {
		this.AbstractLoader_constructor();

		/**
		 * An array of the plugins registered using {{#crossLink "LoadQueue/installPlugin"}}{{/crossLink}}.
		 * @property _plugins
		 * @type {Array}
		 * @private
		 * @since 0.6.1
		 */
		this._plugins = [];

		/**
		 * An object hash of callbacks that are fired for each file type before the file is loaded, giving plugins the
		 * ability to override properties of the load. Please see the {{#crossLink "LoadQueue/installPlugin"}}{{/crossLink}}
		 * method for more information.
		 * @property _typeCallbacks
		 * @type {Object}
		 * @private
		 */
		this._typeCallbacks = {};

		/**
		 * An object hash of callbacks that are fired for each file extension before the file is loaded, giving plugins the
		 * ability to override properties of the load. Please see the {{#crossLink "LoadQueue/installPlugin"}}{{/crossLink}}
		 * method for more information.
		 * @property _extensionCallbacks
		 * @type {null}
		 * @private
		 */
		this._extensionCallbacks = {};

		/**
		 * The next preload queue to process when this one is complete. If an error is thrown in the current queue, and
		 * {{#crossLink "LoadQueue/stopOnError:property"}}{{/crossLink}} is `true`, the next queue will not be processed.
		 * @property next
		 * @type {LoadQueue}
		 * @default null
		 */
		this.next = null;

		/**
		 * Ensure loaded scripts "complete" in the order they are specified. Loaded scripts are added to the document head
		 * once they are loaded. Scripts loaded via tags will load one-at-a-time when this property is `true`, whereas
		 * scripts loaded using XHR can load in any order, but will "finish" and be added to the document in the order
		 * specified.
		 *
		 * Any items can be set to load in order by setting the {{#crossLink "maintainOrder:property"}}{{/crossLink}}
		 * property on the load item, or by ensuring that only one connection can be open at a time using
		 * {{#crossLink "LoadQueue/setMaxConnections"}}{{/crossLink}}. Note that when the `maintainScriptOrder` property
		 * is set to `true`, scripts items are automatically set to `maintainOrder=true`, and changing the
		 * `maintainScriptOrder` to `false` during a load will not change items already in a queue.
		 *
		 * <h4>Example</h4>
		 *
		 *      var queue = new createjs.LoadQueue();
		 *      queue.setMaxConnections(3); // Set a higher number to load multiple items at once
		 *      queue.maintainScriptOrder = true; // Ensure scripts are loaded in order
		 *      queue.loadManifest([
		 *          "script1.js",
		 *          "script2.js",
		 *          "image.png", // Load any time
		 *          {src: "image2.png", maintainOrder: true} // Will wait for script2.js
		 *          "image3.png",
		 *          "script3.js" // Will wait for image2.png before loading (or completing when loading with XHR)
		 *      ]);
		 *
		 * @property maintainScriptOrder
		 * @type {Boolean}
		 * @default true
		 */
		this.maintainScriptOrder = true;

		/**
		 * Determines if the LoadQueue will stop processing the current queue when an error is encountered.
		 * @property stopOnError
		 * @type {Boolean}
		 * @default false
		 */
		this.stopOnError = false;

		/**
		 * The number of maximum open connections that a loadQueue tries to maintain. Please see
		 * {{#crossLink "LoadQueue/setMaxConnections"}}{{/crossLink}} for more information.
		 * @property _maxConnections
		 * @type {Number}
		 * @default 1
		 * @private
		 */
		this._maxConnections = 1;

		/**
		 * An internal list of all the default Loaders that are included with PreloadJS. Before an item is loaded, the
		 * available loader list is iterated, in the order they are included, and as soon as a loader indicates it can
		 * handle the content, it will be selected. The default loader, ({{#crossLink "TextLoader"}}{{/crossLink}} is
		 * last in the list, so it will be used if no other match is found. Typically, loaders will match based on the
		 * {{#crossLink "LoadItem/type"}}{{/crossLink}}, which is automatically determined using the file extension of
		 * the {{#crossLink "LoadItem/src:property"}}{{/crossLink}}.
		 *
		 * Loaders can be removed from PreloadJS by simply not including them.
		 *
		 * Custom loaders installed using {{#crossLink "registerLoader"}}{{/crossLink}} will be prepended to this list
		 * so that they are checked first.
		 * @property _availableLoaders
		 * @type {Array}
		 * @private
		 * @since 0.6.0
		 */
		this._availableLoaders = [
			createjs.ImageLoader,
			createjs.JavaScriptLoader,
			createjs.CSSLoader,
			createjs.JSONLoader,
			createjs.JSONPLoader,
			createjs.SoundLoader,
			createjs.ManifestLoader,
			createjs.SpriteSheetLoader,
			createjs.XMLLoader,
			createjs.SVGLoader,
			createjs.BinaryLoader,
			createjs.VideoLoader,
			createjs.TextLoader
		];

		/**
		 * The number of built in loaders, so they can't be removed by {{#crossLink "unregisterLoader"}}{{/crossLink}.
				 * @property _defaultLoaderLength
		 * @type {Number}
		 * @private
		 * @since 0.6.0
		 */
		this._defaultLoaderLength = this._availableLoaders.length;

		this.init(preferXHR, basePath, crossOrigin);
	}

	var p = createjs.extend(LoadQueue, createjs.AbstractLoader);
	var s = LoadQueue;

	/**
	 * <strong>REMOVED</strong>. Removed in favor of using `MySuperClass_constructor`.
	 * See {{#crossLink "Utility Methods/extend"}}{{/crossLink}} and {{#crossLink "Utility Methods/promote"}}{{/crossLink}}
	 * for details.
	 *
	 * There is an inheritance tutorial distributed with EaselJS in /tutorials/Inheritance.
	 *
	 * @method initialize
	 * @protected
	 * @deprecated
	 */
	// p.initialize = function() {}; // searchable for devs wondering where it is.

	/**
	 * An internal initialization method, which is used for initial set up, but also to reset the LoadQueue.
	 * @method init
	 * @param preferXHR
	 * @param basePath
	 * @param crossOrigin
	 * @private
	 */
	p.init = function (preferXHR, basePath, crossOrigin) {

		// public properties
		/**
		 * @property useXHR
		 * @type {Boolean}
		 * @readonly
		 * @default true
		 * @deprecated Use preferXHR instead.
		 */
		this.useXHR = true;

		/**
		 * Try and use XMLHttpRequest (XHR) when possible. Note that LoadQueue will default to tag loading or XHR
		 * loading depending on the requirements for a media type. For example, HTML audio can not be loaded with XHR,
		 * and plain text can not be loaded with tags, so it will default the the correct type instead of using the
		 * user-defined type.
		 * @type {Boolean}
		 * @default true
		 * @since 0.6.0
		 */
		this.preferXHR = true; //TODO: Get/Set
		this._preferXHR = true;
		this.setPreferXHR(preferXHR);

		// protected properties
		/**
		 * Whether the queue is currently paused or not.
		 * @property _paused
		 * @type {boolean}
		 * @private
		 */
		this._paused = false;

		/**
		 * A path that will be prepended on to the item's {{#crossLink "LoadItem/src:property"}}{{/crossLink}}. The
		 * `_basePath` property will only be used if an item's source is relative, and does not include a protocol such
		 * as `http://`, or a relative path such as `../`.
		 * @property _basePath
		 * @type {String}
		 * @private
		 * @since 0.3.1
		 */
		this._basePath = basePath;

		/**
		 * An optional flag to set on images that are loaded using PreloadJS, which enables CORS support. Images loaded
		 * cross-domain by servers that support CORS require the crossOrigin flag to be loaded and interacted with by
		 * a canvas. When loading locally, or with a server with no CORS support, this flag can cause other security issues,
		 * so it is recommended to only set it if you are sure the server supports it. Currently, supported values are ""
		 * and "Anonymous".
		 * @property _crossOrigin
		 * @type {String}
		 * @default ""
		 * @private
		 * @since 0.4.1
		 */
		this._crossOrigin = crossOrigin;

		/**
		 * Determines if the loadStart event was dispatched already. This event is only fired one time, when the first
		 * file is requested.
		 * @property _loadStartWasDispatched
		 * @type {Boolean}
		 * @default false
		 * @private
		 */
		this._loadStartWasDispatched = false;

		/**
		 * Determines if there is currently a script loading. This helps ensure that only a single script loads at once when
		 * using a script tag to do preloading.
		 * @property _currentlyLoadingScript
		 * @type {Boolean}
		 * @private
		 */
		this._currentlyLoadingScript = null;

		/**
		 * An array containing the currently downloading files.
		 * @property _currentLoads
		 * @type {Array}
		 * @private
		 */
		this._currentLoads = [];

		/**
		 * An array containing the queued items that have not yet started downloading.
		 * @property _loadQueue
		 * @type {Array}
		 * @private
		 */
		this._loadQueue = [];

		/**
		 * An array containing downloads that have not completed, so that the LoadQueue can be properly reset.
		 * @property _loadQueueBackup
		 * @type {Array}
		 * @private
		 */
		this._loadQueueBackup = [];

		/**
		 * An object hash of items that have finished downloading, indexed by the {{#crossLink "LoadItem"}}{{/crossLink}}
		 * id.
		 * @property _loadItemsById
		 * @type {Object}
		 * @private
		 */
		this._loadItemsById = {};

		/**
		 * An object hash of items that have finished downloading, indexed by {{#crossLink "LoadItem"}}{{/crossLink}}
		 * source.
		 * @property _loadItemsBySrc
		 * @type {Object}
		 * @private
		 */
		this._loadItemsBySrc = {};

		/**
		 * An object hash of loaded items, indexed by the ID of the {{#crossLink "LoadItem"}}{{/crossLink}}.
		 * @property _loadedResults
		 * @type {Object}
		 * @private
		 */
		this._loadedResults = {};

		/**
		 * An object hash of un-parsed loaded items, indexed by the ID of the {{#crossLink "LoadItem"}}{{/crossLink}}.
		 * @property _loadedRawResults
		 * @type {Object}
		 * @private
		 */
		this._loadedRawResults = {};

		/**
		 * The number of items that have been requested. This helps manage an overall progress without knowing how large
		 * the files are before they are downloaded. This does not include items inside of loaders such as the
		 * {{#crossLink "ManifestLoader"}}{{/crossLink}}.
		 * @property _numItems
		 * @type {Number}
		 * @default 0
		 * @private
		 */
		this._numItems = 0;

		/**
		 * The number of items that have completed loaded. This helps manage an overall progress without knowing how large
		 * the files are before they are downloaded.
		 * @property _numItemsLoaded
		 * @type {Number}
		 * @default 0
		 * @private
		 */
		this._numItemsLoaded = 0;

		/**
		 * A list of scripts in the order they were requested. This helps ensure that scripts are "completed" in the right
		 * order.
		 * @property _scriptOrder
		 * @type {Array}
		 * @private
		 */
		this._scriptOrder = [];

		/**
		 * A list of scripts that have been loaded. Items are added to this list as <code>null</code> when they are
		 * requested, contain the loaded item if it has completed, but not been dispatched to the user, and <code>true</true>
		 * once they are complete and have been dispatched.
		 * @property _loadedScripts
		 * @type {Array}
		 * @private
		 */
		this._loadedScripts = [];

		/**
		 * The last progress amount. This is used to suppress duplicate progress events.
		 * @property _lastProgress
		 * @type {Number}
		 * @private
		 * @since 0.6.0
		 */
		this._lastProgress = NaN;

	};

// static properties
	/**
	 * The time in milliseconds to assume a load has failed. An {{#crossLink "AbstractLoader/error:event"}}{{/crossLink}}
	 * event is dispatched if the timeout is reached before any data is received.
	 * @property loadTimeout
	 * @type {Number}
	 * @default 8000
	 * @static
	 * @since 0.4.1
	 * @deprecated In favour of {{#crossLink "LoadItem/LOAD_TIMEOUT_DEFAULT:property}}{{/crossLink}} property.
	 */
	s.loadTimeout = 8000;

	/**
	 * The time in milliseconds to assume a load has failed.
	 * @property LOAD_TIMEOUT
	 * @type {Number}
	 * @default 0
	 * @deprecated in favor of the {{#crossLink "LoadQueue/loadTimeout:property"}}{{/crossLink}} property.
	 */
	s.LOAD_TIMEOUT = 0;

// Preload Types
	/**
	 * @property BINARY
	 * @type {String}
	 * @default binary
	 * @static
	 * @deprecated Use the AbstractLoader {{#crossLink "AbstractLoader/BINARY:property"}}{{/crossLink}} instead.
	 */
	s.BINARY = createjs.AbstractLoader.BINARY;

	/**
	 * @property CSS
	 * @type {String}
	 * @default css
	 * @static
	 * @deprecated Use the AbstractLoader {{#crossLink "AbstractLoader/CSS:property"}}{{/crossLink}} instead.
	 */
	s.CSS = createjs.AbstractLoader.CSS;

	/**
	 * @property IMAGE
	 * @type {String}
	 * @default image
	 * @static
	 * @deprecated Use the AbstractLoader {{#crossLink "AbstractLoader/CSS:property"}}{{/crossLink}} instead.
	 */
	s.IMAGE = createjs.AbstractLoader.IMAGE;

	/**
	 * @property JAVASCRIPT
	 * @type {String}
	 * @default javascript
	 * @static
	 * @deprecated Use the AbstractLoader {{#crossLink "AbstractLoader/JAVASCRIPT:property"}}{{/crossLink}} instead.
	 */
	s.JAVASCRIPT = createjs.AbstractLoader.JAVASCRIPT;

	/**
	 * @property JSON
	 * @type {String}
	 * @default json
	 * @static
	 * @deprecated Use the AbstractLoader {{#crossLink "AbstractLoader/JSON:property"}}{{/crossLink}} instead.
	 */
	s.JSON = createjs.AbstractLoader.JSON;

	/**
	 * @property JSONP
	 * @type {String}
	 * @default jsonp
	 * @static
	 * @deprecated Use the AbstractLoader {{#crossLink "AbstractLoader/JSONP:property"}}{{/crossLink}} instead.
	 */
	s.JSONP = createjs.AbstractLoader.JSONP;

	/**
	 * @property MANIFEST
	 * @type {String}
	 * @default manifest
	 * @static
	 * @since 0.4.1
	 * @deprecated Use the AbstractLoader {{#crossLink "AbstractLoader/MANIFEST:property"}}{{/crossLink}} instead.
	 */
	s.MANIFEST = createjs.AbstractLoader.MANIFEST;

	/**
	 * @property SOUND
	 * @type {String}
	 * @default sound
	 * @static
	 * @deprecated Use the AbstractLoader {{#crossLink "AbstractLoader/JAVASCRIPT:property"}}{{/crossLink}} instead.
	 */
	s.SOUND = createjs.AbstractLoader.SOUND;

	/**
	 * @property VIDEO
	 * @type {String}
	 * @default video
	 * @static
	 * @deprecated Use the AbstractLoader {{#crossLink "AbstractLoader/JAVASCRIPT:property"}}{{/crossLink}} instead.
	 */
	s.VIDEO = createjs.AbstractLoader.VIDEO;

	/**
	 * @property SVG
	 * @type {String}
	 * @default svg
	 * @static
	 * @deprecated Use the AbstractLoader {{#crossLink "AbstractLoader/SVG:property"}}{{/crossLink}} instead.
	 */
	s.SVG = createjs.AbstractLoader.SVG;

	/**
	 * @property TEXT
	 * @type {String}
	 * @default text
	 * @static
	 * @deprecated Use the AbstractLoader {{#crossLink "AbstractLoader/TEXT:property"}}{{/crossLink}} instead.
	 */
	s.TEXT = createjs.AbstractLoader.TEXT;

	/**
	 * @property XML
	 * @type {String}
	 * @default xml
	 * @static
	 * @deprecated Use the AbstractLoader {{#crossLink "AbstractLoader/XML:property"}}{{/crossLink}} instead.
	 */
	s.XML = createjs.AbstractLoader.XML;

	/**
	 * @property POST
	 * @type {string}
	 * @deprecated Use the AbstractLoader {{#crossLink "AbstractLoader/POST:property"}}{{/crossLink}} instead.
	 */
	s.POST = createjs.AbstractLoader.POST;

	/**
	 * @property GET
	 * @type {string}
	 * @deprecated Use the AbstractLoader {{#crossLink "AbstractLoader/GET:property"}}{{/crossLink}} instead.
	 */
	s.GET = createjs.AbstractLoader.GET;

// events
	/**
	 * This event is fired when an individual file has loaded, and been processed.
	 * @event fileload
	 * @param {Object} target The object that dispatched the event.
	 * @param {String} type The event type.
	 * @param {Object} item The file item which was specified in the {{#crossLink "LoadQueue/loadFile"}}{{/crossLink}}
	 * or {{#crossLink "LoadQueue/loadManifest"}}{{/crossLink}} call. If only a string path or tag was specified, the
	 * object will contain that value as a `src` property.
	 * @param {Object} result The HTML tag or parsed result of the loaded item.
	 * @param {Object} rawResult The unprocessed result, usually the raw text or binary data before it is converted
	 * to a usable object.
	 * @since 0.3.0
	 */

	/**
	 * This {{#crossLink "ProgressEvent"}}{{/crossLink}} that is fired when an an individual file's progress changes.
	 * @event fileprogress
	 * @since 0.3.0
	 */

	/**
	 * This event is fired when an individual file starts to load.
	 * @event filestart
	 * @param {Object} The object that dispatched the event.
	 * @param {String} type The event type.
	 * @param {Object} item The file item which was specified in the {{#crossLink "LoadQueue/loadFile"}}{{/crossLink}}
	 * or {{#crossLink "LoadQueue/loadManifest"}}{{/crossLink}} call. If only a string path or tag was specified, the
	 * object will contain that value as a property.
	 */

	/**
	 * Although it extends {{#crossLink "AbstractLoader"}}{{/crossLink}}, the `initialize` event is never fired from
	 * a LoadQueue instance.
	 * @event initialize
	 * @private
	 */

// public methods
	/**
	 * Register a custom loaders class. New loaders are given precedence over loaders added earlier and default loaders.
	 * It is recommended that loaders extend {{#crossLink "AbstractLoader"}}{{/crossLink}}. Loaders can only be added
	 * once, and will be prepended to the list of available loaders.
	 * @method registerLoader
	 * @param {Function|AbstractLoader} loader The AbstractLoader class to add.
	 * @since 0.6.0
	 */
	p.registerLoader = function (loader) {
		if (!loader || !loader.canLoadItem) {
			throw new Error("loader is of an incorrect type.");
		} else if (this._availableLoaders.indexOf(loader) != -1) {
			throw new Error("loader already exists."); //LM: Maybe just silently fail here
		}

		this._availableLoaders.unshift(loader);
	};

	/**
	 * Remove a custom loader added using {{#crossLink "registerLoader"}}{{/crossLink}}. Only custom loaders can be
	 * unregistered, the default loaders will always be available.
	 * @method unregisterLoader
	 * @param {Function|AbstractLoader} loader The AbstractLoader class to remove
	 */
	p.unregisterLoader = function (loader) {
		var idx = this._availableLoaders.indexOf(loader);
		if (idx != -1 && idx < this._defaultLoaderLength - 1) {
			this._availableLoaders.splice(idx, 1);
		}
	};

	/**
	 * @method setUseXHR
	 * @param {Boolean} value The new useXHR value to set.
	 * @return {Boolean} The new useXHR value. If XHR is not supported by the browser, this will return false, even if
	 * the provided value argument was true.
	 * @since 0.3.0
	 * @deprecated use the {{#crossLink "LoadQueue/preferXHR:property"}}{{/crossLink}} property, or the
	 * {{#crossLink "LoadQueue/setUseXHR"}}{{/crossLink}} method instead.
	 */
	p.setUseXHR = function (value) {
		return this.setPreferXHR(value);
	};

	/**
	 * Change the {{#crossLink "preferXHR:property"}}{{/crossLink}} value. Note that if this is set to `true`, it may
	 * fail, or be ignored depending on the browser's capabilities and the load type.
	 * @method setPreferXHR
	 * @param {Boolean} value
	 * @returns {Boolean} The value of {{#crossLink "preferXHR"}}{{/crossLink}} that was successfully set.
	 * @since 0.6.0
	 */
	p.setPreferXHR = function (value) {
		// Determine if we can use XHR. XHR defaults to TRUE, but the browser may not support it.
		//TODO: Should we be checking for the other XHR types? Might have to do a try/catch on the different types similar to createXHR.
		this.preferXHR = (value != false && window.XMLHttpRequest != null);
		return this.preferXHR;
	};

	/**
	 * Stops all queued and loading items, and clears the queue. This also removes all internal references to loaded
	 * content, and allows the queue to be used again.
	 * @method removeAll
	 * @since 0.3.0
	 */
	p.removeAll = function () {
		this.remove();
	};

	/**
	 * Stops an item from being loaded, and removes it from the queue. If nothing is passed, all items are removed.
	 * This also removes internal references to loaded item(s).
	 *
	 * <h4>Example</h4>
	 *
	 *      queue.loadManifest([
	 *          {src:"test.png", id:"png"},
	 *          {src:"test.jpg", id:"jpg"},
	 *          {src:"test.mp3", id:"mp3"}
	 *      ]);
	 *      queue.remove("png"); // Single item by ID
	 *      queue.remove("png", "test.jpg"); // Items as arguments. Mixed id and src.
	 *      queue.remove(["test.png", "jpg"]); // Items in an Array. Mixed id and src.
	 *
	 * @method remove
	 * @param {String | Array} idsOrUrls* The id or ids to remove from this queue. You can pass an item, an array of
	 * items, or multiple items as arguments.
	 * @since 0.3.0
	 */
	p.remove = function (idsOrUrls) {
		var args = null;

		if (idsOrUrls && !Array.isArray(idsOrUrls)) {
			args = [idsOrUrls];
		} else if (idsOrUrls) {
			args = idsOrUrls;
		} else if (arguments.length > 0) {
			return;
		}

		var itemsWereRemoved = false;

		// Destroy everything
		if (!args) {
			this.close();
			for (var n in this._loadItemsById) {
				this._disposeItem(this._loadItemsById[n]);
			}
			this.init(this.preferXHR, this._basePath);

			// Remove specific items
		} else {
			while (args.length) {
				var item = args.pop();
				var r = this.getResult(item);

				//Remove from the main load Queue
				for (i = this._loadQueue.length - 1; i >= 0; i--) {
					loadItem = this._loadQueue[i].getItem();
					if (loadItem.id == item || loadItem.src == item) {
						this._loadQueue.splice(i, 1)[0].cancel();
						break;
					}
				}

				//Remove from the backup queue
				for (i = this._loadQueueBackup.length - 1; i >= 0; i--) {
					loadItem = this._loadQueueBackup[i].getItem();
					if (loadItem.id == item || loadItem.src == item) {
						this._loadQueueBackup.splice(i, 1)[0].cancel();
						break;
					}
				}

				if (r) {
					this._disposeItem(this.getItem(item));
				} else {
					for (var i = this._currentLoads.length - 1; i >= 0; i--) {
						var loadItem = this._currentLoads[i].getItem();
						if (loadItem.id == item || loadItem.src == item) {
							this._currentLoads.splice(i, 1)[0].cancel();
							itemsWereRemoved = true;
							break;
						}
					}
				}
			}

			// If this was called during a load, try to load the next item.
			if (itemsWereRemoved) {
				this._loadNext();
			}
		}
	};

	/**
	 * Stops all open loads, destroys any loaded items, and resets the queue, so all items can
	 * be reloaded again by calling {{#crossLink "AbstractLoader/load"}}{{/crossLink}}. Items are not removed from the
	 * queue. To remove items use the {{#crossLink "LoadQueue/remove"}}{{/crossLink}} or
	 * {{#crossLink "LoadQueue/removeAll"}}{{/crossLink}} method.
	 * @method reset
	 * @since 0.3.0
	 */
	p.reset = function () {
		this.close();
		for (var n in this._loadItemsById) {
			this._disposeItem(this._loadItemsById[n]);
		}

		//Reset the queue to its start state
		var a = [];
		for (var i = 0, l = this._loadQueueBackup.length; i < l; i++) {
			a.push(this._loadQueueBackup[i].getItem());
		}

		this.loadManifest(a, false);
	};

	/**
	 * Register a plugin. Plugins can map to load types (sound, image, etc), or specific extensions (png, mp3, etc).
	 * Currently, only one plugin can exist per type/extension.
	 *
	 * When a plugin is installed, a <code>getPreloadHandlers()</code> method will be called on it. For more information
	 * on this method, check out the {{#crossLink "SamplePlugin/getPreloadHandlers"}}{{/crossLink}} method in the
	 * {{#crossLink "SamplePlugin"}}{{/crossLink}} class.
	 *
	 * Before a file is loaded, a matching plugin has an opportunity to modify the load. If a `callback` is returned
	 * from the {{#crossLink "SamplePlugin/getPreloadHandlers"}}{{/crossLink}} method, it will be invoked first, and its
	 * result may cancel or modify the item. The callback method can also return a `completeHandler` to be fired when
	 * the file is loaded, or a `tag` object, which will manage the actual download. For more information on these
	 * methods, check out the {{#crossLink "SamplePlugin/preloadHandler"}}{{/crossLink}} and {{#crossLink "SamplePlugin/fileLoadHandler"}}{{/crossLink}}
	 * methods on the {{#crossLink "SamplePlugin"}}{{/crossLink}}.
	 *
	 * @method installPlugin
	 * @param {Function} plugin The plugin class to install.
	 */
	p.installPlugin = function (plugin) {
		if (plugin == null) {
			return;
		}

		if (plugin.getPreloadHandlers != null) {
			this._plugins.push(plugin);
			var map = plugin.getPreloadHandlers();
			map.scope = plugin;

			if (map.types != null) {
				for (var i = 0, l = map.types.length; i < l; i++) {
					this._typeCallbacks[map.types[i]] = map;
				}
			}

			if (map.extensions != null) {
				for (i = 0, l = map.extensions.length; i < l; i++) {
					this._extensionCallbacks[map.extensions[i]] = map;
				}
			}
		}
	};

	/**
	 * Set the maximum number of concurrent connections. Note that browsers and servers may have a built-in maximum
	 * number of open connections, so any additional connections may remain in a pending state until the browser
	 * opens the connection. When loading scripts using tags, and when {{#crossLink "LoadQueue/maintainScriptOrder:property"}}{{/crossLink}}
	 * is `true`, only one script is loaded at a time due to browser limitations.
	 *
	 * <h4>Example</h4>
	 *
	 *      var queue = new createjs.LoadQueue();
	 *      queue.setMaxConnections(10); // Allow 10 concurrent loads
	 *
	 * @method setMaxConnections
	 * @param {Number} value The number of concurrent loads to allow. By default, only a single connection per LoadQueue
	 * is open at any time.
	 */
	p.setMaxConnections = function (value) {
		this._maxConnections = value;
		if (!this._paused && this._loadQueue.length > 0) {
			this._loadNext();
		}
	};

	/**
	 * Load a single file. To add multiple files at once, use the {{#crossLink "LoadQueue/loadManifest"}}{{/crossLink}}
	 * method.
	 *
	 * Files are always appended to the current queue, so this method can be used multiple times to add files.
	 * To clear the queue first, use the {{#crossLink "AbstractLoader/close"}}{{/crossLink}} method.
	 * @method loadFile
	 * @param {LoadItem|Object|String} file The file object or path to load. A file can be either
	 * <ul>
	 *     <li>A {{#crossLink "LoadItem"}}{{/crossLink}} instance</li>
	 *     <li>An object containing properties defined by {{#crossLink "LoadItem"}}{{/crossLink}}</li>
	 *     <li>OR A string path to a resource. Note that this kind of load item will be converted to a {{#crossLink "LoadItem"}}{{/crossLink}}
	 *     in the background.</li>
	 * </ul>
	 * @param {Boolean} [loadNow=true] Kick off an immediate load (true) or wait for a load call (false). The default
	 * value is true. If the queue is paused using {{#crossLink "LoadQueue/setPaused"}}{{/crossLink}}, and the value is
	 * `true`, the queue will resume automatically.
	 * @param {String} [basePath] A base path that will be prepended to each file. The basePath argument overrides the
	 * path specified in the constructor. Note that if you load a manifest using a file of type {{#crossLink "AbstractLoader/MANIFEST:property"}}{{/crossLink}},
	 * its files will <strong>NOT</strong> use the basePath parameter. <strong>The basePath parameter is deprecated.</strong>
	 * This parameter will be removed in a future version. Please either use the `basePath` parameter in the LoadQueue
	 * constructor, or a `path` property in a manifest definition.
	 */
	p.loadFile = function (file, loadNow, basePath) {
		if (file == null) {
			var event = new createjs.ErrorEvent("PRELOAD_NO_FILE");
			this._sendError(event);
			return;
		}
		this._addItem(file, null, basePath);

		if (loadNow !== false) {
			this.setPaused(false);
		} else {
			this.setPaused(true);
		}
	};

	/**
	 * Load an array of files. To load a single file, use the {{#crossLink "LoadQueue/loadFile"}}{{/crossLink}} method.
	 * The files in the manifest are requested in the same order, but may complete in a different order if the max
	 * connections are set above 1 using {{#crossLink "LoadQueue/setMaxConnections"}}{{/crossLink}}. Scripts will load
	 * in the right order as long as {{#crossLink "LoadQueue/maintainScriptOrder"}}{{/crossLink}} is true (which is
	 * default).
	 *
	 * Files are always appended to the current queue, so this method can be used multiple times to add files.
	 * To clear the queue first, use the {{#crossLink "AbstractLoader/close"}}{{/crossLink}} method.
	 * @method loadManifest
	 * @param {Array|String|Object} manifest An list of files to load. The loadManifest call supports four types of
	 * manifests:
	 * <ol>
	 *     <li>A string path, which points to a manifest file, which is a JSON file that contains a "manifest" property,
	 *     which defines the list of files to load, and can optionally contain a "path" property, which will be
	 *     prepended to each file in the list.</li>
	 *     <li>An object which defines a "src", which is a JSON or JSONP file. A "callback" can be defined for JSONP
	 *     file. The JSON/JSONP file should contain a "manifest" property, which defines the list of files to load,
	 *     and can optionally contain a "path" property, which will be prepended to each file in the list.</li>
	 *     <li>An object which contains a "manifest" property, which defines the list of files to load, and can
	 *     optionally contain a "path" property, which will be prepended to each file in the list.</li>
	 *     <li>An Array of files to load.</li>
	 * </ol>
	 *
	 * Each "file" in a manifest can be either:
	 * <ul>
	 *     <li>A {{#crossLink "LoadItem"}}{{/crossLink}} instance</li>
	 *     <li>An object containing properties defined by {{#crossLink "LoadItem"}}{{/crossLink}}</li>
	 *     <li>OR A string path to a resource. Note that this kind of load item will be converted to a {{#crossLink "LoadItem"}}{{/crossLink}}
	 *     in the background.</li>
	 * </ul>
	 *
	 * @param {Boolean} [loadNow=true] Kick off an immediate load (true) or wait for a load call (false). The default
	 * value is true. If the queue is paused using {{#crossLink "LoadQueue/setPaused"}}{{/crossLink}} and this value is
	 * `true`, the queue will resume automatically.
	 * @param {String} [basePath] A base path that will be prepended to each file. The basePath argument overrides the
	 * path specified in the constructor. Note that if you load a manifest using a file of type {{#crossLink "LoadQueue/MANIFEST:property"}}{{/crossLink}},
	 * its files will <strong>NOT</strong> use the basePath parameter. <strong>The basePath parameter is deprecated.</strong>
	 * This parameter will be removed in a future version. Please either use the `basePath` parameter in the LoadQueue
	 * constructor, or a `path` property in a manifest definition.
	 */
	p.loadManifest = function (manifest, loadNow, basePath) {
		var fileList = null;
		var path = null;

		// Array-based list of items
		if (Array.isArray(manifest)) {
			if (manifest.length == 0) {
				var event = new createjs.ErrorEvent("PRELOAD_MANIFEST_EMPTY");
				this._sendError(event);
				return;
			}
			fileList = manifest;

			// String-based. Only file manifests can be specified this way. Any other types will cause an error when loaded.
		} else if (typeof(manifest) === "string") {
			fileList = [
				{
					src: manifest,
					type: s.MANIFEST
				}
			];

		} else if (typeof(manifest) == "object") {

			// An object that defines a manifest path
			if (manifest.src !== undefined) {
				if (manifest.type == null) {
					manifest.type = s.MANIFEST;
				} else if (manifest.type != s.MANIFEST) {
					var event = new createjs.ErrorEvent("PRELOAD_MANIFEST_TYPE");
					this._sendError(event);
				}
				fileList = [manifest];

				// An object that defines a manifest
			} else if (manifest.manifest !== undefined) {
				fileList = manifest.manifest;
				path = manifest.path;
			}

			// Unsupported. This will throw an error.
		} else {
			var event = new createjs.ErrorEvent("PRELOAD_MANIFEST_NULL");
			this._sendError(event);
			return;
		}

		for (var i = 0, l = fileList.length; i < l; i++) {
			this._addItem(fileList[i], path, basePath);
		}

		if (loadNow !== false) {
			this.setPaused(false);
		} else {
			this.setPaused(true);
		}

	};

	/**
	 * Start a LoadQueue that was created, but not automatically started.
	 * @method load
	 */
	p.load = function () {
		this.setPaused(false);
	};

	/**
	 * Look up a {{#crossLink "LoadItem"}}{{/crossLink}} using either the "id" or "src" that was specified when loading it. Note that if no "id" was
	 * supplied with the load item, the ID will be the "src", including a `path` property defined by a manifest. The
	 * `basePath` will not be part of the ID.
	 * @method getItem
	 * @param {String} value The <code>id</code> or <code>src</code> of the load item.
	 * @return {Object} The load item that was initially requested using {{#crossLink "LoadQueue/loadFile"}}{{/crossLink}}
	 * or {{#crossLink "LoadQueue/loadManifest"}}{{/crossLink}}. This object is also returned via the {{#crossLink "LoadQueue/fileload:event"}}{{/crossLink}}
	 * event as the `item` parameter.
	 */
	p.getItem = function (value) {
		return this._loadItemsById[value] || this._loadItemsBySrc[value];
	};

	/**
	 * Look up a loaded result using either the "id" or "src" that was specified when loading it. Note that if no "id"
	 * was supplied with the load item, the ID will be the "src", including a `path` property defined by a manifest. The
	 * `basePath` will not be part of the ID.
	 * @method getResult
	 * @param {String} value The <code>id</code> or <code>src</code> of the load item.
	 * @param {Boolean} [rawResult=false] Return a raw result instead of a formatted result. This applies to content
	 * loaded via XHR such as scripts, XML, CSS, and Images. If there is no raw result, the formatted result will be
	 * returned instead.
	 * @return {Object} A result object containing the content that was loaded, such as:
	 * <ul>
	 *      <li>An image tag (&lt;image /&gt;) for images</li>
	 *      <li>A script tag for JavaScript (&lt;script /&gt;). Note that scripts are automatically added to the HTML
	 *      DOM.</li>
	 *      <li>A style tag for CSS (&lt;style /&gt; or &lt;link &gt;)</li>
	 *      <li>Raw text for TEXT</li>
	 *      <li>A formatted JavaScript object defined by JSON</li>
	 *      <li>An XML document</li>
	 *      <li>A binary arraybuffer loaded by XHR</li>
	 *      <li>An audio tag (&lt;audio &gt;) for HTML audio. Note that it is recommended to use SoundJS APIs to play
	 *      loaded audio. Specifically, audio loaded by Flash and WebAudio will return a loader object using this method
	 *      which can not be used to play audio back.</li>
	 * </ul>
	 * This object is also returned via the {{#crossLink "LoadQueue/fileload:event"}}{{/crossLink}} event as the 'item`
	 * parameter. Note that if a raw result is requested, but not found, the result will be returned instead.
	 */
	p.getResult = function (value, rawResult) {
		var item = this._loadItemsById[value] || this._loadItemsBySrc[value];
		if (item == null) {
			return null;
		}
		var id = item.id;
		if (rawResult && this._loadedRawResults[id]) {
			return this._loadedRawResults[id];
		}
		return this._loadedResults[id];
	};

	/**
	 * Generate an list of items loaded by this queue.
	 * @method getItems
	 * @param {Boolean} loaded Determines if only items that have been loaded should be returned. If false, in-progress
	 * and failed load items will also be included.
	 * @returns {Array} A list of objects that have been loaded. Each item includes the {{#crossLink "LoadItem"}}{{/crossLink}},
	 * result, and rawResult.
	 * @since 0.6.0
	 */
	p.getItems = function (loaded) {
		var arr = [];
		for (var n in this._loadItemsById) {
			var item = this._loadItemsById[n];
			var result = this.getResult(n);
			if (loaded === true && result == null) {
				continue;
			}
			arr.push({
				item: item,
				result: result,
				rawResult: this.getResult(n, true)
			});
		}
		return arr;
	};

	/**
	 * Pause or resume the current load. Active loads will not be cancelled, but the next items in the queue will not
	 * be processed when active loads complete. LoadQueues are not paused by default.
	 *
	 * Note that if new items are added to the queue using {{#crossLink "LoadQueue/loadFile"}}{{/crossLink}} or
	 * {{#crossLink "LoadQueue/loadManifest"}}{{/crossLink}}, a paused queue will be resumed, unless the `loadNow`
	 * argument is `false`.
	 * @method setPaused
	 * @param {Boolean} value Whether the queue should be paused or not.
	 */
	p.setPaused = function (value) {
		this._paused = value;
		if (!this._paused) {
			this._loadNext();
		}
	};

	/**
	 * Close the active queue. Closing a queue completely empties the queue, and prevents any remaining items from
	 * starting to download. Note that currently any active loads will remain open, and events may be processed.
	 *
	 * To stop and restart a queue, use the {{#crossLink "LoadQueue/setPaused"}}{{/crossLink}} method instead.
	 * @method close
	 */
	p.close = function () {
		while (this._currentLoads.length) {
			this._currentLoads.pop().cancel();
		}
		this._scriptOrder.length = 0;
		this._loadedScripts.length = 0;
		this.loadStartWasDispatched = false;
		this._itemCount = 0;
		this._lastProgress = NaN;
	};

// protected methods
	/**
	 * Add an item to the queue. Items are formatted into a usable object containing all the properties necessary to
	 * load the content. The load queue is populated with the loader instance that handles preloading, and not the load
	 * item that was passed in by the user. To look up the load item by id or src, use the {{#crossLink "LoadQueue.getItem"}}{{/crossLink}}
	 * method.
	 * @method _addItem
	 * @param {String|Object} value The item to add to the queue.
	 * @param {String} [path] An optional path prepended to the `src`. The path will only be prepended if the src is
	 * relative, and does not start with a protocol such as `http://`, or a path like `../`. If the LoadQueue was
	 * provided a {{#crossLink "_basePath"}}{{/crossLink}}, then it will optionally be prepended after.
	 * @param {String} [basePath] <strong>Deprecated</strong>An optional basePath passed into a {{#crossLink "LoadQueue/loadManifest"}}{{/crossLink}}
	 * or {{#crossLink "LoadQueue/loadFile"}}{{/crossLink}} call. This parameter will be removed in a future tagged
	 * version.
	 * @private
	 */
	p._addItem = function (value, path, basePath) {
		var item = this._createLoadItem(value, path, basePath); // basePath and manifest path are added to the src.
		if (item == null) {
			return;
		} // Sometimes plugins or types should be skipped.
		var loader = this._createLoader(item);
		if (loader != null) {
			if ("plugins" in loader) {
				loader.plugins = this._plugins;
			}
			item._loader = loader;
			this._loadQueue.push(loader);
			this._loadQueueBackup.push(loader);

			this._numItems++;
			this._updateProgress();

			// Only worry about script order when using XHR to load scripts. Tags are only loading one at a time.
			if ((this.maintainScriptOrder
					&& item.type == createjs.LoadQueue.JAVASCRIPT
						//&& loader instanceof createjs.XHRLoader //NOTE: Have to track all JS files this way
					)
					|| item.maintainOrder === true) {
				this._scriptOrder.push(item);
				this._loadedScripts.push(null);
			}
		}
	};

	/**
	 * Create a refined {{#crossLink "LoadItem"}}{{/crossLink}}, which contains all the required properties. The type of
	 * item is determined by browser support, requirements based on the file type, and developer settings. For example,
	 * XHR is only used for file types that support it in new browsers.
	 *
	 * Before the item is returned, any plugins registered to handle the type or extension will be fired, which may
	 * alter the load item.
	 * @method _createLoadItem
	 * @param {String | Object | HTMLAudioElement | HTMLImageElement} value The item that needs to be preloaded.
	 * @param {String} [path] A path to prepend to the item's source. Sources beginning with http:// or similar will
	 * not receive a path. Since PreloadJS 0.4.1, the src will be modified to include the `path` and {{#crossLink "LoadQueue/_basePath:property"}}{{/crossLink}}
	 * when it is added.
	 * @param {String} [basePath] <strong>Deprectated</strong> A base path to prepend to the items source in addition to
	 * the path argument.
	 * @return {Object} The loader instance that will be used.
	 * @private
	 */
	p._createLoadItem = function (value, path, basePath) {
		var item = createjs.LoadItem.create(value);
		if (item == null) {
			return null;
		}

		var bp = ""; // Store the generated basePath
		var useBasePath = basePath || this._basePath;

		if (item.src instanceof Object) {
			if (!item.type) {
				return null;
			} // the the src is an object, type is required to pass off to plugin
			if (path) {
				bp = path;
				var pathMatch = createjs.RequestUtils.parseURI(path);
				// Also append basePath
				if (useBasePath != null && !pathMatch.absolute && !pathMatch.relative) {
					bp = useBasePath + bp;
				}
			} else if (useBasePath != null) {
				bp = useBasePath;
			}
		} else {
			// Determine Extension, etc.
			var match = createjs.RequestUtils.parseURI(item.src);
			if (match.extension) {
				item.ext = match.extension;
			}
			if (item.type == null) {
				item.type = createjs.RequestUtils.getTypeByExtension(item.ext);
			}

			// Inject path & basePath
			var autoId = item.src;
			if (!match.absolute && !match.relative) {
				if (path) {
					bp = path;
					var pathMatch = createjs.RequestUtils.parseURI(path);
					autoId = path + autoId;
					// Also append basePath
					if (useBasePath != null && !pathMatch.absolute && !pathMatch.relative) {
						bp = useBasePath + bp;
					}
				} else if (useBasePath != null) {
					bp = useBasePath;
				}
			}
			item.src = bp + item.src;
		}
		item.path = bp;

		// If there's no id, set one now.
		if (item.id === undefined || item.id === null || item.id === "") {
			item.id = autoId;
		}

		// Give plugins a chance to modify the loadItem:
		var customHandler = this._typeCallbacks[item.type] || this._extensionCallbacks[item.ext];
		if (customHandler) {
			// Plugins are now passed both the full source, as well as a combined path+basePath (appropriately)
			var result = customHandler.callback.call(customHandler.scope, item, this);

			// The plugin will handle the load, or has canceled it. Ignore it.
			if (result === false) {
				return null;

				// Load as normal:
			} else if (result === true) {
				// Do Nothing

				// Result is a loader class:
			} else if (result != null) {
				item._loader = result;
			}

			// Update the extension in case the type changed:
			match = createjs.RequestUtils.parseURI(item.src);
			if (match.extension != null) {
				item.ext = match.extension;
			}
		}

		// Store the item for lookup. This also helps clean-up later.
		this._loadItemsById[item.id] = item;
		this._loadItemsBySrc[item.src] = item;

		if (item.crossOrigin == null) {
			item.crossOrigin = this._crossOrigin;
		}

		return item;
	};

	/**
	 * Create a loader for a load item.
	 * @method _createLoader
	 * @param {Object} item A formatted load item that can be used to generate a loader.
	 * @return {AbstractLoader} A loader that can be used to load content.
	 * @private
	 */
	p._createLoader = function (item) {
		if (item._loader != null) { // A plugin already specified a loader
			return item._loader;
		}

		// Initially, try and use the provided/supported XHR mode:
		var preferXHR = this.preferXHR;

		for (var i = 0; i < this._availableLoaders.length; i++) {
			var loader = this._availableLoaders[i];
			if (loader && loader.canLoadItem(item)) {
				return new loader(item, preferXHR);
			}
		}

		// TODO: Log error (requires createjs.log)
		return null;
	};

	/**
	 * Load the next item in the queue. If the queue is empty (all items have been loaded), then the complete event
	 * is processed. The queue will "fill up" any empty slots, up to the max connection specified using
	 * {{#crossLink "LoadQueue.setMaxConnections"}}{{/crossLink}} method. The only exception is scripts that are loaded
	 * using tags, which have to be loaded one at a time to maintain load order.
	 * @method _loadNext
	 * @private
	 */
	p._loadNext = function () {
		if (this._paused) {
			return;
		}

		// Only dispatch loadstart event when the first file is loaded.
		if (!this._loadStartWasDispatched) {
			this._sendLoadStart();
			this._loadStartWasDispatched = true;
		}

		// The queue has completed.
		if (this._numItems == this._numItemsLoaded) {
			this.loaded = true;
			this._sendComplete();

			// Load the next queue, if it has been defined.
			if (this.next && this.next.load) {
				this.next.load();
			}
		} else {
			this.loaded = false;
		}

		// Must iterate forwards to load in the right order.
		for (var i = 0; i < this._loadQueue.length; i++) {
			if (this._currentLoads.length >= this._maxConnections) {
				break;
			}
			var loader = this._loadQueue[i];

			// Determine if we should be only loading one tag-script at a time:
			// Note: maintainOrder items don't do anything here because we can hold onto their loaded value
			if (!this._canStartLoad(loader)) {
				continue;
			}
			this._loadQueue.splice(i, 1);
			i--;
			this._loadItem(loader);
		}
	};

	/**
	 * Begin loading an item. Event listeners are not added to the loaders until the load starts.
	 * @method _loadItem
	 * @param {AbstractLoader} loader The loader instance to start. Currently, this will be an XHRLoader or TagLoader.
	 * @private
	 */
	p._loadItem = function (loader) {
		loader.on("fileload", this._handleFileLoad, this);
		loader.on("progress", this._handleProgress, this);
		loader.on("complete", this._handleFileComplete, this);
		loader.on("error", this._handleError, this);
		loader.on("fileerror", this._handleFileError, this);
		this._currentLoads.push(loader);
		this._sendFileStart(loader.getItem());
		loader.load();
	};

	/**
	 * The callback that is fired when a loader loads a file. This enables loaders like {{#crossLink "ManifestLoader"}}{{/crossLink}}
	 * to maintain internal queues, but for this queue to dispatch the {{#crossLink "fileload:event"}}{{/crossLink}}
	 * events.
	 * @param {Event} event The {{#crossLink "AbstractLoader/fileload:event"}}{{/crossLink}} event from the loader.
	 * @private
	 * @since 0.6.0
	 */
	p._handleFileLoad = function (event) {
		event.target = null;
		this.dispatchEvent(event);
	};

	/**
	 * The callback that is fired when a loader encounters an error from an internal file load operation. This enables
	 * loaders like M
	 * @param event
	 * @private
	 */
	p._handleFileError = function (event) {
		var newEvent = new createjs.ErrorEvent("FILE_LOAD_ERROR", null, event.item);
		this._sendError(newEvent);
	};

	/**
	 * The callback that is fired when a loader encounters an error. The queue will continue loading unless {{#crossLink "LoadQueue/stopOnError:property"}}{{/crossLink}}
	 * is set to `true`.
	 * @method _handleError
	 * @param {ErrorEvent} event The error event, containing relevant error information.
	 * @private
	 */
	p._handleError = function (event) {
		var loader = event.target;
		this._numItemsLoaded++;

		this._finishOrderedItem(loader, true);
		this._updateProgress();

		var newEvent = new createjs.ErrorEvent("FILE_LOAD_ERROR", null, loader.getItem());
		// TODO: Propagate actual error message.

		this._sendError(newEvent);

		if (!this.stopOnError) {
			this._removeLoadItem(loader);
			this._cleanLoadItem(loader);
			this._loadNext();
		} else {
			this.setPaused(true);
		}
	};

	/**
	 * An item has finished loading. We can assume that it is totally loaded, has been parsed for immediate use, and
	 * is available as the "result" property on the load item. The raw text result for a parsed item (such as JSON, XML,
	 * CSS, JavaScript, etc) is available as the "rawResult" property, and can also be looked up using {{#crossLink "LoadQueue/getResult"}}{{/crossLink}}.
	 * @method _handleFileComplete
	 * @param {Event} event The event object from the loader.
	 * @private
	 */
	p._handleFileComplete = function (event) {
		var loader = event.target;
		var item = loader.getItem();

		var result = loader.getResult();
		this._loadedResults[item.id] = result;
		var rawResult = loader.getResult(true);
		if (rawResult != null && rawResult !== result) {
			this._loadedRawResults[item.id] = rawResult;
		}

		this._saveLoadedItems(loader);

		// Remove the load item
		this._removeLoadItem(loader);

		if (!this._finishOrderedItem(loader)) {
			// The item was NOT managed, so process it now
			this._processFinishedLoad(item, loader);
		}

		// Clean up the load item
		this._cleanLoadItem(loader);
	};

	/**
	 * Some loaders might load additional content, other than the item they were passed (such as {{#crossLink "ManifestLoader"}}{{/crossLink}}).
	 * Any items exposed by the loader using {{#crossLink "AbstractLoader/getLoadItems"}}{{/crossLink}} are added to the
	 * LoadQueue's look-ups, including {{#crossLink "getItem"}}{{/crossLink}} and {{#crossLink "getResult"}}{{/crossLink}}
	 * methods.
	 * @method _saveLoadedItems
	 * @param {AbstractLoader} loader
	 * @protected
	 * @since 0.6.0
	 */
	p._saveLoadedItems = function (loader) {
		// TODO: Not sure how to handle this. Would be nice to expose the items.
		// Loaders may load sub-items. This adds them to this queue
		var list = loader.getLoadedItems();
		if (list === null) {
			return;
		}

		for (var i = 0; i < list.length; i++) {
			var item = list[i].item;

			// Store item lookups
			this._loadItemsBySrc[item.src] = item;
			this._loadItemsById[item.id] = item;

			// Store loaded content
			this._loadedResults[item.id] = list[i].result;
			this._loadedRawResults[item.id] = list[i].rawResult;
		}
	};

	/**
	 * Flag an item as finished. If the item's order is being managed, then ensure that it is allowed to finish, and if
	 * so, trigger prior items to trigger as well.
	 * @method _finishOrderedItem
	 * @param {AbstractLoader} loader
	 * @param {Boolean} loadFailed
	 * @return {Boolean} If the item's order is being managed. This allows the caller to take an alternate
	 * behaviour if it is.
	 * @private
	 */
	p._finishOrderedItem = function (loader, loadFailed) {
		var item = loader.getItem();

		if ((this.maintainScriptOrder && item.type == createjs.LoadQueue.JAVASCRIPT)
				|| item.maintainOrder) {

			//TODO: Evaluate removal of the _currentlyLoadingScript
			if (loader instanceof createjs.JavaScriptLoader) {
				this._currentlyLoadingScript = false;
			}

			var index = createjs.indexOf(this._scriptOrder, item);
			if (index == -1) {
				return false;
			} // This loader no longer exists
			this._loadedScripts[index] = (loadFailed === true) ? true : item;

			this._checkScriptLoadOrder();
			return true;
		}

		return false;
	};

	/**
	 * Ensure the scripts load and dispatch in the correct order. When using XHR, scripts are stored in an array in the
	 * order they were added, but with a "null" value. When they are completed, the value is set to the load item,
	 * and then when they are processed and dispatched, the value is set to `true`. This method simply
	 * iterates the array, and ensures that any loaded items that are not preceded by a `null` value are
	 * dispatched.
	 * @method _checkScriptLoadOrder
	 * @private
	 */
	p._checkScriptLoadOrder = function () {
		var l = this._loadedScripts.length;

		for (var i = 0; i < l; i++) {
			var item = this._loadedScripts[i];
			if (item === null) {
				break;
			} // This is still loading. Do not process further.
			if (item === true) {
				continue;
			} // This has completed, and been processed. Move on.

			var loadItem = this._loadedResults[item.id];
			if (item.type == createjs.LoadQueue.JAVASCRIPT) {
				// Append script tags to the head automatically.
				createjs.DomUtils.appendToHead(loadItem);
			}

			var loader = item._loader;
			this._processFinishedLoad(item, loader);
			this._loadedScripts[i] = true;
		}
	};

	/**
	 * A file has completed loading, and the LoadQueue can move on. This triggers the complete event, and kick-starts
	 * the next item.
	 * @method _processFinishedLoad
	 * @param {LoadItem|Object} item
	 * @param {AbstractLoader} loader
	 * @protected
	 */
	p._processFinishedLoad = function (item, loader) {
		this._numItemsLoaded++;

		// Since LoadQueue needs maintain order, we can't append scripts in the loader.
		// So we do it here instead. Or in _checkScriptLoadOrder();
		if (!this.maintainScriptOrder && item.type == createjs.LoadQueue.JAVASCRIPT) {
			var tag = loader.getTag();
			createjs.DomUtils.appendToHead(tag);
		}

		this._updateProgress();
		this._sendFileComplete(item, loader);
		this._loadNext();
	};

	/**
	 * Ensure items with `maintainOrder=true` that are before the specified item have loaded. This only applies to
	 * JavaScript items that are being loaded with a TagLoader, since they have to be loaded and completed <strong>before</strong>
	 * the script can even be started, since it exist in the DOM while loading.
	 * @method _canStartLoad
	 * @param {AbstractLoader} loader The loader for the item
	 * @return {Boolean} Whether the item can start a load or not.
	 * @private
	 */
	p._canStartLoad = function (loader) {
		if (!this.maintainScriptOrder || loader.preferXHR) {
			return true;
		}
		var item = loader.getItem();
		if (item.type != createjs.LoadQueue.JAVASCRIPT) {
			return true;
		}
		if (this._currentlyLoadingScript) {
			return false;
		}

		var index = this._scriptOrder.indexOf(item);
		var i = 0;
		while (i < index) {
			var checkItem = this._loadedScripts[i];
			if (checkItem == null) {
				return false;
			}
			i++;
		}
		this._currentlyLoadingScript = true;
		return true;
	};

	/**
	 * A load item is completed or was canceled, and needs to be removed from the LoadQueue.
	 * @method _removeLoadItem
	 * @param {AbstractLoader} loader A loader instance to remove.
	 * @private
	 */
	p._removeLoadItem = function (loader) {
		var l = this._currentLoads.length;
		for (var i = 0; i < l; i++) {
			if (this._currentLoads[i] == loader) {
				this._currentLoads.splice(i, 1);
				break;
			}
		}
	};

	/**
	 * Remove unneeded references from a loader.
	 *
	 * @param loader
	 * @private
	 */
	p._cleanLoadItem = function(loader) {
		var item = loader.getItem();
		if (item) {
			delete item._loader;
		}
	}

	/**
	 * An item has dispatched progress. Propagate that progress, and update the LoadQueue's overall progress.
	 * @method _handleProgress
	 * @param {ProgressEvent} event The progress event from the item.
	 * @private
	 */
	p._handleProgress = function (event) {
		var loader = event.target;
		this._sendFileProgress(loader.getItem(), loader.progress);
		this._updateProgress();
	};

	/**
	 * Overall progress has changed, so determine the new progress amount and dispatch it. This changes any time an
	 * item dispatches progress or completes. Note that since we don't always know the actual filesize of items before
	 * they are loaded. In this case, we define a "slot" for each item (1 item in 10 would get 10%), and then append
	 * loaded progress on top of the already-loaded items.
	 *
	 * For example, if 5/10 items have loaded, and item 6 is 20% loaded, the total progress would be:
	 * <ul>
	 *      <li>5/10 of the items in the queue (50%)</li>
	 *      <li>plus 20% of item 6's slot (2%)</li>
	 *      <li>equals 52%</li>
	 * </ul>
	 * @method _updateProgress
	 * @private
	 */
	p._updateProgress = function () {
		var loaded = this._numItemsLoaded / this._numItems; // Fully Loaded Progress
		var remaining = this._numItems - this._numItemsLoaded;
		if (remaining > 0) {
			var chunk = 0;
			for (var i = 0, l = this._currentLoads.length; i < l; i++) {
				chunk += this._currentLoads[i].progress;
			}
			loaded += (chunk / remaining) * (remaining / this._numItems);
		}

		if (this._lastProgress != loaded) {
			this._sendProgress(loaded);
			this._lastProgress = loaded;
		}
	};

	/**
	 * Clean out item results, to free them from memory. Mainly, the loaded item and results are cleared from internal
	 * hashes.
	 * @method _disposeItem
	 * @param {LoadItem|Object} item The item that was passed in for preloading.
	 * @private
	 */
	p._disposeItem = function (item) {
		delete this._loadedResults[item.id];
		delete this._loadedRawResults[item.id];
		delete this._loadItemsById[item.id];
		delete this._loadItemsBySrc[item.src];
	};

	/**
	 * Dispatch a "fileprogress" {{#crossLink "Event"}}{{/crossLink}}. Please see the LoadQueue {{#crossLink "LoadQueue/fileprogress:event"}}{{/crossLink}}
	 * event for details on the event payload.
	 * @method _sendFileProgress
	 * @param {LoadItem|Object} item The item that is being loaded.
	 * @param {Number} progress The amount the item has been loaded (between 0 and 1).
	 * @protected
	 */
	p._sendFileProgress = function (item, progress) {
		if (this._isCanceled() || this._paused) {
			return;
		}
		if (!this.hasEventListener("fileprogress")) {
			return;
		}

		//LM: Rework ProgressEvent to support this?
		var event = new createjs.Event("fileprogress");
		event.progress = progress;
		event.loaded = progress;
		event.total = 1;
		event.item = item;

		this.dispatchEvent(event);
	};

	/**
	 * Dispatch a fileload {{#crossLink "Event"}}{{/crossLink}}. Please see the {{#crossLink "LoadQueue/fileload:event"}}{{/crossLink}} event for
	 * details on the event payload.
	 * @method _sendFileComplete
	 * @param {LoadItemObject} item The item that is being loaded.
	 * @param {AbstractLoader} loader
	 * @protected
	 */
	p._sendFileComplete = function (item, loader) {
		if (this._isCanceled() || this._paused) {
			return;
		}

		var event = new createjs.Event("fileload");
		event.loader = loader;
		event.item = item;
		event.result = this._loadedResults[item.id];
		event.rawResult = this._loadedRawResults[item.id];

		// This calls a handler specified on the actual load item. Currently, the SoundJS plugin uses this.
		if (item.completeHandler) {
			item.completeHandler(event);
		}

		this.hasEventListener("fileload") && this.dispatchEvent(event);
	};

	/**
	 * Dispatch a filestart {{#crossLink "Event"}}{{/crossLink}} immediately before a file starts to load. Please see
	 * the {{#crossLink "LoadQueue/filestart:event"}}{{/crossLink}} event for details on the event payload.
	 * @method _sendFileStart
	 * @param {LoadItem|Object} item The item that is being loaded.
	 * @protected
	 */
	p._sendFileStart = function (item) {
		var event = new createjs.Event("filestart");
		event.item = item;
		this.hasEventListener("filestart") && this.dispatchEvent(event);
	};

	p.toString = function () {
		return "[PreloadJS LoadQueue]";
	};

	createjs.LoadQueue = createjs.promote(LoadQueue, "AbstractLoader");
}());

//##############################################################################
// TextLoader.js
//##############################################################################

this.createjs = this.createjs || {};

(function () {
	"use strict";

	// constructor
	/**
	 * A loader for Text files.
	 * @class TextLoader
	 * @param {LoadItem|Object} loadItem
	 * @extends AbstractLoader
	 * @constructor
	 */
	function TextLoader(loadItem) {
		this.AbstractLoader_constructor(loadItem, true, createjs.AbstractLoader.TEXT);
	};

	var p = createjs.extend(TextLoader, createjs.AbstractLoader);
	var s = TextLoader;

	// static methods
	/**
	 * Determines if the loader can load a specific item. This loader loads items that are of type {{#crossLink "AbstractLoader/TEXT:property"}}{{/crossLink}},
	 * but is also the default loader if a file type can not be determined.
	 * @method canLoadItem
	 * @param {LoadItem|Object} item The LoadItem that a LoadQueue is trying to load.
	 * @returns {Boolean} Whether the loader can load the item.
	 * @static
	 */
	s.canLoadItem = function (item) {
		return item.type == createjs.AbstractLoader.TEXT;
	};

	createjs.TextLoader = createjs.promote(TextLoader, "AbstractLoader");

}());

//##############################################################################
// BinaryLoader.js
//##############################################################################

this.createjs = this.createjs || {};

(function () {
	"use strict";

	// constructor
	/**
	 * A loader for binary files. This is useful for loading web audio, or content that requires an ArrayBuffer.
	 * @class BinaryLoader
	 * @param {LoadItem|Object} loadItem
	 * @extends AbstractLoader
	 * @constructor
	 */
	function BinaryLoader(loadItem) {
		this.AbstractLoader_constructor(loadItem, true, createjs.AbstractLoader.BINARY);
		this.on("initialize", this._updateXHR, this);
	};

	var p = createjs.extend(BinaryLoader, createjs.AbstractLoader);
	var s = BinaryLoader;

	// static methods
	/**
	 * Determines if the loader can load a specific item. This loader can only load items that are of type
	 * {{#crossLink "AbstractLoader/BINARY:property"}}{{/crossLink}}
	 * @method canLoadItem
	 * @param {LoadItem|Object} item The LoadItem that a LoadQueue is trying to load.
	 * @returns {Boolean} Whether the loader can load the item.
	 * @static
	 */
	s.canLoadItem = function (item) {
		return item.type == createjs.AbstractLoader.BINARY;
	};

	// private methods
	/**
	 * Before the item loads, set the response type to "arraybuffer"
	 * @property _updateXHR
	 * @param {Event} event
	 * @private
	 */
	p._updateXHR = function (event) {
		event.loader.setResponseType("arraybuffer");
	};

	createjs.BinaryLoader = createjs.promote(BinaryLoader, "AbstractLoader");

}());

//##############################################################################
// CSSLoader.js
//##############################################################################

this.createjs = this.createjs || {};

(function () {
	"use strict";

	// constructor
	/**
	 * A loader for CSS files.
	 * @class CSSLoader
	 * @param {LoadItem|Object} loadItem
	 * @param {Boolean} preferXHR
	 * @extends AbstractLoader
	 * @constructor
	 */
	function CSSLoader(loadItem, preferXHR) {
		this.AbstractLoader_constructor(loadItem, preferXHR, createjs.AbstractLoader.CSS);

		// public properties
		this.resultFormatter = this._formatResult;

		// protected properties
		this._tagSrcAttribute = "href";

		if (preferXHR) {
			this._tag = document.createElement("style");
		} else {
			this._tag = document.createElement("link");
		}

		this._tag.rel = "stylesheet";
		this._tag.type = "text/css";
	};

	var p = createjs.extend(CSSLoader, createjs.AbstractLoader);
	var s = CSSLoader;

	// static methods
	/**
	 * Determines if the loader can load a specific item. This loader can only load items that are of type
	 * {{#crossLink "AbstractLoader/CSS:property"}}{{/crossLink}}.
	 * @method canLoadItem
	 * @param {LoadItem|Object} item The LoadItem that a LoadQueue is trying to load.
	 * @returns {Boolean} Whether the loader can load the item.
	 * @static
	 */
	s.canLoadItem = function (item) {
		return item.type == createjs.AbstractLoader.CSS;
	};

	// protected methods
	/**
	 * The result formatter for CSS files.
	 * @method _formatResult
	 * @param {AbstractLoader} loader
	 * @returns {HTMLLinkElement|HTMLStyleElement}
	 * @private
	 */
	p._formatResult = function (loader) {
		if (this._preferXHR) {
			var tag = loader.getTag();

			if (tag.styleSheet) { // IE
				tag.styleSheet.cssText = loader.getResult(true);
			} else {
				var textNode = document.createTextNode(loader.getResult(true));
				tag.appendChild(textNode);
			}
		} else {
			tag = this._tag;
		}

		createjs.DomUtils.appendToHead(tag);

		return tag;
	};

	createjs.CSSLoader = createjs.promote(CSSLoader, "AbstractLoader");

}());

//##############################################################################
// ImageLoader.js
//##############################################################################

this.createjs = this.createjs || {};

(function () {
	"use strict";

	// constructor
	/**
	 * A loader for image files.
	 * @class ImageLoader
	 * @param {LoadItem|Object} loadItem
	 * @param {Boolean} preferXHR
	 * @extends AbstractLoader
	 * @constructor
	 */
	function ImageLoader (loadItem, preferXHR) {
		this.AbstractLoader_constructor(loadItem, preferXHR, createjs.AbstractLoader.IMAGE);

		// public properties
		this.resultFormatter = this._formatResult;

		// protected properties
		this._tagSrcAttribute = "src";

		// Check if the preload item is already a tag.
		if (createjs.RequestUtils.isImageTag(loadItem)) {
			this._tag = loadItem;
		} else if (createjs.RequestUtils.isImageTag(loadItem.src)) {
			this._tag = loadItem.src;
		} else if (createjs.RequestUtils.isImageTag(loadItem.tag)) {
			this._tag = loadItem.tag;
		}

		if (this._tag != null) {
			this._preferXHR = false;
		} else {
			this._tag = document.createElement("img");
		}

		this.on("initialize", this._updateXHR, this);
	};

	var p = createjs.extend(ImageLoader, createjs.AbstractLoader);
	var s = ImageLoader;

	// static methods
	/**
	 * Determines if the loader can load a specific item. This loader can only load items that are of type
	 * {{#crossLink "AbstractLoader/IMAGE:property"}}{{/crossLink}}.
	 * @method canLoadItem
	 * @param {LoadItem|Object} item The LoadItem that a LoadQueue is trying to load.
	 * @returns {Boolean} Whether the loader can load the item.
	 * @static
	 */
	s.canLoadItem = function (item) {
		return item.type == createjs.AbstractLoader.IMAGE;
	};

	// public methods
	p.load = function () {
		if (this._tag.src != "" && this._tag.complete) {
			this._sendComplete();
			return;
		}

		var crossOrigin = this._item.crossOrigin;
		if (crossOrigin == true) { crossOrigin = "Anonymous"; }
		if (crossOrigin != null && !createjs.RequestUtils.isLocal(this._item.src)) {
			this._tag.crossOrigin = crossOrigin;
		}

		this.AbstractLoader_load();
	};

	// protected methods
	/**
	 * Before the item loads, set its mimeType and responseType.
	 * @property _updateXHR
	 * @param {Event} event
	 * @private
	 */
	p._updateXHR = function (event) {
		event.loader.mimeType = 'text/plain; charset=x-user-defined-binary';

		// Only exists for XHR
		if (event.loader.setResponseType) {
			event.loader.setResponseType("blob");
		}
	};

	/**
	 * The result formatter for Image files.
	 * @method _formatResult
	 * @param {AbstractLoader} loader
	 * @returns {HTMLImageElement}
	 * @private
	 */
	p._formatResult = function (loader) {
		return this._formatImage;
	};

	/**
	 * The asynchronous image formatter function. This is required because images have
	 * a short delay before they are ready.
	 * @method _formatImage
	 * @param {Function} successCallback The method to call when the result has finished formatting
	 * @param {Function} errorCallback The method to call if an error occurs during formatting
	 * @private
	 */
	p._formatImage = function (successCallback, errorCallback) {
		var tag = this._tag;
		var URL = window.URL || window.webkitURL;

		if (!this._preferXHR) {
			//document.body.removeChild(tag);
		} else if (URL) {
			var objURL = URL.createObjectURL(this.getResult(true));
			tag.src = objURL;

			tag.addEventListener("load", this._cleanUpURL, false);
			tag.addEventListener("error", this._cleanUpURL, false);
		} else {
			tag.src = this._item.src;
		}

		if (tag.complete) {
			successCallback(tag);
		} else {
            tag.onload = createjs.proxy(function() {
                successCallback(this._tag);
            }, this);

            tag.onerror = createjs.proxy(function() {
                errorCallback(_this._tag);
            }, this);
		}
	};

	/**
	 * Clean up the ObjectURL, the tag is done with it. Note that this function is run
	 * as an event listener without a proxy/closure, as it doesn't require it - so do not
	 * include any functionality that requires scope without changing it.
	 * @method _cleanUpURL
	 * @param event
	 * @private
	 */
	p._cleanUpURL = function (event) {
		var URL = window.URL || window.webkitURL;
		URL.revokeObjectURL(event.target.src);
	};

	createjs.ImageLoader = createjs.promote(ImageLoader, "AbstractLoader");

}());

//##############################################################################
// JavaScriptLoader.js
//##############################################################################

this.createjs = this.createjs || {};

(function () {
	"use strict";

	// constructor
	/**
	 * A loader for JavaScript files.
	 * @class JavaScriptLoader
	 * @param {LoadItem|Object} loadItem
	 * @param {Boolean} preferXHR
	 * @extends AbstractLoader
	 * @constructor
	 */
	function JavaScriptLoader(loadItem, preferXHR) {
		this.AbstractLoader_constructor(loadItem, preferXHR, createjs.AbstractLoader.JAVASCRIPT);

		// public properties
		this.resultFormatter = this._formatResult;

		// protected properties
		this._tagSrcAttribute = "src";
		this.setTag(document.createElement("script"));
	};

	var p = createjs.extend(JavaScriptLoader, createjs.AbstractLoader);
	var s = JavaScriptLoader;

	// static methods
	/**
	 * Determines if the loader can load a specific item. This loader can only load items that are of type
	 * {{#crossLink "AbstractLoader/JAVASCRIPT:property"}}{{/crossLink}}
	 * @method canLoadItem
	 * @param {LoadItem|Object} item The LoadItem that a LoadQueue is trying to load.
	 * @returns {Boolean} Whether the loader can load the item.
	 * @static
	 */
	s.canLoadItem = function (item) {
		return item.type == createjs.AbstractLoader.JAVASCRIPT;
	};

	// protected methods
	/**
	 * The result formatter for JavaScript files.
	 * @method _formatResult
	 * @param {AbstractLoader} loader
	 * @returns {HTMLLinkElement|HTMLStyleElement}
	 * @private
	 */
	p._formatResult = function (loader) {
		var tag = loader.getTag();
		if (this._preferXHR) {
			tag.text = loader.getResult(true);
		}
		return tag;
	};

	createjs.JavaScriptLoader = createjs.promote(JavaScriptLoader, "AbstractLoader");

}());

//##############################################################################
// JSONLoader.js
//##############################################################################

this.createjs = this.createjs || {};

(function () {
	"use strict";

	// constructor
	/**
	 * A loader for JSON files. To load JSON cross-domain, use JSONP and the {{#crossLink "JSONPLoader"}}{{/crossLink}}
	 * instead. To load JSON-formatted manifests, use {{#crossLink "ManifestLoader"}}{{/crossLink}}, and to
	 * load EaselJS SpriteSheets, use {{#crossLink "SpriteSheetLoader"}}{{/crossLink}}.
	 * @class JSONLoader
	 * @param {LoadItem|Object} loadItem
	 * @extends AbstractLoader
	 * @constructor
	 */
	function JSONLoader(loadItem) {
		this.AbstractLoader_constructor(loadItem, true, createjs.AbstractLoader.JSON);

		// public properties
		this.resultFormatter = this._formatResult;
	};

	var p = createjs.extend(JSONLoader, createjs.AbstractLoader);
	var s = JSONLoader;

	// static methods
	/**
	 * Determines if the loader can load a specific item. This loader can only load items that are of type
	 * {{#crossLink "AbstractLoader/JSON:property"}}{{/crossLink}}.
	 * @method canLoadItem
	 * @param {LoadItem|Object} item The LoadItem that a LoadQueue is trying to load.
	 * @returns {Boolean} Whether the loader can load the item.
	 * @static
	 */
	s.canLoadItem = function (item) {
		return item.type == createjs.AbstractLoader.JSON;
	};

	// protected methods
	/**
	 * The result formatter for JSON files.
	 * @method _formatResult
	 * @param {AbstractLoader} loader
	 * @returns {HTMLLinkElement|HTMLStyleElement}
	 * @private
	 */
	p._formatResult = function (loader) {
		var json = null;
		try {
			json = createjs.DataUtils.parseJSON(loader.getResult(true));
		} catch (e) {
			var event = new createjs.ErrorEvent("JSON_FORMAT", null, e);
			this._sendError(event);
			return e;
		}

		return json;
	};

	createjs.JSONLoader = createjs.promote(JSONLoader, "AbstractLoader");

}());

//##############################################################################
// JSONPLoader.js
//##############################################################################

this.createjs = this.createjs || {};

(function () {
	"use strict";

	// constructor
	/**
	 * A loader for JSONP files, which are JSON-formatted text files, wrapped in a callback. To load regular JSON
	 * without a callback use the {{#crossLink "JSONLoader"}}{{/crossLink}} instead. To load JSON-formatted manifests,
	 * use {{#crossLink "ManifestLoader"}}{{/crossLink}}, and to load EaselJS SpriteSheets, use
	 * {{#crossLink "SpriteSheetLoader"}}{{/crossLink}}.
	 *
	 * JSONP is a format that provides a solution for loading JSON files cross-domain <em>without</em> requiring CORS.
	 * JSONP files are loaded as JavaScript, and the "callback" is executed once they are loaded. The callback in the
	 * JSONP must match the callback passed to the loadItem.
	 *
	 * <h4>Example JSONP</h4>
	 *
	 * 		callbackName({
	 * 			"name": "value",
	 *	 		"num": 3,
	 *			"obj": { "bool":true }
	 * 		});
	 *
	 * <h4>Example</h4>
	 *
	 * 		var loadItem = {id:"json", type:"jsonp", src:"http://server.com/text.json", callback:"callbackName"}
	 * 		var queue = new createjs.LoadQueue();
	 * 		queue.on("complete", handleComplete);
	 * 		queue.loadItem(loadItem);
	 *
	 * 		function handleComplete(event) }
	 * 			var json = queue.getResult("json");
	 * 			console.log(json.obj.bool); // true
	 * 		}
	 *
	 * Note that JSONP files loaded concurrently require a <em>unique</em> callback. To ensure JSONP files are loaded
	 * in order, either use the {{#crossLink "LoadQueue/setMaxConnections"}}{{/crossLink}} method (set to 1),
	 * or set {{#crossLink "LoadItem/maintainOrder:property"}}{{/crossLink}} on items with the same callback.
	 *
	 * @class JSONPLoader
	 * @param {LoadItem|Object} loadItem
	 * @extends AbstractLoader
	 * @constructor
	 */
	function JSONPLoader(loadItem) {
		this.AbstractLoader_constructor(loadItem, false, createjs.AbstractLoader.JSONP);
		this.setTag(document.createElement("script"));
		this.getTag().type = "text/javascript";
	};

	var p = createjs.extend(JSONPLoader, createjs.AbstractLoader);
	var s = JSONPLoader;


	// static methods
	/**
	 * Determines if the loader can load a specific item. This loader can only load items that are of type
	 * {{#crossLink "AbstractLoader/JSONP:property"}}{{/crossLink}}.
	 * @method canLoadItem
	 * @param {LoadItem|Object} item The LoadItem that a LoadQueue is trying to load.
	 * @returns {Boolean} Whether the loader can load the item.
	 * @static
	 */
	s.canLoadItem = function (item) {
		return item.type == createjs.AbstractLoader.JSONP;
	};

	// public methods
	p.cancel = function () {
		this.AbstractLoader_cancel();
		this._dispose();
	};

	/**
	 * Loads the JSONp file.  Because of the unique loading needs of JSONp
	 * we don't use the AbstractLoader.load() method.
	 *
	 * @method load
	 *
	 */
	p.load = function () {
		if (this._item.callback == null) {
			throw new Error('callback is required for loading JSONP requests.');
		}

		// TODO: Look into creating our own iFrame to handle the load
		// In the first attempt, FF did not get the result
		//   result instanceof Object did not work either
		//   so we would need to clone the result.
		if (window[this._item.callback] != null) {
			throw new Error(
				"JSONP callback '" +
				this._item.callback +
				"' already exists on window. You need to specify a different callback or re-name the current one.");
		}

		window[this._item.callback] = createjs.proxy(this._handleLoad, this);
		window.document.body.appendChild(this._tag);

		this._loadTimeout = setTimeout(createjs.proxy(this._handleTimeout, this), this._item.loadTimeout);

		// Load the tag
		this._tag.src = this._item.src;
	};

	// private methods
	/**
	 * Handle the JSONP callback, which is a public method defined on `window`.
	 * @method _handleLoad
	 * @param {Object} data The formatted JSON data.
	 * @private
	 */
	p._handleLoad = function (data) {
		this._result = this._rawResult = data;
		this._sendComplete();

		this._dispose();
	};

	/**
	 * The tag request has not loaded within the time specfied in loadTimeout.
	 * @method _handleError
	 * @param {Object} event The XHR error event.
	 * @private
	 */
	p._handleTimeout = function () {
		this._dispose();
		this.dispatchEvent(new createjs.ErrorEvent("timeout"));
	};

	/**
	 * Clean up the JSONP load. This clears out the callback and script tag that this loader creates.
	 * @method _dispose
	 * @private
	 */
	p._dispose = function () {
		window.document.body.removeChild(this._tag);
		delete window[this._item.callback];

		clearTimeout(this._loadTimeout);
	};

	createjs.JSONPLoader = createjs.promote(JSONPLoader, "AbstractLoader");

}());

//##############################################################################
// ManifestLoader.js
//##############################################################################

this.createjs = this.createjs || {};

(function () {
	"use strict";

	// constructor
	/**
	 * A loader for JSON manifests. Items inside the manifest are loaded before the loader completes. To load manifests
	 * using JSONP, specify a {{#crossLink "LoadItem/callback:property"}}{{/crossLink}} as part of the
	 * {{#crossLink "LoadItem"}}{{/crossLink}}.
	 *
	 * The list of files in the manifest must be defined on the top-level JSON object in a `manifest` property. This
	 * example shows a sample manifest definition, as well as how to to include a sub-manifest.
	 *
	 * 		{
	 * 			"path": "assets/",
	 *	 	    "manifest": [
	 *				"image.png",
	 *				{"src": "image2.png", "id":"image2"},
	 *				{"src": "sub-manifest.json", "type":"manifest", "callback":"jsonCallback"}
	 *	 	    ]
	 *	 	}
	 *
	 * When a ManifestLoader has completed loading, the parent loader (usually a {{#crossLink "LoadQueue"}}{{/crossLink}},
	 * but could also be another ManifestLoader) will inherit all the loaded items, so you can access them directly.
	 *
	 * Note that the {{#crossLink "JSONLoader"}}{{/crossLink}} and {{#crossLink "JSONPLoader"}}{{/crossLink}} are
	 * higher priority loaders, so manifests <strong>must</strong> set the {{#crossLink "LoadItem"}}{{/crossLink}}
	 * {{#crossLink "LoadItem/type:property"}}{{/crossLink}} property to {{#crossLink "AbstractLoader/MANIFEST:property"}}{{/crossLink}}.
	 * @class ManifestLoader
	 * @param {LoadItem|Object} loadItem
	 * @extends AbstractLoader
	 * @constructor
	 */
	function ManifestLoader(loadItem) {
		this.AbstractLoader_constructor(loadItem, null, createjs.AbstractLoader.MANIFEST);

	// Public Properties
		/**
		 * An array of the plugins registered using {{#crossLink "LoadQueue/installPlugin"}}{{/crossLink}},
		 * used to pass plugins to new LoadQueues that may be created.
		 * @property _plugins
		 * @type {Array}
		 * @private
		 * @since 0.6.1
		 */
		this.plugins = null;


	// Protected Properties
		/**
		 * An internal {{#crossLink "LoadQueue"}}{{/crossLink}} that loads the contents of the manifest.
		 * @property _manifestQueue
		 * @type {LoadQueue}
		 * @private
		 */
		this._manifestQueue = null;
	};

	var p = createjs.extend(ManifestLoader, createjs.AbstractLoader);
	var s = ManifestLoader;

	// static properties
	/**
	 * The amount of progress that the manifest itself takes up.
	 * @property MANIFEST_PROGRESS
	 * @type {number}
	 * @default 0.25 (25%)
	 * @private
	 * @static
	 */
	s.MANIFEST_PROGRESS = 0.25;

	// static methods
	/**
	 * Determines if the loader can load a specific item. This loader can only load items that are of type
	 * {{#crossLink "AbstractLoader/MANIFEST:property"}}{{/crossLink}}
	 * @method canLoadItem
	 * @param {LoadItem|Object} item The LoadItem that a LoadQueue is trying to load.
	 * @returns {Boolean} Whether the loader can load the item.
	 * @static
	 */
	s.canLoadItem = function (item) {
		return item.type == createjs.AbstractLoader.MANIFEST;
	};

	// public methods
	p.load = function () {
		this.AbstractLoader_load();
	};

	// protected methods
	p._createRequest = function() {
		var callback = this._item.callback;
		if (callback != null) {
			this._request = new createjs.JSONPLoader(this._item);
		} else {
			this._request = new createjs.JSONLoader(this._item);
		}
	};

	p.handleEvent = function (event) {
		switch (event.type) {
			case "complete":
				this._rawResult = event.target.getResult(true);
				this._result = event.target.getResult();
				this._sendProgress(s.MANIFEST_PROGRESS);
				this._loadManifest(this._result);
				return;
			case "progress":
				event.loaded *= s.MANIFEST_PROGRESS;
				this.progress = event.loaded / event.total;
				if (isNaN(this.progress) || this.progress == Infinity) { this.progress = 0; }
				this._sendProgress(event);
				return;
		}
		this.AbstractLoader_handleEvent(event);
	};

	p.destroy = function() {
		this.AbstractLoader_destroy();
		this._manifestQueue.close();
	};

	/**
	 * Create and load the manifest items once the actual manifest has been loaded.
	 * @method _loadManifest
	 * @param {Object} json
	 * @private
	 */
	p._loadManifest = function (json) {
		if (json && json.manifest) {
			var queue = this._manifestQueue = new createjs.LoadQueue();
			queue.on("fileload", this._handleManifestFileLoad, this);
			queue.on("progress", this._handleManifestProgress, this);
			queue.on("complete", this._handleManifestComplete, this, true);
			queue.on("error", this._handleManifestError, this, true);
			for(var i = 0, l = this.plugins.length; i < l; i++) {	// conserve order of plugins
				queue.installPlugin(this.plugins[i]);
			}
			queue.loadManifest(json);
		} else {
			this._sendComplete();
		}
	};

	/**
	 * An item from the {{#crossLink "_manifestQueue:property"}}{{/crossLink}} has completed.
	 * @method _handleManifestFileLoad
	 * @param {Event} event
	 * @private
	 */
	p._handleManifestFileLoad = function (event) {
		event.target = null;
		this.dispatchEvent(event);
	};

	/**
	 * The manifest has completed loading. This triggers the {{#crossLink "AbstractLoader/complete:event"}}{{/crossLink}}
	 * {{#crossLink "Event"}}{{/crossLink}} from the ManifestLoader.
	 * @method _handleManifestComplete
	 * @param {Event} event
	 * @private
	 */
	p._handleManifestComplete = function (event) {
		this._loadedItems = this._manifestQueue.getItems(true);
		this._sendComplete();
	};

	/**
	 * The manifest has reported progress.
	 * @method _handleManifestProgress
	 * @param {ProgressEvent} event
	 * @private
	 */
	p._handleManifestProgress = function (event) {
		this.progress = event.progress * (1 - s.MANIFEST_PROGRESS) + s.MANIFEST_PROGRESS;
		this._sendProgress(this.progress);
	};

	/**
	 * The manifest has reported an error with one of the files.
	 * @method _handleManifestError
	 * @param {ErrorEvent} event
	 * @private
	 */
	p._handleManifestError = function (event) {
		var newEvent = new createjs.Event("fileerror");
		newEvent.item = event.data;
		this.dispatchEvent(newEvent);
	};

	createjs.ManifestLoader = createjs.promote(ManifestLoader, "AbstractLoader");

}());

//##############################################################################
// SoundLoader.js
//##############################################################################

this.createjs = this.createjs || {};

(function () {
	"use strict";

	// constructor
	/**
	 * A loader for HTML audio files. PreloadJS can not load WebAudio files, as a WebAudio context is required, which
	 * should be created by either a library playing the sound (such as <a href="http://soundjs.com">SoundJS</a>, or an
	 * external framework that handles audio playback. To load content that can be played by WebAudio, use the
	 * {{#crossLink "BinaryLoader"}}{{/crossLink}}, and handle the audio context decoding manually.
	 * @class SoundLoader
	 * @param {LoadItem|Object} loadItem
	 * @param {Boolean} preferXHR
	 * @extends AbstractMediaLoader
	 * @constructor
	 */
	function SoundLoader(loadItem, preferXHR) {
		this.AbstractMediaLoader_constructor(loadItem, preferXHR, createjs.AbstractLoader.SOUND);

		// protected properties
		if (createjs.RequestUtils.isAudioTag(loadItem)) {
			this._tag = loadItem;
		} else if (createjs.RequestUtils.isAudioTag(loadItem.src)) {
			this._tag = loadItem;
		} else if (createjs.RequestUtils.isAudioTag(loadItem.tag)) {
			this._tag = createjs.RequestUtils.isAudioTag(loadItem) ? loadItem : loadItem.src;
		}

		if (this._tag != null) {
			this._preferXHR = false;
		}
	};

	var p = createjs.extend(SoundLoader, createjs.AbstractMediaLoader);
	var s = SoundLoader;

	// static methods
	/**
	 * Determines if the loader can load a specific item. This loader can only load items that are of type
	 * {{#crossLink "AbstractLoader/SOUND:property"}}{{/crossLink}}.
	 * @method canLoadItem
	 * @param {LoadItem|Object} item The LoadItem that a LoadQueue is trying to load.
	 * @returns {Boolean} Whether the loader can load the item.
	 * @static
	 */
	s.canLoadItem = function (item) {
		return item.type == createjs.AbstractLoader.SOUND;
	};

	// protected methods
	p._createTag = function (src) {
		var tag = document.createElement("audio");
		tag.autoplay = false;
		tag.preload = "none";

		//LM: Firefox fails when this the preload="none" for other tags, but it needs to be "none" to ensure PreloadJS works.
		tag.src = src;
		return tag;
	};

	createjs.SoundLoader = createjs.promote(SoundLoader, "AbstractMediaLoader");

}());

//##############################################################################
// VideoLoader.js
//##############################################################################

this.createjs = this.createjs || {};

(function () {
	"use strict";

	// constructor
	/**
	 * A loader for video files.
	 * @class VideoLoader
	 * @param {LoadItem|Object} loadItem
	 * @param {Boolean} preferXHR
	 * @extends AbstractMediaLoader
	 * @constructor
	 */
	function VideoLoader(loadItem, preferXHR) {
		this.AbstractMediaLoader_constructor(loadItem, preferXHR, createjs.AbstractLoader.VIDEO);

		if (createjs.RequestUtils.isVideoTag(loadItem) || createjs.RequestUtils.isVideoTag(loadItem.src)) {
			this.setTag(createjs.RequestUtils.isVideoTag(loadItem)?loadItem:loadItem.src);

			// We can't use XHR for a tag that's passed in.
			this._preferXHR = false;
		} else {
			this.setTag(this._createTag());
		}
	};

	var p = createjs.extend(VideoLoader, createjs.AbstractMediaLoader);
	var s = VideoLoader;

	/**
	 * Create a new video tag
	 *
	 * @returns {HTMLElement}
	 * @private
	 */
	p._createTag = function () {
		return document.createElement("video");
	};

	// static methods
	/**
	 * Determines if the loader can load a specific item. This loader can only load items that are of type
	 * {{#crossLink "AbstractLoader/VIDEO:property"}}{{/crossLink}}.
	 * @method canLoadItem
	 * @param {LoadItem|Object} item The LoadItem that a LoadQueue is trying to load.
	 * @returns {Boolean} Whether the loader can load the item.
	 * @static
	 */
	s.canLoadItem = function (item) {
		return item.type == createjs.AbstractLoader.VIDEO;
	};

	createjs.VideoLoader = createjs.promote(VideoLoader, "AbstractMediaLoader");

}());

//##############################################################################
// SpriteSheetLoader.js
//##############################################################################

this.createjs = this.createjs || {};

(function () {
	"use strict";

	// constructor
	/**
	 * A loader for EaselJS SpriteSheets. Images inside the spritesheet definition are loaded before the loader
	 * completes. To load SpriteSheets using JSONP, specify a {{#crossLink "LoadItem/callback:property"}}{{/crossLink}}
	 * as part of the {{#crossLink "LoadItem"}}{{/crossLink}}. Note that the {{#crossLink "JSONLoader"}}{{/crossLink}}
	 * and {{#crossLink "JSONPLoader"}}{{/crossLink}} are higher priority loaders, so SpriteSheets <strong>must</strong>
	 * set the {{#crossLink "LoadItem"}}{{/crossLink}} {{#crossLink "LoadItem/type:property"}}{{/crossLink}} property
	 * to {{#crossLink "AbstractLoader/SPRITESHEET:property"}}{{/crossLink}}.
	 *
	 * The {{#crossLink "LoadItem"}}{{/crossLink}} {{#crossLink "LoadItem/crossOrigin:property"}}{{/crossLink}} as well
	 * as the {{#crossLink "LoadQueue's"}}{{/crossLink}} `basePath` argument and {{#crossLink "LoadQueue/_preferXHR"}}{{/crossLink}}
	 * property supplied to the {{#crossLink "LoadQueue"}}{{/crossLink}} are passed on to the sub-manifest that loads
	 * the SpriteSheet images.
	 *
	 * Note that the SpriteSheet JSON does not respect the {{#crossLink "LoadQueue/_preferXHR:property"}}{{/crossLink}}
	 * property, which should instead be determined by the presence of a {{#crossLink "LoadItem/callback:property"}}{{/crossLink}}
	 * property on the SpriteSheet load item. This is because the JSON loaded will have a different format depending on
	 * if it is loaded as JSON, so just changing `preferXHR` is not enough to change how it is loaded.
	 * @class SpriteSheetLoader
	 * @param {LoadItem|Object} loadItem
	 * @extends AbstractLoader
	 * @constructor
	 */
	function SpriteSheetLoader(loadItem, preferXHR) {
		this.AbstractLoader_constructor(loadItem, preferXHR, createjs.AbstractLoader.SPRITESHEET);

		// protected properties
		/**
		 * An internal queue which loads the SpriteSheet's images.
		 * @method _manifestQueue
		 * @type {LoadQueue}
		 * @private
		 */
		this._manifestQueue = null;
	}

	var p = createjs.extend(SpriteSheetLoader, createjs.AbstractLoader);
	var s = SpriteSheetLoader;

	// static properties
	/**
	 * The amount of progress that the manifest itself takes up.
	 * @property SPRITESHEET_PROGRESS
	 * @type {number}
	 * @default 0.25 (25%)
	 * @private
	 * @static
	 */
	s.SPRITESHEET_PROGRESS = 0.25;

	// static methods
	/**
	 * Determines if the loader can load a specific item. This loader can only load items that are of type
	 * {{#crossLink "AbstractLoader/SPRITESHEET:property"}}{{/crossLink}}
	 * @method canLoadItem
	 * @param {LoadItem|Object} item The LoadItem that a LoadQueue is trying to load.
	 * @returns {Boolean} Whether the loader can load the item.
	 * @static
	 */
	s.canLoadItem = function (item) {
		return item.type == createjs.AbstractLoader.SPRITESHEET;
	};

	// public methods
	p.destroy = function() {
		this.AbstractLoader_destroy;
		this._manifestQueue.close();
	};

	// protected methods
	p._createRequest = function() {
		var callback = this._item.callback;
		if (callback != null) {
			this._request = new createjs.JSONPLoader(this._item);
		} else {
			this._request = new createjs.JSONLoader(this._item);
		}
	};

	p.handleEvent = function (event) {
		switch (event.type) {
			case "complete":
				this._rawResult = event.target.getResult(true);
				this._result = event.target.getResult();
				this._sendProgress(s.SPRITESHEET_PROGRESS);
				this._loadManifest(this._result);
				return;
			case "progress":
				event.loaded *= s.SPRITESHEET_PROGRESS;
				this.progress = event.loaded / event.total;
				if (isNaN(this.progress) || this.progress == Infinity) { this.progress = 0; }
				this._sendProgress(event);
				return;
		}
		this.AbstractLoader_handleEvent(event);
	};

	/**
	 * Create and load the images once the SpriteSheet JSON has been loaded.
	 * @method _loadManifest
	 * @param {Object} json
	 * @private
	 */
	p._loadManifest = function (json) {
		if (json && json.images) {
			var queue = this._manifestQueue = new createjs.LoadQueue(this._preferXHR, this._item.path, this._item.crossOrigin);
			queue.on("complete", this._handleManifestComplete, this, true);
			queue.on("fileload", this._handleManifestFileLoad, this);
			queue.on("progress", this._handleManifestProgress, this);
			queue.on("error", this._handleManifestError, this, true);
			queue.loadManifest(json.images);
		}
	};

	/**
	 * An item from the {{#crossLink "_manifestQueue:property"}}{{/crossLink}} has completed.
	 * @method _handleManifestFileLoad
	 * @param {Event} event
	 * @private
	 */
	p._handleManifestFileLoad = function (event) {
		var image = event.result;
		if (image != null) {
			var images = this.getResult().images;
			var pos = images.indexOf(event.item.src);
			images[pos] = image;
		}
	};

	/**
	 * The images have completed loading. This triggers the {{#crossLink "AbstractLoader/complete:event"}}{{/crossLink}}
	 * {{#crossLink "Event"}}{{/crossLink}} from the SpriteSheetLoader.
	 * @method _handleManifestComplete
	 * @param {Event} event
	 * @private
	 */
	p._handleManifestComplete = function (event) {
		this._result = new createjs.SpriteSheet(this._result);
		this._loadedItems = this._manifestQueue.getItems(true);
		this._sendComplete();
	};

	/**
	 * The images {{#crossLink "LoadQueue"}}{{/crossLink}} has reported progress.
	 * @method _handleManifestProgress
	 * @param {ProgressEvent} event
	 * @private
	 */
	p._handleManifestProgress = function (event) {
		this.progress = event.progress * (1 - s.SPRITESHEET_PROGRESS) + s.SPRITESHEET_PROGRESS;
		this._sendProgress(this.progress);
	};

	/**
	 * An image has reported an error.
	 * @method _handleManifestError
	 * @param {ErrorEvent} event
	 * @private
	 */
	p._handleManifestError = function (event) {
		var newEvent = new createjs.Event("fileerror");
		newEvent.item = event.data;
		this.dispatchEvent(newEvent);
	};

	createjs.SpriteSheetLoader = createjs.promote(SpriteSheetLoader, "AbstractLoader");

}());

//##############################################################################
// SVGLoader.js
//##############################################################################

this.createjs = this.createjs || {};

(function () {
	"use strict";

	// constructor
	/**
	 * A loader for SVG files.
	 * @class SVGLoader
	 * @param {LoadItem|Object} loadItem
	 * @param {Boolean} preferXHR
	 * @extends AbstractLoader
	 * @constructor
	 */
	function SVGLoader(loadItem, preferXHR) {
		this.AbstractLoader_constructor(loadItem, preferXHR, createjs.AbstractLoader.SVG);

		// public properties
		this.resultFormatter = this._formatResult;

		// protected properties
		this._tagSrcAttribute = "data";

		if (preferXHR) {
			this.setTag(document.createElement("svg"));
		} else {
			this.setTag(document.createElement("object"));
			this.getTag().type = "image/svg+xml";
		}
	};

	var p = createjs.extend(SVGLoader, createjs.AbstractLoader);
	var s = SVGLoader;

	// static methods
	/**
	 * Determines if the loader can load a specific item. This loader can only load items that are of type
	 * {{#crossLink "AbstractLoader/SVG:property"}}{{/crossLink}}
	 * @method canLoadItem
	 * @param {LoadItem|Object} item The LoadItem that a LoadQueue is trying to load.
	 * @returns {Boolean} Whether the loader can load the item.
	 * @static
	 */
	s.canLoadItem = function (item) {
		return item.type == createjs.AbstractLoader.SVG;
	};

	// protected methods
	/**
	 * The result formatter for SVG files.
	 * @method _formatResult
	 * @param {AbstractLoader} loader
	 * @returns {Object}
	 * @private
	 */
	p._formatResult = function (loader) {
		// mime should be image/svg+xml, but Opera requires text/xml
		var xml = createjs.DataUtils.parseXML(loader.getResult(true), "text/xml");
		var tag = loader.getTag();

		if (!this._preferXHR && document.body.contains(tag)) {
			document.body.removeChild(tag);
		}

		if (xml.documentElement != null) {
			tag.appendChild(xml.documentElement);
			tag.style.visibility = "visible";
			return tag;
		} else { // For browsers that don't support SVG, just give them the XML. (IE 9-8)
			return xml;
		}
	};

	createjs.SVGLoader = createjs.promote(SVGLoader, "AbstractLoader");

}());

//##############################################################################
// XMLLoader.js
//##############################################################################

this.createjs = this.createjs || {};

(function () {
	"use strict";

	// constructor
	/**
	 * A loader for CSS files.
	 * @class XMLLoader
	 * @param {LoadItem|Object} loadItem
	 * @extends AbstractLoader
	 * @constructor
	 */
	function XMLLoader(loadItem) {
		this.AbstractLoader_constructor(loadItem, true, createjs.AbstractLoader.XML);

		// public properties
		this.resultFormatter = this._formatResult;
	};

	var p = createjs.extend(XMLLoader, createjs.AbstractLoader);
	var s = XMLLoader;

	// static methods
	/**
	 * Determines if the loader can load a specific item. This loader can only load items that are of type
	 * {{#crossLink "AbstractLoader/XML:property"}}{{/crossLink}}.
	 * @method canLoadItem
	 * @param {LoadItem|Object} item The LoadItem that a LoadQueue is trying to load.
	 * @returns {Boolean} Whether the loader can load the item.
	 * @static
	 */
	s.canLoadItem = function (item) {
		return item.type == createjs.AbstractLoader.XML;
	};

	// protected methods
	/**
	 * The result formatter for XML files.
	 * @method _formatResult
	 * @param {AbstractLoader} loader
	 * @returns {XMLDocument}
	 * @private
	 */
	p._formatResult = function (loader) {
		return createjs.DataUtils.parseXML(loader.getResult(true), "text/xml");
	};

	createjs.XMLLoader = createjs.promote(XMLLoader, "AbstractLoader");

}());
/*!
* SoundJS
* Visit http://createjs.com/ for documentation, updates and examples.
*
* Copyright (c) 2010 gskinner.com, inc.
*
* 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.
*/


//##############################################################################
// version.js
//##############################################################################

this.createjs = this.createjs || {};

(function () {

	/**
	 * Static class holding library specific information such as the version and buildDate of the library.
	 * The SoundJS class has been renamed {{#crossLink "Sound"}}{{/crossLink}}.  Please see {{#crossLink "Sound"}}{{/crossLink}}
	 * for information on using sound.
	 * @class SoundJS
	 **/
	var s = createjs.SoundJS = createjs.SoundJS || {};

	/**
	 * The version string for this release.
	 * @property version
	 * @type String
	 * @static
	 **/
	s.version = /*=version*/"0.6.2"; // injected by build process

	/**
	 * The build date for this release in UTC format.
	 * @property buildDate
	 * @type String
	 * @static
	 **/
	s.buildDate = /*=date*/"Thu, 26 Nov 2015 20:44:31 GMT"; // injected by build process

})();

//##############################################################################
// extend.js
//##############################################################################

this.createjs = this.createjs||{};

/**
 * @class Utility Methods
 */

/**
 * Sets up the prototype chain and constructor property for a new class.
 *
 * This should be called right after creating the class constructor.
 *
 * 	function MySubClass() {}
 * 	createjs.extend(MySubClass, MySuperClass);
 * 	MySubClass.prototype.doSomething = function() { }
 *
 * 	var foo = new MySubClass();
 * 	console.log(foo instanceof MySuperClass); // true
 * 	console.log(foo.prototype.constructor === MySubClass); // true
 *
 * @method extend
 * @param {Function} subclass The subclass.
 * @param {Function} superclass The superclass to extend.
 * @return {Function} Returns the subclass's new prototype.
 */
createjs.extend = function(subclass, superclass) {
	"use strict";

	function o() { this.constructor = subclass; }
	o.prototype = superclass.prototype;
	return (subclass.prototype = new o());
};

//##############################################################################
// promote.js
//##############################################################################

this.createjs = this.createjs||{};

/**
 * @class Utility Methods
 */

/**
 * Promotes any methods on the super class that were overridden, by creating an alias in the format `prefix_methodName`.
 * It is recommended to use the super class's name as the prefix.
 * An alias to the super class's constructor is always added in the format `prefix_constructor`.
 * This allows the subclass to call super class methods without using `function.call`, providing better performance.
 *
 * For example, if `MySubClass` extends `MySuperClass`, and both define a `draw` method, then calling `promote(MySubClass, "MySuperClass")`
 * would add a `MySuperClass_constructor` method to MySubClass and promote the `draw` method on `MySuperClass` to the
 * prototype of `MySubClass` as `MySuperClass_draw`.
 *
 * This should be called after the class's prototype is fully defined.
 *
 * 	function ClassA(name) {
 * 		this.name = name;
 * 	}
 * 	ClassA.prototype.greet = function() {
 * 		return "Hello "+this.name;
 * 	}
 *
 * 	function ClassB(name, punctuation) {
 * 		this.ClassA_constructor(name);
 * 		this.punctuation = punctuation;
 * 	}
 * 	createjs.extend(ClassB, ClassA);
 * 	ClassB.prototype.greet = function() {
 * 		return this.ClassA_greet()+this.punctuation;
 * 	}
 * 	createjs.promote(ClassB, "ClassA");
 *
 * 	var foo = new ClassB("World", "!?!");
 * 	console.log(foo.greet()); // Hello World!?!
 *
 * @method promote
 * @param {Function} subclass The class to promote super class methods on.
 * @param {String} prefix The prefix to add to the promoted method names. Usually the name of the superclass.
 * @return {Function} Returns the subclass.
 */
createjs.promote = function(subclass, prefix) {
	"use strict";

	var subP = subclass.prototype, supP = (Object.getPrototypeOf&&Object.getPrototypeOf(subP))||subP.__proto__;
	if (supP) {
		subP[(prefix+="_") + "constructor"] = supP.constructor; // constructor is not always innumerable
		for (var n in supP) {
			if (subP.hasOwnProperty(n) && (typeof supP[n] == "function")) { subP[prefix + n] = supP[n]; }
		}
	}
	return subclass;
};

//##############################################################################
// IndexOf.js
//##############################################################################

this.createjs = this.createjs||{};

/**
 * @class Utility Methods
 */

/**
 * Finds the first occurrence of a specified value searchElement in the passed in array, and returns the index of
 * that value.  Returns -1 if value is not found.
 *
 *      var i = createjs.indexOf(myArray, myElementToFind);
 *
 * @method indexOf
 * @param {Array} array Array to search for searchElement
 * @param searchElement Element to find in array.
 * @return {Number} The first index of searchElement in array.
 */
createjs.indexOf = function (array, searchElement){
	"use strict";

	for (var i = 0,l=array.length; i < l; i++) {
		if (searchElement === array[i]) {
			return i;
		}
	}
	return -1;
};

//##############################################################################
// Proxy.js
//##############################################################################

this.createjs = this.createjs||{};

/**
 * Various utilities that the CreateJS Suite uses. Utilities are created as separate files, and will be available on the
 * createjs namespace directly.
 *
 * <h4>Example</h4>
 *
 *      myObject.addEventListener("change", createjs.proxy(myMethod, scope));
 *
 * @class Utility Methods
 * @main Utility Methods
 */

(function() {
	"use strict";

	/**
	 * A function proxy for methods. By default, JavaScript methods do not maintain scope, so passing a method as a
	 * callback will result in the method getting called in the scope of the caller. Using a proxy ensures that the
	 * method gets called in the correct scope.
	 *
	 * Additional arguments can be passed that will be applied to the function when it is called.
	 *
	 * <h4>Example</h4>
	 *
	 *      myObject.addEventListener("event", createjs.proxy(myHandler, this, arg1, arg2));
	 *
	 *      function myHandler(arg1, arg2) {
	 *           // This gets called when myObject.myCallback is executed.
	 *      }
	 *
	 * @method proxy
	 * @param {Function} method The function to call
	 * @param {Object} scope The scope to call the method name on
	 * @param {mixed} [arg] * Arguments that are appended to the callback for additional params.
	 * @public
	 * @static
	 */
	createjs.proxy = function (method, scope) {
		var aArgs = Array.prototype.slice.call(arguments, 2);
		return function () {
			return method.apply(scope, Array.prototype.slice.call(arguments, 0).concat(aArgs));
		};
	}

}());

//##############################################################################
// BrowserDetect.js
//##############################################################################

this.createjs = this.createjs||{};

/**
 * @class Utility Methods
 */
(function() {
	"use strict";

	/**
	 * An object that determines the current browser, version, operating system, and other environment
	 * variables via user agent string.
	 *
	 * Used for audio because feature detection is unable to detect the many limitations of mobile devices.
	 *
	 * <h4>Example</h4>
	 *
	 *      if (createjs.BrowserDetect.isIOS) { // do stuff }
	 *
	 * @property BrowserDetect
	 * @type {Object}
	 * @param {Boolean} isFirefox True if our browser is Firefox.
	 * @param {Boolean} isOpera True if our browser is opera.
	 * @param {Boolean} isChrome True if our browser is Chrome.  Note that Chrome for Android returns true, but is a
	 * completely different browser with different abilities.
	 * @param {Boolean} isIOS True if our browser is safari for iOS devices (iPad, iPhone, and iPod).
	 * @param {Boolean} isAndroid True if our browser is Android.
	 * @param {Boolean} isBlackberry True if our browser is Blackberry.
	 * @constructor
	 * @static
	 */
	function BrowserDetect() {
		throw "BrowserDetect cannot be instantiated";
	};

	var agent = BrowserDetect.agent = window.navigator.userAgent;
	BrowserDetect.isWindowPhone = (agent.indexOf("IEMobile") > -1) || (agent.indexOf("Windows Phone") > -1);
	BrowserDetect.isFirefox = (agent.indexOf("Firefox") > -1);
	BrowserDetect.isOpera = (window.opera != null);
	BrowserDetect.isChrome = (agent.indexOf("Chrome") > -1);  // NOTE that Chrome on Android returns true but is a completely different browser with different abilities
	BrowserDetect.isIOS = (agent.indexOf("iPod") > -1 || agent.indexOf("iPhone") > -1 || agent.indexOf("iPad") > -1) && !BrowserDetect.isWindowPhone;
	BrowserDetect.isAndroid = (agent.indexOf("Android") > -1) && !BrowserDetect.isWindowPhone;
	BrowserDetect.isBlackberry = (agent.indexOf("Blackberry") > -1);

	createjs.BrowserDetect = BrowserDetect;

}());

//##############################################################################
// EventDispatcher.js
//##############################################################################

this.createjs = this.createjs||{};

(function() {
	"use strict";


// constructor:
	/**
	 * EventDispatcher provides methods for managing queues of event listeners and dispatching events.
	 *
	 * You can either extend EventDispatcher or mix its methods into an existing prototype or instance by using the
	 * EventDispatcher {{#crossLink "EventDispatcher/initialize"}}{{/crossLink}} method.
	 * 
	 * Together with the CreateJS Event class, EventDispatcher provides an extended event model that is based on the
	 * DOM Level 2 event model, including addEventListener, removeEventListener, and dispatchEvent. It supports
	 * bubbling / capture, preventDefault, stopPropagation, stopImmediatePropagation, and handleEvent.
	 * 
	 * EventDispatcher also exposes a {{#crossLink "EventDispatcher/on"}}{{/crossLink}} method, which makes it easier
	 * to create scoped listeners, listeners that only run once, and listeners with associated arbitrary data. The 
	 * {{#crossLink "EventDispatcher/off"}}{{/crossLink}} method is merely an alias to
	 * {{#crossLink "EventDispatcher/removeEventListener"}}{{/crossLink}}.
	 * 
	 * Another addition to the DOM Level 2 model is the {{#crossLink "EventDispatcher/removeAllEventListeners"}}{{/crossLink}}
	 * method, which can be used to listeners for all events, or listeners for a specific event. The Event object also 
	 * includes a {{#crossLink "Event/remove"}}{{/crossLink}} method which removes the active listener.
	 *
	 * <h4>Example</h4>
	 * Add EventDispatcher capabilities to the "MyClass" class.
	 *
	 *      EventDispatcher.initialize(MyClass.prototype);
	 *
	 * Add an event (see {{#crossLink "EventDispatcher/addEventListener"}}{{/crossLink}}).
	 *
	 *      instance.addEventListener("eventName", handlerMethod);
	 *      function handlerMethod(event) {
	 *          console.log(event.target + " Was Clicked");
	 *      }
	 *
	 * <b>Maintaining proper scope</b><br />
	 * Scope (ie. "this") can be be a challenge with events. Using the {{#crossLink "EventDispatcher/on"}}{{/crossLink}}
	 * method to subscribe to events simplifies this.
	 *
	 *      instance.addEventListener("click", function(event) {
	 *          console.log(instance == this); // false, scope is ambiguous.
	 *      });
	 *      
	 *      instance.on("click", function(event) {
	 *          console.log(instance == this); // true, "on" uses dispatcher scope by default.
	 *      });
	 * 
	 * If you want to use addEventListener instead, you may want to use function.bind() or a similar proxy to manage
	 * scope.
	 *
	 * <b>Browser support</b>
	 * The event model in CreateJS can be used separately from the suite in any project, however the inheritance model
	 * requires modern browsers (IE9+).
	 *      
	 *
	 * @class EventDispatcher
	 * @constructor
	 **/
	function EventDispatcher() {
	
	
	// private properties:
		/**
		 * @protected
		 * @property _listeners
		 * @type Object
		 **/
		this._listeners = null;
		
		/**
		 * @protected
		 * @property _captureListeners
		 * @type Object
		 **/
		this._captureListeners = null;
	}
	var p = EventDispatcher.prototype;

	/**
	 * <strong>REMOVED</strong>. Removed in favor of using `MySuperClass_constructor`.
	 * See {{#crossLink "Utility Methods/extend"}}{{/crossLink}} and {{#crossLink "Utility Methods/promote"}}{{/crossLink}}
	 * for details.
	 *
	 * There is an inheritance tutorial distributed with EaselJS in /tutorials/Inheritance.
	 *
	 * @method initialize
	 * @protected
	 * @deprecated
	 */
	// p.initialize = function() {}; // searchable for devs wondering where it is.


// static public methods:
	/**
	 * Static initializer to mix EventDispatcher methods into a target object or prototype.
	 * 
	 * 		EventDispatcher.initialize(MyClass.prototype); // add to the prototype of the class
	 * 		EventDispatcher.initialize(myObject); // add to a specific instance
	 * 
	 * @method initialize
	 * @static
	 * @param {Object} target The target object to inject EventDispatcher methods into. This can be an instance or a
	 * prototype.
	 **/
	EventDispatcher.initialize = function(target) {
		target.addEventListener = p.addEventListener;
		target.on = p.on;
		target.removeEventListener = target.off =  p.removeEventListener;
		target.removeAllEventListeners = p.removeAllEventListeners;
		target.hasEventListener = p.hasEventListener;
		target.dispatchEvent = p.dispatchEvent;
		target._dispatchEvent = p._dispatchEvent;
		target.willTrigger = p.willTrigger;
	};
	

// public methods:
	/**
	 * Adds the specified event listener. Note that adding multiple listeners to the same function will result in
	 * multiple callbacks getting fired.
	 *
	 * <h4>Example</h4>
	 *
	 *      displayObject.addEventListener("click", handleClick);
	 *      function handleClick(event) {
	 *         // Click happened.
	 *      }
	 *
	 * @method addEventListener
	 * @param {String} type The string type of the event.
	 * @param {Function | Object} listener An object with a handleEvent method, or a function that will be called when
	 * the event is dispatched.
	 * @param {Boolean} [useCapture] For events that bubble, indicates whether to listen for the event in the capture or bubbling/target phase.
	 * @return {Function | Object} Returns the listener for chaining or assignment.
	 **/
	p.addEventListener = function(type, listener, useCapture) {
		var listeners;
		if (useCapture) {
			listeners = this._captureListeners = this._captureListeners||{};
		} else {
			listeners = this._listeners = this._listeners||{};
		}
		var arr = listeners[type];
		if (arr) { this.removeEventListener(type, listener, useCapture); }
		arr = listeners[type]; // remove may have deleted the array
		if (!arr) { listeners[type] = [listener];  }
		else { arr.push(listener); }
		return listener;
	};
	
	/**
	 * A shortcut method for using addEventListener that makes it easier to specify an execution scope, have a listener
	 * only run once, associate arbitrary data with the listener, and remove the listener.
	 * 
	 * This method works by creating an anonymous wrapper function and subscribing it with addEventListener.
	 * The wrapper function is returned for use with `removeEventListener` (or `off`).
	 * 
	 * <b>IMPORTANT:</b> To remove a listener added with `on`, you must pass in the returned wrapper function as the listener, or use
	 * {{#crossLink "Event/remove"}}{{/crossLink}}. Likewise, each time you call `on` a NEW wrapper function is subscribed, so multiple calls
	 * to `on` with the same params will create multiple listeners.
	 * 
	 * <h4>Example</h4>
	 * 
	 * 		var listener = myBtn.on("click", handleClick, null, false, {count:3});
	 * 		function handleClick(evt, data) {
	 * 			data.count -= 1;
	 * 			console.log(this == myBtn); // true - scope defaults to the dispatcher
	 * 			if (data.count == 0) {
	 * 				alert("clicked 3 times!");
	 * 				myBtn.off("click", listener);
	 * 				// alternately: evt.remove();
	 * 			}
	 * 		}
	 * 
	 * @method on
	 * @param {String} type The string type of the event.
	 * @param {Function | Object} listener An object with a handleEvent method, or a function that will be called when
	 * the event is dispatched.
	 * @param {Object} [scope] The scope to execute the listener in. Defaults to the dispatcher/currentTarget for function listeners, and to the listener itself for object listeners (ie. using handleEvent).
	 * @param {Boolean} [once=false] If true, the listener will remove itself after the first time it is triggered.
	 * @param {*} [data] Arbitrary data that will be included as the second parameter when the listener is called.
	 * @param {Boolean} [useCapture=false] For events that bubble, indicates whether to listen for the event in the capture or bubbling/target phase.
	 * @return {Function} Returns the anonymous function that was created and assigned as the listener. This is needed to remove the listener later using .removeEventListener.
	 **/
	p.on = function(type, listener, scope, once, data, useCapture) {
		if (listener.handleEvent) {
			scope = scope||listener;
			listener = listener.handleEvent;
		}
		scope = scope||this;
		return this.addEventListener(type, function(evt) {
				listener.call(scope, evt, data);
				once&&evt.remove();
			}, useCapture);
	};

	/**
	 * Removes the specified event listener.
	 *
	 * <b>Important Note:</b> that you must pass the exact function reference used when the event was added. If a proxy
	 * function, or function closure is used as the callback, the proxy/closure reference must be used - a new proxy or
	 * closure will not work.
	 *
	 * <h4>Example</h4>
	 *
	 *      displayObject.removeEventListener("click", handleClick);
	 *
	 * @method removeEventListener
	 * @param {String} type The string type of the event.
	 * @param {Function | Object} listener The listener function or object.
	 * @param {Boolean} [useCapture] For events that bubble, indicates whether to listen for the event in the capture or bubbling/target phase.
	 **/
	p.removeEventListener = function(type, listener, useCapture) {
		var listeners = useCapture ? this._captureListeners : this._listeners;
		if (!listeners) { return; }
		var arr = listeners[type];
		if (!arr) { return; }
		for (var i=0,l=arr.length; i<l; i++) {
			if (arr[i] == listener) {
				if (l==1) { delete(listeners[type]); } // allows for faster checks.
				else { arr.splice(i,1); }
				break;
			}
		}
	};
	
	/**
	 * A shortcut to the removeEventListener method, with the same parameters and return value. This is a companion to the
	 * .on method.
	 * 
	 * <b>IMPORTANT:</b> To remove a listener added with `on`, you must pass in the returned wrapper function as the listener. See 
	 * {{#crossLink "EventDispatcher/on"}}{{/crossLink}} for an example.
	 *
	 * @method off
	 * @param {String} type The string type of the event.
	 * @param {Function | Object} listener The listener function or object.
	 * @param {Boolean} [useCapture] For events that bubble, indicates whether to listen for the event in the capture or bubbling/target phase.
	 **/
	p.off = p.removeEventListener;

	/**
	 * Removes all listeners for the specified type, or all listeners of all types.
	 *
	 * <h4>Example</h4>
	 *
	 *      // Remove all listeners
	 *      displayObject.removeAllEventListeners();
	 *
	 *      // Remove all click listeners
	 *      displayObject.removeAllEventListeners("click");
	 *
	 * @method removeAllEventListeners
	 * @param {String} [type] The string type of the event. If omitted, all listeners for all types will be removed.
	 **/
	p.removeAllEventListeners = function(type) {
		if (!type) { this._listeners = this._captureListeners = null; }
		else {
			if (this._listeners) { delete(this._listeners[type]); }
			if (this._captureListeners) { delete(this._captureListeners[type]); }
		}
	};

	/**
	 * Dispatches the specified event to all listeners.
	 *
	 * <h4>Example</h4>
	 *
	 *      // Use a string event
	 *      this.dispatchEvent("complete");
	 *
	 *      // Use an Event instance
	 *      var event = new createjs.Event("progress");
	 *      this.dispatchEvent(event);
	 *
	 * @method dispatchEvent
	 * @param {Object | String | Event} eventObj An object with a "type" property, or a string type.
	 * While a generic object will work, it is recommended to use a CreateJS Event instance. If a string is used,
	 * dispatchEvent will construct an Event instance if necessary with the specified type. This latter approach can
	 * be used to avoid event object instantiation for non-bubbling events that may not have any listeners.
	 * @param {Boolean} [bubbles] Specifies the `bubbles` value when a string was passed to eventObj.
	 * @param {Boolean} [cancelable] Specifies the `cancelable` value when a string was passed to eventObj.
	 * @return {Boolean} Returns false if `preventDefault()` was called on a cancelable event, true otherwise.
	 **/
	p.dispatchEvent = function(eventObj, bubbles, cancelable) {
		if (typeof eventObj == "string") {
			// skip everything if there's no listeners and it doesn't bubble:
			var listeners = this._listeners;
			if (!bubbles && (!listeners || !listeners[eventObj])) { return true; }
			eventObj = new createjs.Event(eventObj, bubbles, cancelable);
		} else if (eventObj.target && eventObj.clone) {
			// redispatching an active event object, so clone it:
			eventObj = eventObj.clone();
		}
		
		// TODO: it would be nice to eliminate this. Maybe in favour of evtObj instanceof Event? Or !!evtObj.createEvent
		try { eventObj.target = this; } catch (e) {} // try/catch allows redispatching of native events

		if (!eventObj.bubbles || !this.parent) {
			this._dispatchEvent(eventObj, 2);
		} else {
			var top=this, list=[top];
			while (top.parent) { list.push(top = top.parent); }
			var i, l=list.length;

			// capture & atTarget
			for (i=l-1; i>=0 && !eventObj.propagationStopped; i--) {
				list[i]._dispatchEvent(eventObj, 1+(i==0));
			}
			// bubbling
			for (i=1; i<l && !eventObj.propagationStopped; i++) {
				list[i]._dispatchEvent(eventObj, 3);
			}
		}
		return !eventObj.defaultPrevented;
	};

	/**
	 * Indicates whether there is at least one listener for the specified event type.
	 * @method hasEventListener
	 * @param {String} type The string type of the event.
	 * @return {Boolean} Returns true if there is at least one listener for the specified event.
	 **/
	p.hasEventListener = function(type) {
		var listeners = this._listeners, captureListeners = this._captureListeners;
		return !!((listeners && listeners[type]) || (captureListeners && captureListeners[type]));
	};
	
	/**
	 * Indicates whether there is at least one listener for the specified event type on this object or any of its
	 * ancestors (parent, parent's parent, etc). A return value of true indicates that if a bubbling event of the
	 * specified type is dispatched from this object, it will trigger at least one listener.
	 * 
	 * This is similar to {{#crossLink "EventDispatcher/hasEventListener"}}{{/crossLink}}, but it searches the entire
	 * event flow for a listener, not just this object.
	 * @method willTrigger
	 * @param {String} type The string type of the event.
	 * @return {Boolean} Returns `true` if there is at least one listener for the specified event.
	 **/
	p.willTrigger = function(type) {
		var o = this;
		while (o) {
			if (o.hasEventListener(type)) { return true; }
			o = o.parent;
		}
		return false;
	};

	/**
	 * @method toString
	 * @return {String} a string representation of the instance.
	 **/
	p.toString = function() {
		return "[EventDispatcher]";
	};


// private methods:
	/**
	 * @method _dispatchEvent
	 * @param {Object | String | Event} eventObj
	 * @param {Object} eventPhase
	 * @protected
	 **/
	p._dispatchEvent = function(eventObj, eventPhase) {
		var l, listeners = (eventPhase==1) ? this._captureListeners : this._listeners;
		if (eventObj && listeners) {
			var arr = listeners[eventObj.type];
			if (!arr||!(l=arr.length)) { return; }
			try { eventObj.currentTarget = this; } catch (e) {}
			try { eventObj.eventPhase = eventPhase; } catch (e) {}
			eventObj.removed = false;
			
			arr = arr.slice(); // to avoid issues with items being removed or added during the dispatch
			for (var i=0; i<l && !eventObj.immediatePropagationStopped; i++) {
				var o = arr[i];
				if (o.handleEvent) { o.handleEvent(eventObj); }
				else { o(eventObj); }
				if (eventObj.removed) {
					this.off(eventObj.type, o, eventPhase==1);
					eventObj.removed = false;
				}
			}
		}
	};


	createjs.EventDispatcher = EventDispatcher;
}());

//##############################################################################
// Event.js
//##############################################################################

this.createjs = this.createjs||{};

(function() {
	"use strict";

// constructor:
	/**
	 * Contains properties and methods shared by all events for use with
	 * {{#crossLink "EventDispatcher"}}{{/crossLink}}.
	 * 
	 * Note that Event objects are often reused, so you should never
	 * rely on an event object's state outside of the call stack it was received in.
	 * @class Event
	 * @param {String} type The event type.
	 * @param {Boolean} bubbles Indicates whether the event will bubble through the display list.
	 * @param {Boolean} cancelable Indicates whether the default behaviour of this event can be cancelled.
	 * @constructor
	 **/
	function Event(type, bubbles, cancelable) {
		
	
	// public properties:
		/**
		 * The type of event.
		 * @property type
		 * @type String
		 **/
		this.type = type;
	
		/**
		 * The object that generated an event.
		 * @property target
		 * @type Object
		 * @default null
		 * @readonly
		*/
		this.target = null;
	
		/**
		 * The current target that a bubbling event is being dispatched from. For non-bubbling events, this will
		 * always be the same as target. For example, if childObj.parent = parentObj, and a bubbling event
		 * is generated from childObj, then a listener on parentObj would receive the event with
		 * target=childObj (the original target) and currentTarget=parentObj (where the listener was added).
		 * @property currentTarget
		 * @type Object
		 * @default null
		 * @readonly
		*/
		this.currentTarget = null;
	
		/**
		 * For bubbling events, this indicates the current event phase:<OL>
		 * 	<LI> capture phase: starting from the top parent to the target</LI>
		 * 	<LI> at target phase: currently being dispatched from the target</LI>
		 * 	<LI> bubbling phase: from the target to the top parent</LI>
		 * </OL>
		 * @property eventPhase
		 * @type Number
		 * @default 0
		 * @readonly
		*/
		this.eventPhase = 0;
	
		/**
		 * Indicates whether the event will bubble through the display list.
		 * @property bubbles
		 * @type Boolean
		 * @default false
		 * @readonly
		*/
		this.bubbles = !!bubbles;
	
		/**
		 * Indicates whether the default behaviour of this event can be cancelled via
		 * {{#crossLink "Event/preventDefault"}}{{/crossLink}}. This is set via the Event constructor.
		 * @property cancelable
		 * @type Boolean
		 * @default false
		 * @readonly
		*/
		this.cancelable = !!cancelable;
	
		/**
		 * The epoch time at which this event was created.
		 * @property timeStamp
		 * @type Number
		 * @default 0
		 * @readonly
		*/
		this.timeStamp = (new Date()).getTime();
	
		/**
		 * Indicates if {{#crossLink "Event/preventDefault"}}{{/crossLink}} has been called
		 * on this event.
		 * @property defaultPrevented
		 * @type Boolean
		 * @default false
		 * @readonly
		*/
		this.defaultPrevented = false;
	
		/**
		 * Indicates if {{#crossLink "Event/stopPropagation"}}{{/crossLink}} or
		 * {{#crossLink "Event/stopImmediatePropagation"}}{{/crossLink}} has been called on this event.
		 * @property propagationStopped
		 * @type Boolean
		 * @default false
		 * @readonly
		*/
		this.propagationStopped = false;
	
		/**
		 * Indicates if {{#crossLink "Event/stopImmediatePropagation"}}{{/crossLink}} has been called
		 * on this event.
		 * @property immediatePropagationStopped
		 * @type Boolean
		 * @default false
		 * @readonly
		*/
		this.immediatePropagationStopped = false;
		
		/**
		 * Indicates if {{#crossLink "Event/remove"}}{{/crossLink}} has been called on this event.
		 * @property removed
		 * @type Boolean
		 * @default false
		 * @readonly
		*/
		this.removed = false;
	}
	var p = Event.prototype;

	/**
	 * <strong>REMOVED</strong>. Removed in favor of using `MySuperClass_constructor`.
	 * See {{#crossLink "Utility Methods/extend"}}{{/crossLink}} and {{#crossLink "Utility Methods/promote"}}{{/crossLink}}
	 * for details.
	 *
	 * There is an inheritance tutorial distributed with EaselJS in /tutorials/Inheritance.
	 *
	 * @method initialize
	 * @protected
	 * @deprecated
	 */
	// p.initialize = function() {}; // searchable for devs wondering where it is.

// public methods:
	/**
	 * Sets {{#crossLink "Event/defaultPrevented"}}{{/crossLink}} to true if the event is cancelable.
	 * Mirrors the DOM level 2 event standard. In general, cancelable events that have `preventDefault()` called will
	 * cancel the default behaviour associated with the event.
	 * @method preventDefault
	 **/
	p.preventDefault = function() {
		this.defaultPrevented = this.cancelable&&true;
	};

	/**
	 * Sets {{#crossLink "Event/propagationStopped"}}{{/crossLink}} to true.
	 * Mirrors the DOM event standard.
	 * @method stopPropagation
	 **/
	p.stopPropagation = function() {
		this.propagationStopped = true;
	};

	/**
	 * Sets {{#crossLink "Event/propagationStopped"}}{{/crossLink}} and
	 * {{#crossLink "Event/immediatePropagationStopped"}}{{/crossLink}} to true.
	 * Mirrors the DOM event standard.
	 * @method stopImmediatePropagation
	 **/
	p.stopImmediatePropagation = function() {
		this.immediatePropagationStopped = this.propagationStopped = true;
	};
	
	/**
	 * Causes the active listener to be removed via removeEventListener();
	 * 
	 * 		myBtn.addEventListener("click", function(evt) {
	 * 			// do stuff...
	 * 			evt.remove(); // removes this listener.
	 * 		});
	 * 
	 * @method remove
	 **/
	p.remove = function() {
		this.removed = true;
	};
	
	/**
	 * Returns a clone of the Event instance.
	 * @method clone
	 * @return {Event} a clone of the Event instance.
	 **/
	p.clone = function() {
		return new Event(this.type, this.bubbles, this.cancelable);
	};
	
	/**
	 * Provides a chainable shortcut method for setting a number of properties on the instance.
	 *
	 * @method set
	 * @param {Object} props A generic object containing properties to copy to the instance.
	 * @return {Event} Returns the instance the method is called on (useful for chaining calls.)
	 * @chainable
	*/
	p.set = function(props) {
		for (var n in props) { this[n] = props[n]; }
		return this;
	};

	/**
	 * Returns a string representation of this object.
	 * @method toString
	 * @return {String} a string representation of the instance.
	 **/
	p.toString = function() {
		return "[Event (type="+this.type+")]";
	};

	createjs.Event = Event;
}());

//##############################################################################
// ErrorEvent.js
//##############################################################################

this.createjs = this.createjs||{};

(function() {
	"use strict";

	/**
	 * A general error {{#crossLink "Event"}}{{/crossLink}}, that describes an error that occurred, as well as any details.
	 * @class ErrorEvent
	 * @param {String} [title] The error title
	 * @param {String} [message] The error description
	 * @param {Object} [data] Additional error data
	 * @constructor
	 */
	function ErrorEvent(title, message, data) {
		this.Event_constructor("error");

		/**
		 * The short error title, which indicates the type of error that occurred.
		 * @property title
		 * @type String
		 */
		this.title = title;

		/**
		 * The verbose error message, containing details about the error.
		 * @property message
		 * @type String
		 */
		this.message = message;

		/**
		 * Additional data attached to an error.
		 * @property data
		 * @type {Object}
		 */
		this.data = data;
	}

	var p = createjs.extend(ErrorEvent, createjs.Event);

	p.clone = function() {
		return new createjs.ErrorEvent(this.title, this.message, this.data);
	};

	createjs.ErrorEvent = createjs.promote(ErrorEvent, "Event");

}());

//##############################################################################
// ProgressEvent.js
//##############################################################################

this.createjs = this.createjs || {};

(function (scope) {
	"use strict";

	// constructor
	/**
	 * A CreateJS {{#crossLink "Event"}}{{/crossLink}} that is dispatched when progress changes.
	 * @class ProgressEvent
	 * @param {Number} loaded The amount that has been loaded. This can be any number relative to the total.
	 * @param {Number} [total=1] The total amount that will load. This will default to 1, so if the `loaded` value is
	 * a percentage (between 0 and 1), it can be omitted.
	 * @todo Consider having this event be a "fileprogress" event as well
	 * @constructor
	 */
	function ProgressEvent(loaded, total) {
		this.Event_constructor("progress");

		/**
		 * The amount that has been loaded (out of a total amount)
		 * @property loaded
		 * @type {Number}
		 */
		this.loaded = loaded;

		/**
		 * The total "size" of the load.
		 * @property total
		 * @type {Number}
		 * @default 1
		 */
		this.total = (total == null) ? 1 : total;

		/**
		 * The percentage (out of 1) that the load has been completed. This is calculated using `loaded/total`.
		 * @property progress
		 * @type {Number}
		 * @default 0
		 */
		this.progress = (total == 0) ? 0 : this.loaded / this.total;
	};

	var p = createjs.extend(ProgressEvent, createjs.Event);

	/**
	 * Returns a clone of the ProgressEvent instance.
	 * @method clone
	 * @return {ProgressEvent} a clone of the Event instance.
	 **/
	p.clone = function() {
		return new createjs.ProgressEvent(this.loaded, this.total);
	};

	createjs.ProgressEvent = createjs.promote(ProgressEvent, "Event");

}(window));

//##############################################################################
// LoadItem.js
//##############################################################################

this.createjs = this.createjs || {};

(function () {
	"use strict";

	/**
	 * All loaders accept an item containing the properties defined in this class. If a raw object is passed instead,
	 * it will not be affected, but it must contain at least a {{#crossLink "src:property"}}{{/crossLink}} property. A
	 * string path or HTML tag is also acceptable, but it will be automatically converted to a LoadItem using the
	 * {{#crossLink "create"}}{{/crossLink}} method by {{#crossLink "AbstractLoader"}}{{/crossLink}}
	 * @class LoadItem
	 * @constructor
	 * @since 0.6.0
	 */
	function LoadItem() {
		/**
		 * The source of the file that is being loaded. This property is <b>required</b>. The source can either be a
		 * string (recommended), or an HTML tag.
		 * This can also be an object, but in that case it has to include a type and be handled by a plugin.
		 * @property src
		 * @type {String}
		 * @default null
		 */
		this.src = null;

		/**
		 * The type file that is being loaded. The type of the file is usually inferred by the extension, but can also
		 * be set manually. This is helpful in cases where a file does not have an extension.
		 * @property type
		 * @type {String}
		 * @default null
		 */
		this.type = null;

		/**
		 * A string identifier which can be used to reference the loaded object. If none is provided, this will be
		 * automatically set to the {{#crossLink "src:property"}}{{/crossLink}}.
		 * @property id
		 * @type {String}
		 * @default null
		 */
		this.id = null;

		/**
		 * Determines if a manifest will maintain the order of this item, in relation to other items in the manifest
		 * that have also set the `maintainOrder` property to `true`. This only applies when the max connections has
		 * been set above 1 (using {{#crossLink "LoadQueue/setMaxConnections"}}{{/crossLink}}). Everything with this
		 * property set to `false` will finish as it is loaded. Ordered items are combined with script tags loading in
		 * order when {{#crossLink "LoadQueue/maintainScriptOrder:property"}}{{/crossLink}} is set to `true`.
		 * @property maintainOrder
		 * @type {Boolean}
		 * @default false
		 */
		this.maintainOrder = false;

		/**
		 * A callback used by JSONP requests that defines what global method to call when the JSONP content is loaded.
		 * @property callback
		 * @type {String}
		 * @default null
		 */
		this.callback = null;

		/**
		 * An arbitrary data object, which is included with the loaded object.
		 * @property data
		 * @type {Object}
		 * @default null
		 */
		this.data = null;

		/**
		 * The request method used for HTTP calls. Both {{#crossLink "AbstractLoader/GET:property"}}{{/crossLink}} or
		 * {{#crossLink "AbstractLoader/POST:property"}}{{/crossLink}} request types are supported, and are defined as
		 * constants on {{#crossLink "AbstractLoader"}}{{/crossLink}}.
		 * @property method
		 * @type {String}
		 * @default get
		 */
		this.method = createjs.LoadItem.GET;

		/**
		 * An object hash of name/value pairs to send to the server.
		 * @property values
		 * @type {Object}
		 * @default null
		 */
		this.values = null;

		/**
		 * An object hash of headers to attach to an XHR request. PreloadJS will automatically attach some default
		 * headers when required, including "Origin", "Content-Type", and "X-Requested-With". You may override the
		 * default headers by including them in your headers object.
		 * @property headers
		 * @type {Object}
		 * @default null
		 */
		this.headers = null;

		/**
		 * Enable credentials for XHR requests.
		 * @property withCredentials
		 * @type {Boolean}
		 * @default false
		 */
		this.withCredentials = false;

		/**
		 * Set the mime type of XHR-based requests. This is automatically set to "text/plain; charset=utf-8" for text
		 * based files (json, xml, text, css, js).
		 * @property mimeType
		 * @type {String}
		 * @default null
		 */
		this.mimeType = null;

		/**
		 * Sets the crossOrigin attribute for CORS-enabled images loading cross-domain.
		 * @property crossOrigin
		 * @type {boolean}
		 * @default Anonymous
		 */
		this.crossOrigin = null;

		/**
		 * The duration in milliseconds to wait before a request times out. This only applies to tag-based and and XHR
		 * (level one) loading, as XHR (level 2) provides its own timeout event.
		 * @property loadTimeout
		 * @type {Number}
		 * @default 8000 (8 seconds)
		 */
		this.loadTimeout = s.LOAD_TIMEOUT_DEFAULT;
	};

	var p = LoadItem.prototype = {};
	var s = LoadItem;

	/**
	 * Default duration in milliseconds to wait before a request times out. This only applies to tag-based and and XHR
	 * (level one) loading, as XHR (level 2) provides its own timeout event.
	 * @property LOAD_TIMEOUT_DEFAULT
	 * @type {number}
	 * @static
	 */
	s.LOAD_TIMEOUT_DEFAULT = 8000;

	/**
	 * Create a LoadItem.
	 * <ul>
	 *     <li>String-based items are converted to a LoadItem with a populated {{#crossLink "src:property"}}{{/crossLink}}.</li>
	 *     <li>LoadItem instances are returned as-is</li>
	 *     <li>Objects are returned with any needed properties added</li>
	 * </ul>
	 * @method create
	 * @param {LoadItem|String|Object} value The load item value
	 * @returns {LoadItem|Object}
	 * @static
	 */
	s.create = function (value) {
		if (typeof value == "string") {
			var item = new LoadItem();
			item.src = value;
			return item;
		} else if (value instanceof s) {
			return value;
		} else if (value instanceof Object && value.src) {
			if (value.loadTimeout == null) {
				value.loadTimeout = s.LOAD_TIMEOUT_DEFAULT;
			}
			return value;
		} else {
			throw new Error("Type not recognized.");
		}
	};

	/**
	 * Provides a chainable shortcut method for setting a number of properties on the instance.
	 *
	 * <h4>Example</h4>
	 *
	 *      var loadItem = new createjs.LoadItem().set({src:"image.png", maintainOrder:true});
	 *
	 * @method set
	 * @param {Object} props A generic object containing properties to copy to the LoadItem instance.
	 * @return {LoadItem} Returns the instance the method is called on (useful for chaining calls.)
	*/
	p.set = function(props) {
		for (var n in props) { this[n] = props[n]; }
		return this;
	};

	createjs.LoadItem = s;

}());

//##############################################################################
// RequestUtils.js
//##############################################################################

(function () {

	/**
	 * Utilities that assist with parsing load items, and determining file types, etc.
	 * @class RequestUtils
	 */
	var s = {};

	/**
	 * The Regular Expression used to test file URLS for an absolute path.
	 * @property ABSOLUTE_PATH
	 * @type {RegExp}
	 * @static
	 */
	s.ABSOLUTE_PATT = /^(?:\w+:)?\/{2}/i;

	/**
	 * The Regular Expression used to test file URLS for a relative path.
	 * @property RELATIVE_PATH
	 * @type {RegExp}
	 * @static
	 */
	s.RELATIVE_PATT = (/^[./]*?\//i);

	/**
	 * The Regular Expression used to test file URLS for an extension. Note that URIs must already have the query string
	 * removed.
	 * @property EXTENSION_PATT
	 * @type {RegExp}
	 * @static
	 */
	s.EXTENSION_PATT = /\/?[^/]+\.(\w{1,5})$/i;

	/**
	 * Parse a file path to determine the information we need to work with it. Currently, PreloadJS needs to know:
	 * <ul>
	 *     <li>If the path is absolute. Absolute paths start with a protocol (such as `http://`, `file://`, or
	 *     `//networkPath`)</li>
	 *     <li>If the path is relative. Relative paths start with `../` or `/path` (or similar)</li>
	 *     <li>The file extension. This is determined by the filename with an extension. Query strings are dropped, and
	 *     the file path is expected to follow the format `name.ext`.</li>
	 * </ul>
	 * @method parseURI
	 * @param {String} path
	 * @returns {Object} An Object with an `absolute` and `relative` Boolean values, as well as an optional 'extension`
	 * property, which is the lowercase extension.
	 * @static
	 */
	s.parseURI = function (path) {
		var info = {absolute: false, relative: false};
		if (path == null) { return info; }

		// Drop the query string
		var queryIndex = path.indexOf("?");
		if (queryIndex > -1) {
			path = path.substr(0, queryIndex);
		}

		// Absolute
		var match;
		if (s.ABSOLUTE_PATT.test(path)) {
			info.absolute = true;

			// Relative
		} else if (s.RELATIVE_PATT.test(path)) {
			info.relative = true;
		}

		// Extension
		if (match = path.match(s.EXTENSION_PATT)) {
			info.extension = match[1].toLowerCase();
		}
		return info;
	};

	/**
	 * Formats an object into a query string for either a POST or GET request.
	 * @method formatQueryString
	 * @param {Object} data The data to convert to a query string.
	 * @param {Array} [query] Existing name/value pairs to append on to this query.
	 * @static
	 */
	s.formatQueryString = function (data, query) {
		if (data == null) {
			throw new Error('You must specify data.');
		}
		var params = [];
		for (var n in data) {
			params.push(n + '=' + escape(data[n]));
		}
		if (query) {
			params = params.concat(query);
		}
		return params.join('&');
	};

	/**
	 * A utility method that builds a file path using a source and a data object, and formats it into a new path.
	 * @method buildPath
	 * @param {String} src The source path to add values to.
	 * @param {Object} [data] Object used to append values to this request as a query string. Existing parameters on the
	 * path will be preserved.
	 * @returns {string} A formatted string that contains the path and the supplied parameters.
	 * @static
	 */
	s.buildPath = function (src, data) {
		if (data == null) {
			return src;
		}

		var query = [];
		var idx = src.indexOf('?');

		if (idx != -1) {
			var q = src.slice(idx + 1);
			query = query.concat(q.split('&'));
		}

		if (idx != -1) {
			return src.slice(0, idx) + '?' + this.formatQueryString(data, query);
		} else {
			return src + '?' + this.formatQueryString(data, query);
		}
	};

	/**
	 * @method isCrossDomain
	 * @param {LoadItem|Object} item A load item with a `src` property.
	 * @return {Boolean} If the load item is loading from a different domain than the current location.
	 * @static
	 */
	s.isCrossDomain = function (item) {
		var target = document.createElement("a");
		target.href = item.src;

		var host = document.createElement("a");
		host.href = location.href;

		var crossdomain = (target.hostname != "") &&
						  (target.port != host.port ||
						   target.protocol != host.protocol ||
						   target.hostname != host.hostname);
		return crossdomain;
	};

	/**
	 * @method isLocal
	 * @param {LoadItem|Object} item A load item with a `src` property
	 * @return {Boolean} If the load item is loading from the "file:" protocol. Assume that the host must be local as
	 * well.
	 * @static
	 */
	s.isLocal = function (item) {
		var target = document.createElement("a");
		target.href = item.src;
		return target.hostname == "" && target.protocol == "file:";
	};

	/**
	 * Determine if a specific type should be loaded as a binary file. Currently, only images and items marked
	 * specifically as "binary" are loaded as binary. Note that audio is <b>not</b> a binary type, as we can not play
	 * back using an audio tag if it is loaded as binary. Plugins can change the item type to binary to ensure they get
	 * a binary result to work with. Binary files are loaded using XHR2. Types are defined as static constants on
	 * {{#crossLink "AbstractLoader"}}{{/crossLink}}.
	 * @method isBinary
	 * @param {String} type The item type.
	 * @return {Boolean} If the specified type is binary.
	 * @static
	 */
	s.isBinary = function (type) {
		switch (type) {
			case createjs.AbstractLoader.IMAGE:
			case createjs.AbstractLoader.BINARY:
				return true;
			default:
				return false;
		}
	};

	/**
	 * Check if item is a valid HTMLImageElement
	 * @method isImageTag
	 * @param {Object} item
	 * @returns {Boolean}
	 * @static
	 */
	s.isImageTag = function(item) {
		return item instanceof HTMLImageElement;
	};

	/**
	 * Check if item is a valid HTMLAudioElement
	 * @method isAudioTag
	 * @param {Object} item
	 * @returns {Boolean}
	 * @static
	 */
	s.isAudioTag = function(item) {
		if (window.HTMLAudioElement) {
			return item instanceof HTMLAudioElement;
		} else {
			return false;
		}
	};

	/**
	 * Check if item is a valid HTMLVideoElement
	 * @method isVideoTag
	 * @param {Object} item
	 * @returns {Boolean}
	 * @static
	 */
	s.isVideoTag = function(item) {
		if (window.HTMLVideoElement) {
			return item instanceof HTMLVideoElement;
		} else {
			return false;
		}
	};

	/**
	 * Determine if a specific type is a text-based asset, and should be loaded as UTF-8.
	 * @method isText
	 * @param {String} type The item type.
	 * @return {Boolean} If the specified type is text.
	 * @static
	 */
	s.isText = function (type) {
		switch (type) {
			case createjs.AbstractLoader.TEXT:
			case createjs.AbstractLoader.JSON:
			case createjs.AbstractLoader.MANIFEST:
			case createjs.AbstractLoader.XML:
			case createjs.AbstractLoader.CSS:
			case createjs.AbstractLoader.SVG:
			case createjs.AbstractLoader.JAVASCRIPT:
			case createjs.AbstractLoader.SPRITESHEET:
				return true;
			default:
				return false;
		}
	};

	/**
	 * Determine the type of the object using common extensions. Note that the type can be passed in with the load item
	 * if it is an unusual extension.
	 * @method getTypeByExtension
	 * @param {String} extension The file extension to use to determine the load type.
	 * @return {String} The determined load type (for example, <code>AbstractLoader.IMAGE</code>). Will return `null` if
	 * the type can not be determined by the extension.
	 * @static
	 */
	s.getTypeByExtension = function (extension) {
		if (extension == null) {
			return createjs.AbstractLoader.TEXT;
		}

		switch (extension.toLowerCase()) {
			case "jpeg":
			case "jpg":
			case "gif":
			case "png":
			case "webp":
			case "bmp":
				return createjs.AbstractLoader.IMAGE;
			case "ogg":
			case "mp3":
			case "webm":
				return createjs.AbstractLoader.SOUND;
			case "mp4":
			case "webm":
			case "ts":
				return createjs.AbstractLoader.VIDEO;
			case "json":
				return createjs.AbstractLoader.JSON;
			case "xml":
				return createjs.AbstractLoader.XML;
			case "css":
				return createjs.AbstractLoader.CSS;
			case "js":
				return createjs.AbstractLoader.JAVASCRIPT;
			case 'svg':
				return createjs.AbstractLoader.SVG;
			default:
				return createjs.AbstractLoader.TEXT;
		}
	};

	createjs.RequestUtils = s;

}());

//##############################################################################
// AbstractLoader.js
//##############################################################################

this.createjs = this.createjs || {};

(function () {
	"use strict";

// constructor
	/**
	 * The base loader, which defines all the generic methods, properties, and events. All loaders extend this class,
	 * including the {{#crossLink "LoadQueue"}}{{/crossLink}}.
	 * @class AbstractLoader
	 * @param {LoadItem|object|string} loadItem The item to be loaded.
	 * @param {Boolean} [preferXHR] Determines if the LoadItem should <em>try</em> and load using XHR, or take a
	 * tag-based approach, which can be better in cross-domain situations. Not all loaders can load using one or the
	 * other, so this is a suggested directive.
	 * @param {String} [type] The type of loader. Loader types are defined as constants on the AbstractLoader class,
	 * such as {{#crossLink "IMAGE:property"}}{{/crossLink}}, {{#crossLink "CSS:property"}}{{/crossLink}}, etc.
	 * @extends EventDispatcher
	 */
	function AbstractLoader(loadItem, preferXHR, type) {
		this.EventDispatcher_constructor();

		// public properties
		/**
		 * If the loader has completed loading. This provides a quick check, but also ensures that the different approaches
		 * used for loading do not pile up resulting in more than one `complete` {{#crossLink "Event"}}{{/crossLink}}.
		 * @property loaded
		 * @type {Boolean}
		 * @default false
		 */
		this.loaded = false;

		/**
		 * Determine if the loader was canceled. Canceled loads will not fire complete events. Note that this property
		 * is readonly, so {{#crossLink "LoadQueue"}}{{/crossLink}} queues should be closed using {{#crossLink "LoadQueue/close"}}{{/crossLink}}
		 * instead.
		 * @property canceled
		 * @type {Boolean}
		 * @default false
		 * @readonly
		 */
		this.canceled = false;

		/**
		 * The current load progress (percentage) for this item. This will be a number between 0 and 1.
		 *
		 * <h4>Example</h4>
		 *
		 *     var queue = new createjs.LoadQueue();
		 *     queue.loadFile("largeImage.png");
		 *     queue.on("progress", function() {
		 *         console.log("Progress:", queue.progress, event.progress);
		 *     });
		 *
		 * @property progress
		 * @type {Number}
		 * @default 0
		 */
		this.progress = 0;

		/**
		 * The type of item this loader will load. See {{#crossLink "AbstractLoader"}}{{/crossLink}} for a full list of
		 * supported types.
		 * @property type
		 * @type {String}
		 */
		this.type = type;

		/**
		 * A formatter function that converts the loaded raw result into the final result. For example, the JSONLoader
		 * converts a string of text into a JavaScript object. Not all loaders have a resultFormatter, and this property
		 * can be overridden to provide custom formatting.
		 *
		 * Optionally, a resultFormatter can return a callback function in cases where the formatting needs to be
		 * asynchronous, such as creating a new image. The callback function is passed 2 parameters, which are callbacks
		 * to handle success and error conditions in the resultFormatter. Note that the resultFormatter method is
		 * called in the current scope, as well as the success and error callbacks.
		 *
		 * <h4>Example asynchronous resultFormatter</h4>
		 *
		 * 	function _formatResult(loader) {
		 * 		return function(success, error) {
		 * 			if (errorCondition) { error(errorDetailEvent); }
		 * 			success(result);
		 * 		}
		 * 	}
		 * @property resultFormatter
		 * @type {Function}
		 * @default null
		 */
		this.resultFormatter = null;

		// protected properties
		/**
		 * The {{#crossLink "LoadItem"}}{{/crossLink}} this loader represents. Note that this is null in a {{#crossLink "LoadQueue"}}{{/crossLink}},
		 * but will be available on loaders such as {{#crossLink "XMLLoader"}}{{/crossLink}} and {{#crossLink "ImageLoader"}}{{/crossLink}}.
		 * @property _item
		 * @type {LoadItem|Object}
		 * @private
		 */
		if (loadItem) {
			this._item = createjs.LoadItem.create(loadItem);
		} else {
			this._item = null;
		}

		/**
		 * Whether the loader will try and load content using XHR (true) or HTML tags (false).
		 * @property _preferXHR
		 * @type {Boolean}
		 * @private
		 */
		this._preferXHR = preferXHR;

		/**
		 * The loaded result after it is formatted by an optional {{#crossLink "resultFormatter"}}{{/crossLink}}. For
		 * items that are not formatted, this will be the same as the {{#crossLink "_rawResult:property"}}{{/crossLink}}.
		 * The result is accessed using the {{#crossLink "getResult"}}{{/crossLink}} method.
		 * @property _result
		 * @type {Object|String}
		 * @private
		 */
		this._result = null;

		/**
		 * The loaded result before it is formatted. The rawResult is accessed using the {{#crossLink "getResult"}}{{/crossLink}}
		 * method, and passing `true`.
		 * @property _rawResult
		 * @type {Object|String}
		 * @private
		 */
		this._rawResult = null;

		/**
		 * A list of items that loaders load behind the scenes. This does not include the main item the loader is
		 * responsible for loading. Examples of loaders that have sub-items include the {{#crossLink "SpriteSheetLoader"}}{{/crossLink}} and
		 * {{#crossLink "ManifestLoader"}}{{/crossLink}}.
		 * @property _loadItems
		 * @type {null}
		 * @protected
		 */
		this._loadedItems = null;

		/**
		 * The attribute the items loaded using tags use for the source.
		 * @type {string}
		 * @default null
		 * @private
		 */
		this._tagSrcAttribute = null;

		/**
		 * An HTML tag (or similar) that a loader may use to load HTML content, such as images, scripts, etc.
		 * @property _tag
		 * @type {Object}
		 * @private
		 */
		this._tag = null;
	};

	var p = createjs.extend(AbstractLoader, createjs.EventDispatcher);
	var s = AbstractLoader;

	// TODO: deprecated
	// p.initialize = function() {}; // searchable for devs wondering where it is. REMOVED. See docs for details.


	/**
	 * Defines a POST request, use for a method value when loading data.
	 * @property POST
	 * @type {string}
	 * @default post
	 * @static
	 */
	s.POST = "POST";

	/**
	 * Defines a GET request, use for a method value when loading data.
	 * @property GET
	 * @type {string}
	 * @default get
	 * @static
	 */
	s.GET = "GET";

	/**
	 * The preload type for generic binary types. Note that images are loaded as binary files when using XHR.
	 * @property BINARY
	 * @type {String}
	 * @default binary
	 * @static
	 * @since 0.6.0
	 */
	s.BINARY = "binary";

	/**
	 * The preload type for css files. CSS files are loaded using a &lt;link&gt; when loaded with XHR, or a
	 * &lt;style&gt; tag when loaded with tags.
	 * @property CSS
	 * @type {String}
	 * @default css
	 * @static
	 * @since 0.6.0
	 */
	s.CSS = "css";

	/**
	 * The preload type for image files, usually png, gif, or jpg/jpeg. Images are loaded into an &lt;image&gt; tag.
	 * @property IMAGE
	 * @type {String}
	 * @default image
	 * @static
	 * @since 0.6.0
	 */
	s.IMAGE = "image";

	/**
	 * The preload type for javascript files, usually with the "js" file extension. JavaScript files are loaded into a
	 * &lt;script&gt; tag.
	 *
	 * Since version 0.4.1+, due to how tag-loaded scripts work, all JavaScript files are automatically injected into
	 * the body of the document to maintain parity between XHR and tag-loaded scripts. In version 0.4.0 and earlier,
	 * only tag-loaded scripts are injected.
	 * @property JAVASCRIPT
	 * @type {String}
	 * @default javascript
	 * @static
	 * @since 0.6.0
	 */
	s.JAVASCRIPT = "javascript";

	/**
	 * The preload type for json files, usually with the "json" file extension. JSON data is loaded and parsed into a
	 * JavaScript object. Note that if a `callback` is present on the load item, the file will be loaded with JSONP,
	 * no matter what the {{#crossLink "LoadQueue/preferXHR:property"}}{{/crossLink}} property is set to, and the JSON
	 * must contain a matching wrapper function.
	 * @property JSON
	 * @type {String}
	 * @default json
	 * @static
	 * @since 0.6.0
	 */
	s.JSON = "json";

	/**
	 * The preload type for jsonp files, usually with the "json" file extension. JSON data is loaded and parsed into a
	 * JavaScript object. You are required to pass a callback parameter that matches the function wrapper in the JSON.
	 * Note that JSONP will always be used if there is a callback present, no matter what the {{#crossLink "LoadQueue/preferXHR:property"}}{{/crossLink}}
	 * property is set to.
	 * @property JSONP
	 * @type {String}
	 * @default jsonp
	 * @static
	 * @since 0.6.0
	 */
	s.JSONP = "jsonp";

	/**
	 * The preload type for json-based manifest files, usually with the "json" file extension. The JSON data is loaded
	 * and parsed into a JavaScript object. PreloadJS will then look for a "manifest" property in the JSON, which is an
	 * Array of files to load, following the same format as the {{#crossLink "LoadQueue/loadManifest"}}{{/crossLink}}
	 * method. If a "callback" is specified on the manifest object, then it will be loaded using JSONP instead,
	 * regardless of what the {{#crossLink "LoadQueue/preferXHR:property"}}{{/crossLink}} property is set to.
	 * @property MANIFEST
	 * @type {String}
	 * @default manifest
	 * @static
	 * @since 0.6.0
	 */
	s.MANIFEST = "manifest";

	/**
	 * The preload type for sound files, usually mp3, ogg, or wav. When loading via tags, audio is loaded into an
	 * &lt;audio&gt; tag.
	 * @property SOUND
	 * @type {String}
	 * @default sound
	 * @static
	 * @since 0.6.0
	 */
	s.SOUND = "sound";

	/**
	 * The preload type for video files, usually mp4, ts, or ogg. When loading via tags, video is loaded into an
	 * &lt;video&gt; tag.
	 * @property VIDEO
	 * @type {String}
	 * @default video
	 * @static
	 * @since 0.6.0
	 */
	s.VIDEO = "video";

	/**
	 * The preload type for SpriteSheet files. SpriteSheet files are JSON files that contain string image paths.
	 * @property SPRITESHEET
	 * @type {String}
	 * @default spritesheet
	 * @static
	 * @since 0.6.0
	 */
	s.SPRITESHEET = "spritesheet";

	/**
	 * The preload type for SVG files.
	 * @property SVG
	 * @type {String}
	 * @default svg
	 * @static
	 * @since 0.6.0
	 */
	s.SVG = "svg";

	/**
	 * The preload type for text files, which is also the default file type if the type can not be determined. Text is
	 * loaded as raw text.
	 * @property TEXT
	 * @type {String}
	 * @default text
	 * @static
	 * @since 0.6.0
	 */
	s.TEXT = "text";

	/**
	 * The preload type for xml files. XML is loaded into an XML document.
	 * @property XML
	 * @type {String}
	 * @default xml
	 * @static
	 * @since 0.6.0
	 */
	s.XML = "xml";

// Events
	/**
	 * The {{#crossLink "ProgressEvent"}}{{/crossLink}} that is fired when the overall progress changes. Prior to
	 * version 0.6.0, this was just a regular {{#crossLink "Event"}}{{/crossLink}}.
	 * @event progress
	 * @since 0.3.0
	 */

	/**
	 * The {{#crossLink "Event"}}{{/crossLink}} that is fired when a load starts.
	 * @event loadstart
	 * @param {Object} target The object that dispatched the event.
	 * @param {String} type The event type.
	 * @since 0.3.1
	 */

	/**
	 * The {{#crossLink "Event"}}{{/crossLink}} that is fired when the entire queue has been loaded.
	 * @event complete
	 * @param {Object} target The object that dispatched the event.
	 * @param {String} type The event type.
	 * @since 0.3.0
	 */

	/**
	 * The {{#crossLink "ErrorEvent"}}{{/crossLink}} that is fired when the loader encounters an error. If the error was
	 * encountered by a file, the event will contain the item that caused the error. Prior to version 0.6.0, this was
	 * just a regular {{#crossLink "Event"}}{{/crossLink}}.
	 * @event error
	 * @since 0.3.0
	 */

	/**
	 * The {{#crossLink "Event"}}{{/crossLink}} that is fired when the loader encounters an internal file load error.
	 * This enables loaders to maintain internal queues, and surface file load errors.
	 * @event fileerror
	 * @param {Object} target The object that dispatched the event.
	 * @param {String} type The even type ("fileerror")
	 * @param {LoadItem|object} The item that encountered the error
	 * @since 0.6.0
	 */

	/**
	 * The {{#crossLink "Event"}}{{/crossLink}} that is fired when a loader internally loads a file. This enables
	 * loaders such as {{#crossLink "ManifestLoader"}}{{/crossLink}} to maintain internal {{#crossLink "LoadQueue"}}{{/crossLink}}s
	 * and notify when they have loaded a file. The {{#crossLink "LoadQueue"}}{{/crossLink}} class dispatches a
	 * slightly different {{#crossLink "LoadQueue/fileload:event"}}{{/crossLink}} event.
	 * @event fileload
	 * @param {Object} target The object that dispatched the event.
	 * @param {String} type The event type ("fileload")
	 * @param {Object} item The file item which was specified in the {{#crossLink "LoadQueue/loadFile"}}{{/crossLink}}
	 * or {{#crossLink "LoadQueue/loadManifest"}}{{/crossLink}} call. If only a string path or tag was specified, the
	 * object will contain that value as a `src` property.
	 * @param {Object} result The HTML tag or parsed result of the loaded item.
	 * @param {Object} rawResult The unprocessed result, usually the raw text or binary data before it is converted
	 * to a usable object.
	 * @since 0.6.0
	 */

	/**
	 * The {{#crossLink "Event"}}{{/crossLink}} that is fired after the internal request is created, but before a load.
	 * This allows updates to the loader for specific loading needs, such as binary or XHR image loading.
	 * @event initialize
	 * @param {Object} target The object that dispatched the event.
	 * @param {String} type The event type ("initialize")
	 * @param {AbstractLoader} loader The loader that has been initialized.
	 */


	/**
	 * Get a reference to the manifest item that is loaded by this loader. In some cases this will be the value that was
	 * passed into {{#crossLink "LoadQueue"}}{{/crossLink}} using {{#crossLink "LoadQueue/loadFile"}}{{/crossLink}} or
	 * {{#crossLink "LoadQueue/loadManifest"}}{{/crossLink}}. However if only a String path was passed in, then it will
	 * be a {{#crossLink "LoadItem"}}{{/crossLink}}.
	 * @method getItem
	 * @return {Object} The manifest item that this loader is responsible for loading.
	 * @since 0.6.0
	 */
	p.getItem = function () {
		return this._item;
	};

	/**
	 * Get a reference to the content that was loaded by the loader (only available after the {{#crossLink "complete:event"}}{{/crossLink}}
	 * event is dispatched.
	 * @method getResult
	 * @param {Boolean} [raw=false] Determines if the returned result will be the formatted content, or the raw loaded
	 * data (if it exists).
	 * @return {Object}
	 * @since 0.6.0
	 */
	p.getResult = function (raw) {
		return raw ? this._rawResult : this._result;
	};

	/**
	 * Return the `tag` this object creates or uses for loading.
	 * @method getTag
	 * @return {Object} The tag instance
	 * @since 0.6.0
	 */
	p.getTag = function () {
		return this._tag;
	};

	/**
	 * Set the `tag` this item uses for loading.
	 * @method setTag
	 * @param {Object} tag The tag instance
	 * @since 0.6.0
	 */
	p.setTag = function(tag) {
	  this._tag = tag;
	};

	/**
	 * Begin loading the item. This method is required when using a loader by itself.
	 *
	 * <h4>Example</h4>
	 *
	 *      var queue = new createjs.LoadQueue();
	 *      queue.on("complete", handleComplete);
	 *      queue.loadManifest(fileArray, false); // Note the 2nd argument that tells the queue not to start loading yet
	 *      queue.load();
	 *
	 * @method load
	 */
	p.load = function () {
		this._createRequest();

		this._request.on("complete", this, this);
		this._request.on("progress", this, this);
		this._request.on("loadStart", this, this);
		this._request.on("abort", this, this);
		this._request.on("timeout", this, this);
		this._request.on("error", this, this);

		var evt = new createjs.Event("initialize");
		evt.loader = this._request;
		this.dispatchEvent(evt);

		this._request.load();
	};

	/**
	 * Close the the item. This will stop any open requests (although downloads using HTML tags may still continue in
	 * the background), but events will not longer be dispatched.
	 * @method cancel
	 */
	p.cancel = function () {
		this.canceled = true;
		this.destroy();
	};

	/**
	 * Clean up the loader.
	 * @method destroy
	 */
	p.destroy = function() {
		if (this._request) {
			this._request.removeAllEventListeners();
			this._request.destroy();
		}

		this._request = null;

		this._item = null;
		this._rawResult = null;
		this._result = null;

		this._loadItems = null;

		this.removeAllEventListeners();
	};

	/**
	 * Get any items loaded internally by the loader. The enables loaders such as {{#crossLink "ManifestLoader"}}{{/crossLink}}
	 * to expose items it loads internally.
	 * @method getLoadedItems
	 * @return {Array} A list of the items loaded by the loader.
	 * @since 0.6.0
	 */
	p.getLoadedItems = function () {
		return this._loadedItems;
	};


	// Private methods
	/**
	 * Create an internal request used for loading. By default, an {{#crossLink "XHRRequest"}}{{/crossLink}} or
	 * {{#crossLink "TagRequest"}}{{/crossLink}} is created, depending on the value of {{#crossLink "preferXHR:property"}}{{/crossLink}}.
	 * Other loaders may override this to use different request types, such as {{#crossLink "ManifestLoader"}}{{/crossLink}},
	 * which uses {{#crossLink "JSONLoader"}}{{/crossLink}} or {{#crossLink "JSONPLoader"}}{{/crossLink}} under the hood.
	 * @method _createRequest
	 * @protected
	 */
	p._createRequest = function() {
		if (!this._preferXHR) {
			this._request = new createjs.TagRequest(this._item, this._tag || this._createTag(), this._tagSrcAttribute);
		} else {
			this._request = new createjs.XHRRequest(this._item);
		}
	};

	/**
	 * Create the HTML tag used for loading. This method does nothing by default, and needs to be implemented
	 * by loaders that require tag loading.
	 * @method _createTag
	 * @param {String} src The tag source
	 * @return {HTMLElement} The tag that was created
	 * @protected
	 */
	p._createTag = function(src) { return null; };

	/**
	 * Dispatch a loadstart {{#crossLink "Event"}}{{/crossLink}}. Please see the {{#crossLink "AbstractLoader/loadstart:event"}}{{/crossLink}}
	 * event for details on the event payload.
	 * @method _sendLoadStart
	 * @protected
	 */
	p._sendLoadStart = function () {
		if (this._isCanceled()) { return; }
		this.dispatchEvent("loadstart");
	};

	/**
	 * Dispatch a {{#crossLink "ProgressEvent"}}{{/crossLink}}.
	 * @method _sendProgress
	 * @param {Number | Object} value The progress of the loaded item, or an object containing <code>loaded</code>
	 * and <code>total</code> properties.
	 * @protected
	 */
	p._sendProgress = function (value) {
		if (this._isCanceled()) { return; }
		var event = null;
		if (typeof(value) == "number") {
			this.progress = value;
			event = new createjs.ProgressEvent(this.progress);
		} else {
			event = value;
			this.progress = value.loaded / value.total;
			event.progress = this.progress;
			if (isNaN(this.progress) || this.progress == Infinity) { this.progress = 0; }
		}
		this.hasEventListener("progress") && this.dispatchEvent(event);
	};

	/**
	 * Dispatch a complete {{#crossLink "Event"}}{{/crossLink}}. Please see the {{#crossLink "AbstractLoader/complete:event"}}{{/crossLink}} event
	 * @method _sendComplete
	 * @protected
	 */
	p._sendComplete = function () {
		if (this._isCanceled()) { return; }

		this.loaded = true;

		var event = new createjs.Event("complete");
		event.rawResult = this._rawResult;

		if (this._result != null) {
			event.result = this._result;
		}

		this.dispatchEvent(event);
	};

	/**
	 * Dispatch an error {{#crossLink "Event"}}{{/crossLink}}. Please see the {{#crossLink "AbstractLoader/error:event"}}{{/crossLink}}
	 * event for details on the event payload.
	 * @method _sendError
	 * @param {ErrorEvent} event The event object containing specific error properties.
	 * @protected
	 */
	p._sendError = function (event) {
		if (this._isCanceled() || !this.hasEventListener("error")) { return; }
		if (event == null) {
			event = new createjs.ErrorEvent("PRELOAD_ERROR_EMPTY"); // TODO: Populate error
		}
		this.dispatchEvent(event);
	};

	/**
	 * Determine if the load has been canceled. This is important to ensure that method calls or asynchronous events
	 * do not cause issues after the queue has been cleaned up.
	 * @method _isCanceled
	 * @return {Boolean} If the loader has been canceled.
	 * @protected
	 */
	p._isCanceled = function () {
		if (window.createjs == null || this.canceled) {
			return true;
		}
		return false;
	};

	/**
	 * A custom result formatter function, which is called just before a request dispatches its complete event. Most
	 * loader types already have an internal formatter, but this can be user-overridden for custom formatting. The
	 * formatted result will be available on Loaders using {{#crossLink "getResult"}}{{/crossLink}}, and passing `true`.
	 * @property resultFormatter
	 * @type Function
	 * @return {Object} The formatted result
	 * @since 0.6.0
	 */
	p.resultFormatter = null;

	/**
	 * Handle events from internal requests. By default, loaders will handle, and redispatch the necessary events, but
	 * this method can be overridden for custom behaviours.
	 * @method handleEvent
	 * @param {Event} event The event that the internal request dispatches.
	 * @protected
	 * @since 0.6.0
	 */
	p.handleEvent = function (event) {
		switch (event.type) {
			case "complete":
				this._rawResult = event.target._response;
				var result = this.resultFormatter && this.resultFormatter(this);
				if (result instanceof Function) {
					result.call(this,
							createjs.proxy(this._resultFormatSuccess, this),
							createjs.proxy(this._resultFormatFailed, this)
					);
				} else {
					this._result =  result || this._rawResult;
					this._sendComplete();
				}
				break;
			case "progress":
				this._sendProgress(event);
				break;
			case "error":
				this._sendError(event);
				break;
			case "loadstart":
				this._sendLoadStart();
				break;
			case "abort":
			case "timeout":
				if (!this._isCanceled()) {
					this.dispatchEvent(new createjs.ErrorEvent("PRELOAD_" + event.type.toUpperCase() + "_ERROR"));
				}
				break;
		}
	};

	/**
	 * The "success" callback passed to {{#crossLink "AbstractLoader/resultFormatter"}}{{/crossLink}} asynchronous
	 * functions.
	 * @method _resultFormatSuccess
	 * @param {Object} result The formatted result
	 * @private
	 */
	p._resultFormatSuccess = function (result) {
		this._result = result;
		this._sendComplete();
	};

	/**
	 * The "error" callback passed to {{#crossLink "AbstractLoader/resultFormatter"}}{{/crossLink}} asynchronous
	 * functions.
	 * @method _resultFormatSuccess
	 * @param {Object} error The error event
	 * @private
	 */
	p._resultFormatFailed = function (event) {
		this._sendError(event);
	};

	/**
	 * @method buildPath
	 * @protected
	 * @deprecated Use the {{#crossLink "RequestUtils"}}{{/crossLink}} method {{#crossLink "RequestUtils/buildPath"}}{{/crossLink}}
	 * instead.
	 */
	p.buildPath = function (src, data) {
		return createjs.RequestUtils.buildPath(src, data);
	};

	/**
	 * @method toString
	 * @return {String} a string representation of the instance.
	 */
	p.toString = function () {
		return "[PreloadJS AbstractLoader]";
	};

	createjs.AbstractLoader = createjs.promote(AbstractLoader, "EventDispatcher");

}());

//##############################################################################
// AbstractMediaLoader.js
//##############################################################################

this.createjs = this.createjs || {};

(function () {
	"use strict";

	// constructor
	/**
	 * The AbstractMediaLoader is a base class that handles some of the shared methods and properties of loaders that
	 * handle HTML media elements, such as Video and Audio.
	 * @class AbstractMediaLoader
	 * @param {LoadItem|Object} loadItem
	 * @param {Boolean} preferXHR
	 * @param {String} type The type of media to load. Usually "video" or "audio".
	 * @extends AbstractLoader
	 * @constructor
	 */
	function AbstractMediaLoader(loadItem, preferXHR, type) {
		this.AbstractLoader_constructor(loadItem, preferXHR, type);

		// public properties
		this.resultFormatter = this._formatResult;

		// protected properties
		this._tagSrcAttribute = "src";

        this.on("initialize", this._updateXHR, this);
	};

	var p = createjs.extend(AbstractMediaLoader, createjs.AbstractLoader);

	// static properties
	// public methods
	p.load = function () {
		// TagRequest will handle most of this, but Sound / Video need a few custom properties, so just handle them here.
		if (!this._tag) {
			this._tag = this._createTag(this._item.src);
		}

		this._tag.preload = "auto";
		this._tag.load();

		this.AbstractLoader_load();
	};

	// protected methods
	/**
	 * Creates a new tag for loading if it doesn't exist yet.
	 * @method _createTag
	 * @private
	 */
	p._createTag = function () {};


	p._createRequest = function() {
		if (!this._preferXHR) {
			this._request = new createjs.MediaTagRequest(this._item, this._tag || this._createTag(), this._tagSrcAttribute);
		} else {
			this._request = new createjs.XHRRequest(this._item);
		}
	};

    // protected methods
    /**
     * Before the item loads, set its mimeType and responseType.
     * @property _updateXHR
     * @param {Event} event
     * @private
     */
    p._updateXHR = function (event) {
        // Only exists for XHR
        if (event.loader.setResponseType) {
            event.loader.setResponseType("blob");
        }
    };

	/**
	 * The result formatter for media files.
	 * @method _formatResult
	 * @param {AbstractLoader} loader
	 * @returns {HTMLVideoElement|HTMLAudioElement}
	 * @private
	 */
	p._formatResult = function (loader) {
		this._tag.removeEventListener && this._tag.removeEventListener("canplaythrough", this._loadedHandler);
		this._tag.onstalled = null;
		if (this._preferXHR) {
            var URL = window.URL || window.webkitURL;
            var result = loader.getResult(true);

			loader.getTag().src = URL.createObjectURL(result);
		}
		return loader.getTag();
	};

	createjs.AbstractMediaLoader = createjs.promote(AbstractMediaLoader, "AbstractLoader");

}());

//##############################################################################
// AbstractRequest.js
//##############################################################################

this.createjs = this.createjs || {};

(function () {
	"use strict";

	/**
	 * A base class for actual data requests, such as {{#crossLink "XHRRequest"}}{{/crossLink}}, {{#crossLink "TagRequest"}}{{/crossLink}},
	 * and {{#crossLink "MediaRequest"}}{{/crossLink}}. PreloadJS loaders will typically use a data loader under the
	 * hood to get data.
	 * @class AbstractRequest
	 * @param {LoadItem} item
	 * @constructor
	 */
	var AbstractRequest = function (item) {
		this._item = item;
	};

	var p = createjs.extend(AbstractRequest, createjs.EventDispatcher);

	// public methods
	/**
	 * Begin a load.
	 * @method load
	 */
	p.load =  function() {};

	/**
	 * Clean up a request.
	 * @method destroy
	 */
	p.destroy = function() {};

	/**
	 * Cancel an in-progress request.
	 * @method cancel
	 */
	p.cancel = function() {};

	createjs.AbstractRequest = createjs.promote(AbstractRequest, "EventDispatcher");

}());

//##############################################################################
// TagRequest.js
//##############################################################################

this.createjs = this.createjs || {};

(function () {
	"use strict";

	// constructor
	/**
	 * An {{#crossLink "AbstractRequest"}}{{/crossLink}} that loads HTML tags, such as images and scripts.
	 * @class TagRequest
	 * @param {LoadItem} loadItem
	 * @param {HTMLElement} tag
	 * @param {String} srcAttribute The tag attribute that specifies the source, such as "src", "href", etc.
	 */
	function TagRequest(loadItem, tag, srcAttribute) {
		this.AbstractRequest_constructor(loadItem);

		// protected properties
		/**
		 * The HTML tag instance that is used to load.
		 * @property _tag
		 * @type {HTMLElement}
		 * @protected
		 */
		this._tag = tag;

		/**
		 * The tag attribute that specifies the source, such as "src", "href", etc.
		 * @property _tagSrcAttribute
		 * @type {String}
		 * @protected
		 */
		this._tagSrcAttribute = srcAttribute;

		/**
		 * A method closure used for handling the tag load event.
		 * @property _loadedHandler
		 * @type {Function}
		 * @private
		 */
		this._loadedHandler = createjs.proxy(this._handleTagComplete, this);

		/**
		 * Determines if the element was added to the DOM automatically by PreloadJS, so it can be cleaned up after.
		 * @property _addedToDOM
		 * @type {Boolean}
		 * @private
		 */
		this._addedToDOM = false;

		/**
		 * Determines what the tags initial style.visibility was, so we can set it correctly after a load.
		 *
		 * @type {null}
		 * @private
		 */
		this._startTagVisibility = null;
	};

	var p = createjs.extend(TagRequest, createjs.AbstractRequest);

	// public methods
	p.load = function () {
		this._tag.onload = createjs.proxy(this._handleTagComplete, this);
		this._tag.onreadystatechange = createjs.proxy(this._handleReadyStateChange, this);
		this._tag.onerror = createjs.proxy(this._handleError, this);

		var evt = new createjs.Event("initialize");
		evt.loader = this._tag;

		this.dispatchEvent(evt);

		this._hideTag();

		this._loadTimeout = setTimeout(createjs.proxy(this._handleTimeout, this), this._item.loadTimeout);

		this._tag[this._tagSrcAttribute] = this._item.src;

		// wdg:: Append the tag AFTER setting the src, or SVG loading on iOS will fail.
		if (this._tag.parentNode == null) {
			window.document.body.appendChild(this._tag);
			this._addedToDOM = true;
		}
	};

	p.destroy = function() {
		this._clean();
		this._tag = null;

		this.AbstractRequest_destroy();
	};

	// private methods
	/**
	 * Handle the readyStateChange event from a tag. We need this in place of the `onload` callback (mainly SCRIPT
	 * and LINK tags), but other cases may exist.
	 * @method _handleReadyStateChange
	 * @private
	 */
	p._handleReadyStateChange = function () {
		clearTimeout(this._loadTimeout);
		// This is strictly for tags in browsers that do not support onload.
		var tag = this._tag;

		// Complete is for old IE support.
		if (tag.readyState == "loaded" || tag.readyState == "complete") {
			this._handleTagComplete();
		}
	};

	/**
	 * Handle any error events from the tag.
	 * @method _handleError
	 * @protected
	 */
	p._handleError = function() {
		this._clean();
		this.dispatchEvent("error");
	};

	/**
	 * Handle the tag's onload callback.
	 * @method _handleTagComplete
	 * @private
	 */
	p._handleTagComplete = function () {
		this._rawResult = this._tag;
		this._result = this.resultFormatter && this.resultFormatter(this) || this._rawResult;

		this._clean();
		this._showTag();

		this.dispatchEvent("complete");
	};

	/**
	 * The tag request has not loaded within the time specified in loadTimeout.
	 * @method _handleError
	 * @param {Object} event The XHR error event.
	 * @private
	 */
	p._handleTimeout = function () {
		this._clean();
		this.dispatchEvent(new createjs.Event("timeout"));
	};

	/**
	 * Remove event listeners, but don't destroy the request object
	 * @method _clean
	 * @private
	 */
	p._clean = function() {
		this._tag.onload = null;
		this._tag.onreadystatechange = null;
		this._tag.onerror = null;
		if (this._addedToDOM && this._tag.parentNode != null) {
			this._tag.parentNode.removeChild(this._tag);
		}
		clearTimeout(this._loadTimeout);
	};

	p._hideTag = function() {
		this._startTagVisibility = this._tag.style.visibility;
		this._tag.style.visibility = "hidden";
	};

	p._showTag = function() {
		this._tag.style.visibility = this._startTagVisibility;
	};

	/**
	 * Handle a stalled audio event. The main place this happens is with HTMLAudio in Chrome when playing back audio
	 * that is already in a load, but not complete.
	 * @method _handleStalled
	 * @private
	 */
	p._handleStalled = function () {
		//Ignore, let the timeout take care of it. Sometimes its not really stopped.
	};

	createjs.TagRequest = createjs.promote(TagRequest, "AbstractRequest");

}());

//##############################################################################
// MediaTagRequest.js
//##############################################################################

this.createjs = this.createjs || {};

(function () {
	"use strict";

	// constructor
	/**
	 * An {{#crossLink "TagRequest"}}{{/crossLink}} that loads HTML tags for video and audio.
	 * @class MediaTagRequest
	 * @param {LoadItem} loadItem
	 * @param {HTMLAudioElement|HTMLVideoElement} tag
	 * @param {String} srcAttribute The tag attribute that specifies the source, such as "src", "href", etc.
	 * @constructor
	 */
	function MediaTagRequest(loadItem, tag, srcAttribute) {
		this.AbstractRequest_constructor(loadItem);

		// protected properties
		this._tag = tag;
		this._tagSrcAttribute = srcAttribute;
		this._loadedHandler = createjs.proxy(this._handleTagComplete, this);
	};

	var p = createjs.extend(MediaTagRequest, createjs.TagRequest);
	var s = MediaTagRequest;

	// public methods
	p.load = function () {
		var sc = createjs.proxy(this._handleStalled, this);
		this._stalledCallback = sc;

		var pc = createjs.proxy(this._handleProgress, this);
		this._handleProgress = pc;

		this._tag.addEventListener("stalled", sc);
		this._tag.addEventListener("progress", pc);

		// This will tell us when audio is buffered enough to play through, but not when its loaded.
		// The tag doesn't keep loading in Chrome once enough has buffered, and we have decided that behaviour is sufficient.
		this._tag.addEventListener && this._tag.addEventListener("canplaythrough", this._loadedHandler, false); // canplaythrough callback doesn't work in Chrome, so we use an event.

		this.TagRequest_load();
	};

	// private methods
	p._handleReadyStateChange = function () {
		clearTimeout(this._loadTimeout);
		// This is strictly for tags in browsers that do not support onload.
		var tag = this._tag;

		// Complete is for old IE support.
		if (tag.readyState == "loaded" || tag.readyState == "complete") {
			this._handleTagComplete();
		}
	};

	p._handleStalled = function () {
		//Ignore, let the timeout take care of it. Sometimes its not really stopped.
	};

	/**
	 * An XHR request has reported progress.
	 * @method _handleProgress
	 * @param {Object} event The XHR progress event.
	 * @private
	 */
	p._handleProgress = function (event) {
		if (!event || event.loaded > 0 && event.total == 0) {
			return; // Sometimes we get no "total", so just ignore the progress event.
		}

		var newEvent = new createjs.ProgressEvent(event.loaded, event.total);
		this.dispatchEvent(newEvent);
	};

	// protected methods
	p._clean = function () {
		this._tag.removeEventListener && this._tag.removeEventListener("canplaythrough", this._loadedHandler);
		this._tag.removeEventListener("stalled", this._stalledCallback);
		this._tag.removeEventListener("progress", this._progressCallback);

		this.TagRequest__clean();
	};

	createjs.MediaTagRequest = createjs.promote(MediaTagRequest, "TagRequest");

}());

//##############################################################################
// XHRRequest.js
//##############################################################################

this.createjs = this.createjs || {};

(function () {
	"use strict";

// constructor
	/**
	 * A preloader that loads items using XHR requests, usually XMLHttpRequest. However XDomainRequests will be used
	 * for cross-domain requests if possible, and older versions of IE fall back on to ActiveX objects when necessary.
	 * XHR requests load the content as text or binary data, provide progress and consistent completion events, and
	 * can be canceled during load. Note that XHR is not supported in IE 6 or earlier, and is not recommended for
	 * cross-domain loading.
	 * @class XHRRequest
	 * @constructor
	 * @param {Object} item The object that defines the file to load. Please see the {{#crossLink "LoadQueue/loadFile"}}{{/crossLink}}
	 * for an overview of supported file properties.
	 * @extends AbstractLoader
	 */
	function XHRRequest (item) {
		this.AbstractRequest_constructor(item);

		// protected properties
		/**
		 * A reference to the XHR request used to load the content.
		 * @property _request
		 * @type {XMLHttpRequest | XDomainRequest | ActiveX.XMLHTTP}
		 * @private
		 */
		this._request = null;

		/**
		 * A manual load timeout that is used for browsers that do not support the onTimeout event on XHR (XHR level 1,
		 * typically IE9).
		 * @property _loadTimeout
		 * @type {Number}
		 * @private
		 */
		this._loadTimeout = null;

		/**
		 * The browser's XHR (XMLHTTPRequest) version. Supported versions are 1 and 2. There is no official way to detect
		 * the version, so we use capabilities to make a best guess.
		 * @property _xhrLevel
		 * @type {Number}
		 * @default 1
		 * @private
		 */
		this._xhrLevel = 1;

		/**
		 * The response of a loaded file. This is set because it is expensive to look up constantly. This property will be
		 * null until the file is loaded.
		 * @property _response
		 * @type {mixed}
		 * @private
		 */
		this._response = null;

		/**
		 * The response of the loaded file before it is modified. In most cases, content is converted from raw text to
		 * an HTML tag or a formatted object which is set to the <code>result</code> property, but the developer may still
		 * want to access the raw content as it was loaded.
		 * @property _rawResponse
		 * @type {String|Object}
		 * @private
		 */
		this._rawResponse = null;

		this._canceled = false;

		// Setup our event handlers now.
		this._handleLoadStartProxy = createjs.proxy(this._handleLoadStart, this);
		this._handleProgressProxy = createjs.proxy(this._handleProgress, this);
		this._handleAbortProxy = createjs.proxy(this._handleAbort, this);
		this._handleErrorProxy = createjs.proxy(this._handleError, this);
		this._handleTimeoutProxy = createjs.proxy(this._handleTimeout, this);
		this._handleLoadProxy = createjs.proxy(this._handleLoad, this);
		this._handleReadyStateChangeProxy = createjs.proxy(this._handleReadyStateChange, this);

		if (!this._createXHR(item)) {
			//TODO: Throw error?
		}
	};

	var p = createjs.extend(XHRRequest, createjs.AbstractRequest);

// static properties
	/**
	 * A list of XMLHTTP object IDs to try when building an ActiveX object for XHR requests in earlier versions of IE.
	 * @property ACTIVEX_VERSIONS
	 * @type {Array}
	 * @since 0.4.2
	 * @private
	 */
	XHRRequest.ACTIVEX_VERSIONS = [
		"Msxml2.XMLHTTP.6.0",
		"Msxml2.XMLHTTP.5.0",
		"Msxml2.XMLHTTP.4.0",
		"MSXML2.XMLHTTP.3.0",
		"MSXML2.XMLHTTP",
		"Microsoft.XMLHTTP"
	];

// Public methods
	/**
	 * Look up the loaded result.
	 * @method getResult
	 * @param {Boolean} [raw=false] Return a raw result instead of a formatted result. This applies to content
	 * loaded via XHR such as scripts, XML, CSS, and Images. If there is no raw result, the formatted result will be
	 * returned instead.
	 * @return {Object} A result object containing the content that was loaded, such as:
	 * <ul>
	 *      <li>An image tag (&lt;image /&gt;) for images</li>
	 *      <li>A script tag for JavaScript (&lt;script /&gt;). Note that scripts loaded with tags may be added to the
	 *      HTML head.</li>
	 *      <li>A style tag for CSS (&lt;style /&gt;)</li>
	 *      <li>Raw text for TEXT</li>
	 *      <li>A formatted JavaScript object defined by JSON</li>
	 *      <li>An XML document</li>
	 *      <li>An binary arraybuffer loaded by XHR</li>
	 * </ul>
	 * Note that if a raw result is requested, but not found, the result will be returned instead.
	 */
	p.getResult = function (raw) {
		if (raw && this._rawResponse) {
			return this._rawResponse;
		}
		return this._response;
	};

	// Overrides abstract method in AbstractRequest
	p.cancel = function () {
		this.canceled = true;
		this._clean();
		this._request.abort();
	};

	// Overrides abstract method in AbstractLoader
	p.load = function () {
		if (this._request == null) {
			this._handleError();
			return;
		}

		//Events
		if (this._request.addEventListener != null) {
			this._request.addEventListener("loadstart", this._handleLoadStartProxy, false);
			this._request.addEventListener("progress", this._handleProgressProxy, false);
			this._request.addEventListener("abort", this._handleAbortProxy, false);
			this._request.addEventListener("error", this._handleErrorProxy, false);
			this._request.addEventListener("timeout", this._handleTimeoutProxy, false);

			// Note: We don't get onload in all browsers (earlier FF and IE). onReadyStateChange handles these.
			this._request.addEventListener("load", this._handleLoadProxy, false);
			this._request.addEventListener("readystatechange", this._handleReadyStateChangeProxy, false);
		} else {
			// IE9 support
			this._request.onloadstart = this._handleLoadStartProxy;
			this._request.onprogress = this._handleProgressProxy;
			this._request.onabort = this._handleAbortProxy;
			this._request.onerror = this._handleErrorProxy;
			this._request.ontimeout = this._handleTimeoutProxy;

			// Note: We don't get onload in all browsers (earlier FF and IE). onReadyStateChange handles these.
			this._request.onload = this._handleLoadProxy;
			this._request.onreadystatechange = this._handleReadyStateChangeProxy;
		}

		// Set up a timeout if we don't have XHR2
		if (this._xhrLevel == 1) {
			this._loadTimeout = setTimeout(createjs.proxy(this._handleTimeout, this), this._item.loadTimeout);
		}

		// Sometimes we get back 404s immediately, particularly when there is a cross origin request.  // note this does not catch in Chrome
		try {
			if (!this._item.values || this._item.method == createjs.AbstractLoader.GET) {
				this._request.send();
			} else if (this._item.method == createjs.AbstractLoader.POST) {
				this._request.send(createjs.RequestUtils.formatQueryString(this._item.values));
			}
		} catch (error) {
			this.dispatchEvent(new createjs.ErrorEvent("XHR_SEND", null, error));
		}
	};

	p.setResponseType = function (type) {
		// Some old browsers doesn't support blob, so we convert arraybuffer to blob after response is downloaded
		if (type === 'blob') {
			type = window.URL ? 'blob' : 'arraybuffer';
			this._responseType = type;
		}
		this._request.responseType = type;
	};

	/**
	 * Get all the response headers from the XmlHttpRequest.
	 *
	 * <strong>From the docs:</strong> Return all the HTTP headers, excluding headers that are a case-insensitive match
	 * for Set-Cookie or Set-Cookie2, as a single string, with each header line separated by a U+000D CR U+000A LF pair,
	 * excluding the status line, and with each header name and header value separated by a U+003A COLON U+0020 SPACE
	 * pair.
	 * @method getAllResponseHeaders
	 * @return {String}
	 * @since 0.4.1
	 */
	p.getAllResponseHeaders = function () {
		if (this._request.getAllResponseHeaders instanceof Function) {
			return this._request.getAllResponseHeaders();
		} else {
			return null;
		}
	};

	/**
	 * Get a specific response header from the XmlHttpRequest.
	 *
	 * <strong>From the docs:</strong> Returns the header field value from the response of which the field name matches
	 * header, unless the field name is Set-Cookie or Set-Cookie2.
	 * @method getResponseHeader
	 * @param {String} header The header name to retrieve.
	 * @return {String}
	 * @since 0.4.1
	 */
	p.getResponseHeader = function (header) {
		if (this._request.getResponseHeader instanceof Function) {
			return this._request.getResponseHeader(header);
		} else {
			return null;
		}
	};

// protected methods
	/**
	 * The XHR request has reported progress.
	 * @method _handleProgress
	 * @param {Object} event The XHR progress event.
	 * @private
	 */
	p._handleProgress = function (event) {
		if (!event || event.loaded > 0 && event.total == 0) {
			return; // Sometimes we get no "total", so just ignore the progress event.
		}

		var newEvent = new createjs.ProgressEvent(event.loaded, event.total);
		this.dispatchEvent(newEvent);
	};

	/**
	 * The XHR request has reported a load start.
	 * @method _handleLoadStart
	 * @param {Object} event The XHR loadStart event.
	 * @private
	 */
	p._handleLoadStart = function (event) {
		clearTimeout(this._loadTimeout);
		this.dispatchEvent("loadstart");
	};

	/**
	 * The XHR request has reported an abort event.
	 * @method handleAbort
	 * @param {Object} event The XHR abort event.
	 * @private
	 */
	p._handleAbort = function (event) {
		this._clean();
		this.dispatchEvent(new createjs.ErrorEvent("XHR_ABORTED", null, event));
	};

	/**
	 * The XHR request has reported an error event.
	 * @method _handleError
	 * @param {Object} event The XHR error event.
	 * @private
	 */
	p._handleError = function (event) {
		this._clean();
		this.dispatchEvent(new createjs.ErrorEvent(event.message));
	};

	/**
	 * The XHR request has reported a readyState change. Note that older browsers (IE 7 & 8) do not provide an onload
	 * event, so we must monitor the readyStateChange to determine if the file is loaded.
	 * @method _handleReadyStateChange
	 * @param {Object} event The XHR readyStateChange event.
	 * @private
	 */
	p._handleReadyStateChange = function (event) {
		if (this._request.readyState == 4) {
			this._handleLoad();
		}
	};

	/**
	 * The XHR request has completed. This is called by the XHR request directly, or by a readyStateChange that has
	 * <code>request.readyState == 4</code>. Only the first call to this method will be processed.
	 * @method _handleLoad
	 * @param {Object} event The XHR load event.
	 * @private
	 */
	p._handleLoad = function (event) {
		if (this.loaded) {
			return;
		}
		this.loaded = true;

		var error = this._checkError();
		if (error) {
			this._handleError(error);
			return;
		}

		this._response = this._getResponse();
		// Convert arraybuffer back to blob
		if (this._responseType === 'arraybuffer') {
			try {
				this._response = new Blob([this._response]);
			} catch (e) {
				// Fallback to use BlobBuilder if Blob constructor is not supported
				// Tested on Android 2.3 ~ 4.2 and iOS5 safari
				window.BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder;
				if (e.name === 'TypeError' && window.BlobBuilder) {
					var builder = new BlobBuilder();
					builder.append(this._response);
					this._response = builder.getBlob();
				}
			}
		}
		this._clean();

		this.dispatchEvent(new createjs.Event("complete"));
	};

	/**
	 * The XHR request has timed out. This is called by the XHR request directly, or via a <code>setTimeout</code>
	 * callback.
	 * @method _handleTimeout
	 * @param {Object} [event] The XHR timeout event. This is occasionally null when called by the backup setTimeout.
	 * @private
	 */
	p._handleTimeout = function (event) {
		this._clean();

		this.dispatchEvent(new createjs.ErrorEvent("PRELOAD_TIMEOUT", null, event));
	};

// Protected
	/**
	 * Determine if there is an error in the current load. This checks the status of the request for problem codes. Note
	 * that this does not check for an actual response. Currently, it only checks for 404 or 0 error code.
	 * @method _checkError
	 * @return {int} If the request status returns an error code.
	 * @private
	 */
	p._checkError = function () {
		//LM: Probably need additional handlers here, maybe 501
		var status = parseInt(this._request.status);

		switch (status) {
			case 404:   // Not Found
			case 0:     // Not Loaded
				return new Error(status);
		}
		return null;
	};

	/**
	 * Validate the response. Different browsers have different approaches, some of which throw errors when accessed
	 * in other browsers. If there is no response, the <code>_response</code> property will remain null.
	 * @method _getResponse
	 * @private
	 */
	p._getResponse = function () {
		if (this._response != null) {
			return this._response;
		}

		if (this._request.response != null) {
			return this._request.response;
		}

		// Android 2.2 uses .responseText
		try {
			if (this._request.responseText != null) {
				return this._request.responseText;
			}
		} catch (e) {
		}

		// When loading XML, IE9 does not return .response, instead it returns responseXML.xml
		try {
			if (this._request.responseXML != null) {
				return this._request.responseXML;
			}
		} catch (e) {
		}

		return null;
	};

	/**
	 * Create an XHR request. Depending on a number of factors, we get totally different results.
	 * <ol><li>Some browsers get an <code>XDomainRequest</code> when loading cross-domain.</li>
	 *      <li>XMLHttpRequest are created when available.</li>
	 *      <li>ActiveX.XMLHTTP objects are used in older IE browsers.</li>
	 *      <li>Text requests override the mime type if possible</li>
	 *      <li>Origin headers are sent for crossdomain requests in some browsers.</li>
	 *      <li>Binary loads set the response type to "arraybuffer"</li></ol>
	 * @method _createXHR
	 * @param {Object} item The requested item that is being loaded.
	 * @return {Boolean} If an XHR request or equivalent was successfully created.
	 * @private
	 */
	p._createXHR = function (item) {
		// Check for cross-domain loads. We can't fully support them, but we can try.
		var crossdomain = createjs.RequestUtils.isCrossDomain(item);
		var headers = {};

		// Create the request. Fallback to whatever support we have.
		var req = null;
		if (window.XMLHttpRequest) {
			req = new XMLHttpRequest();
			// This is 8 or 9, so use XDomainRequest instead.
			if (crossdomain && req.withCredentials === undefined && window.XDomainRequest) {
				req = new XDomainRequest();
			}
		} else { // Old IE versions use a different approach
			for (var i = 0, l = s.ACTIVEX_VERSIONS.length; i < l; i++) {
				var axVersion = s.ACTIVEX_VERSIONS[i];
				try {
					req = new ActiveXObject(axVersion);
					break;
				} catch (e) {
				}
			}
			if (req == null) {
				return false;
			}
		}

		// Default to utf-8 for Text requests.
		if (item.mimeType == null && createjs.RequestUtils.isText(item.type)) {
			item.mimeType = "text/plain; charset=utf-8";
		}

		// IE9 doesn't support overrideMimeType(), so we need to check for it.
		if (item.mimeType && req.overrideMimeType) {
			req.overrideMimeType(item.mimeType);
		}

		// Determine the XHR level
		this._xhrLevel = (typeof req.responseType === "string") ? 2 : 1;

		var src = null;
		if (item.method == createjs.AbstractLoader.GET) {
			src = createjs.RequestUtils.buildPath(item.src, item.values);
		} else {
			src = item.src;
		}

		// Open the request.  Set cross-domain flags if it is supported (XHR level 1 only)
		req.open(item.method || createjs.AbstractLoader.GET, src, true);

		if (crossdomain && req instanceof XMLHttpRequest && this._xhrLevel == 1) {
			headers["Origin"] = location.origin;
		}

		// To send data we need to set the Content-type header)
		if (item.values && item.method == createjs.AbstractLoader.POST) {
			headers["Content-Type"] = "application/x-www-form-urlencoded";
		}

		if (!crossdomain && !headers["X-Requested-With"]) {
			headers["X-Requested-With"] = "XMLHttpRequest";
		}

		if (item.headers) {
			for (var n in item.headers) {
				headers[n] = item.headers[n];
			}
		}

		for (n in headers) {
			req.setRequestHeader(n, headers[n])
		}

		if (req instanceof XMLHttpRequest && item.withCredentials !== undefined) {
			req.withCredentials = item.withCredentials;
		}

		this._request = req;

		return true;
	};

	/**
	 * A request has completed (or failed or canceled), and needs to be disposed.
	 * @method _clean
	 * @private
	 */
	p._clean = function () {
		clearTimeout(this._loadTimeout);

		if (this._request.removeEventListener != null) {
			this._request.removeEventListener("loadstart", this._handleLoadStartProxy);
			this._request.removeEventListener("progress", this._handleProgressProxy);
			this._request.removeEventListener("abort", this._handleAbortProxy);
			this._request.removeEventListener("error", this._handleErrorProxy);
			this._request.removeEventListener("timeout", this._handleTimeoutProxy);
			this._request.removeEventListener("load", this._handleLoadProxy);
			this._request.removeEventListener("readystatechange", this._handleReadyStateChangeProxy);
		} else {
			this._request.onloadstart = null;
			this._request.onprogress = null;
			this._request.onabort = null;
			this._request.onerror = null;
			this._request.ontimeout = null;
			this._request.onload = null;
			this._request.onreadystatechange = null;
		}
	};

	p.toString = function () {
		return "[PreloadJS XHRRequest]";
	};

	createjs.XHRRequest = createjs.promote(XHRRequest, "AbstractRequest");

}());

//##############################################################################
// SoundLoader.js
//##############################################################################

this.createjs = this.createjs || {};

(function () {
	"use strict";

	// constructor
	/**
	 * A loader for HTML audio files. PreloadJS can not load WebAudio files, as a WebAudio context is required, which
	 * should be created by either a library playing the sound (such as <a href="http://soundjs.com">SoundJS</a>, or an
	 * external framework that handles audio playback. To load content that can be played by WebAudio, use the
	 * {{#crossLink "BinaryLoader"}}{{/crossLink}}, and handle the audio context decoding manually.
	 * @class SoundLoader
	 * @param {LoadItem|Object} loadItem
	 * @param {Boolean} preferXHR
	 * @extends AbstractMediaLoader
	 * @constructor
	 */
	function SoundLoader(loadItem, preferXHR) {
		this.AbstractMediaLoader_constructor(loadItem, preferXHR, createjs.AbstractLoader.SOUND);

		// protected properties
		if (createjs.RequestUtils.isAudioTag(loadItem)) {
			this._tag = loadItem;
		} else if (createjs.RequestUtils.isAudioTag(loadItem.src)) {
			this._tag = loadItem;
		} else if (createjs.RequestUtils.isAudioTag(loadItem.tag)) {
			this._tag = createjs.RequestUtils.isAudioTag(loadItem) ? loadItem : loadItem.src;
		}

		if (this._tag != null) {
			this._preferXHR = false;
		}
	};

	var p = createjs.extend(SoundLoader, createjs.AbstractMediaLoader);
	var s = SoundLoader;

	// static methods
	/**
	 * Determines if the loader can load a specific item. This loader can only load items that are of type
	 * {{#crossLink "AbstractLoader/SOUND:property"}}{{/crossLink}}.
	 * @method canLoadItem
	 * @param {LoadItem|Object} item The LoadItem that a LoadQueue is trying to load.
	 * @returns {Boolean} Whether the loader can load the item.
	 * @static
	 */
	s.canLoadItem = function (item) {
		return item.type == createjs.AbstractLoader.SOUND;
	};

	// protected methods
	p._createTag = function (src) {
		var tag = document.createElement("audio");
		tag.autoplay = false;
		tag.preload = "none";

		//LM: Firefox fails when this the preload="none" for other tags, but it needs to be "none" to ensure PreloadJS works.
		tag.src = src;
		return tag;
	};

	createjs.SoundLoader = createjs.promote(SoundLoader, "AbstractMediaLoader");

}());

//##############################################################################
// AudioSprite.js
//##############################################################################

//  NOTE this is "Class" is purely to document audioSprite Setup and usage.


/**
 * <strong>Note: AudioSprite is not a class, but its usage is easily lost in the documentation, so it has been called
 * out here for quick reference.</strong>
 *
 * Audio sprites are much like CSS sprites or image sprite sheets: multiple audio assets grouped into a single file.
 * Audio sprites work around limitations in certain browsers, where only a single sound can be loaded and played at a
 * time. We recommend at least 300ms of silence between audio clips to deal with HTML audio tag inaccuracy, and to prevent
 * accidentally playing bits of the neighbouring clips.
 *
 * <strong>Benefits of Audio Sprites:</strong>
 * <ul>
 *     <li>More robust support for older browsers and devices that only allow a single audio instance, such as iOS 5.</li>
 *     <li>They provide a work around for the Internet Explorer 9 audio tag limit, which restricts how many different
 *     sounds that could be loaded at once.</li>
 *     <li>Faster loading by only requiring a single network request for several sounds, especially on mobile devices
 * where the network round trip for each file can add significant latency.</li>
 * </ul>
 *
 * <strong>Drawbacks of Audio Sprites</strong>
 * <ul>
 *     <li>No guarantee of smooth looping when using HTML or Flash audio. If you have a track that needs to loop
 * 		smoothly and you are supporting non-web audio browsers, do not use audio sprites for that sound if you can avoid
 * 		it.</li>
 *     <li>No guarantee that HTML audio will play back immediately, especially the first time. In some browsers
 *     (Chrome!), HTML audio will only load enough to play through at the current download speed – so we rely on the
 *     `canplaythrough` event to determine if the audio is loaded. Since audio sprites must jump ahead to play specific
 *     sounds, the audio may not yet have downloaded fully.</li>
 *     <li>Audio sprites share the same core source, so if you have a sprite with 5 sounds and are limited to 2
 * 		concurrently playing instances, you can only play 2 of the sounds at the same time.</li>
 * </ul>
 *
 * <h4>Example</h4>
 *
 *		createjs.Sound.initializeDefaultPlugins();
 *		var assetsPath = "./assets/";
 *		var sounds = [{
 *			src:"MyAudioSprite.ogg", data: {
 *				audioSprite: [
 *					{id:"sound1", startTime:0, duration:500},
 *					{id:"sound2", startTime:1000, duration:400},
 *					{id:"sound3", startTime:1700, duration: 1000}
 *				]}
 *			}
 *		];
 *		createjs.Sound.alternateExtensions = ["mp3"];
 *		createjs.Sound.on("fileload", loadSound);
 *		createjs.Sound.registerSounds(sounds, assetsPath);
 *		// after load is complete
 *		createjs.Sound.play("sound2");
 *
 * You can also create audio sprites on the fly by setting the startTime and duration when creating an new AbstractSoundInstance.
 *
 * 		createjs.Sound.play("MyAudioSprite", {startTime: 1000, duration: 400});
 *
 * The excellent CreateJS community has created a tool to create audio sprites, available at
 * <a href="https://github.com/tonistiigi/audiosprite" target="_blank">https://github.com/tonistiigi/audiosprite</a>,
 * as well as a <a href="http://jsfiddle.net/bharat_battu/g8fFP/12/" target="_blank">jsfiddle</a> to convert the output
 * to SoundJS format.
 *
 * @class AudioSprite
 * @since 0.6.0
 */

//##############################################################################
// PlayPropsConfig.js
//##############################################################################

this.createjs = this.createjs || {};

(function () {
	"use strict";
	/**
	 * A class to store the optional play properties passed in {{#crossLink "Sound/play"}}{{/crossLink}} and
	 * {{#crossLink "AbstractSoundInstance/play"}}{{/crossLink}} calls.
	 *
	 * Optional Play Properties Include:
	 * <ul>
	 * <li>interrupt - How to interrupt any currently playing instances of audio with the same source,
	 * if the maximum number of instances of the sound are already playing. Values are defined as <code>INTERRUPT_TYPE</code>
	 * constants on the Sound class, with the default defined by {{#crossLink "Sound/defaultInterruptBehavior:property"}}{{/crossLink}}.</li>
	 * <li>delay - The amount of time to delay the start of audio playback, in milliseconds.</li>
	 * <li>offset - The offset from the start of the audio to begin playback, in milliseconds.</li>
	 * <li>loop - How many times the audio loops when it reaches the end of playback. The default is 0 (no
	 * loops), and -1 can be used for infinite playback.</li>
	 * <li>volume - The volume of the sound, between 0 and 1. Note that the master volume is applied
	 * against the individual volume.</li>
	 * <li>pan - The left-right pan of the sound (if supported), between -1 (left) and 1 (right).</li>
	 * <li>startTime - To create an audio sprite (with duration), the initial offset to start playback and loop from, in milliseconds.</li>
	 * <li>duration - To create an audio sprite (with startTime), the amount of time to play the clip for, in milliseconds.</li>
	 * </ul>
	 *
	 * <h4>Example</h4>
	 *
	 * 	var ppc = new createjs.PlayPropsConfig().set({interrupt: createjs.Sound.INTERRUPT_ANY, loop: -1, volume: 0.5})
	 * 	createjs.Sound.play("mySound", ppc);
	 * 	mySoundInstance.play(ppc);
	 *
	 * @class PlayPropsConfig
	 * @constructor
	 * @since 0.6.1
	 */
	// TODO think of a better name for this class
	var PlayPropsConfig = function () {
// Public Properties
		/**
		 * How to interrupt any currently playing instances of audio with the same source,
		 * if the maximum number of instances of the sound are already playing. Values are defined as
		 * <code>INTERRUPT_TYPE</code> constants on the Sound class, with the default defined by
		 * {{#crossLink "Sound/defaultInterruptBehavior:property"}}{{/crossLink}}.
		 * @property interrupt
		 * @type {string}
		 * @default null
		 */
		this.interrupt = null;

		/**
		 * The amount of time to delay the start of audio playback, in milliseconds.
		 * @property delay
		 * @type {Number}
		 * @default null
		 */
		this.delay = null;

		/**
		 * The offset from the start of the audio to begin playback, in milliseconds.
		 * @property offset
		 * @type {number}
		 * @default null
		 */
		this.offset = null;

		/**
		 * How many times the audio loops when it reaches the end of playback. The default is 0 (no
		 * loops), and -1 can be used for infinite playback.
		 * @property loop
		 * @type {number}
		 * @default null
		 */
		this.loop = null;

		/**
		 * The volume of the sound, between 0 and 1. Note that the master volume is applied
		 * against the individual volume.
		 * @property volume
		 * @type {number}
		 * @default null
		 */
		this.volume = null;

		/**
		 * The left-right pan of the sound (if supported), between -1 (left) and 1 (right).
		 * @property pan
		 * @type {number}
		 * @default null
		 */
		this.pan = null;

		/**
		 * Used to create an audio sprite (with duration), the initial offset to start playback and loop from, in milliseconds.
		 * @property startTime
		 * @type {number}
		 * @default null
		 */
		this.startTime = null;

		/**
		 * Used to create an audio sprite (with startTime), the amount of time to play the clip for, in milliseconds.
		 * @property duration
		 * @type {number}
		 * @default null
		 */
		this.duration = null;
	};
	var p = PlayPropsConfig.prototype = {};
	var s = PlayPropsConfig;


// Static Methods
	/**
	 * Creates a PlayPropsConfig from another PlayPropsConfig or an Object.
	 *
	 * @method create
	 * @param {PlayPropsConfig|Object} value The play properties
	 * @returns {PlayPropsConfig}
	 * @static
	 */
	s.create = function (value) {
		if (value instanceof s || value instanceof Object) {
			var ppc = new createjs.PlayPropsConfig();
			ppc.set(value);
			return ppc;
		} else {
			throw new Error("Type not recognized.");
		}
	};

// Public Methods
	/**
	 * Provides a chainable shortcut method for setting a number of properties on the instance.
	 *
	 * <h4>Example</h4>
	 *
	 *      var PlayPropsConfig = new createjs.PlayPropsConfig().set({loop:-1, volume:0.7});
	 *
	 * @method set
	 * @param {Object} props A generic object containing properties to copy to the PlayPropsConfig instance.
	 * @return {PlayPropsConfig} Returns the instance the method is called on (useful for chaining calls.)
	*/
	p.set = function(props) {
		for (var n in props) { this[n] = props[n]; }
		return this;
	};

	p.toString = function() {
		return "[PlayPropsConfig]";
	};

	createjs.PlayPropsConfig = s;

}());

//##############################################################################
// Sound.js
//##############################################################################

this.createjs = this.createjs || {};



(function () {
	"use strict";

	/**
	 * The Sound class is the public API for creating sounds, controlling the overall sound levels, and managing plugins.
	 * All Sound APIs on this class are static.
	 *
	 * <b>Registering and Preloading</b><br />
	 * Before you can play a sound, it <b>must</b> be registered. You can do this with {{#crossLink "Sound/registerSound"}}{{/crossLink}},
	 * or register multiple sounds using {{#crossLink "Sound/registerSounds"}}{{/crossLink}}. If you don't register a
	 * sound prior to attempting to play it using {{#crossLink "Sound/play"}}{{/crossLink}} or create it using {{#crossLink "Sound/createInstance"}}{{/crossLink}},
	 * the sound source will be automatically registered but playback will fail as the source will not be ready. If you use
	 * <a href="http://preloadjs.com" target="_blank">PreloadJS</a>, registration is handled for you when the sound is
	 * preloaded. It is recommended to preload sounds either internally using the register functions or externally using
	 * PreloadJS so they are ready when you want to use them.
	 *
	 * <b>Playback</b><br />
	 * To play a sound once it's been registered and preloaded, use the {{#crossLink "Sound/play"}}{{/crossLink}} method.
	 * This method returns a {{#crossLink "AbstractSoundInstance"}}{{/crossLink}} which can be paused, resumed, muted, etc.
	 * Please see the {{#crossLink "AbstractSoundInstance"}}{{/crossLink}} documentation for more on the instance control APIs.
	 *
	 * <b>Plugins</b><br />
	 * By default, the {{#crossLink "WebAudioPlugin"}}{{/crossLink}} or the {{#crossLink "HTMLAudioPlugin"}}{{/crossLink}}
	 * are used (when available), although developers can change plugin priority or add new plugins (such as the
	 * provided {{#crossLink "FlashAudioPlugin"}}{{/crossLink}}). Please see the {{#crossLink "Sound"}}{{/crossLink}} API
	 * methods for more on the playback and plugin APIs. To install plugins, or specify a different plugin order, see
	 * {{#crossLink "Sound/installPlugins"}}{{/crossLink}}.
	 *
	 * <h4>Example</h4>
	 *
	 *      createjs.FlashAudioPlugin.swfPath = "../src/soundjs/flashaudio";
	 *      createjs.Sound.registerPlugins([createjs.WebAudioPlugin, createjs.FlashAudioPlugin]);
	 *      createjs.Sound.alternateExtensions = ["mp3"];
	 *      createjs.Sound.on("fileload", this.loadHandler, this);
	 *      createjs.Sound.registerSound("path/to/mySound.ogg", "sound");
	 *      function loadHandler(event) {
     *          // This is fired for each sound that is registered.
     *          var instance = createjs.Sound.play("sound");  // play using id.  Could also use full source path or event.src.
     *          instance.on("complete", this.handleComplete, this);
     *          instance.volume = 0.5;
	 *      }
	 *
	 * The maximum number of concurrently playing instances of the same sound can be specified in the "data" argument
	 * of {{#crossLink "Sound/registerSound"}}{{/crossLink}}.  Note that if not specified, the active plugin will apply
	 * a default limit.  Currently HTMLAudioPlugin sets a default limit of 2, while WebAudioPlugin and FlashAudioPlugin set a
	 * default limit of 100.
	 *
	 *      createjs.Sound.registerSound("sound.mp3", "soundId", 4);
	 *
	 * Sound can be used as a plugin with PreloadJS to help preload audio properly. Audio preloaded with PreloadJS is
	 * automatically registered with the Sound class. When audio is not preloaded, Sound will do an automatic internal
	 * load. As a result, it may fail to play the first time play is called if the audio is not finished loading. Use
	 * the {{#crossLink "Sound/fileload:event"}}{{/crossLink}} event to determine when a sound has finished internally
	 * preloading. It is recommended that all audio is preloaded before it is played.
	 *
	 *      var queue = new createjs.LoadQueue();
	 *		queue.installPlugin(createjs.Sound);
	 *
	 * <b>Audio Sprites</b><br />
	 * SoundJS has added support for {{#crossLink "AudioSprite"}}{{/crossLink}}, available as of version 0.6.0.
	 * For those unfamiliar with audio sprites, they are much like CSS sprites or sprite sheets: multiple audio assets
	 * grouped into a single file.
	 *
	 * <h4>Example</h4>
	 *
	 *		var assetsPath = "./assets/";
	 *		var sounds = [{
	 *			src:"MyAudioSprite.ogg", data: {
	 *				audioSprite: [
	 *					{id:"sound1", startTime:0, duration:500},
	 *					{id:"sound2", startTime:1000, duration:400},
	 *					{id:"sound3", startTime:1700, duration: 1000}
	 *				]}
 	 *			}
	 *		];
	 *		createjs.Sound.alternateExtensions = ["mp3"];
	 *		createjs.Sound.on("fileload", loadSound);
	 *		createjs.Sound.registerSounds(sounds, assetsPath);
	 *		// after load is complete
	 *		createjs.Sound.play("sound2");
	 *
	 * <b>Mobile Playback</b><br />
	 * Devices running iOS require the WebAudio context to be "unlocked" by playing at least one sound inside of a user-
	 * initiated event (such as touch/click). Earlier versions of SoundJS included a "MobileSafe" sample, but this is no
	 * longer necessary as of SoundJS 0.6.2.
	 * <ul>
	 *     <li>
	 *         In SoundJS 0.4.1 and above, you can either initialize plugins or use the {{#crossLink "WebAudioPlugin/playEmptySound"}}{{/crossLink}}
	 *         method in the call stack of a user input event to manually unlock the audio context.
	 *     </li>
	 *     <li>
	 *         In SoundJS 0.6.2 and above, SoundJS will automatically listen for the first document-level "mousedown"
	 *         and "touchend" event, and unlock WebAudio. This will continue to check these events until the WebAudio
	 *         context becomes "unlocked" (changes from "suspended" to "running")
	 *     </li>
	 *     <li>
	 *         Both the "mousedown" and "touchend" events can be used to unlock audio in iOS9+, the "touchstart" event
	 *         will work in iOS8 and below. The "touchend" event will only work in iOS9 when the gesture is interpreted
	 *         as a "click", so if the user long-presses the button, it will no longer work.
	 *     </li>
	 *     <li>
	 *         When using the <a href="http://www.createjs.com/docs/easeljs/classes/Touch.html">EaselJS Touch class</a>,
	 *         the "mousedown" event will not fire when a canvas is clicked, since MouseEvents are prevented, to ensure
	 *         only touch events fire. To get around this, you can either rely on "touchend", or:
	 *         <ol>
	 *             <li>Set the `allowDefault` property on the Touch class constructor to `true` (defaults to `false`).</li>
	 *             <li>Set the `preventSelection` property on the EaselJS `Stage` to `false`.</li>
	 *         </ol>
	 *         These settings may change how your application behaves, and are not recommended.
	 *     </li>
	 * </ul>
	 *
	 * <b>Loading Alternate Paths and Extension-less Files</b><br />
	 * SoundJS supports loading alternate paths and extension-less files by passing an object instead of a string for
	 * the `src` property, which is a hash using the format `{extension:"path", extension2:"path2"}`. These labels are
	 * how SoundJS determines if the browser will support the sound. This also enables multiple formats to live in
	 * different folders, or on CDNs, which often has completely different filenames for each file.
	 *
	 * Priority is determined by the property order (first property is tried first).  This is supported by both internal loading
	 * and loading with PreloadJS.
	 *
	 * <em>Note: an id is required for playback.</em>
	 *
	 * <h4>Example</h4>
	 *
	 *		var sounds = {path:"./audioPath/",
	 * 				manifest: [
	 *				{id: "cool", src: {mp3:"mp3/awesome.mp3", ogg:"noExtensionOggFile"}}
	 *		]};
	 *
	 *		createjs.Sound.alternateExtensions = ["mp3"];
	 *		createjs.Sound.addEventListener("fileload", handleLoad);
	 *		createjs.Sound.registerSounds(sounds);
	 *
	 * <h3>Known Browser and OS issues</h3>
	 * <b>IE 9 HTML Audio limitations</b><br />
	 * <ul><li>There is a delay in applying volume changes to tags that occurs once playback is started. So if you have
	 * muted all sounds, they will all play during this delay until the mute applies internally. This happens regardless of
	 * when or how you apply the volume change, as the tag seems to need to play to apply it.</li>
     * <li>MP3 encoding will not always work for audio tags, particularly in Internet Explorer. We've found default
	 * encoding with 64kbps works.</li>
	 * <li>Occasionally very short samples will get cut off.</li>
	 * <li>There is a limit to how many audio tags you can load and play at once, which appears to be determined by
	 * hardware and browser settings.  See {{#crossLink "HTMLAudioPlugin.MAX_INSTANCES"}}{{/crossLink}} for a safe
	 * estimate.</li></ul>
	 *
	 * <b>Firefox 25 Web Audio limitations</b>
	 * <ul><li>mp3 audio files do not load properly on all windows machines, reported
	 * <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=929969" target="_blank">here</a>. </br>
	 * For this reason it is recommended to pass another FF supported type (ie ogg) first until this bug is resolved, if
	 * possible.</li></ul>

	 * <b>Safari limitations</b><br />
	 * <ul><li>Safari requires Quicktime to be installed for audio playback.</li></ul>
	 *
	 * <b>iOS 6 Web Audio limitations</b><br />
	 * <ul><li>Sound is initially locked, and must be unlocked via a user-initiated event. Please see the section on
	 * Mobile Playback above.</li>
	 * <li>A bug exists that will distort un-cached web audio when a video element is present in the DOM that has audio
	 * at a different sampleRate.</li>
	 * </ul>
	 *
	 * <b>Android HTML Audio limitations</b><br />
	 * <ul><li>We have no control over audio volume. Only the user can set volume on their device.</li>
	 * <li>We can only play audio inside a user event (touch/click).  This currently means you cannot loop sound or use
	 * a delay.</li></ul>
	 *
	 * <b>Web Audio and PreloadJS</b><br />
	 * <ul><li>Web Audio must be loaded through XHR, therefore when used with PreloadJS, tag loading is not possible.
	 * This means that tag loading can not be used to avoid cross domain issues.</li><ul>
	 *
	 * @class Sound
	 * @static
	 * @uses EventDispatcher
	 */
	function Sound() {
		throw "Sound cannot be instantiated";
	}

	var s = Sound;


// Static Properties
	/**
	 * The interrupt value to interrupt any currently playing instance with the same source, if the maximum number of
	 * instances of the sound are already playing.
	 * @property INTERRUPT_ANY
	 * @type {String}
	 * @default any
	 * @static
	 */
	s.INTERRUPT_ANY = "any";

	/**
	 * The interrupt value to interrupt the earliest currently playing instance with the same source that progressed the
	 * least distance in the audio track, if the maximum number of instances of the sound are already playing.
	 * @property INTERRUPT_EARLY
	 * @type {String}
	 * @default early
	 * @static
	 */
	s.INTERRUPT_EARLY = "early";

	/**
	 * The interrupt value to interrupt the currently playing instance with the same source that progressed the most
	 * distance in the audio track, if the maximum number of instances of the sound are already playing.
	 * @property INTERRUPT_LATE
	 * @type {String}
	 * @default late
	 * @static
	 */
	s.INTERRUPT_LATE = "late";

	/**
	 * The interrupt value to not interrupt any currently playing instances with the same source, if the maximum number of
	 * instances of the sound are already playing.
	 * @property INTERRUPT_NONE
	 * @type {String}
	 * @default none
	 * @static
	 */
	s.INTERRUPT_NONE = "none";

	/**
	 * Defines the playState of an instance that is still initializing.
	 * @property PLAY_INITED
	 * @type {String}
	 * @default playInited
	 * @static
	 */
	s.PLAY_INITED = "playInited";

	/**
	 * Defines the playState of an instance that is currently playing or paused.
	 * @property PLAY_SUCCEEDED
	 * @type {String}
	 * @default playSucceeded
	 * @static
	 */
	s.PLAY_SUCCEEDED = "playSucceeded";

	/**
	 * Defines the playState of an instance that was interrupted by another instance.
	 * @property PLAY_INTERRUPTED
	 * @type {String}
	 * @default playInterrupted
	 * @static
	 */
	s.PLAY_INTERRUPTED = "playInterrupted";

	/**
	 * Defines the playState of an instance that completed playback.
	 * @property PLAY_FINISHED
	 * @type {String}
	 * @default playFinished
	 * @static
	 */
	s.PLAY_FINISHED = "playFinished";

	/**
	 * Defines the playState of an instance that failed to play. This is usually caused by a lack of available channels
	 * when the interrupt mode was "INTERRUPT_NONE", the playback stalled, or the sound could not be found.
	 * @property PLAY_FAILED
	 * @type {String}
	 * @default playFailed
	 * @static
	 */
	s.PLAY_FAILED = "playFailed";

	/**
	 * A list of the default supported extensions that Sound will <i>try</i> to play. Plugins will check if the browser
	 * can play these types, so modifying this list before a plugin is initialized will allow the plugins to try to
	 * support additional media types.
	 *
	 * NOTE this does not currently work for {{#crossLink "FlashAudioPlugin"}}{{/crossLink}}.
	 *
	 * More details on file formats can be found at <a href="http://en.wikipedia.org/wiki/Audio_file_format" target="_blank">http://en.wikipedia.org/wiki/Audio_file_format</a>.<br />
	 * A very detailed list of file formats can be found at <a href="http://www.fileinfo.com/filetypes/audio" target="_blank">http://www.fileinfo.com/filetypes/audio</a>.
	 * @property SUPPORTED_EXTENSIONS
	 * @type {Array[String]}
	 * @default ["mp3", "ogg", "opus", "mpeg", "wav", "m4a", "mp4", "aiff", "wma", "mid"]
	 * @since 0.4.0
	 * @static
	 */
	s.SUPPORTED_EXTENSIONS = ["mp3", "ogg", "opus", "mpeg", "wav", "m4a", "mp4", "aiff", "wma", "mid"];

	/**
	 * Some extensions use another type of extension support to play (one of them is a codex).  This allows you to map
	 * that support so plugins can accurately determine if an extension is supported.  Adding to this list can help
	 * plugins determine more accurately if an extension is supported.
	 *
 	 * A useful list of extensions for each format can be found at <a href="http://html5doctor.com/html5-audio-the-state-of-play/" target="_blank">http://html5doctor.com/html5-audio-the-state-of-play/</a>.
	 * @property EXTENSION_MAP
	 * @type {Object}
	 * @since 0.4.0
	 * @default {m4a:"mp4"}
	 * @static
	 */
	s.EXTENSION_MAP = {
		m4a:"mp4"
	};

	/**
	 * The RegExp pattern used to parse file URIs. This supports simple file names, as well as full domain URIs with
	 * query strings. The resulting match is: protocol:$1 domain:$2 path:$3 file:$4 extension:$5 query:$6.
	 * @property FILE_PATTERN
	 * @type {RegExp}
	 * @static
	 * @protected
	 */
	s.FILE_PATTERN = /^(?:(\w+:)\/{2}(\w+(?:\.\w+)*\/?))?([/.]*?(?:[^?]+)?\/)?((?:[^/?]+)\.(\w+))(?:\?(\S+)?)?$/;


// Class Public properties
	/**
	 * Determines the default behavior for interrupting other currently playing instances with the same source, if the
	 * maximum number of instances of the sound are already playing.  Currently the default is {{#crossLink "Sound/INTERRUPT_NONE:property"}}{{/crossLink}}
	 * but this can be set and will change playback behavior accordingly.  This is only used when {{#crossLink "Sound/play"}}{{/crossLink}}
	 * is called without passing a value for interrupt.
	 * @property defaultInterruptBehavior
	 * @type {String}
	 * @default Sound.INTERRUPT_NONE, or "none"
	 * @static
	 * @since 0.4.0
	 */
	s.defaultInterruptBehavior = s.INTERRUPT_NONE;  // OJR does s.INTERRUPT_ANY make more sense as default?  Needs game dev testing to see which case makes more sense.

	/**
	 * An array of extensions to attempt to use when loading sound, if the default is unsupported by the active plugin.
	 * These are applied in order, so if you try to Load Thunder.ogg in a browser that does not support ogg, and your
	 * extensions array is ["mp3", "m4a", "wav"] it will check mp3 support, then m4a, then wav. The audio files need
	 * to exist in the same location, as only the extension is altered.
	 *
	 * Note that regardless of which file is loaded, you can call {{#crossLink "Sound/createInstance"}}{{/crossLink}}
	 * and {{#crossLink "Sound/play"}}{{/crossLink}} using the same id or full source path passed for loading.
	 *
	 * <h4>Example</h4>
	 *
	 *	var sounds = [
	 *		{src:"myPath/mySound.ogg", id:"example"},
	 *	];
	 *	createjs.Sound.alternateExtensions = ["mp3"]; // now if ogg is not supported, SoundJS will try asset0.mp3
	 *	createjs.Sound.on("fileload", handleLoad); // call handleLoad when each sound loads
	 *	createjs.Sound.registerSounds(sounds, assetPath);
	 *	// ...
	 *	createjs.Sound.play("myPath/mySound.ogg"); // works regardless of what extension is supported.  Note calling with ID is a better approach
	 *
	 * @property alternateExtensions
	 * @type {Array}
	 * @since 0.5.2
	 * @static
	 */
	s.alternateExtensions = [];

	/**
	 * The currently active plugin. If this is null, then no plugin could be initialized. If no plugin was specified,
	 * Sound attempts to apply the default plugins: {{#crossLink "WebAudioPlugin"}}{{/crossLink}}, followed by
	 * {{#crossLink "HTMLAudioPlugin"}}{{/crossLink}}.
	 * @property activePlugin
	 * @type {Object}
	 * @static
	 */
    s.activePlugin = null;


// class getter / setter properties
	/**
	 * Set the master volume of Sound. The master volume is multiplied against each sound's individual volume.  For
	 * example, if master volume is 0.5 and a sound's volume is 0.5, the resulting volume is 0.25. To set individual
	 * sound volume, use AbstractSoundInstance {{#crossLink "AbstractSoundInstance/volume:property"}}{{/crossLink}} instead.
	 *
	 * <h4>Example</h4>
	 *
	 *     createjs.Sound.volume = 0.5;
	 *
	 *
	 * @property volume
	 * @type {Number}
	 * @default 1
	 * @since 0.6.1
	 */
	s._masterVolume = 1;
	Object.defineProperty(s, "volume", {
		get: function () {return this._masterVolume;},
		set: function (value) {
				if (Number(value) == null) {return false;}
				value = Math.max(0, Math.min(1, value));
				s._masterVolume = value;
				if (!this.activePlugin || !this.activePlugin.setVolume || !this.activePlugin.setVolume(value)) {
					var instances = this._instances;
					for (var i = 0, l = instances.length; i < l; i++) {
						instances[i].setMasterVolume(value);
					}
				}
			}
	});

	/**
	 * Mute/Unmute all audio. Note that muted audio still plays at 0 volume. This global mute value is maintained
	 * separately and when set will override, but not change the mute property of individual instances. To mute an individual
	 * instance, use AbstractSoundInstance {{#crossLink "AbstractSoundInstance/muted:property"}}{{/crossLink}} instead.
	 *
	 * <h4>Example</h4>
	 *
	 *     createjs.Sound.muted = true;
	 *
	 *
	 * @property muted
	 * @type {Boolean}
	 * @default false
	 * @since 0.6.1
	 */
	s._masterMute = false;
	// OJR references to the methods were not working, so the code had to be duplicated here
	Object.defineProperty(s, "muted", {
		get: function () {return this._masterMute;},
		set: function (value) {
				if (value == null) {return false;}

				this._masterMute = value;
				if (!this.activePlugin || !this.activePlugin.setMute || !this.activePlugin.setMute(value)) {
					var instances = this._instances;
					for (var i = 0, l = instances.length; i < l; i++) {
						instances[i].setMasterMute(value);
					}
				}
				return true;
			}
	});

	/**
	 * Get the active plugins capabilities, which help determine if a plugin can be used in the current environment,
	 * or if the plugin supports a specific feature. Capabilities include:
	 * <ul>
	 *     <li><b>panning:</b> If the plugin can pan audio from left to right</li>
	 *     <li><b>volume;</b> If the plugin can control audio volume.</li>
	 *     <li><b>tracks:</b> The maximum number of audio tracks that can be played back at a time. This will be -1
	 *     if there is no known limit.</li>
	 * <br />An entry for each file type in {{#crossLink "Sound/SUPPORTED_EXTENSIONS:property"}}{{/crossLink}}:
	 *     <li><b>mp3:</b> If MP3 audio is supported.</li>
	 *     <li><b>ogg:</b> If OGG audio is supported.</li>
	 *     <li><b>wav:</b> If WAV audio is supported.</li>
	 *     <li><b>mpeg:</b> If MPEG audio is supported.</li>
	 *     <li><b>m4a:</b> If M4A audio is supported.</li>
	 *     <li><b>mp4:</b> If MP4 audio is supported.</li>
	 *     <li><b>aiff:</b> If aiff audio is supported.</li>
	 *     <li><b>wma:</b> If wma audio is supported.</li>
	 *     <li><b>mid:</b> If mid audio is supported.</li>
	 * </ul>
	 *
	 * You can get a specific capability of the active plugin using standard object notation
	 *
	 * <h4>Example</h4>
	 *
	 *      var mp3 = createjs.Sound.capabilities.mp3;
	 *
	 * Note this property is read only.
	 *
	 * @property capabilities
	 * @type {Object}
	 * @static
	 * @readOnly
	 * @since 0.6.1
	 */
	Object.defineProperty(s, "capabilities", {
		get: function () {
					if (s.activePlugin == null) {return null;}
					return s.activePlugin._capabilities;
				},
		set: function (value) { return false;}
	});


// Class Private properties
	/**
	 * Determines if the plugins have been registered. If false, the first call to play() will instantiate the default
	 * plugins ({{#crossLink "WebAudioPlugin"}}{{/crossLink}}, followed by {{#crossLink "HTMLAudioPlugin"}}{{/crossLink}}).
	 * If plugins have been registered, but none are applicable, then sound playback will fail.
	 * @property _pluginsRegistered
	 * @type {Boolean}
	 * @default false
	 * @static
	 * @protected
	 */
	s._pluginsRegistered = false;

	/**
	 * Used internally to assign unique IDs to each AbstractSoundInstance.
	 * @property _lastID
	 * @type {Number}
	 * @static
	 * @protected
	 */
	s._lastID = 0;

	/**
	 * An array containing all currently playing instances. This allows Sound to control the volume, mute, and playback of
	 * all instances when using static APIs like {{#crossLink "Sound/stop"}}{{/crossLink}} and {{#crossLink "Sound/setVolume"}}{{/crossLink}}.
	 * When an instance has finished playback, it gets removed via the {{#crossLink "Sound/finishedPlaying"}}{{/crossLink}}
	 * method. If the user replays an instance, it gets added back in via the {{#crossLink "Sound/_beginPlaying"}}{{/crossLink}}
	 * method.
	 * @property _instances
	 * @type {Array}
	 * @protected
	 * @static
	 */
	s._instances = [];

	/**
	 * An object hash storing objects with sound sources, startTime, and duration via there corresponding ID.
	 * @property _idHash
	 * @type {Object}
	 * @protected
	 * @static
	 */
	s._idHash = {};

	/**
	 * An object hash that stores preloading sound sources via the parsed source that is passed to the plugin.  Contains the
	 * source, id, and data that was passed in by the user.  Parsed sources can contain multiple instances of source, id,
	 * and data.
	 * @property _preloadHash
	 * @type {Object}
	 * @protected
	 * @static
	 */
	s._preloadHash = {};

	/**
	 * An object hash storing {{#crossLink "PlayPropsConfig"}}{{/crossLink}} via the parsed source that is passed as defaultPlayProps in
	 * {{#crossLink "Sound/registerSound"}}{{/crossLink}} and {{#crossLink "Sound/registerSounds"}}{{/crossLink}}.
	 * @property _defaultPlayPropsHash
	 * @type {Object}
	 * @protected
	 * @static
	 * @since 0.6.1
	 */
	s._defaultPlayPropsHash = {};


// EventDispatcher methods:
	s.addEventListener = null;
	s.removeEventListener = null;
	s.removeAllEventListeners = null;
	s.dispatchEvent = null;
	s.hasEventListener = null;
	s._listeners = null;

	createjs.EventDispatcher.initialize(s); // inject EventDispatcher methods.


// Events
	/**
	 * This event is fired when a file finishes loading internally. This event is fired for each loaded sound,
	 * so any handler methods should look up the <code>event.src</code> to handle a particular sound.
	 * @event fileload
	 * @param {Object} target The object that dispatched the event.
	 * @param {String} type The event type.
	 * @param {String} src The source of the sound that was loaded.
	 * @param {String} [id] The id passed in when the sound was registered. If one was not provided, it will be null.
	 * @param {Number|Object} [data] Any additional data associated with the item. If not provided, it will be undefined.
	 * @since 0.4.1
	 */

	/**
	 * This event is fired when a file fails loading internally. This event is fired for each loaded sound,
	 * so any handler methods should look up the <code>event.src</code> to handle a particular sound.
	 * @event fileerror
	 * @param {Object} target The object that dispatched the event.
	 * @param {String} type The event type.
	 * @param {String} src The source of the sound that was loaded.
	 * @param {String} [id] The id passed in when the sound was registered. If one was not provided, it will be null.
	 * @param {Number|Object} [data] Any additional data associated with the item. If not provided, it will be undefined.
	 * @since 0.6.0
	 */


// Class Public Methods
	/**
	 * Get the preload rules to allow Sound to be used as a plugin by <a href="http://preloadjs.com" target="_blank">PreloadJS</a>.
	 * Any load calls that have the matching type or extension will fire the callback method, and use the resulting
	 * object, which is potentially modified by Sound. This helps when determining the correct path, as well as
	 * registering the audio instance(s) with Sound. This method should not be called, except by PreloadJS.
	 * @method getPreloadHandlers
	 * @return {Object} An object containing:
	 * <ul><li>callback: A preload callback that is fired when a file is added to PreloadJS, which provides
	 *      Sound a mechanism to modify the load parameters, select the correct file format, register the sound, etc.</li>
	 *      <li>types: A list of file types that are supported by Sound (currently supports "sound").</li>
	 *      <li>extensions: A list of file extensions that are supported by Sound (see {{#crossLink "Sound/SUPPORTED_EXTENSIONS:property"}}{{/crossLink}}).</li></ul>
	 * @static
	 * @protected
	 */
	s.getPreloadHandlers = function () {
		return {
			callback:createjs.proxy(s.initLoad, s),
			types:["sound"],
			extensions:s.SUPPORTED_EXTENSIONS
		};
	};

	/**
	 * Used to dispatch fileload events from internal loading.
	 * @method _handleLoadComplete
	 * @param event A loader event.
	 * @protected
	 * @static
	 * @since 0.6.0
	 */
	s._handleLoadComplete = function(event) {
		var src = event.target.getItem().src;
		if (!s._preloadHash[src]) {return;}

		for (var i = 0, l = s._preloadHash[src].length; i < l; i++) {
			var item = s._preloadHash[src][i];
			s._preloadHash[src][i] = true;

			if (!s.hasEventListener("fileload")) { continue; }

			var event = new createjs.Event("fileload");
			event.src = item.src;
			event.id = item.id;
			event.data = item.data;
			event.sprite = item.sprite;

			s.dispatchEvent(event);
		}
	};

	/**
	 * Used to dispatch error events from internal preloading.
	 * @param event
	 * @protected
	 * @since 0.6.0
	 * @static
	 */
	s._handleLoadError = function(event) {
		var src = event.target.getItem().src;
		if (!s._preloadHash[src]) {return;}

		for (var i = 0, l = s._preloadHash[src].length; i < l; i++) {
			var item = s._preloadHash[src][i];
			s._preloadHash[src][i] = false;

			if (!s.hasEventListener("fileerror")) { continue; }

			var event = new createjs.Event("fileerror");
			event.src = item.src;
			event.id = item.id;
			event.data = item.data;
			event.sprite = item.sprite;

			s.dispatchEvent(event);
		}
	};

	/**
	 * Used by {{#crossLink "Sound/registerPlugins"}}{{/crossLink}} to register a Sound plugin.
	 *
	 * @method _registerPlugin
	 * @param {Object} plugin The plugin class to install.
	 * @return {Boolean} Whether the plugin was successfully initialized.
	 * @static
	 * @private
	 */
	s._registerPlugin = function (plugin) {
		// Note: Each plugin is passed in as a class reference, but we store the activePlugin as an instance
		if (plugin.isSupported()) {
			s.activePlugin = new plugin();
			return true;
		}
		return false;
	};

	/**
	 * Register a list of Sound plugins, in order of precedence. To register a single plugin, pass a single element in the array.
	 *
	 * <h4>Example</h4>
	 *
	 *      createjs.FlashAudioPlugin.swfPath = "../src/soundjs/flashaudio/";
	 *      createjs.Sound.registerPlugins([createjs.WebAudioPlugin, createjs.HTMLAudioPlugin, createjs.FlashAudioPlugin]);
	 *
	 * @method registerPlugins
	 * @param {Array} plugins An array of plugins classes to install.
	 * @return {Boolean} Whether a plugin was successfully initialized.
	 * @static
	 */
	s.registerPlugins = function (plugins) {
		s._pluginsRegistered = true;
		for (var i = 0, l = plugins.length; i < l; i++) {
			if (s._registerPlugin(plugins[i])) {
				return true;
			}
		}
		return false;
	};

	/**
	 * Initialize the default plugins. This method is automatically called when any audio is played or registered before
	 * the user has manually registered plugins, and enables Sound to work without manual plugin setup. Currently, the
	 * default plugins are {{#crossLink "WebAudioPlugin"}}{{/crossLink}} followed by {{#crossLink "HTMLAudioPlugin"}}{{/crossLink}}.
	 *
	 * <h4>Example</h4>
	 *
	 * 	if (!createjs.initializeDefaultPlugins()) { return; }
	 *
	 * @method initializeDefaultPlugins
	 * @returns {Boolean} True if a plugin was initialized, false otherwise.
	 * @since 0.4.0
	 * @static
	 */
	s.initializeDefaultPlugins = function () {
		if (s.activePlugin != null) {return true;}
		if (s._pluginsRegistered) {return false;}
		if (s.registerPlugins([createjs.WebAudioPlugin, createjs.HTMLAudioPlugin])) {return true;}
		return false;
	};

	/**
	 * Determines if Sound has been initialized, and a plugin has been activated.
	 *
	 * <h4>Example</h4>
	 * This example sets up a Flash fallback, but only if there is no plugin specified yet.
	 *
	 * 	if (!createjs.Sound.isReady()) {
	 *		createjs.FlashAudioPlugin.swfPath = "../src/soundjs/flashaudio/";
	 * 		createjs.Sound.registerPlugins([createjs.WebAudioPlugin, createjs.HTMLAudioPlugin, createjs.FlashAudioPlugin]);
	 *	}
	 *
	 * @method isReady
	 * @return {Boolean} If Sound has initialized a plugin.
	 * @static
	 */
	s.isReady = function () {
		return (s.activePlugin != null);
	};

	/**
	 * Deprecated, please use {{#crossLink "Sound/capabilities:property"}}{{/crossLink}} instead.
	 *
	 * @method getCapabilities
	 * @return {Object} An object containing the capabilities of the active plugin.
	 * @static
	 * @deprecated
	 */
	s.getCapabilities = function () {
		if (s.activePlugin == null) {return null;}
		return s.activePlugin._capabilities;
	};

	/**
	 * Deprecated, please use {{#crossLink "Sound/capabilities:property"}}{{/crossLink}} instead.
	 *
	 * @method getCapability
	 * @param {String} key The capability to retrieve
	 * @return {Number|Boolean} The value of the capability.
	 * @static
	 * @see getCapabilities
	 * @deprecated
	 */
	s.getCapability = function (key) {
		if (s.activePlugin == null) {return null;}
		return s.activePlugin._capabilities[key];
	};

	/**
	 * Process manifest items from <a href="http://preloadjs.com" target="_blank">PreloadJS</a>. This method is intended
	 * for usage by a plugin, and not for direct interaction.
	 * @method initLoad
	 * @param {Object} src The object to load.
	 * @return {Object|AbstractLoader} An instance of AbstractLoader.
	 * @protected
	 * @static
	 */
	s.initLoad = function (loadItem) {
		return s._registerSound(loadItem);
	};

	/**
	 * Internal method for loading sounds.  This should not be called directly.
	 *
	 * @method _registerSound
	 * @param {Object} src The object to load, containing src property and optionally containing id and data.
	 * @return {Object} An object with the modified values that were passed in, which defines the sound.
	 * Returns false if the source cannot be parsed or no plugins can be initialized.
	 * Returns true if the source is already loaded.
	 * @static
	 * @private
	 * @since 0.6.0
	 */

	s._registerSound = function (loadItem) {
		if (!s.initializeDefaultPlugins()) {return false;}

		var details;
		if (loadItem.src instanceof Object) {
			details = s._parseSrc(loadItem.src);
			details.src = loadItem.path + details.src;
		} else {
			details = s._parsePath(loadItem.src);
		}
		if (details == null) {return false;}
		loadItem.src = details.src;
		loadItem.type = "sound";

		var data = loadItem.data;
		var numChannels = null;
		if (data != null) {
			if (!isNaN(data.channels)) {
				numChannels = parseInt(data.channels);
			} else if (!isNaN(data)) {
				numChannels = parseInt(data);
			}

			if(data.audioSprite) {
				var sp;
				for(var i = data.audioSprite.length; i--; ) {
					sp = data.audioSprite[i];
					s._idHash[sp.id] = {src: loadItem.src, startTime: parseInt(sp.startTime), duration: parseInt(sp.duration)};

					if (sp.defaultPlayProps) {
						s._defaultPlayPropsHash[sp.id] = createjs.PlayPropsConfig.create(sp.defaultPlayProps);
					}
				}
			}
		}
		if (loadItem.id != null) {s._idHash[loadItem.id] = {src: loadItem.src}};
		var loader = s.activePlugin.register(loadItem);

		SoundChannel.create(loadItem.src, numChannels);

		// return the number of instances to the user.  This will also be returned in the load event.
		if (data == null || !isNaN(data)) {
			loadItem.data = numChannels || SoundChannel.maxPerChannel();
		} else {
			loadItem.data.channels = numChannels || SoundChannel.maxPerChannel();
		}

		if (loader.type) {loadItem.type = loader.type;}

		if (loadItem.defaultPlayProps) {
			s._defaultPlayPropsHash[loadItem.src] = createjs.PlayPropsConfig.create(loadItem.defaultPlayProps);
		}
		return loader;
	};

	/**
	 * Register an audio file for loading and future playback in Sound. This is automatically called when using
	 * <a href="http://preloadjs.com" target="_blank">PreloadJS</a>.  It is recommended to register all sounds that
	 * need to be played back in order to properly prepare and preload them. Sound does internal preloading when required.
	 *
	 * <h4>Example</h4>
	 *
	 *      createjs.Sound.alternateExtensions = ["mp3"];
	 *      createjs.Sound.on("fileload", handleLoad); // add an event listener for when load is completed
	 *      createjs.Sound.registerSound("myAudioPath/mySound.ogg", "myID", 3);
	 *      createjs.Sound.registerSound({ogg:"path1/mySound.ogg", mp3:"path2/mySoundNoExtension"}, "myID", 3);
	 *
	 *
	 * @method registerSound
	 * @param {String | Object} src The source or an Object with a "src" property or an Object with multiple extension labeled src properties.
	 * @param {String} [id] An id specified by the user to play the sound later.  Note id is required for when src is multiple extension labeled src properties.
	 * @param {Number | Object} [data] Data associated with the item. Sound uses the data parameter as the number of
	 * channels for an audio instance, however a "channels" property can be appended to the data object if it is used
	 * for other information. The audio channels will set a default based on plugin if no value is found.
	 * Sound also uses the data property to hold an {{#crossLink "AudioSprite"}}{{/crossLink}} array of objects in the following format {id, startTime, duration}.<br/>
	 *   id used to play the sound later, in the same manner as a sound src with an id.<br/>
	 *   startTime is the initial offset to start playback and loop from, in milliseconds.<br/>
	 *   duration is the amount of time to play the clip for, in milliseconds.<br/>
	 * This allows Sound to support audio sprites that are played back by id.
	 * @param {string} basePath Set a path that will be prepended to src for loading.
	 * @param {Object | PlayPropsConfig} defaultPlayProps Optional Playback properties that will be set as the defaults on any new AbstractSoundInstance.
	 * See {{#crossLink "PlayPropsConfig"}}{{/crossLink}} for options.
	 * @return {Object} An object with the modified values that were passed in, which defines the sound.
	 * Returns false if the source cannot be parsed or no plugins can be initialized.
	 * Returns true if the source is already loaded.
	 * @static
	 * @since 0.4.0
	 */
	s.registerSound = function (src, id, data, basePath, defaultPlayProps) {
		var loadItem = {src: src, id: id, data:data, defaultPlayProps:defaultPlayProps};
		if (src instanceof Object && src.src) {
			basePath = id;
			loadItem = src;
		}
		loadItem = createjs.LoadItem.create(loadItem);
		loadItem.path = basePath;

		if (basePath != null && !(loadItem.src instanceof Object)) {loadItem.src = basePath + src;}

		var loader = s._registerSound(loadItem);
		if(!loader) {return false;}

		if (!s._preloadHash[loadItem.src]) { s._preloadHash[loadItem.src] = [];}
		s._preloadHash[loadItem.src].push(loadItem);
		if (s._preloadHash[loadItem.src].length == 1) {
			// OJR note this will disallow reloading a sound if loading fails or the source changes
			loader.on("complete", createjs.proxy(this._handleLoadComplete, this));
			loader.on("error", createjs.proxy(this._handleLoadError, this));
			s.activePlugin.preload(loader);
		} else {
			if (s._preloadHash[loadItem.src][0] == true) {return true;}
		}

		return loadItem;
	};

	/**
	 * Register an array of audio files for loading and future playback in Sound. It is recommended to register all
	 * sounds that need to be played back in order to properly prepare and preload them. Sound does internal preloading
	 * when required.
	 *
	 * <h4>Example</h4>
	 *
	 * 		var assetPath = "./myAudioPath/";
	 *      var sounds = [
	 *          {src:"asset0.ogg", id:"example"},
	 *          {src:"asset1.ogg", id:"1", data:6},
	 *          {src:"asset2.mp3", id:"works"}
	 *          {src:{mp3:"path1/asset3.mp3", ogg:"path2/asset3NoExtension}, id:"better"}
	 *      ];
	 *      createjs.Sound.alternateExtensions = ["mp3"];	// if the passed extension is not supported, try this extension
	 *      createjs.Sound.on("fileload", handleLoad); // call handleLoad when each sound loads
	 *      createjs.Sound.registerSounds(sounds, assetPath);
	 *
	 * @method registerSounds
	 * @param {Array} sounds An array of objects to load. Objects are expected to be in the format needed for
	 * {{#crossLink "Sound/registerSound"}}{{/crossLink}}: <code>{src:srcURI, id:ID, data:Data}</code>
	 * with "id" and "data" being optional.
	 * You can also pass an object with path and manifest properties, where path is a basePath and manifest is an array of objects to load.
	 * Note id is required if src is an object with extension labeled src properties.
	 * @param {string} basePath Set a path that will be prepended to each src when loading.  When creating, playing, or removing
	 * audio that was loaded with a basePath by src, the basePath must be included.
	 * @return {Object} An array of objects with the modified values that were passed in, which defines each sound.
	 * Like registerSound, it will return false for any values when the source cannot be parsed or if no plugins can be initialized.
	 * Also, it will return true for any values when the source is already loaded.
	 * @static
	 * @since 0.6.0
	 */
	s.registerSounds = function (sounds, basePath) {
		var returnValues = [];
		if (sounds.path) {
			if (!basePath) {
				basePath = sounds.path;
			} else {
				basePath = basePath + sounds.path;
			}
			sounds = sounds.manifest;
			// TODO document this feature
		}
		for (var i = 0, l = sounds.length; i < l; i++) {
			returnValues[i] = createjs.Sound.registerSound(sounds[i].src, sounds[i].id, sounds[i].data, basePath, sounds[i].defaultPlayProps);
		}
		return returnValues;
	};

	/**
	 * Remove a sound that has been registered with {{#crossLink "Sound/registerSound"}}{{/crossLink}} or
	 * {{#crossLink "Sound/registerSounds"}}{{/crossLink}}.
	 * <br />Note this will stop playback on active instances playing this sound before deleting them.
	 * <br />Note if you passed in a basePath, you need to pass it or prepend it to the src here.
	 *
	 * <h4>Example</h4>
	 *
	 *      createjs.Sound.removeSound("myID");
	 *      createjs.Sound.removeSound("myAudioBasePath/mySound.ogg");
	 *      createjs.Sound.removeSound("myPath/myOtherSound.mp3", "myBasePath/");
	 *      createjs.Sound.removeSound({mp3:"musicNoExtension", ogg:"music.ogg"}, "myBasePath/");
	 *
	 * @method removeSound
	 * @param {String | Object} src The src or ID of the audio, or an Object with a "src" property, or an Object with multiple extension labeled src properties.
	 * @param {string} basePath Set a path that will be prepended to each src when removing.
	 * @return {Boolean} True if sound is successfully removed.
	 * @static
	 * @since 0.4.1
	 */
	s.removeSound = function(src, basePath) {
		if (s.activePlugin == null) {return false;}

		if (src instanceof Object && src.src) {src = src.src;}

		var details;
		if (src instanceof Object) {
			details = s._parseSrc(src);
		} else {
			src = s._getSrcById(src).src;
			details = s._parsePath(src);
		}
		if (details == null) {return false;}
		src = details.src;
		if (basePath != null) {src = basePath + src;}

		for(var prop in s._idHash){
			if(s._idHash[prop].src == src) {
				delete(s._idHash[prop]);
			}
		}

		// clear from SoundChannel, which also stops and deletes all instances
		SoundChannel.removeSrc(src);

		delete(s._preloadHash[src]);

		s.activePlugin.removeSound(src);

		return true;
	};

	/**
	 * Remove an array of audio files that have been registered with {{#crossLink "Sound/registerSound"}}{{/crossLink}} or
	 * {{#crossLink "Sound/registerSounds"}}{{/crossLink}}.
	 * <br />Note this will stop playback on active instances playing this audio before deleting them.
	 * <br />Note if you passed in a basePath, you need to pass it or prepend it to the src here.
	 *
	 * <h4>Example</h4>
	 *
	 * 		assetPath = "./myPath/";
	 *      var sounds = [
	 *          {src:"asset0.ogg", id:"example"},
	 *          {src:"asset1.ogg", id:"1", data:6},
	 *          {src:"asset2.mp3", id:"works"}
	 *      ];
	 *      createjs.Sound.removeSounds(sounds, assetPath);
	 *
	 * @method removeSounds
	 * @param {Array} sounds An array of objects to remove. Objects are expected to be in the format needed for
	 * {{#crossLink "Sound/removeSound"}}{{/crossLink}}: <code>{srcOrID:srcURIorID}</code>.
	 * You can also pass an object with path and manifest properties, where path is a basePath and manifest is an array of objects to remove.
	 * @param {string} basePath Set a path that will be prepended to each src when removing.
	 * @return {Object} An array of Boolean values representing if the sounds with the same array index were
	 * successfully removed.
	 * @static
	 * @since 0.4.1
	 */
	s.removeSounds = function (sounds, basePath) {
		var returnValues = [];
		if (sounds.path) {
			if (!basePath) {
				basePath = sounds.path;
			} else {
				basePath = basePath + sounds.path;
			}
			sounds = sounds.manifest;
		}
		for (var i = 0, l = sounds.length; i < l; i++) {
			returnValues[i] = createjs.Sound.removeSound(sounds[i].src, basePath);
		}
		return returnValues;
	};

	/**
	 * Remove all sounds that have been registered with {{#crossLink "Sound/registerSound"}}{{/crossLink}} or
	 * {{#crossLink "Sound/registerSounds"}}{{/crossLink}}.
	 * <br />Note this will stop playback on all active sound instances before deleting them.
	 *
	 * <h4>Example</h4>
	 *
	 *     createjs.Sound.removeAllSounds();
	 *
	 * @method removeAllSounds
	 * @static
	 * @since 0.4.1
	 */
	s.removeAllSounds = function() {
		s._idHash = {};
		s._preloadHash = {};
		SoundChannel.removeAll();
		if (s.activePlugin) {s.activePlugin.removeAllSounds();}
	};

	/**
	 * Check if a source has been loaded by internal preloaders. This is necessary to ensure that sounds that are
	 * not completed preloading will not kick off a new internal preload if they are played.
	 *
	 * <h4>Example</h4>
	 *
	 *     var mySound = "assetPath/asset0.ogg";
	 *     if(createjs.Sound.loadComplete(mySound) {
	 *         createjs.Sound.play(mySound);
	 *     }
	 *
	 * @method loadComplete
	 * @param {String} src The src or id that is being loaded.
	 * @return {Boolean} If the src is already loaded.
	 * @since 0.4.0
	 * @static
	 */
	s.loadComplete = function (src) {
		if (!s.isReady()) { return false; }
		var details = s._parsePath(src);
		if (details) {
			src = s._getSrcById(details.src).src;
		} else {
			src = s._getSrcById(src).src;
		}
		if(s._preloadHash[src] == undefined) {return false;}
		return (s._preloadHash[src][0] == true);  // src only loads once, so if it's true for the first it's true for all
	};

	/**
	 * Parse the path of a sound. Alternate extensions will be attempted in order if the
	 * current extension is not supported
	 * @method _parsePath
	 * @param {String} value The path to an audio source.
	 * @return {Object} A formatted object that can be registered with the {{#crossLink "Sound/activePlugin:property"}}{{/crossLink}}
	 * and returned to a preloader like <a href="http://preloadjs.com" target="_blank">PreloadJS</a>.
	 * @protected
	 * @static
	 */
	s._parsePath = function (value) {
		if (typeof(value) != "string") {value = value.toString();}

		var match = value.match(s.FILE_PATTERN);
		if (match == null) {return false;}

		var name = match[4];
		var ext = match[5];
		var c = s.capabilities;
		var i = 0;
		while (!c[ext]) {
			ext = s.alternateExtensions[i++];
			if (i > s.alternateExtensions.length) { return null;}	// no extensions are supported
		}
		value = value.replace("."+match[5], "."+ext);

		var ret = {name:name, src:value, extension:ext};
		return ret;
	};

	/**
	 * Parse the path of a sound based on properties of src matching with supported extensions.
	 * Returns false if none of the properties are supported
	 * @method _parseSrc
	 * @param {Object} value The paths to an audio source, indexed by extension type.
	 * @return {Object} A formatted object that can be registered with the {{#crossLink "Sound/activePlugin:property"}}{{/crossLink}}
	 * and returned to a preloader like <a href="http://preloadjs.com" target="_blank">PreloadJS</a>.
	 * @protected
	 * @static
	 */
	s._parseSrc = function (value) {
		var ret = {name:undefined, src:undefined, extension:undefined};
		var c = s.capabilities;

		for (var prop in value) {
		  if(value.hasOwnProperty(prop) && c[prop]) {
				ret.src = value[prop];
				ret.extension = prop;
				break;
		  }
		}
		if (!ret.src) {return false;}	// no matches

		var i = ret.src.lastIndexOf("/");
		if (i != -1) {
			ret.name = ret.src.slice(i+1);
		} else {
			ret.name = ret.src;
		}

		return ret;
	};

	/* ---------------
	 Static API.
	 --------------- */
	/**
	 * Play a sound and get a {{#crossLink "AbstractSoundInstance"}}{{/crossLink}} to control. If the sound fails to play, a
	 * AbstractSoundInstance will still be returned, and have a playState of {{#crossLink "Sound/PLAY_FAILED:property"}}{{/crossLink}}.
	 * Note that even on sounds with failed playback, you may still be able to call AbstractSoundInstance {{#crossLink "AbstractSoundInstance/play"}}{{/crossLink}},
	 * since the failure could be due to lack of available channels. If the src does not have a supported extension or
	 * if there is no available plugin, a default AbstractSoundInstance will be returned which will not play any audio, but will not generate errors.
	 *
	 * <h4>Example</h4>
	 *
	 *      createjs.Sound.on("fileload", handleLoad);
	 *      createjs.Sound.registerSound("myAudioPath/mySound.mp3", "myID", 3);
	 *      function handleLoad(event) {
	 *      	createjs.Sound.play("myID");
	 *      	// store off AbstractSoundInstance for controlling
	 *      	var myInstance = createjs.Sound.play("myID", {interrupt: createjs.Sound.INTERRUPT_ANY, loop:-1});
	 *      }
	 *
	 * NOTE to create an audio sprite that has not already been registered, both startTime and duration need to be set.
	 * This is only when creating a new audio sprite, not when playing using the id of an already registered audio sprite.
	 *
	 * <b>Parameters Deprecated</b><br />
	 * The parameters for this method are deprecated in favor of a single parameter that is an Object or {{#crossLink "PlayPropsConfig"}}{{/crossLink}}.
	 *
	 * @method play
	 * @param {String} src The src or ID of the audio.
	 * @param {String | Object} [interrupt="none"|options] <b>This parameter will be renamed playProps in the next release.</b><br />
	 * This parameter can be an instance of {{#crossLink "PlayPropsConfig"}}{{/crossLink}} or an Object that contains any or all optional properties by name,
	 * including: interrupt, delay, offset, loop, volume, pan, startTime, and duration (see the above code sample).
	 * <br /><strong>OR</strong><br />
	 * <b>Deprecated</b> How to interrupt any currently playing instances of audio with the same source,
	 * if the maximum number of instances of the sound are already playing. Values are defined as <code>INTERRUPT_TYPE</code>
	 * constants on the Sound class, with the default defined by {{#crossLink "Sound/defaultInterruptBehavior:property"}}{{/crossLink}}.
	 * @param {Number} [delay=0] <b>Deprecated</b> The amount of time to delay the start of audio playback, in milliseconds.
	 * @param {Number} [offset=0] <b>Deprecated</b> The offset from the start of the audio to begin playback, in milliseconds.
	 * @param {Number} [loop=0] <b>Deprecated</b> How many times the audio loops when it reaches the end of playback. The default is 0 (no
	 * loops), and -1 can be used for infinite playback.
	 * @param {Number} [volume=1] <b>Deprecated</b> The volume of the sound, between 0 and 1. Note that the master volume is applied
	 * against the individual volume.
	 * @param {Number} [pan=0] <b>Deprecated</b> The left-right pan of the sound (if supported), between -1 (left) and 1 (right).
	 * @param {Number} [startTime=null] <b>Deprecated</b> To create an audio sprite (with duration), the initial offset to start playback and loop from, in milliseconds.
	 * @param {Number} [duration=null] <b>Deprecated</b> To create an audio sprite (with startTime), the amount of time to play the clip for, in milliseconds.
	 * @return {AbstractSoundInstance} A {{#crossLink "AbstractSoundInstance"}}{{/crossLink}} that can be controlled after it is created.
	 * @static
	 */
	s.play = function (src, interrupt, delay, offset, loop, volume, pan, startTime, duration) {
		var playProps;
		if (interrupt instanceof Object || interrupt instanceof createjs.PlayPropsConfig) {
			playProps = createjs.PlayPropsConfig.create(interrupt);
		} else {
			playProps = createjs.PlayPropsConfig.create({interrupt:interrupt, delay:delay, offset:offset, loop:loop, volume:volume, pan:pan, startTime:startTime, duration:duration});
		}
		var instance = s.createInstance(src, playProps.startTime, playProps.duration);
		var ok = s._playInstance(instance, playProps);
		if (!ok) {instance._playFailed();}
		return instance;
	};

	/**
	 * Creates a {{#crossLink "AbstractSoundInstance"}}{{/crossLink}} using the passed in src. If the src does not have a
	 * supported extension or if there is no available plugin, a default AbstractSoundInstance will be returned that can be
	 * called safely but does nothing.
	 *
	 * <h4>Example</h4>
	 *
	 *      var myInstance = null;
	 *      createjs.Sound.on("fileload", handleLoad);
	 *      createjs.Sound.registerSound("myAudioPath/mySound.mp3", "myID", 3);
	 *      function handleLoad(event) {
	 *      	myInstance = createjs.Sound.createInstance("myID");
	 *      	// alternately we could call the following
	 *      	myInstance = createjs.Sound.createInstance("myAudioPath/mySound.mp3");
	 *      }
	 *
	 * NOTE to create an audio sprite that has not already been registered, both startTime and duration need to be set.
	 * This is only when creating a new audio sprite, not when playing using the id of an already registered audio sprite.
	 *
	 * @method createInstance
	 * @param {String} src The src or ID of the audio.
	 * @param {Number} [startTime=null] To create an audio sprite (with duration), the initial offset to start playback and loop from, in milliseconds.
	 * @param {Number} [duration=null] To create an audio sprite (with startTime), the amount of time to play the clip for, in milliseconds.
	 * @return {AbstractSoundInstance} A {{#crossLink "AbstractSoundInstance"}}{{/crossLink}} that can be controlled after it is created.
	 * Unsupported extensions will return the default AbstractSoundInstance.
	 * @since 0.4.0
	 * @static
	 */
	s.createInstance = function (src, startTime, duration) {
		if (!s.initializeDefaultPlugins()) {return new createjs.DefaultSoundInstance(src, startTime, duration);}

		var defaultPlayProps = s._defaultPlayPropsHash[src];	// for audio sprites, which create and store defaults by id
		src = s._getSrcById(src);

		var details = s._parsePath(src.src);

		var instance = null;
		if (details != null && details.src != null) {
			SoundChannel.create(details.src);
			if (startTime == null) {startTime = src.startTime;}
			instance = s.activePlugin.create(details.src, startTime, duration || src.duration);

			defaultPlayProps = defaultPlayProps || s._defaultPlayPropsHash[details.src];
			if(defaultPlayProps) {
				instance.applyPlayProps(defaultPlayProps);
			}
		} else {
			instance = new createjs.DefaultSoundInstance(src, startTime, duration);
		}

		instance.uniqueId = s._lastID++;

		return instance;
	};

	/**
	 * Stop all audio (global stop). Stopped audio is reset, and not paused. To play audio that has been stopped,
	 * call AbstractSoundInstance {{#crossLink "AbstractSoundInstance/play"}}{{/crossLink}}.
	 *
	 * <h4>Example</h4>
	 *
	 *     createjs.Sound.stop();
	 *
	 * @method stop
	 * @static
	 */
	s.stop = function () {
		var instances = this._instances;
		for (var i = instances.length; i--; ) {
			instances[i].stop();  // NOTE stop removes instance from this._instances
		}
	};

	/**
	 * Deprecated, please use {{#crossLink "Sound/volume:property"}}{{/crossLink}} instead.
	 *
	 * @method setVolume
	 * @param {Number} value The master volume value. The acceptable range is 0-1.
	 * @static
	 * @deprecated
	 */
	s.setVolume = function (value) {
		if (Number(value) == null) {return false;}
		value = Math.max(0, Math.min(1, value));
		s._masterVolume = value;
		if (!this.activePlugin || !this.activePlugin.setVolume || !this.activePlugin.setVolume(value)) {
			var instances = this._instances;
			for (var i = 0, l = instances.length; i < l; i++) {
				instances[i].setMasterVolume(value);
			}
		}
	};

	/**
	 * Deprecated, please use {{#crossLink "Sound/volume:property"}}{{/crossLink}} instead.
	 *
	 * @method getVolume
	 * @return {Number} The master volume, in a range of 0-1.
	 * @static
	 * @deprecated
	 */
	s.getVolume = function () {
		return this._masterVolume;
	};

	/**
	 * Deprecated, please use {{#crossLink "Sound/muted:property"}}{{/crossLink}} instead.
	 *
	 * @method setMute
	 * @param {Boolean} value Whether the audio should be muted or not.
	 * @return {Boolean} If the mute was set.
	 * @static
	 * @since 0.4.0
	 * @deprecated
	 */
	s.setMute = function (value) {
		if (value == null) {return false;}

		this._masterMute = value;
		if (!this.activePlugin || !this.activePlugin.setMute || !this.activePlugin.setMute(value)) {
			var instances = this._instances;
			for (var i = 0, l = instances.length; i < l; i++) {
				instances[i].setMasterMute(value);
			}
		}
		return true;
	};

	/**
	 * Deprecated, please use {{#crossLink "Sound/muted:property"}}{{/crossLink}} instead.
	 *
	 * @method getMute
	 * @return {Boolean} The mute value of Sound.
	 * @static
	 * @since 0.4.0
	 * @deprecated
	 */
	s.getMute = function () {
		return this._masterMute;
	};

	/**
	 * Set the default playback properties for all new SoundInstances of the passed in src or ID.
	 * See {{#crossLink "PlayPropsConfig"}}{{/crossLink}} for available properties.
	 *
	 * @method setDefaultPlayProps
	 * @param {String} src The src or ID used to register the audio.
	 * @param {Object | PlayPropsConfig} playProps The playback properties you would like to set.
	 * @since 0.6.1
	 */
	s.setDefaultPlayProps = function(src, playProps) {
		src = s._getSrcById(src);
		s._defaultPlayPropsHash[s._parsePath(src.src).src] = createjs.PlayPropsConfig.create(playProps);
	};

	/**
	 * Get the default playback properties for the passed in src or ID.  These properties are applied to all
	 * new SoundInstances.  Returns null if default does not exist.
	 *
	 * @method getDefaultPlayProps
	 * @param {String} src The src or ID used to register the audio.
	 * @returns {PlayPropsConfig} returns an existing PlayPropsConfig or null if one does not exist
	 * @since 0.6.1
	 */
	s.getDefaultPlayProps = function(src) {
		src = s._getSrcById(src);
		return s._defaultPlayPropsHash[s._parsePath(src.src).src];
	};


	/* ---------------
	 Internal methods
	 --------------- */
	/**
	 * Play an instance. This is called by the static API, as well as from plugins. This allows the core class to
	 * control delays.
	 * @method _playInstance
	 * @param {AbstractSoundInstance} instance The {{#crossLink "AbstractSoundInstance"}}{{/crossLink}} to start playing.
	 * @param {PlayPropsConfig} playProps A PlayPropsConfig object.
	 * @return {Boolean} If the sound can start playing. Sounds that fail immediately will return false. Sounds that
	 * have a delay will return true, but may still fail to play.
	 * @protected
	 * @static
	 */
	s._playInstance = function (instance, playProps) {
		var defaultPlayProps = s._defaultPlayPropsHash[instance.src] || {};
		if (playProps.interrupt == null) {playProps.interrupt = defaultPlayProps.interrupt || s.defaultInterruptBehavior};
		if (playProps.delay == null) {playProps.delay = defaultPlayProps.delay || 0;}
		if (playProps.offset == null) {playProps.offset = instance.getPosition();}
		if (playProps.loop == null) {playProps.loop = instance.loop;}
		if (playProps.volume == null) {playProps.volume = instance.volume;}
		if (playProps.pan == null) {playProps.pan = instance.pan;}

		if (playProps.delay == 0) {
			var ok = s._beginPlaying(instance, playProps);
			if (!ok) {return false;}
		} else {
			//Note that we can't pass arguments to proxy OR setTimeout (IE only), so just wrap the function call.
			// OJR WebAudio may want to handle this differently, so it might make sense to move this functionality into the plugins in the future
			var delayTimeoutId = setTimeout(function () {
				s._beginPlaying(instance, playProps);
			}, playProps.delay);
			instance.delayTimeoutId = delayTimeoutId;
		}

		this._instances.push(instance);

		return true;
	};

	/**
	 * Begin playback. This is called immediately or after delay by {{#crossLink "Sound/playInstance"}}{{/crossLink}}.
	 * @method _beginPlaying
	 * @param {AbstractSoundInstance} instance A {{#crossLink "AbstractSoundInstance"}}{{/crossLink}} to begin playback.
	 * @param {PlayPropsConfig} playProps A PlayPropsConfig object.
	 * @return {Boolean} If the sound can start playing. If there are no available channels, or the instance fails to
	 * start, this will return false.
	 * @protected
	 * @static
	 */
	s._beginPlaying = function (instance, playProps) {
		if (!SoundChannel.add(instance, playProps.interrupt)) {
			return false;
		}
		var result = instance._beginPlaying(playProps);
		if (!result) {
			var index = createjs.indexOf(this._instances, instance);
			if (index > -1) {this._instances.splice(index, 1);}
			return false;
		}
		return true;
	};

	/**
	 * Get the source of a sound via the ID passed in with a register call. If no ID is found the value is returned
	 * instead.
	 * @method _getSrcById
	 * @param {String} value The ID the sound was registered with.
	 * @return {String} The source of the sound if it has been registered with this ID or the value that was passed in.
	 * @protected
	 * @static
	 */
	s._getSrcById = function (value) {
		return s._idHash[value] || {src: value};
	};

	/**
	 * A sound has completed playback, been interrupted, failed, or been stopped. This method removes the instance from
	 * Sound management. It will be added again, if the sound re-plays. Note that this method is called from the
	 * instances themselves.
	 * @method _playFinished
	 * @param {AbstractSoundInstance} instance The instance that finished playback.
	 * @protected
	 * @static
	 */
	s._playFinished = function (instance) {
		SoundChannel.remove(instance);
		var index = createjs.indexOf(this._instances, instance);
		if (index > -1) {this._instances.splice(index, 1);}	// OJR this will always be > -1, there is no way for an instance to exist without being added to this._instances
	};

	createjs.Sound = Sound;

	/**
	 * An internal class that manages the number of active {{#crossLink "AbstractSoundInstance"}}{{/crossLink}} instances for
	 * each sound type. This method is only used internally by the {{#crossLink "Sound"}}{{/crossLink}} class.
	 *
	 * The number of sounds is artificially limited by Sound in order to prevent over-saturation of a
	 * single sound, as well as to stay within hardware limitations, although the latter may disappear with better
	 * browser support.
	 *
	 * When a sound is played, this class ensures that there is an available instance, or interrupts an appropriate
	 * sound that is already playing.
	 * #class SoundChannel
	 * @param {String} src The source of the instances
	 * @param {Number} [max=1] The number of instances allowed
	 * @constructor
	 * @protected
	 */
	function SoundChannel(src, max) {
		this.init(src, max);
	}

	/* ------------
	 Static API
	 ------------ */
	/**
	 * A hash of channel instances indexed by source.
	 * #property channels
	 * @type {Object}
	 * @static
	 */
	SoundChannel.channels = {};

	/**
	 * Create a sound channel. Note that if the sound channel already exists, this will fail.
	 * #method create
	 * @param {String} src The source for the channel
	 * @param {Number} max The maximum amount this channel holds. The default is {{#crossLink "SoundChannel.maxDefault"}}{{/crossLink}}.
	 * @return {Boolean} If the channels were created.
	 * @static
	 */
	SoundChannel.create = function (src, max) {
		var channel = SoundChannel.get(src);
		if (channel == null) {
			SoundChannel.channels[src] = new SoundChannel(src, max);
			return true;
		}
		return false;
	};
	/**
	 * Delete a sound channel, stop and delete all related instances. Note that if the sound channel does not exist, this will fail.
	 * #method remove
	 * @param {String} src The source for the channel
	 * @return {Boolean} If the channels were deleted.
	 * @static
	 */
	SoundChannel.removeSrc = function (src) {
		var channel = SoundChannel.get(src);
		if (channel == null) {return false;}
		channel._removeAll();	// this stops and removes all active instances
		delete(SoundChannel.channels[src]);
		return true;
	};
	/**
	 * Delete all sound channels, stop and delete all related instances.
	 * #method removeAll
	 * @static
	 */
	SoundChannel.removeAll = function () {
		for(var channel in SoundChannel.channels) {
			SoundChannel.channels[channel]._removeAll();	// this stops and removes all active instances
		}
		SoundChannel.channels = {};
	};
	/**
	 * Add an instance to a sound channel.
	 * #method add
	 * @param {AbstractSoundInstance} instance The instance to add to the channel
	 * @param {String} interrupt The interrupt value to use. Please see the {{#crossLink "Sound/play"}}{{/crossLink}}
	 * for details on interrupt modes.
	 * @return {Boolean} The success of the method call. If the channel is full, it will return false.
	 * @static
	 */
	SoundChannel.add = function (instance, interrupt) {
		var channel = SoundChannel.get(instance.src);
		if (channel == null) {return false;}
		return channel._add(instance, interrupt);
	};
	/**
	 * Remove an instance from the channel.
	 * #method remove
	 * @param {AbstractSoundInstance} instance The instance to remove from the channel
	 * @return The success of the method call. If there is no channel, it will return false.
	 * @static
	 */
	SoundChannel.remove = function (instance) {
		var channel = SoundChannel.get(instance.src);
		if (channel == null) {return false;}
		channel._remove(instance);
		return true;
	};
	/**
	 * Get the maximum number of sounds you can have in a channel.
	 * #method maxPerChannel
	 * @return {Number} The maximum number of sounds you can have in a channel.
	 */
	SoundChannel.maxPerChannel = function () {
		return p.maxDefault;
	};
	/**
	 * Get a channel instance by its src.
	 * #method get
	 * @param {String} src The src to use to look up the channel
	 * @static
	 */
	SoundChannel.get = function (src) {
		return SoundChannel.channels[src];
	};

	var p = SoundChannel.prototype;
	p.constructor = SoundChannel;

	/**
	 * <strong>REMOVED</strong>. Removed in favor of using `MySuperClass_constructor`.
	 * See {{#crossLink "Utility Methods/extend"}}{{/crossLink}} and {{#crossLink "Utility Methods/promote"}}{{/crossLink}}
	 * for details.
	 *
	 * There is an inheritance tutorial distributed with EaselJS in /tutorials/Inheritance.
	 *
	 * @method initialize
	 * @protected
	 * @deprecated
	 */
	// p.initialize = function() {}; // searchable for devs wondering where it is.


	/**
	 * The source of the channel.
	 * #property src
	 * @type {String}
	 */
	p.src = null;

	/**
	 * The maximum number of instances in this channel.  -1 indicates no limit
	 * #property max
	 * @type {Number}
	 */
	p.max = null;

	/**
	 * The default value to set for max, if it isn't passed in.  Also used if -1 is passed.
	 * #property maxDefault
	 * @type {Number}
	 * @default 100
	 * @since 0.4.0
	 */
	p.maxDefault = 100;

	/**
	 * The current number of active instances.
	 * #property length
	 * @type {Number}
	 */
	p.length = 0;

	/**
	 * Initialize the channel.
	 * #method init
	 * @param {String} src The source of the channel
	 * @param {Number} max The maximum number of instances in the channel
	 * @protected
	 */
	p.init = function (src, max) {
		this.src = src;
		this.max = max || this.maxDefault;
		if (this.max == -1) {this.max = this.maxDefault;}
		this._instances = [];
	};

	/**
	 * Get an instance by index.
	 * #method get
	 * @param {Number} index The index to return.
	 * @return {AbstractSoundInstance} The AbstractSoundInstance at a specific instance.
	 */
	p._get = function (index) {
		return this._instances[index];
	};

	/**
	 * Add a new instance to the channel.
	 * #method add
	 * @param {AbstractSoundInstance} instance The instance to add.
	 * @return {Boolean} The success of the method call. If the channel is full, it will return false.
	 */
	p._add = function (instance, interrupt) {
		if (!this._getSlot(interrupt, instance)) {return false;}
		this._instances.push(instance);
		this.length++;
		return true;
	};

	/**
	 * Remove an instance from the channel, either when it has finished playing, or it has been interrupted.
	 * #method remove
	 * @param {AbstractSoundInstance} instance The instance to remove
	 * @return {Boolean} The success of the remove call. If the instance is not found in this channel, it will
	 * return false.
	 */
	p._remove = function (instance) {
		var index = createjs.indexOf(this._instances, instance);
		if (index == -1) {return false;}
		this._instances.splice(index, 1);
		this.length--;
		return true;
	};

	/**
	 * Stop playback and remove all instances from the channel.  Usually in response to a delete call.
	 * #method removeAll
	 */
	p._removeAll = function () {
		// Note that stop() removes the item from the list
		for (var i=this.length-1; i>=0; i--) {
			this._instances[i].stop();
		}
	};

	/**
	 * Get an available slot depending on interrupt value and if slots are available.
	 * #method getSlot
	 * @param {String} interrupt The interrupt value to use.
	 * @param {AbstractSoundInstance} instance The sound instance that will go in the channel if successful.
	 * @return {Boolean} Determines if there is an available slot. Depending on the interrupt mode, if there are no slots,
	 * an existing AbstractSoundInstance may be interrupted. If there are no slots, this method returns false.
	 */
	p._getSlot = function (interrupt, instance) {
		var target, replacement;

		if (interrupt != Sound.INTERRUPT_NONE) {
			// First replacement candidate
			replacement = this._get(0);
			if (replacement == null) {
				return true;
			}
		}

		for (var i = 0, l = this.max; i < l; i++) {
			target = this._get(i);

			// Available Space
			if (target == null) {
				return true;
			}

			// Audio is complete or not playing
			if (target.playState == Sound.PLAY_FINISHED ||
				target.playState == Sound.PLAY_INTERRUPTED ||
				target.playState == Sound.PLAY_FAILED) {
				replacement = target;
				break;
			}

			if (interrupt == Sound.INTERRUPT_NONE) {
				continue;
			}

			// Audio is a better candidate than the current target, according to playhead
			if ((interrupt == Sound.INTERRUPT_EARLY && target.getPosition() < replacement.getPosition()) ||
				(interrupt == Sound.INTERRUPT_LATE && target.getPosition() > replacement.getPosition())) {
					replacement = target;
			}
		}

		if (replacement != null) {
			replacement._interrupt();
			this._remove(replacement);
			return true;
		}
		return false;
	};

	p.toString = function () {
		return "[Sound SoundChannel]";
	};
	// do not add SoundChannel to namespace

}());

//##############################################################################
// AbstractSoundInstance.js
//##############################################################################

this.createjs = this.createjs || {};

/**
 * A AbstractSoundInstance is created when any calls to the Sound API method {{#crossLink "Sound/play"}}{{/crossLink}} or
 * {{#crossLink "Sound/createInstance"}}{{/crossLink}} are made. The AbstractSoundInstance is returned by the active plugin
 * for control by the user.
 *
 * <h4>Example</h4>
 *
 *      var myInstance = createjs.Sound.play("myAssetPath/mySrcFile.mp3");
 *
 * A number of additional parameters provide a quick way to determine how a sound is played. Please see the Sound
 * API method {{#crossLink "Sound/play"}}{{/crossLink}} for a list of arguments.
 *
 * Once a AbstractSoundInstance is created, a reference can be stored that can be used to control the audio directly through
 * the AbstractSoundInstance. If the reference is not stored, the AbstractSoundInstance will play out its audio (and any loops), and
 * is then de-referenced from the {{#crossLink "Sound"}}{{/crossLink}} class so that it can be cleaned up. If audio
 * playback has completed, a simple call to the {{#crossLink "AbstractSoundInstance/play"}}{{/crossLink}} instance method
 * will rebuild the references the Sound class need to control it.
 *
 *      var myInstance = createjs.Sound.play("myAssetPath/mySrcFile.mp3", {loop:2});
 *      myInstance.on("loop", handleLoop);
 *      function handleLoop(event) {
 *          myInstance.volume = myInstance.volume * 0.5;
 *      }
 *
 * Events are dispatched from the instance to notify when the sound has completed, looped, or when playback fails
 *
 *      var myInstance = createjs.Sound.play("myAssetPath/mySrcFile.mp3");
 *      myInstance.on("complete", handleComplete);
 *      myInstance.on("loop", handleLoop);
 *      myInstance.on("failed", handleFailed);
 *
 *
 * @class AbstractSoundInstance
 * @param {String} src The path to and file name of the sound.
 * @param {Number} startTime Audio sprite property used to apply an offset, in milliseconds.
 * @param {Number} duration Audio sprite property used to set the time the clip plays for, in milliseconds.
 * @param {Object} playbackResource Any resource needed by plugin to support audio playback.
 * @extends EventDispatcher
 * @constructor
 */

(function () {
	"use strict";


// Constructor:
	var AbstractSoundInstance = function (src, startTime, duration, playbackResource) {
		this.EventDispatcher_constructor();


	// public properties:
		/**
		 * The source of the sound.
		 * @property src
		 * @type {String}
		 * @default null
		 */
		this.src = src;

		/**
		 * The unique ID of the instance. This is set by {{#crossLink "Sound"}}{{/crossLink}}.
		 * @property uniqueId
		 * @type {String} | Number
		 * @default -1
		 */
		this.uniqueId = -1;

		/**
		 * The play state of the sound. Play states are defined as constants on {{#crossLink "Sound"}}{{/crossLink}}.
		 * @property playState
		 * @type {String}
		 * @default null
		 */
		this.playState = null;

		/**
		 * A Timeout created by {{#crossLink "Sound"}}{{/crossLink}} when this AbstractSoundInstance is played with a delay.
		 * This allows AbstractSoundInstance to remove the delay if stop, pause, or cleanup are called before playback begins.
		 * @property delayTimeoutId
		 * @type {timeoutVariable}
		 * @default null
		 * @protected
		 * @since 0.4.0
		 */
		this.delayTimeoutId = null;
		// TODO consider moving delay into AbstractSoundInstance so it can be handled by plugins


	// private properties
	// Getter / Setter Properties
		// OJR TODO find original reason that we didn't use defined functions.  I think it was performance related
		/**
		 * The volume of the sound, between 0 and 1.
		 *
		 * The actual output volume of a sound can be calculated using:
		 * <code>myInstance.volume * createjs.Sound.getVolume();</code>
		 *
		 * @property volume
		 * @type {Number}
		 * @default 1
		 */
		this._volume =  1;
		Object.defineProperty(this, "volume", {
			get: this.getVolume,
			set: this.setVolume
		});

		/**
		 * The pan of the sound, between -1 (left) and 1 (right). Note that pan is not supported by HTML Audio.
		 *
		 * <br />Note in WebAudioPlugin this only gives us the "x" value of what is actually 3D audio.
		 *
		 * @property pan
		 * @type {Number}
		 * @default 0
		 */
		this._pan =  0;
		Object.defineProperty(this, "pan", {
			get: this.getPan,
			set: this.setPan
		});

		/**
		 * Audio sprite property used to determine the starting offset.
		 * @property startTime
		 * @type {Number}
		 * @default 0
		 * @since 0.6.1
		 */
		this._startTime = Math.max(0, startTime || 0);
		Object.defineProperty(this, "startTime", {
			get: this.getStartTime,
			set: this.setStartTime
		});

		/**
		 * Sets or gets the length of the audio clip, value is in milliseconds.
		 *
		 * @property duration
		 * @type {Number}
		 * @default 0
		 * @since 0.6.0
		 */
		this._duration = Math.max(0, duration || 0);
		Object.defineProperty(this, "duration", {
			get: this.getDuration,
			set: this.setDuration
		});

		/**
		 * Object that holds plugin specific resource need for audio playback.
		 * This is set internally by the plugin.  For example, WebAudioPlugin will set an array buffer,
		 * HTMLAudioPlugin will set a tag, FlashAudioPlugin will set a flash reference.
		 *
		 * @property playbackResource
		 * @type {Object}
		 * @default null
		 */
		this._playbackResource = null;
		Object.defineProperty(this, "playbackResource", {
			get: this.getPlaybackResource,
			set: this.setPlaybackResource
		});
		if(playbackResource !== false && playbackResource !== true) { this.setPlaybackResource(playbackResource); }

		/**
		 * The position of the playhead in milliseconds. This can be set while a sound is playing, paused, or stopped.
		 *
		 * @property position
		 * @type {Number}
		 * @default 0
		 * @since 0.6.0
		 */
		this._position = 0;
		Object.defineProperty(this, "position", {
			get: this.getPosition,
			set: this.setPosition
		});

		/**
		 * The number of play loops remaining. Negative values will loop infinitely.
		 *
		 * @property loop
		 * @type {Number}
		 * @default 0
		 * @public
		 * @since 0.6.0
		 */
		this._loop = 0;
		Object.defineProperty(this, "loop", {
			get: this.getLoop,
			set: this.setLoop
		});

		/**
		 * Mutes or unmutes the current audio instance.
		 *
		 * @property muted
		 * @type {Boolean}
		 * @default false
		 * @since 0.6.0
		 */
		this._muted = false;
		Object.defineProperty(this, "muted", {
			get: this.getMuted,
			set: this.setMuted
		});

		/**
		 * Pauses or resumes the current audio instance.
		 *
		 * @property paused
		 * @type {Boolean}
		 */
		this._paused = false;
		Object.defineProperty(this, "paused", {
			get: this.getPaused,
			set: this.setPaused
		});


	// Events
		/**
		 * The event that is fired when playback has started successfully.
		 * @event succeeded
		 * @param {Object} target The object that dispatched the event.
		 * @param {String} type The event type.
		 * @since 0.4.0
		 */

		/**
		 * The event that is fired when playback is interrupted. This happens when another sound with the same
		 * src property is played using an interrupt value that causes this instance to stop playing.
		 * @event interrupted
		 * @param {Object} target The object that dispatched the event.
		 * @param {String} type The event type.
		 * @since 0.4.0
		 */

		/**
		 * The event that is fired when playback has failed. This happens when there are too many channels with the same
		 * src property already playing (and the interrupt value doesn't cause an interrupt of another instance), or
		 * the sound could not be played, perhaps due to a 404 error.
		 * @event failed
		 * @param {Object} target The object that dispatched the event.
		 * @param {String} type The event type.
		 * @since 0.4.0
		 */

		/**
		 * The event that is fired when a sound has completed playing but has loops remaining.
		 * @event loop
		 * @param {Object} target The object that dispatched the event.
		 * @param {String} type The event type.
		 * @since 0.4.0
		 */

		/**
		 * The event that is fired when playback completes. This means that the sound has finished playing in its
		 * entirety, including its loop iterations.
		 * @event complete
		 * @param {Object} target The object that dispatched the event.
		 * @param {String} type The event type.
		 * @since 0.4.0
		 */
	};

	var p = createjs.extend(AbstractSoundInstance, createjs.EventDispatcher);

	// TODO: deprecated
	// p.initialize = function() {}; // searchable for devs wondering where it is. REMOVED. See docs for details.


// Public Methods:
	/**
	 * Play an instance. This method is intended to be called on SoundInstances that already exist (created
	 * with the Sound API {{#crossLink "Sound/createInstance"}}{{/crossLink}} or {{#crossLink "Sound/play"}}{{/crossLink}}).
	 *
	 * <h4>Example</h4>
	 *
	 *      var myInstance = createjs.Sound.createInstance(mySrc);
	 *      myInstance.play({interrupt:createjs.Sound.INTERRUPT_ANY, loop:2, pan:0.5});
	 *
	 * Note that if this sound is already playing, this call will still set the passed in parameters.

	 * <b>Parameters Deprecated</b><br />
	 * The parameters for this method are deprecated in favor of a single parameter that is an Object or {{#crossLink "PlayPropsConfig"}}{{/crossLink}}.
	 *
	 * @method play
	 * @param {String | Object} [interrupt="none"|options] <b>This parameter will be renamed playProps in the next release.</b><br />
	 * This parameter can be an instance of {{#crossLink "PlayPropsConfig"}}{{/crossLink}} or an Object that contains any or all optional properties by name,
	 * including: interrupt, delay, offset, loop, volume, pan, startTime, and duration (see the above code sample).
	 * <br /><strong>OR</strong><br />
	 * <b>Deprecated</b> How to interrupt any currently playing instances of audio with the same source,
	 * if the maximum number of instances of the sound are already playing. Values are defined as <code>INTERRUPT_TYPE</code>
	 * constants on the Sound class, with the default defined by {{#crossLink "Sound/defaultInterruptBehavior:property"}}{{/crossLink}}.
	 * @param {Number} [delay=0] <b>Deprecated</b> The amount of time to delay the start of audio playback, in milliseconds.
	 * @param {Number} [offset=0] <b>Deprecated</b> The offset from the start of the audio to begin playback, in milliseconds.
	 * @param {Number} [loop=0] <b>Deprecated</b> How many times the audio loops when it reaches the end of playback. The default is 0 (no
	 * loops), and -1 can be used for infinite playback.
	 * @param {Number} [volume=1] <b>Deprecated</b> The volume of the sound, between 0 and 1. Note that the master volume is applied
	 * against the individual volume.
	 * @param {Number} [pan=0] <b>Deprecated</b> The left-right pan of the sound (if supported), between -1 (left) and 1 (right).
	 * Note that pan is not supported for HTML Audio.
	 * @return {AbstractSoundInstance} A reference to itself, intended for chaining calls.
	 */
	p.play = function (interrupt, delay, offset, loop, volume, pan) {
		var playProps;
		if (interrupt instanceof Object || interrupt instanceof createjs.PlayPropsConfig) {
			playProps = createjs.PlayPropsConfig.create(interrupt);
		} else {
			playProps = createjs.PlayPropsConfig.create({interrupt:interrupt, delay:delay, offset:offset, loop:loop, volume:volume, pan:pan});
		}

		if (this.playState == createjs.Sound.PLAY_SUCCEEDED) {
			this.applyPlayProps(playProps);
			if (this._paused) {	this.setPaused(false); }
			return;
		}
		this._cleanUp();
		createjs.Sound._playInstance(this, playProps);	// make this an event dispatch??
		return this;
	};

	/**
	 * Stop playback of the instance. Stopped sounds will reset their position to 0, and calls to {{#crossLink "AbstractSoundInstance/resume"}}{{/crossLink}}
	 * will fail. To start playback again, call {{#crossLink "AbstractSoundInstance/play"}}{{/crossLink}}.
     *
     * If you don't want to lose your position use yourSoundInstance.paused = true instead. {{#crossLink "AbstractSoundInstance/paused"}}{{/crossLink}}.
	 *
	 * <h4>Example</h4>
	 *
	 *     myInstance.stop();
	 *
	 * @method stop
	 * @return {AbstractSoundInstance} A reference to itself, intended for chaining calls.
	 */
	p.stop = function () {
		this._position = 0;
		this._paused = false;
		this._handleStop();
		this._cleanUp();
		this.playState = createjs.Sound.PLAY_FINISHED;
		return this;
	};

	/**
	 * Remove all external references and resources from AbstractSoundInstance.  Note this is irreversible and AbstractSoundInstance will no longer work
	 * @method destroy
	 * @since 0.6.0
	 */
	p.destroy = function() {
		this._cleanUp();
		this.src = null;
		this.playbackResource = null;

		this.removeAllEventListeners();
	};

	/**
	 * Takes an PlayPropsConfig or Object with the same properties and sets them on this instance.
	 * @method applyPlayProps
	 * @param {PlayPropsConfig | Object} playProps A PlayPropsConfig or object containing the same properties.
	 * @since 0.6.1
	 * @return {AbstractSoundInstance} A reference to itself, intended for chaining calls.
	 */
	p.applyPlayProps = function(playProps) {
		if (playProps.offset != null) { this.setPosition(playProps.offset) }
		if (playProps.loop != null) { this.setLoop(playProps.loop); }
		if (playProps.volume != null) { this.setVolume(playProps.volume); }
		if (playProps.pan != null) { this.setPan(playProps.pan); }
		if (playProps.startTime != null) {
			this.setStartTime(playProps.startTime);
			this.setDuration(playProps.duration);
		}
		return this;
	};

	p.toString = function () {
		return "[AbstractSoundInstance]";
	};

// get/set methods that allow support for IE8
	/**
	 * DEPRECATED, please use {{#crossLink "AbstractSoundInstance/paused:property"}}{{/crossLink}} directly as a property,
	 *
	 * @deprecated
	 * @method getPaused
	 * @returns {boolean} If the instance is currently paused
	 * @since 0.6.0
	 */
	p.getPaused = function() {
		return this._paused;
	};

	/**
	 * DEPRECATED, please use {{#crossLink "AbstractSoundInstance/paused:property"}}{{/crossLink}} directly as a property
	 *
	 * @deprecated
	 * @method setPaused
	 * @param {boolean} value
	 * @since 0.6.0
	 * @return {AbstractSoundInstance} A reference to itself, intended for chaining calls.
	 */
	p.setPaused = function (value) {
		if ((value !== true && value !== false) || this._paused == value) {return;}
		if (value == true && this.playState != createjs.Sound.PLAY_SUCCEEDED) {return;}
		this._paused = value;
		if(value) {
			this._pause();
		} else {
			this._resume();
		}
		clearTimeout(this.delayTimeoutId);
		return this;
	};

	/**
	 * DEPRECATED, please use {{#crossLink "AbstractSoundInstance/volume:property"}}{{/crossLink}} directly as a property
	 *
	 * @deprecated
	 * @method setVolume
	 * @param {Number} value The volume to set, between 0 and 1.
	 * @return {AbstractSoundInstance} A reference to itself, intended for chaining calls.
	 */
	p.setVolume = function (value) {
		if (value == this._volume) { return this; }
		this._volume = Math.max(0, Math.min(1, value));
		if (!this._muted) {
			this._updateVolume();
		}
		return this;
	};

	/**
	 * DEPRECATED, please use {{#crossLink "AbstractSoundInstance/volume:property"}}{{/crossLink}} directly as a property
	 *
	 * @deprecated
	 * @method getVolume
	 * @return {Number} The current volume of the sound instance.
	 */
	p.getVolume = function () {
		return this._volume;
	};

	/**
	 * DEPRECATED, please use {{#crossLink "AbstractSoundInstance/muted:property"}}{{/crossLink}} directly as a property
	 *
	 * @deprecated
	 * @method setMuted
	 * @param {Boolean} value If the sound should be muted.
	 * @return {AbstractSoundInstance} A reference to itself, intended for chaining calls.
	 * @since 0.6.0
	 */
	p.setMuted = function (value) {
		if (value !== true && value !== false) {return;}
		this._muted = value;
		this._updateVolume();
		return this;
	};

	/**
	 * DEPRECATED, please use {{#crossLink "AbstractSoundInstance/muted:property"}}{{/crossLink}} directly as a property
	 *
	 * @deprecated
	 * @method getMuted
	 * @return {Boolean} If the sound is muted.
	 * @since 0.6.0
	 */
	p.getMuted = function () {
		return this._muted;
	};

	/**
	 * DEPRECATED, please use {{#crossLink "AbstractSoundInstance/pan:property"}}{{/crossLink}} directly as a property
	 *
	 * @deprecated
	 * @method setPan
	 * @param {Number} value The pan value, between -1 (left) and 1 (right).
	 * @return {AbstractSoundInstance} Returns reference to itself for chaining calls
	 */
	p.setPan = function (value) {
		if(value == this._pan) { return this; }
		this._pan = Math.max(-1, Math.min(1, value));
		this._updatePan();
		return this;
	};

	/**
	 * DEPRECATED, please use {{#crossLink "AbstractSoundInstance/pan:property"}}{{/crossLink}} directly as a property
	 *
	 * @deprecated
	 * @method getPan
	 * @return {Number} The value of the pan, between -1 (left) and 1 (right).
	 */
	p.getPan = function () {
		return this._pan;
	};

	/**
	 * DEPRECATED, please use {{#crossLink "AbstractSoundInstance/position:property"}}{{/crossLink}} directly as a property
	 *
	 * @deprecated
	 * @method getPosition
	 * @return {Number} The position of the playhead in the sound, in milliseconds.
	 */
	p.getPosition = function () {
		if (!this._paused && this.playState == createjs.Sound.PLAY_SUCCEEDED) {
			this._position = this._calculateCurrentPosition();
		}
		return this._position;
	};

	/**
	 * DEPRECATED, please use {{#crossLink "AbstractSoundInstance/position:property"}}{{/crossLink}} directly as a property
	 *
	 * @deprecated
	 * @method setPosition
	 * @param {Number} value The position to place the playhead, in milliseconds.
	 * @return {AbstractSoundInstance} Returns reference to itself for chaining calls
	 */
	p.setPosition = function (value) {
		this._position = Math.max(0, value);
		if (this.playState == createjs.Sound.PLAY_SUCCEEDED) {
			this._updatePosition();
		}
		return this;
	};

	/**
	 * DEPRECATED, please use {{#crossLink "AbstractSoundInstance/startTime:property"}}{{/crossLink}} directly as a property
	 *
	 * @deprecated
	 * @method getStartTime
	 * @return {Number} The startTime of the sound instance in milliseconds.
	 */
	p.getStartTime = function () {
		return this._startTime;
	};

	/**
	 * DEPRECATED, please use {{#crossLink "AbstractSoundInstance/startTime:property"}}{{/crossLink}} directly as a property
	 *
	 * @deprecated
	 * @method setStartTime
	 * @param {number} value The new startTime time in milli seconds.
	 * @return {AbstractSoundInstance} Returns reference to itself for chaining calls
	 */
	p.setStartTime = function (value) {
		if (value == this._startTime) { return this; }
		this._startTime = Math.max(0, value || 0);
		this._updateStartTime();
		return this;
	};

	/**
	 * DEPRECATED, please use {{#crossLink "AbstractSoundInstance/duration:property"}}{{/crossLink}} directly as a property
	 *
	 * @deprecated
	 * @method getDuration
	 * @return {Number} The duration of the sound instance in milliseconds.
	 */
	p.getDuration = function () {
		return this._duration;
	};

	/**
	 * DEPRECATED, please use {{#crossLink "AbstractSoundInstance/duration:property"}}{{/crossLink}} directly as a property
	 *
	 * @deprecated
	 * @method setDuration
	 * @param {number} value The new duration time in milli seconds.
	 * @return {AbstractSoundInstance} Returns reference to itself for chaining calls
	 * @since 0.6.0
	 */
	p.setDuration = function (value) {
		if (value == this._duration) { return this; }
		this._duration = Math.max(0, value || 0);
		this._updateDuration();
		return this;
	};

	/**
	 * DEPRECATED, please use {{#crossLink "AbstractSoundInstance/playbackResource:property"}}{{/crossLink}} directly as a property
	 *
	 * @deprecated
	 * @method setPlayback
	 * @param {Object} value The new playback resource.
	 * @return {AbstractSoundInstance} Returns reference to itself for chaining calls
	 * @since 0.6.0
	 **/
	p.setPlaybackResource = function (value) {
		this._playbackResource = value;
		if (this._duration == 0) { this._setDurationFromSource(); }
		return this;
	};

	/**
	 * DEPRECATED, please use {{#crossLink "AbstractSoundInstance/playbackResource:property"}}{{/crossLink}} directly as a property
	 *
	 * @deprecated
	 * @method setPlayback
	 * @param {Object} value The new playback resource.
	 * @return {Object} playback resource used for playing audio
	 * @since 0.6.0
	 **/
	p.getPlaybackResource = function () {
		return this._playbackResource;
	};

	/**
	 * DEPRECATED, please use {{#crossLink "AbstractSoundInstance/loop:property"}}{{/crossLink}} directly as a property
	 *
	 * @deprecated
	 * @method getLoop
	 * @return {number}
	 * @since 0.6.0
	 **/
	p.getLoop = function () {
		return this._loop;
	};

	/**
	 * DEPRECATED, please use {{#crossLink "AbstractSoundInstance/loop:property"}}{{/crossLink}} directly as a property,
	 *
	 * @deprecated
	 * @method setLoop
	 * @param {number} value The number of times to loop after play.
	 * @since 0.6.0
	 */
	p.setLoop = function (value) {
		if(this._playbackResource != null) {
			// remove looping
			if (this._loop != 0 && value == 0) {
				this._removeLooping(value);
			}
			// add looping
			else if (this._loop == 0 && value != 0) {
				this._addLooping(value);
			}
		}
		this._loop = value;
	};


// Private Methods:
	/**
	 * A helper method that dispatches all events for AbstractSoundInstance.
	 * @method _sendEvent
	 * @param {String} type The event type
	 * @protected
	 */
	p._sendEvent = function (type) {
		var event = new createjs.Event(type);
		this.dispatchEvent(event);
	};

	/**
	 * Clean up the instance. Remove references and clean up any additional properties such as timers.
	 * @method _cleanUp
	 * @protected
	 */
	p._cleanUp = function () {
		clearTimeout(this.delayTimeoutId); // clear timeout that plays delayed sound
		this._handleCleanUp();
		this._paused = false;

		createjs.Sound._playFinished(this);	// TODO change to an event
	};

	/**
	 * The sound has been interrupted.
	 * @method _interrupt
	 * @protected
	 */
	p._interrupt = function () {
		this._cleanUp();
		this.playState = createjs.Sound.PLAY_INTERRUPTED;
		this._sendEvent("interrupted");
	};

	/**
	 * Called by the Sound class when the audio is ready to play (delay has completed). Starts sound playing if the
	 * src is loaded, otherwise playback will fail.
	 * @method _beginPlaying
	 * @param {PlayPropsConfig} playProps A PlayPropsConfig object.
	 * @return {Boolean} If playback succeeded.
	 * @protected
	 */
	// OJR FlashAudioSoundInstance overwrites
	p._beginPlaying = function (playProps) {
		this.setPosition(playProps.offset);
		this.setLoop(playProps.loop);
		this.setVolume(playProps.volume);
		this.setPan(playProps.pan);
		if (playProps.startTime != null) {
			this.setStartTime(playProps.startTime);
			this.setDuration(playProps.duration);
		}

		if (this._playbackResource != null && this._position < this._duration) {
			this._paused = false;
			this._handleSoundReady();
			this.playState = createjs.Sound.PLAY_SUCCEEDED;
			this._sendEvent("succeeded");
			return true;
		} else {
			this._playFailed();
			return false;
		}
	};

	/**
	 * Play has failed, which can happen for a variety of reasons.
	 * Cleans up instance and dispatches failed event
	 * @method _playFailed
	 * @private
	 */
	p._playFailed = function () {
		this._cleanUp();
		this.playState = createjs.Sound.PLAY_FAILED;
		this._sendEvent("failed");
	};

	/**
	 * Audio has finished playing. Manually loop it if required.
	 * @method _handleSoundComplete
	 * @param event
	 * @protected
	 */
	p._handleSoundComplete = function (event) {
		this._position = 0;  // have to set this as it can be set by pause during playback

		if (this._loop != 0) {
			this._loop--;  // NOTE this introduces a theoretical limit on loops = float max size x 2 - 1
			this._handleLoop();
			this._sendEvent("loop");
			return;
		}

		this._cleanUp();
		this.playState = createjs.Sound.PLAY_FINISHED;
		this._sendEvent("complete");
	};

// Plugin specific code
	/**
	 * Handles starting playback when the sound is ready for playing.
	 * @method _handleSoundReady
	 * @protected
 	 */
	p._handleSoundReady = function () {
		// plugin specific code
	};

	/**
	 * Internal function used to update the volume based on the instance volume, master volume, instance mute value,
	 * and master mute value.
	 * @method _updateVolume
	 * @protected
	 */
	p._updateVolume = function () {
		// plugin specific code
	};

	/**
	 * Internal function used to update the pan
	 * @method _updatePan
	 * @protected
	 * @since 0.6.0
	 */
	p._updatePan = function () {
		// plugin specific code
	};

	/**
	 * Internal function used to update the startTime of the audio.
	 * @method _updateStartTime
	 * @protected
	 * @since 0.6.1
	 */
	p._updateStartTime = function () {
		// plugin specific code
	};

	/**
	 * Internal function used to update the duration of the audio.
	 * @method _updateDuration
	 * @protected
	 * @since 0.6.0
	 */
	p._updateDuration = function () {
		// plugin specific code
	};

	/**
	 * Internal function used to get the duration of the audio from the source we'll be playing.
	 * @method _updateDuration
	 * @protected
	 * @since 0.6.0
	 */
	p._setDurationFromSource = function () {
		// plugin specific code
	};

	/**
	 * Internal function that calculates the current position of the playhead and sets this._position to that value
	 * @method _calculateCurrentPosition
	 * @protected
	 * @since 0.6.0
	 */
	p._calculateCurrentPosition = function () {
		// plugin specific code that sets this.position
	};

	/**
	 * Internal function used to update the position of the playhead.
	 * @method _updatePosition
	 * @protected
	 * @since 0.6.0
	 */
	p._updatePosition = function () {
		// plugin specific code
	};

	/**
	 * Internal function called when looping is removed during playback.
	 * @method _removeLooping
	 * @param {number} value The number of times to loop after play.
	 * @protected
	 * @since 0.6.0
	 */
	p._removeLooping = function (value) {
		// plugin specific code
	};

	/**
	 * Internal function called when looping is added during playback.
	 * @method _addLooping
	 * @param {number} value The number of times to loop after play.
	 * @protected
	 * @since 0.6.0
	 */
	p._addLooping = function (value) {
		// plugin specific code
	};

	/**
	 * Internal function called when pausing playback
	 * @method _pause
	 * @protected
	 * @since 0.6.0
	 */
	p._pause = function () {
		// plugin specific code
	};

	/**
	 * Internal function called when resuming playback
	 * @method _resume
	 * @protected
	 * @since 0.6.0
	 */
	p._resume = function () {
		// plugin specific code
	};

	/**
	 * Internal function called when stopping playback
	 * @method _handleStop
	 * @protected
	 * @since 0.6.0
	 */
	p._handleStop = function() {
		// plugin specific code
	};

	/**
	 * Internal function called when AbstractSoundInstance is being cleaned up
	 * @method _handleCleanUp
	 * @protected
	 * @since 0.6.0
	 */
	p._handleCleanUp = function() {
		// plugin specific code
	};

	/**
	 * Internal function called when AbstractSoundInstance has played to end and is looping
	 * @method _handleLoop
	 * @protected
	 * @since 0.6.0
	 */
	p._handleLoop = function () {
		// plugin specific code
	};

	createjs.AbstractSoundInstance = createjs.promote(AbstractSoundInstance, "EventDispatcher");
	createjs.DefaultSoundInstance = createjs.AbstractSoundInstance;	// used when no plugin is supported
}());

//##############################################################################
// AbstractPlugin.js
//##############################################################################

this.createjs = this.createjs || {};

(function () {
	"use strict";


// constructor:
 	/**
	 * A default plugin class used as a base for all other plugins.
	 * @class AbstractPlugin
	 * @constructor
	 * @since 0.6.0
	 */

	var AbstractPlugin = function () {
	// private properties:
		/**
		 * The capabilities of the plugin.
		 * method and is used internally.
		 * @property _capabilities
		 * @type {Object}
		 * @default null
		 * @protected
		 * @static
		 */
		this._capabilities = null;

		/**
		 * Object hash indexed by the source URI of all created loaders, used to properly destroy them if sources are removed.
		 * @type {Object}
		 * @protected
		 */
		this._loaders = {};

		/**
		 * Object hash indexed by the source URI of each file to indicate if an audio source has begun loading,
		 * is currently loading, or has completed loading.  Can be used to store non boolean data after loading
		 * is complete (for example arrayBuffers for web audio).
		 * @property _audioSources
		 * @type {Object}
		 * @protected
		 */
		this._audioSources = {};

		/**
		 * Object hash indexed by the source URI of all created SoundInstances, updates the playbackResource if it loads after they are created,
		 * and properly destroy them if sources are removed
		 * @type {Object}
		 * @protected
		 */
		this._soundInstances = {};

		/**
		 * The internal master volume value of the plugin.
		 * @property _volume
		 * @type {Number}
		 * @default 1
		 * @protected
		 */
		this._volume = 1;

		/**
		 * A reference to a loader class used by a plugin that must be set.
		 * @type {Object}
		 * @protected
		 */
		this._loaderClass;

		/**
		 * A reference to an AbstractSoundInstance class used by a plugin that must be set.
		 * @type {Object}
		 * @protected;
		 */
		this._soundInstanceClass;
	};
	var p = AbstractPlugin.prototype;

	/**
	 * <strong>REMOVED</strong>. Removed in favor of using `MySuperClass_constructor`.
	 * See {{#crossLink "Utility Methods/extend"}}{{/crossLink}} and {{#crossLink "Utility Methods/promote"}}{{/crossLink}}
	 * for details.
	 *
	 * There is an inheritance tutorial distributed with EaselJS in /tutorials/Inheritance.
	 *
	 * @method initialize
	 * @protected
	 * @deprecated
	 */
	// p.initialize = function() {}; // searchable for devs wondering where it is.


// Static Properties:
// NOTE THESE PROPERTIES NEED TO BE ADDED TO EACH PLUGIN
	/**
	 * The capabilities of the plugin. This is generated via the _generateCapabilities method and is used internally.
	 * @property _capabilities
	 * @type {Object}
	 * @default null
	 * @protected
	 * @static
	 */
	AbstractPlugin._capabilities = null;

	/**
	 * Determine if the plugin can be used in the current browser/OS.
	 * @method isSupported
	 * @return {Boolean} If the plugin can be initialized.
	 * @static
	 */
	AbstractPlugin.isSupported = function () {
		return true;
	};


// public methods:
	/**
	 * Pre-register a sound for preloading and setup. This is called by {{#crossLink "Sound"}}{{/crossLink}}.
	 * Note all plugins provide a <code>Loader</code> instance, which <a href="http://preloadjs.com" target="_blank">PreloadJS</a>
	 * can use to assist with preloading.
	 * @method register
	 * @param {String} loadItem An Object containing the source of the audio
	 * Note that not every plugin will manage this value.
	 * @return {Object} A result object, containing a "tag" for preloading purposes.
	 */
	p.register = function (loadItem) {
		var loader = this._loaders[loadItem.src];
		if(loader && !loader.canceled) {return this._loaders[loadItem.src];}	// already loading/loaded this, so don't load twice
		// OJR potential issue that we won't be firing loaded event, might need to trigger if this is already loaded?
		this._audioSources[loadItem.src] = true;
		this._soundInstances[loadItem.src] = [];
		loader = new this._loaderClass(loadItem);
		loader.on("complete", this._handlePreloadComplete, this);
		this._loaders[loadItem.src] = loader;
		return loader;
	};

	// note sound calls register before calling preload
	/**
	 * Internally preload a sound.
	 * @method preload
	 * @param {Loader} loader The sound URI to load.
	 */
	p.preload = function (loader) {
		loader.on("error", this._handlePreloadError, this);
		loader.load();
	};

	/**
	 * Checks if preloading has started for a specific source. If the source is found, we can assume it is loading,
	 * or has already finished loading.
	 * @method isPreloadStarted
	 * @param {String} src The sound URI to check.
	 * @return {Boolean}
	 */
	p.isPreloadStarted = function (src) {
		return (this._audioSources[src] != null);
	};

	/**
	 * Checks if preloading has finished for a specific source.
	 * @method isPreloadComplete
	 * @param {String} src The sound URI to load.
	 * @return {Boolean}
	 */
	p.isPreloadComplete = function (src) {
		return (!(this._audioSources[src] == null || this._audioSources[src] == true));
	};

	/**
	 * Remove a sound added using {{#crossLink "WebAudioPlugin/register"}}{{/crossLink}}. Note this does not cancel a preload.
	 * @method removeSound
	 * @param {String} src The sound URI to unload.
	 */
	p.removeSound = function (src) {
		if (!this._soundInstances[src]) { return; }
		for (var i = this._soundInstances[src].length; i--; ) {
			var item = this._soundInstances[src][i];
			item.destroy();
		}
		delete(this._soundInstances[src]);
		delete(this._audioSources[src]);
		if(this._loaders[src]) { this._loaders[src].destroy(); }
		delete(this._loaders[src]);
	};

	/**
	 * Remove all sounds added using {{#crossLink "WebAudioPlugin/register"}}{{/crossLink}}. Note this does not cancel a preload.
	 * @method removeAllSounds
	 * @param {String} src The sound URI to unload.
	 */
	p.removeAllSounds = function () {
		for(var key in this._audioSources) {
			this.removeSound(key);
		}
	};

	/**
	 * Create a sound instance. If the sound has not been preloaded, it is internally preloaded here.
	 * @method create
	 * @param {String} src The sound source to use.
	 * @param {Number} startTime Audio sprite property used to apply an offset, in milliseconds.
	 * @param {Number} duration Audio sprite property used to set the time the clip plays for, in milliseconds.
	 * @return {AbstractSoundInstance} A sound instance for playback and control.
	 */
	p.create = function (src, startTime, duration) {
		if (!this.isPreloadStarted(src)) {
			this.preload(this.register(src));
		}
		var si = new this._soundInstanceClass(src, startTime, duration, this._audioSources[src]);
		this._soundInstances[src].push(si);
		return si;
	};

	// if a plugin does not support volume and mute, it should set these to null
	/**
	 * Set the master volume of the plugin, which affects all SoundInstances.
	 * @method setVolume
	 * @param {Number} value The volume to set, between 0 and 1.
	 * @return {Boolean} If the plugin processes the setVolume call (true). The Sound class will affect all the
	 * instances manually otherwise.
	 */
	p.setVolume = function (value) {
		this._volume = value;
		this._updateVolume();
		return true;
	};

	/**
	 * Get the master volume of the plugin, which affects all SoundInstances.
	 * @method getVolume
	 * @return {Number} The volume level, between 0 and 1.
	 */
	p.getVolume = function () {
		return this._volume;
	};

	/**
	 * Mute all sounds via the plugin.
	 * @method setMute
	 * @param {Boolean} value If all sound should be muted or not. Note that plugin-level muting just looks up
	 * the mute value of Sound {{#crossLink "Sound/getMute"}}{{/crossLink}}, so this property is not used here.
	 * @return {Boolean} If the mute call succeeds.
	 */
	p.setMute = function (value) {
		this._updateVolume();
		return true;
	};

	// plugins should overwrite this method
	p.toString = function () {
		return "[AbstractPlugin]";
	};


// private methods:
	/**
	 * Handles internal preload completion.
	 * @method _handlePreloadComplete
	 * @protected
	 */
	p._handlePreloadComplete = function (event) {
		var src = event.target.getItem().src;
		this._audioSources[src] = event.result;
		for (var i = 0, l = this._soundInstances[src].length; i < l; i++) {
			var item = this._soundInstances[src][i];
			item.setPlaybackResource(this._audioSources[src]);
			// ToDo consider adding play call here if playstate == playfailed
		}
	};

	/**
	 * Handles internal preload erros
	 * @method _handlePreloadError
	 * @param event
	 * @protected
	 */
	p._handlePreloadError = function(event) {
		//delete(this._audioSources[src]);
	};

	/**
	 * Set the gain value for master audio. Should not be called externally.
	 * @method _updateVolume
	 * @protected
	 */
	p._updateVolume = function () {
		// Plugin Specific code
	};

	createjs.AbstractPlugin = AbstractPlugin;
}());

//##############################################################################
// WebAudioLoader.js
//##############################################################################

this.createjs = this.createjs || {};

(function () {
	"use strict";

	/**
	 * Loader provides a mechanism to preload Web Audio content via PreloadJS or internally. Instances are returned to
	 * the preloader, and the load method is called when the asset needs to be requested.
	 *
	 * @class WebAudioLoader
	 * @param {String} loadItem The item to be loaded
	 * @extends XHRRequest
	 * @protected
	 */
	function Loader(loadItem) {
		this.AbstractLoader_constructor(loadItem, true, createjs.AbstractLoader.SOUND);

	};
	var p = createjs.extend(Loader, createjs.AbstractLoader);

	// TODO: deprecated
	// p.initialize = function() {}; // searchable for devs wondering where it is. REMOVED. See docs for details.


	/**
	 * web audio context required for decoding audio
	 * @property context
	 * @type {AudioContext}
	 * @static
	 */
	Loader.context = null;


// public methods
	p.toString = function () {
		return "[WebAudioLoader]";
	};


// private methods
	p._createRequest = function() {
		this._request = new createjs.XHRRequest(this._item, false);
		this._request.setResponseType("arraybuffer");
	};

	p._sendComplete = function (event) {
		// OJR we leave this wrapped in Loader because we need to reference src and the handler only receives a single argument, the decodedAudio
		Loader.context.decodeAudioData(this._rawResult,
	         createjs.proxy(this._handleAudioDecoded, this),
	         createjs.proxy(this._sendError, this));
	};


	/**
	* The audio has been decoded.
	* @method handleAudioDecoded
	* @param decoded
	* @protected
	*/
	p._handleAudioDecoded = function (decodedAudio) {
		this._result = decodedAudio;
		this.AbstractLoader__sendComplete();
	};

	createjs.WebAudioLoader = createjs.promote(Loader, "AbstractLoader");
}());

//##############################################################################
// WebAudioSoundInstance.js
//##############################################################################

this.createjs = this.createjs || {};

/**
 * WebAudioSoundInstance extends the base api of {{#crossLink "AbstractSoundInstance"}}{{/crossLink}} and is used by
 * {{#crossLink "WebAudioPlugin"}}{{/crossLink}}.
 *
 * WebAudioSoundInstance exposes audioNodes for advanced users.
 *
 * @param {String} src The path to and file name of the sound.
 * @param {Number} startTime Audio sprite property used to apply an offset, in milliseconds.
 * @param {Number} duration Audio sprite property used to set the time the clip plays for, in milliseconds.
 * @param {Object} playbackResource Any resource needed by plugin to support audio playback.
 * @class WebAudioSoundInstance
 * @extends AbstractSoundInstance
 * @constructor
 */
(function () {
	"use strict";

	function WebAudioSoundInstance(src, startTime, duration, playbackResource) {
		this.AbstractSoundInstance_constructor(src, startTime, duration, playbackResource);


// public properties
		/**
		 * NOTE this is only intended for use by advanced users.
		 * <br />GainNode for controlling <code>WebAudioSoundInstance</code> volume. Connected to the {{#crossLink "WebAudioSoundInstance/destinationNode:property"}}{{/crossLink}}.
		 * @property gainNode
		 * @type {AudioGainNode}
		 * @since 0.4.0
		 *
		 */
		this.gainNode = s.context.createGain();

		/**
		 * NOTE this is only intended for use by advanced users.
		 * <br />A panNode allowing left and right audio channel panning only. Connected to WebAudioSoundInstance {{#crossLink "WebAudioSoundInstance/gainNode:property"}}{{/crossLink}}.
		 * @property panNode
		 * @type {AudioPannerNode}
		 * @since 0.4.0
		 */
		this.panNode = s.context.createPanner();
		this.panNode.panningModel = s._panningModel;
		this.panNode.connect(this.gainNode);
		this._updatePan();

		/**
		 * NOTE this is only intended for use by advanced users.
		 * <br />sourceNode is the audio source. Connected to WebAudioSoundInstance {{#crossLink "WebAudioSoundInstance/panNode:property"}}{{/crossLink}}.
		 * @property sourceNode
		 * @type {AudioNode}
		 * @since 0.4.0
		 *
		 */
		this.sourceNode = null;


// private properties
		/**
		 * Timeout that is created internally to handle sound playing to completion.
		 * Stored so we can remove it when stop, pause, or cleanup are called
		 * @property _soundCompleteTimeout
		 * @type {timeoutVariable}
		 * @default null
		 * @protected
		 * @since 0.4.0
		 */
		this._soundCompleteTimeout = null;

		/**
		 * NOTE this is only intended for use by very advanced users.
		 * _sourceNodeNext is the audio source for the next loop, inserted in a look ahead approach to allow for smooth
		 * looping. Connected to {{#crossLink "WebAudioSoundInstance/gainNode:property"}}{{/crossLink}}.
		 * @property _sourceNodeNext
		 * @type {AudioNode}
		 * @default null
		 * @protected
		 * @since 0.4.1
		 *
		 */
		this._sourceNodeNext = null;

		/**
		 * Time audio started playback, in seconds. Used to handle set position, get position, and resuming from paused.
		 * @property _playbackStartTime
		 * @type {Number}
		 * @default 0
		 * @protected
		 * @since 0.4.0
		 */
		this._playbackStartTime = 0;

		// Proxies, make removing listeners easier.
		this._endedHandler = createjs.proxy(this._handleSoundComplete, this);
	};
	var p = createjs.extend(WebAudioSoundInstance, createjs.AbstractSoundInstance);
	var s = WebAudioSoundInstance;

	// TODO: deprecated
	// p.initialize = function() {}; // searchable for devs wondering where it is. REMOVED. See docs for details.


	/**
	 * Note this is only intended for use by advanced users.
	 * <br />Audio context used to create nodes.  This is and needs to be the same context used by {{#crossLink "WebAudioPlugin"}}{{/crossLink}}.
  	 * @property context
	 * @type {AudioContext}
	 * @static
	 * @since 0.6.0
	 */
	s.context = null;

	/**
	 * Note this is only intended for use by advanced users.
	 * <br />The scratch buffer that will be assigned to the buffer property of a source node on close.  
	 * This is and should be the same scratch buffer referenced by {{#crossLink "WebAudioPlugin"}}{{/crossLink}}.
  	 * @property _scratchBuffer
	 * @type {AudioBufferSourceNode}
	 * @static
	 */
	s._scratchBuffer = null;

	/**
	 * Note this is only intended for use by advanced users.
	 * <br /> Audio node from WebAudioPlugin that sequences to <code>context.destination</code>
	 * @property destinationNode
	 * @type {AudioNode}
	 * @static
	 * @since 0.6.0
	 */
	s.destinationNode = null;

	/**
	 * Value to set panning model to equal power for WebAudioSoundInstance.  Can be "equalpower" or 0 depending on browser implementation.
	 * @property _panningModel
	 * @type {Number / String}
	 * @protected
	 * @static
	 * @since 0.6.0
	 */
	s._panningModel = "equalpower";


// Public methods
	p.destroy = function() {
		this.AbstractSoundInstance_destroy();

		this.panNode.disconnect(0);
		this.panNode = null;
		this.gainNode.disconnect(0);
		this.gainNode = null;
	};

	p.toString = function () {
		return "[WebAudioSoundInstance]";
	};


// Private Methods
	p._updatePan = function() {
		this.panNode.setPosition(this._pan, 0, -0.5);
		// z need to be -0.5 otherwise the sound only plays in left, right, or center
	};

	p._removeLooping = function(value) {
		this._sourceNodeNext = this._cleanUpAudioNode(this._sourceNodeNext);
	};

	p._addLooping = function(value) {
		if (this.playState != createjs.Sound.PLAY_SUCCEEDED) { return; }
		this._sourceNodeNext = this._createAndPlayAudioNode(this._playbackStartTime, 0);
	};

	p._setDurationFromSource = function () {
		this._duration = this.playbackResource.duration * 1000;
	};

	p._handleCleanUp = function () {
		if (this.sourceNode && this.playState == createjs.Sound.PLAY_SUCCEEDED) {
			this.sourceNode = this._cleanUpAudioNode(this.sourceNode);
			this._sourceNodeNext = this._cleanUpAudioNode(this._sourceNodeNext);
		}

		if (this.gainNode.numberOfOutputs != 0) {this.gainNode.disconnect(0);}
		// OJR there appears to be a bug that this doesn't always work in webkit (Chrome and Safari). According to the documentation, this should work.

		clearTimeout(this._soundCompleteTimeout);

		this._playbackStartTime = 0;	// This is used by getPosition
	};

	/**
	 * Turn off and disconnect an audioNode, then set reference to null to release it for garbage collection
	 * @method _cleanUpAudioNode
	 * @param audioNode
	 * @return {audioNode}
	 * @protected
	 * @since 0.4.1
	 */
	p._cleanUpAudioNode = function(audioNode) {
		if(audioNode) {
			audioNode.stop(0);
			audioNode.disconnect(0);
			// necessary to prevent leak on iOS Safari 7-9. will throw in almost all other
			// browser implementations.
			try { audioNode.buffer = s._scratchBuffer; } catch(e) {}
			audioNode = null;
		}
		return audioNode;
	};

	p._handleSoundReady = function (event) {
		this.gainNode.connect(s.destinationNode);  // this line can cause a memory leak.  Nodes need to be disconnected from the audioDestination or any sequence that leads to it.

		var dur = this._duration * 0.001;
		var pos = this._position * 0.001;
		if (pos > dur) {pos = dur;}
		this.sourceNode = this._createAndPlayAudioNode((s.context.currentTime - dur), pos);
		this._playbackStartTime = this.sourceNode.startTime - pos;

		this._soundCompleteTimeout = setTimeout(this._endedHandler, (dur - pos) * 1000);

		if(this._loop != 0) {
			this._sourceNodeNext = this._createAndPlayAudioNode(this._playbackStartTime, 0);
		}
	};

	/**
	 * Creates an audio node using the current src and context, connects it to the gain node, and starts playback.
	 * @method _createAndPlayAudioNode
	 * @param {Number} startTime The time to add this to the web audio context, in seconds.
	 * @param {Number} offset The amount of time into the src audio to start playback, in seconds.
	 * @return {audioNode}
	 * @protected
	 * @since 0.4.1
	 */
	p._createAndPlayAudioNode = function(startTime, offset) {
		var audioNode = s.context.createBufferSource();
		audioNode.buffer = this.playbackResource;
		audioNode.connect(this.panNode);
		var dur = this._duration * 0.001;
		audioNode.startTime = Math.max(0, startTime + dur);
		audioNode.start(audioNode.startTime, Math.max(0,offset)+(this._startTime*0.001), dur - Math.max(0,offset));
		return audioNode;
	};

	p._pause = function () {
		this._position = (s.context.currentTime - this._playbackStartTime) * 1000;  // * 1000 to give milliseconds, lets us restart at same point
		this.sourceNode = this._cleanUpAudioNode(this.sourceNode);
		this._sourceNodeNext = this._cleanUpAudioNode(this._sourceNodeNext);

		if (this.gainNode.numberOfOutputs != 0) {this.gainNode.disconnect(0);}

		clearTimeout(this._soundCompleteTimeout);
	};

	p._resume = function () {
		this._handleSoundReady();
	};

	/*
	p._handleStop = function () {
		// web audio does not need to do anything extra
	};
	*/

	p._updateVolume = function () {
		var newVolume = this._muted ? 0 : this._volume;
	  	if (newVolume != this.gainNode.gain.value) {
		  this.gainNode.gain.value = newVolume;
  		}
	};

	p._calculateCurrentPosition = function () {
		return ((s.context.currentTime - this._playbackStartTime) * 1000); // pos in seconds * 1000 to give milliseconds
	};

	p._updatePosition = function () {
		this.sourceNode = this._cleanUpAudioNode(this.sourceNode);
		this._sourceNodeNext = this._cleanUpAudioNode(this._sourceNodeNext);
		clearTimeout(this._soundCompleteTimeout);

		if (!this._paused) {this._handleSoundReady();}
	};

	// OJR we are using a look ahead approach to ensure smooth looping.
	// We add _sourceNodeNext to the audio context so that it starts playing even if this callback is delayed.
	// This technique is described here:  http://www.html5rocks.com/en/tutorials/audio/scheduling/
	// NOTE the cost of this is that our audio loop may not always match the loop event timing precisely.
	p._handleLoop = function () {
		this._cleanUpAudioNode(this.sourceNode);
		this.sourceNode = this._sourceNodeNext;
		this._playbackStartTime = this.sourceNode.startTime;
		this._sourceNodeNext = this._createAndPlayAudioNode(this._playbackStartTime, 0);
		this._soundCompleteTimeout = setTimeout(this._endedHandler, this._duration);
	};

	p._updateDuration = function () {
		if(this.playState == createjs.Sound.PLAY_SUCCEEDED) {
			this._pause();
			this._resume();
		}
	};

	createjs.WebAudioSoundInstance = createjs.promote(WebAudioSoundInstance, "AbstractSoundInstance");
}());

//##############################################################################
// WebAudioPlugin.js
//##############################################################################

this.createjs = this.createjs || {};

(function () {

	"use strict";

	/**
	 * Play sounds using Web Audio in the browser. The WebAudioPlugin is currently the default plugin, and will be used
	 * anywhere that it is supported. To change plugin priority, check out the Sound API
	 * {{#crossLink "Sound/registerPlugins"}}{{/crossLink}} method.

	 * <h4>Known Browser and OS issues for Web Audio</h4>
	 * <b>Firefox 25</b>
	 * <li>
	 *     mp3 audio files do not load properly on all windows machines, reported <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=929969" target="_blank">here</a>.
	 *     <br />For this reason it is recommended to pass another FireFox-supported type (i.e. ogg) as the default
	 *     extension, until this bug is resolved
	 * </li>
	 *
	 * <b>Webkit (Chrome and Safari)</b>
	 * <li>
	 *     AudioNode.disconnect does not always seem to work.  This can cause the file size to grow over time if you
	 * 	   are playing a lot of audio files.
	 * </li>
	 *
	 * <b>iOS 6 limitations</b>
	 * <ul>
	 *     <li>
	 *         Sound is initially muted and will only unmute through play being called inside a user initiated event
	 *         (touch/click). Please read the mobile playback notes in the the {{#crossLink "Sound"}}{{/crossLink}}
	 *         class for a full overview of the limitations, and how to get around them.
	 *     </li>
	 *	   <li>
	 *	       A bug exists that will distort un-cached audio when a video element is present in the DOM. You can avoid
	 *	       this bug by ensuring the audio and video audio share the same sample rate.
	 *	   </li>
	 * </ul>
	 * @class WebAudioPlugin
	 * @extends AbstractPlugin
	 * @constructor
	 * @since 0.4.0
	 */
	function WebAudioPlugin() {
		this.AbstractPlugin_constructor();


// Private Properties
		/**
		 * Value to set panning model to equal power for WebAudioSoundInstance.  Can be "equalpower" or 0 depending on browser implementation.
		 * @property _panningModel
		 * @type {Number / String}
		 * @protected
		 */
		this._panningModel = s._panningModel;;

		/**
		 * The web audio context, which WebAudio uses to play audio. All nodes that interact with the WebAudioPlugin
		 * need to be created within this context.
		 * @property context
		 * @type {AudioContext}
		 */
		this.context = s.context;

		/**
		 * A DynamicsCompressorNode, which is used to improve sound quality and prevent audio distortion.
		 * It is connected to <code>context.destination</code>.
		 *
		 * Can be accessed by advanced users through createjs.Sound.activePlugin.dynamicsCompressorNode.
		 * @property dynamicsCompressorNode
		 * @type {AudioNode}
		 */
		this.dynamicsCompressorNode = this.context.createDynamicsCompressor();
		this.dynamicsCompressorNode.connect(this.context.destination);

		/**
		 * A GainNode for controlling master volume. It is connected to {{#crossLink "WebAudioPlugin/dynamicsCompressorNode:property"}}{{/crossLink}}.
		 *
		 * Can be accessed by advanced users through createjs.Sound.activePlugin.gainNode.
		 * @property gainNode
		 * @type {AudioGainNode}
		 */
		this.gainNode = this.context.createGain();
		this.gainNode.connect(this.dynamicsCompressorNode);
		createjs.WebAudioSoundInstance.destinationNode = this.gainNode;

		this._capabilities = s._capabilities;

		this._loaderClass = createjs.WebAudioLoader;
		this._soundInstanceClass = createjs.WebAudioSoundInstance;

		this._addPropsToClasses();
	}
	var p = createjs.extend(WebAudioPlugin, createjs.AbstractPlugin);

	// TODO: deprecated
	// p.initialize = function() {}; // searchable for devs wondering where it is. REMOVED. See docs for details.


// Static Properties
	var s = WebAudioPlugin;
	/**
	 * The capabilities of the plugin. This is generated via the {{#crossLink "WebAudioPlugin/_generateCapabilities:method"}}{{/crossLink}}
	 * method and is used internally.
	 * @property _capabilities
	 * @type {Object}
	 * @default null
	 * @protected
	 * @static
	 */
	s._capabilities = null;

	/**
	 * Value to set panning model to equal power for WebAudioSoundInstance.  Can be "equalpower" or 0 depending on browser implementation.
	 * @property _panningModel
	 * @type {Number / String}
	 * @protected
	 * @static
	 */
	s._panningModel = "equalpower";

	/**
	 * The web audio context, which WebAudio uses to play audio. All nodes that interact with the WebAudioPlugin
	 * need to be created within this context.
	 *
	 * Advanced users can set this to an existing context, but <b>must</b> do so before they call
	 * {{#crossLink "Sound/registerPlugins"}}{{/crossLink}} or {{#crossLink "Sound/initializeDefaultPlugins"}}{{/crossLink}}.
	 *
	 * @property context
	 * @type {AudioContext}
	 * @static
	 */
	s.context = null;

	/**
	 * The scratch buffer that will be assigned to the buffer property of a source node on close.
	 * Works around an iOS Safari bug: https://github.com/CreateJS/SoundJS/issues/102
	 *
	 * Advanced users can set this to an existing source node, but <b>must</b> do so before they call
	 * {{#crossLink "Sound/registerPlugins"}}{{/crossLink}} or {{#crossLink "Sound/initializeDefaultPlugins"}}{{/crossLink}}.
	 *
	 * @property _scratchBuffer
	 * @type {AudioBuffer}
	 * @protected
	 * @static
	 */
	 s._scratchBuffer = null;

	/**
	 * Indicated whether audio on iOS has been unlocked, which requires a touchend/mousedown event that plays an
	 * empty sound.
	 * @property _unlocked
	 * @type {boolean}
	 * @since 0.6.2
	 * @private
	 */
	s._unlocked = false;


// Static Public Methods
	/**
	 * Determine if the plugin can be used in the current browser/OS.
	 * @method isSupported
	 * @return {Boolean} If the plugin can be initialized.
	 * @static
	 */
	s.isSupported = function () {
		// check if this is some kind of mobile device, Web Audio works with local protocol under PhoneGap and it is unlikely someone is trying to run a local file
		var isMobilePhoneGap = createjs.BrowserDetect.isIOS || createjs.BrowserDetect.isAndroid || createjs.BrowserDetect.isBlackberry;
		// OJR isMobile may be redundant with _isFileXHRSupported available.  Consider removing.
		if (location.protocol == "file:" && !isMobilePhoneGap && !this._isFileXHRSupported()) { return false; }  // Web Audio requires XHR, which is not usually available locally
		s._generateCapabilities();
		if (s.context == null) {return false;}
		return true;
	};

	/**
	 * Plays an empty sound in the web audio context.  This is used to enable web audio on iOS devices, as they
	 * require the first sound to be played inside of a user initiated event (touch/click).  This is called when
	 * {{#crossLink "WebAudioPlugin"}}{{/crossLink}} is initialized (by Sound {{#crossLink "Sound/initializeDefaultPlugins"}}{{/crossLink}}
	 * for example).
	 *
	 * <h4>Example</h4>
	 *
	 *     function handleTouch(event) {
	 *         createjs.WebAudioPlugin.playEmptySound();
	 *     }
	 *
	 * @method playEmptySound
	 * @static
	 * @since 0.4.1
	 */
	s.playEmptySound = function() {
		if (s.context == null) {return;}
		var source = s.context.createBufferSource();
		source.buffer = s._scratchBuffer;
		source.connect(s.context.destination);
		source.start(0, 0, 0);
	};


// Static Private Methods
	/**
	 * Determine if XHR is supported, which is necessary for web audio.
	 * @method _isFileXHRSupported
	 * @return {Boolean} If XHR is supported.
	 * @since 0.4.2
	 * @protected
	 * @static
	 */
	s._isFileXHRSupported = function() {
		// it's much easier to detect when something goes wrong, so let's start optimistically
		var supported = true;

		var xhr = new XMLHttpRequest();
		try {
			xhr.open("GET", "WebAudioPluginTest.fail", false); // loading non-existant file triggers 404 only if it could load (synchronous call)
		} catch (error) {
			// catch errors in cases where the onerror is passed by
			supported = false;
			return supported;
		}
		xhr.onerror = function() { supported = false; }; // cause irrelevant
		// with security turned off, we can get empty success results, which is actually a failed read (status code 0?)
		xhr.onload = function() { supported = this.status == 404 || (this.status == 200 || (this.status == 0 && this.response != "")); };
		try {
			xhr.send();
		} catch (error) {
			// catch errors in cases where the onerror is passed by
			supported = false;
		}

		return supported;
	};

	/**
	 * Determine the capabilities of the plugin. Used internally. Please see the Sound API {{#crossLink "Sound/getCapabilities"}}{{/crossLink}}
	 * method for an overview of plugin capabilities.
	 * @method _generateCapabilities
	 * @static
	 * @protected
	 */
	s._generateCapabilities = function () {
		if (s._capabilities != null) {return;}
		// Web Audio can be in any formats supported by the audio element, from http://www.w3.org/TR/webaudio/#AudioContext-section
		var t = document.createElement("audio");
		if (t.canPlayType == null) {return null;}

		if (s.context == null) {
			if (window.AudioContext) {
				s.context = new AudioContext();
			} else if (window.webkitAudioContext) {
				s.context = new webkitAudioContext();
			} else {
				return null;
			}
		}
		if (s._scratchBuffer == null) {
			s._scratchBuffer = s.context.createBuffer(1, 1, 22050);
		}

		s._compatibilitySetUp();

		// Listen for document level clicks to unlock WebAudio on iOS. See the _unlock method.
		if ("ontouchstart" in window && s.context.state != "running") {
			s._unlock(); // When played inside of a touch event, this will enable audio on iOS immediately.
			document.addEventListener("mousedown", s._unlock, true);
			document.addEventListener("touchend", s._unlock, true);
		}


		s._capabilities = {
			panning:true,
			volume:true,
			tracks:-1
		};

		// determine which extensions our browser supports for this plugin by iterating through Sound.SUPPORTED_EXTENSIONS
		var supportedExtensions = createjs.Sound.SUPPORTED_EXTENSIONS;
		var extensionMap = createjs.Sound.EXTENSION_MAP;
		for (var i = 0, l = supportedExtensions.length; i < l; i++) {
			var ext = supportedExtensions[i];
			var playType = extensionMap[ext] || ext;
			s._capabilities[ext] = (t.canPlayType("audio/" + ext) != "no" && t.canPlayType("audio/" + ext) != "") || (t.canPlayType("audio/" + playType) != "no" && t.canPlayType("audio/" + playType) != "");
		}  // OJR another way to do this might be canPlayType:"m4a", codex: mp4

		// 0=no output, 1=mono, 2=stereo, 4=surround, 6=5.1 surround.
		// See http://www.w3.org/TR/webaudio/#AudioChannelSplitter for more details on channels.
		if (s.context.destination.numberOfChannels < 2) {
			s._capabilities.panning = false;
		}
	};

	/**
	 * Set up compatibility if only deprecated web audio calls are supported.
	 * See http://www.w3.org/TR/webaudio/#DeprecationNotes
	 * Needed so we can support new browsers that don't support deprecated calls (Firefox) as well as old browsers that
	 * don't support new calls.
	 *
	 * @method _compatibilitySetUp
	 * @static
	 * @protected
	 * @since 0.4.2
	 */
	s._compatibilitySetUp = function() {
		s._panningModel = "equalpower";
		//assume that if one new call is supported, they all are
		if (s.context.createGain) { return; }

		// simple name change, functionality the same
		s.context.createGain = s.context.createGainNode;

		// source node, add to prototype
		var audioNode = s.context.createBufferSource();
		audioNode.__proto__.start = audioNode.__proto__.noteGrainOn;	// note that noteGrainOn requires all 3 parameters
		audioNode.__proto__.stop = audioNode.__proto__.noteOff;

		// panningModel
		s._panningModel = 0;
	};

	/**
	 * Try to unlock audio on iOS. This is triggered from either WebAudio plugin setup (which will work if inside of
	 * a `mousedown` or `touchend` event stack), or the first document touchend/mousedown event. If it fails (touchend
	 * will fail if the user presses for too long, indicating a scroll event instead of a click event.
	 *
	 * Note that earlier versions of iOS supported `touchstart` for this, but iOS9 removed this functionality. Adding
	 * a `touchstart` event to support older platforms may preclude a `mousedown` even from getting fired on iOS9, so we
	 * stick with `mousedown` and `touchend`.
	 * @method _unlock
	 * @since 0.6.2
	 * @private
	 */
	s._unlock = function() {
		if (s._unlocked) { return; }
		s.playEmptySound();
		if (s.context.state == "running") {
			document.removeEventListener("mousedown", s._unlock, true);
			document.removeEventListener("touchend", s._unlock, true);
			s._unlocked = true;
		}
	};


// Public Methods
	p.toString = function () {
		return "[WebAudioPlugin]";
	};


// Private Methods
	/**
	 * Set up needed properties on supported classes WebAudioSoundInstance and WebAudioLoader.
	 * @method _addPropsToClasses
	 * @static
	 * @protected
	 * @since 0.6.0
	 */
	p._addPropsToClasses = function() {
		var c = this._soundInstanceClass;
		c.context = this.context;
		c._scratchBuffer = s._scratchBuffer;
		c.destinationNode = this.gainNode;
		c._panningModel = this._panningModel;

		this._loaderClass.context = this.context;
	};


	/**
	 * Set the gain value for master audio. Should not be called externally.
	 * @method _updateVolume
	 * @protected
	 */
	p._updateVolume = function () {
		var newVolume = createjs.Sound._masterMute ? 0 : this._volume;
		if (newVolume != this.gainNode.gain.value) {
			this.gainNode.gain.value = newVolume;
		}
	};

	createjs.WebAudioPlugin = createjs.promote(WebAudioPlugin, "AbstractPlugin");
}());

//##############################################################################
// HTMLAudioTagPool.js
//##############################################################################

this.createjs = this.createjs || {};

(function () {
	"use strict";

	/**
	 * HTMLAudioTagPool is an object pool for HTMLAudio tag instances.
	 * @class HTMLAudioTagPool
	 * @param {String} src The source of the channel.
	 * @protected
	 */
	function HTMLAudioTagPool() {
			throw "HTMLAudioTagPool cannot be instantiated";
	}

	var s = HTMLAudioTagPool;

// Static Properties
	/**
	 * A hash lookup of each base audio tag, indexed by the audio source.
	 * @property _tags
	 * @type {{}}
	 * @static
	 * @protected
	 */
	s._tags = {};

	/**
	 * An object pool for html audio tags
	 * @property _tagPool
	 * @type {TagPool}
	 * @static
	 * @protected
	 */
	s._tagPool = new TagPool();

	/**
	 * A hash lookup of if a base audio tag is available, indexed by the audio source
	 * @property _tagsUsed
	 * @type {{}}
	 * @protected
	 * @static
	 */
	s._tagUsed = {};

// Static Methods
	/**
	  * Get an audio tag with the given source.
	  * @method get
	  * @param {String} src The source file used by the audio tag.
	  * @static
	  */
	 s.get = function (src) {
		var t = s._tags[src];
		if (t == null) {
			// create new base tag
			t = s._tags[src] = s._tagPool.get();
			t.src = src;
		} else {
			// get base or pool
			if (s._tagUsed[src]) {
				t = s._tagPool.get();
				t.src = src;
			} else {
				s._tagUsed[src] = true;
			}
		}
		return t;
	 };

	 /**
	  * Return an audio tag to the pool.
	  * @method set
	  * @param {String} src The source file used by the audio tag.
	  * @param {HTMLElement} tag Audio tag to set.
	  * @static
	  */
	 s.set = function (src, tag) {
		 // check if this is base, if yes set boolean if not return to pool
		 if(tag == s._tags[src]) {
			 s._tagUsed[src] = false;
		 } else {
			 s._tagPool.set(tag);
		 }
	 };

	/**
	 * Delete stored tag reference and return them to pool. Note that if the tag reference does not exist, this will fail.
	 * @method remove
	 * @param {String} src The source for the tag
	 * @return {Boolean} If the TagPool was deleted.
	 * @static
	 */
	s.remove = function (src) {
		var tag = s._tags[src];
		if (tag == null) {return false;}
		s._tagPool.set(tag);
		delete(s._tags[src]);
		delete(s._tagUsed[src]);
		return true;
	};

	/**
	 * Gets the duration of the src audio in milliseconds
	 * @method getDuration
	 * @param {String} src The source file used by the audio tag.
	 * @return {Number} Duration of src in milliseconds
	 * @static
	 */
	s.getDuration= function (src) {
		var t = s._tags[src];
		if (t == null || !t.duration) {return 0;}	// OJR duration is NaN if loading has not completed
		return t.duration * 1000;
	};

	createjs.HTMLAudioTagPool = HTMLAudioTagPool;


// ************************************************************************************************************
	/**
	 * The TagPool is an object pool for HTMLAudio tag instances.
	 * #class TagPool
	 * @param {String} src The source of the channel.
	 * @protected
	 */
	function TagPool(src) {

// Public Properties
		/**
		 * A list of all available tags in the pool.
		 * #property tags
		 * @type {Array}
		 * @protected
		 */
		this._tags = [];
	};

	var p = TagPool.prototype;
	p.constructor = TagPool;


// Public Methods
	/**
	 * Get an HTMLAudioElement for immediate playback. This takes it out of the pool.
	 * #method get
	 * @return {HTMLAudioElement} An HTML audio tag.
	 */
	p.get = function () {
		var tag;
		if (this._tags.length == 0) {
			tag = this._createTag();
		} else {
			tag = this._tags.pop();
		}
		if (tag.parentNode == null) {document.body.appendChild(tag);}
		return tag;
	};

	/**
	 * Put an HTMLAudioElement back in the pool for use.
	 * #method set
	 * @param {HTMLAudioElement} tag HTML audio tag
	 */
	p.set = function (tag) {
		// OJR this first step seems unnecessary
		var index = createjs.indexOf(this._tags, tag);
		if (index == -1) {
			this._tags.src = null;
			this._tags.push(tag);
		}
	};

	p.toString = function () {
		return "[TagPool]";
	};


// Private Methods
	/**
	 * Create an HTML audio tag.
	 * #method _createTag
	 * @param {String} src The source file to set for the audio tag.
	 * @return {HTMLElement} Returns an HTML audio tag.
	 * @protected
	 */
	p._createTag = function () {
		var tag = document.createElement("audio");
		tag.autoplay = false;
		tag.preload = "none";
		//LM: Firefox fails when this the preload="none" for other tags, but it needs to be "none" to ensure PreloadJS works.
		return tag;
	};

}());

//##############################################################################
// HTMLAudioSoundInstance.js
//##############################################################################

this.createjs = this.createjs || {};

(function () {
	"use strict";

	/**
	 * HTMLAudioSoundInstance extends the base api of {{#crossLink "AbstractSoundInstance"}}{{/crossLink}} and is used by
	 * {{#crossLink "HTMLAudioPlugin"}}{{/crossLink}}.
	 *
	 * @param {String} src The path to and file name of the sound.
	 * @param {Number} startTime Audio sprite property used to apply an offset, in milliseconds.
	 * @param {Number} duration Audio sprite property used to set the time the clip plays for, in milliseconds.
	 * @param {Object} playbackResource Any resource needed by plugin to support audio playback.
	 * @class HTMLAudioSoundInstance
	 * @extends AbstractSoundInstance
	 * @constructor
	 */
	function HTMLAudioSoundInstance(src, startTime, duration, playbackResource) {
		this.AbstractSoundInstance_constructor(src, startTime, duration, playbackResource);


// Private Properties
		this._audioSpriteStopTime = null;
		this._delayTimeoutId = null;

		// Proxies, make removing listeners easier.
		this._endedHandler = createjs.proxy(this._handleSoundComplete, this);
		this._readyHandler = createjs.proxy(this._handleTagReady, this);
		this._stalledHandler = createjs.proxy(this._playFailed, this);
		this._audioSpriteEndHandler = createjs.proxy(this._handleAudioSpriteLoop, this);
		this._loopHandler = createjs.proxy(this._handleSoundComplete, this);

		if (duration) {
			this._audioSpriteStopTime = (startTime + duration) * 0.001;
		} else {
			this._duration = createjs.HTMLAudioTagPool.getDuration(this.src);
		}
	}
	var p = createjs.extend(HTMLAudioSoundInstance, createjs.AbstractSoundInstance);

	// TODO: deprecated
	// p.initialize = function() {}; // searchable for devs wondering where it is. REMOVED. See docs for details.


// Public Methods
	/**
	 * Called by {{#crossLink "Sound"}}{{/crossLink}} when plugin does not handle master volume.
	 * undoc'd because it is not meant to be used outside of Sound
	 * #method setMasterVolume
	 * @param value
	 */
	p.setMasterVolume = function (value) {
		this._updateVolume();
	};

	/**
	 * Called by {{#crossLink "Sound"}}{{/crossLink}} when plugin does not handle master mute.
	 * undoc'd because it is not meant to be used outside of Sound
	 * #method setMasterMute
	 * @param value
	 */
	p.setMasterMute = function (isMuted) {
		this._updateVolume();
	};

	p.toString = function () {
		return "[HTMLAudioSoundInstance]";
	};

//Private Methods
	p._removeLooping = function() {
		if(this._playbackResource == null) {return;}
		this._playbackResource.loop = false;
		this._playbackResource.removeEventListener(createjs.HTMLAudioPlugin._AUDIO_SEEKED, this._loopHandler, false);
	};

	p._addLooping = function() {
		if(this._playbackResource == null  || this._audioSpriteStopTime) {return;}
		this._playbackResource.addEventListener(createjs.HTMLAudioPlugin._AUDIO_SEEKED, this._loopHandler, false);
		this._playbackResource.loop = true;
	};

	p._handleCleanUp = function () {
		var tag = this._playbackResource;
		if (tag != null) {
			tag.pause();
			tag.loop = false;
			tag.removeEventListener(createjs.HTMLAudioPlugin._AUDIO_ENDED, this._endedHandler, false);
			tag.removeEventListener(createjs.HTMLAudioPlugin._AUDIO_READY, this._readyHandler, false);
			tag.removeEventListener(createjs.HTMLAudioPlugin._AUDIO_STALLED, this._stalledHandler, false);
			tag.removeEventListener(createjs.HTMLAudioPlugin._AUDIO_SEEKED, this._loopHandler, false);
			tag.removeEventListener(createjs.HTMLAudioPlugin._TIME_UPDATE, this._audioSpriteEndHandler, false);

			try {
				tag.currentTime = this._startTime;
			} catch (e) {
			} // Reset Position
			createjs.HTMLAudioTagPool.set(this.src, tag);
			this._playbackResource = null;
		}
	};

	p._beginPlaying = function (playProps) {
		this._playbackResource = createjs.HTMLAudioTagPool.get(this.src);
		return this.AbstractSoundInstance__beginPlaying(playProps);
	};

	p._handleSoundReady = function (event) {
		if (this._playbackResource.readyState !== 4) {
			var tag = this._playbackResource;
			tag.addEventListener(createjs.HTMLAudioPlugin._AUDIO_READY, this._readyHandler, false);
			tag.addEventListener(createjs.HTMLAudioPlugin._AUDIO_STALLED, this._stalledHandler, false);
			tag.preload = "auto"; // This is necessary for Firefox, as it won't ever "load" until this is set.
			tag.load();
			return;
		}

		this._updateVolume();
		this._playbackResource.currentTime = (this._startTime + this._position) * 0.001;
		if (this._audioSpriteStopTime) {
			this._playbackResource.addEventListener(createjs.HTMLAudioPlugin._TIME_UPDATE, this._audioSpriteEndHandler, false);
		} else {
			this._playbackResource.addEventListener(createjs.HTMLAudioPlugin._AUDIO_ENDED, this._endedHandler, false);
			if(this._loop != 0) {
				this._playbackResource.addEventListener(createjs.HTMLAudioPlugin._AUDIO_SEEKED, this._loopHandler, false);
				this._playbackResource.loop = true;
			}
		}

		this._playbackResource.play();
	};

	/**
	 * Used to handle when a tag is not ready for immediate playback when it is returned from the HTMLAudioTagPool.
	 * @method _handleTagReady
	 * @param event
	 * @protected
	 */
	p._handleTagReady = function (event) {
		this._playbackResource.removeEventListener(createjs.HTMLAudioPlugin._AUDIO_READY, this._readyHandler, false);
		this._playbackResource.removeEventListener(createjs.HTMLAudioPlugin._AUDIO_STALLED, this._stalledHandler, false);

		this._handleSoundReady();
	};

	p._pause = function () {
		this._playbackResource.pause();
	};

	p._resume = function () {
		this._playbackResource.play();
	};

	p._updateVolume = function () {
		if (this._playbackResource != null) {
			var newVolume = (this._muted || createjs.Sound._masterMute) ? 0 : this._volume * createjs.Sound._masterVolume;
			if (newVolume != this._playbackResource.volume) {this._playbackResource.volume = newVolume;}
		}
	};

	p._calculateCurrentPosition = function() {
		return (this._playbackResource.currentTime * 1000) - this._startTime;
	};

	p._updatePosition = function() {
		this._playbackResource.removeEventListener(createjs.HTMLAudioPlugin._AUDIO_SEEKED, this._loopHandler, false);
		this._playbackResource.addEventListener(createjs.HTMLAudioPlugin._AUDIO_SEEKED, this._handleSetPositionSeek, false);
		try {
			this._playbackResource.currentTime = (this._position + this._startTime) * 0.001;
		} catch (error) { // Out of range
			this._handleSetPositionSeek(null);
		}
	};

	/**
	 * Used to enable setting position, as we need to wait for that seek to be done before we add back our loop handling seek listener
	 * @method _handleSetPositionSeek
	 * @param event
	 * @protected
	 */
	p._handleSetPositionSeek = function(event) {
		if (this._playbackResource == null) { return; }
		this._playbackResource.removeEventListener(createjs.HTMLAudioPlugin._AUDIO_SEEKED, this._handleSetPositionSeek, false);
		this._playbackResource.addEventListener(createjs.HTMLAudioPlugin._AUDIO_SEEKED, this._loopHandler, false);
	};

	/**
	 * Timer used to loop audio sprites.
	 * NOTE because of the inaccuracies in the timeupdate event (15 - 250ms) and in setting the tag to the desired timed
	 * (up to 300ms), it is strongly recommended not to loop audio sprites with HTML Audio if smooth looping is desired
	 *
	 * @method _handleAudioSpriteLoop
	 * @param event
	 * @private
	 */
	p._handleAudioSpriteLoop = function (event) {
		if(this._playbackResource.currentTime <= this._audioSpriteStopTime) {return;}
		this._playbackResource.pause();
		if(this._loop == 0) {
			this._handleSoundComplete(null);
		} else {
			this._position = 0;
			this._loop--;
			this._playbackResource.currentTime = this._startTime * 0.001;
			if(!this._paused) {this._playbackResource.play();}
			this._sendEvent("loop");
		}
	};

	// NOTE with this approach audio will loop as reliably as the browser allows
	// but we could end up sending the loop event after next loop playback begins
	p._handleLoop = function (event) {
		if(this._loop == 0) {
			this._playbackResource.loop = false;
			this._playbackResource.removeEventListener(createjs.HTMLAudioPlugin._AUDIO_SEEKED, this._loopHandler, false);
		}
	};

	p._updateStartTime = function () {
		this._audioSpriteStopTime = (this._startTime + this._duration) * 0.001;

		if(this.playState == createjs.Sound.PLAY_SUCCEEDED) {
			this._playbackResource.removeEventListener(createjs.HTMLAudioPlugin._AUDIO_ENDED, this._endedHandler, false);
			this._playbackResource.addEventListener(createjs.HTMLAudioPlugin._TIME_UPDATE, this._audioSpriteEndHandler, false);
		}
	};

	p._updateDuration = function () {
		this._audioSpriteStopTime = (this._startTime + this._duration) * 0.001;

		if(this.playState == createjs.Sound.PLAY_SUCCEEDED) {
			this._playbackResource.removeEventListener(createjs.HTMLAudioPlugin._AUDIO_ENDED, this._endedHandler, false);
			this._playbackResource.addEventListener(createjs.HTMLAudioPlugin._TIME_UPDATE, this._audioSpriteEndHandler, false);
		}
	};

	p._setDurationFromSource = function () {
		this._duration = createjs.HTMLAudioTagPool.getDuration(this.src);
		this._playbackResource = null;
	};

	createjs.HTMLAudioSoundInstance = createjs.promote(HTMLAudioSoundInstance, "AbstractSoundInstance");
}());

//##############################################################################
// HTMLAudioPlugin.js
//##############################################################################

this.createjs = this.createjs || {};

(function () {

	"use strict";

	/**
	 * Play sounds using HTML &lt;audio&gt; tags in the browser. This plugin is the second priority plugin installed
	 * by default, after the {{#crossLink "WebAudioPlugin"}}{{/crossLink}}.  For older browsers that do not support html
	 * audio, include and install the {{#crossLink "FlashAudioPlugin"}}{{/crossLink}}.
	 *
	 * <h4>Known Browser and OS issues for HTML Audio</h4>
	 * <b>All browsers</b><br />
	 * Testing has shown in all browsers there is a limit to how many audio tag instances you are allowed.  If you exceed
	 * this limit, you can expect to see unpredictable results. Please use {{#crossLink "Sound.MAX_INSTANCES"}}{{/crossLink}} as
	 * a guide to how many total audio tags you can safely use in all browsers.  This issue is primarily limited to IE9.
	 *
     * <b>IE html limitations</b><br />
     * <ul><li>There is a delay in applying volume changes to tags that occurs once playback is started. So if you have
     * muted all sounds, they will all play during this delay until the mute applies internally. This happens regardless of
     * when or how you apply the volume change, as the tag seems to need to play to apply it.</li>
     * <li>MP3 encoding will not always work for audio tags if it's not default.  We've found default encoding with
     * 64kbps works.</li>
	 * <li>Occasionally very short samples will get cut off.</li>
	 * <li>There is a limit to how many audio tags you can load or play at once, which appears to be determined by
	 * hardware and browser settings.  See {{#crossLink "HTMLAudioPlugin.MAX_INSTANCES"}}{{/crossLink}} for a safe estimate.
	 * Note that audio sprites can be used as a solution to this issue.</li></ul>
	 *
	 * <b>Safari limitations</b><br />
	 * <ul><li>Safari requires Quicktime to be installed for audio playback.</li></ul>
	 *
	 * <b>iOS 6 limitations</b><br />
	 * <ul><li>can only have one &lt;audio&gt; tag</li>
	 * 		<li>can not preload or autoplay the audio</li>
	 * 		<li>can not cache the audio</li>
	 * 		<li>can not play the audio except inside a user initiated event.</li>
	 *		<li>Note it is recommended to use {{#crossLink "WebAudioPlugin"}}{{/crossLink}} for iOS (6+)</li>
	 * 		<li>audio sprites can be used to mitigate some of these issues and are strongly recommended on iOS</li>
	 * </ul>
	 *
	 * <b>Android Native Browser limitations</b><br />
	 * <ul><li>We have no control over audio volume. Only the user can set volume on their device.</li>
	 *      <li>We can only play audio inside a user event (touch/click).  This currently means you cannot loop sound or use a delay.</li></ul>
	 * <b> Android Chrome 26.0.1410.58 specific limitations</b><br />
	 * <ul> <li>Can only play 1 sound at a time.</li>
	 *      <li>Sound is not cached.</li>
	 *      <li>Sound can only be loaded in a user initiated touch/click event.</li>
	 *      <li>There is a delay before a sound is played, presumably while the src is loaded.</li>
	 * </ul>
	 *
	 * See {{#crossLink "Sound"}}{{/crossLink}} for general notes on known issues.
	 *
	 * @class HTMLAudioPlugin
	 * @extends AbstractPlugin
	 * @constructor
	 */
	function HTMLAudioPlugin() {
		this.AbstractPlugin_constructor();


	// Public Properties
		/**
		 * This is no longer needed as we are now using object pooling for tags.
		 *
		 * <b>NOTE this property only exists as a limitation of HTML audio.</b>
		 * @property defaultNumChannels
		 * @type {Number}
		 * @default 2
		 * @since 0.4.0
		 * @deprecated
		 */
		this.defaultNumChannels = 2;

		this._capabilities = s._capabilities;

		this._loaderClass = createjs.SoundLoader;
		this._soundInstanceClass = createjs.HTMLAudioSoundInstance;
	}

	var p = createjs.extend(HTMLAudioPlugin, createjs.AbstractPlugin);
	var s = HTMLAudioPlugin;

	// TODO: deprecated
	// p.initialize = function() {}; // searchable for devs wondering where it is. REMOVED. See docs for details.


// Static Properties
	/**
	 * The maximum number of instances that can be loaded or played. This is a browser limitation, primarily limited to IE9.
	 * The actual number varies from browser to browser (and is largely hardware dependant), but this is a safe estimate.
	 * Audio sprites work around this limitation.
	 * @property MAX_INSTANCES
	 * @type {Number}
	 * @default 30
	 * @static
	 */
	s.MAX_INSTANCES = 30;

	/**
	 * Event constant for the "canPlayThrough" event for cleaner code.
	 * @property _AUDIO_READY
	 * @type {String}
	 * @default canplaythrough
	 * @static
	 * @protected
	 */
	s._AUDIO_READY = "canplaythrough";

	/**
	 * Event constant for the "ended" event for cleaner code.
	 * @property _AUDIO_ENDED
	 * @type {String}
	 * @default ended
	 * @static
	 * @protected
	 */
	s._AUDIO_ENDED = "ended";

	/**
	 * Event constant for the "seeked" event for cleaner code.  We utilize this event for maintaining loop events.
	 * @property _AUDIO_SEEKED
	 * @type {String}
	 * @default seeked
	 * @static
	 * @protected
	 */
	s._AUDIO_SEEKED = "seeked";

	/**
	 * Event constant for the "stalled" event for cleaner code.
	 * @property _AUDIO_STALLED
	 * @type {String}
	 * @default stalled
	 * @static
	 * @protected
	 */
	s._AUDIO_STALLED = "stalled";

	/**
	 * Event constant for the "timeupdate" event for cleaner code.  Utilized for looping audio sprites.
	 * This event callsback ever 15 to 250ms and can be dropped by the browser for performance.
	 * @property _TIME_UPDATE
	 * @type {String}
	 * @default timeupdate
	 * @static
	 * @protected
	 */
	s._TIME_UPDATE = "timeupdate";

	/**
	 * The capabilities of the plugin. This is generated via the {{#crossLink "HTMLAudioPlugin/_generateCapabilities"}}{{/crossLink}}
	 * method. Please see the Sound {{#crossLink "Sound/getCapabilities"}}{{/crossLink}} method for an overview of all
	 * of the available properties.
	 * @property _capabilities
	 * @type {Object}
	 * @protected
	 * @static
	 */
	s._capabilities = null;


// Static Methods
	/**
	 * Determine if the plugin can be used in the current browser/OS. Note that HTML audio is available in most modern
	 * browsers, but is disabled in iOS because of its limitations.
	 * @method isSupported
	 * @return {Boolean} If the plugin can be initialized.
	 * @static
	 */
	s.isSupported = function () {
		s._generateCapabilities();
		return (s._capabilities != null);
	};

	/**
	 * Determine the capabilities of the plugin. Used internally. Please see the Sound API {{#crossLink "Sound/getCapabilities"}}{{/crossLink}}
	 * method for an overview of plugin capabilities.
	 * @method _generateCapabilities
	 * @static
	 * @protected
	 */
	s._generateCapabilities = function () {
		if (s._capabilities != null) {return;}
		var t = document.createElement("audio");
		if (t.canPlayType == null) {return null;}

		s._capabilities = {
			panning:false,
			volume:true,
			tracks:-1
		};

		// determine which extensions our browser supports for this plugin by iterating through Sound.SUPPORTED_EXTENSIONS
		var supportedExtensions = createjs.Sound.SUPPORTED_EXTENSIONS;
		var extensionMap = createjs.Sound.EXTENSION_MAP;
		for (var i = 0, l = supportedExtensions.length; i < l; i++) {
			var ext = supportedExtensions[i];
			var playType = extensionMap[ext] || ext;
			s._capabilities[ext] = (t.canPlayType("audio/" + ext) != "no" && t.canPlayType("audio/" + ext) != "") || (t.canPlayType("audio/" + playType) != "no" && t.canPlayType("audio/" + playType) != "");
		}  // OJR another way to do this might be canPlayType:"m4a", codex: mp4
	};


// public methods
	p.register = function (loadItem) {
		var tag = createjs.HTMLAudioTagPool.get(loadItem.src);
		var loader = this.AbstractPlugin_register(loadItem);
		loader.setTag(tag);

		return loader;
	};

	p.removeSound = function (src) {
		this.AbstractPlugin_removeSound(src);
		createjs.HTMLAudioTagPool.remove(src);
	};

	p.create = function (src, startTime, duration) {
		var si = this.AbstractPlugin_create(src, startTime, duration);
		si.setPlaybackResource(null);
		return si;
	};

	p.toString = function () {
		return "[HTMLAudioPlugin]";
	};

	// plugin does not support these
	p.setVolume = p.getVolume = p.setMute = null;


	createjs.HTMLAudioPlugin = createjs.promote(HTMLAudioPlugin, "AbstractPlugin");
}());
(function() {

    var debug = false;

    var root = this;

    var EXIF = function(obj) {
        if (obj instanceof EXIF) return obj;
        if (!(this instanceof EXIF)) return new EXIF(obj);
        this.EXIFwrapped = obj;
    };

    if (typeof exports !== 'undefined') {
        if (typeof module !== 'undefined' && module.exports) {
            exports = module.exports = EXIF;
        }
        exports.EXIF = EXIF;
    } else {
        root.EXIF = EXIF;
    }

    var ExifTags = EXIF.Tags = {

        // version tags
        0x9000 : "ExifVersion",             // EXIF version
        0xA000 : "FlashpixVersion",         // Flashpix format version

        // colorspace tags
        0xA001 : "ColorSpace",              // Color space information tag

        // image configuration
        0xA002 : "PixelXDimension",         // Valid width of meaningful image
        0xA003 : "PixelYDimension",         // Valid height of meaningful image
        0x9101 : "ComponentsConfiguration", // Information about channels
        0x9102 : "CompressedBitsPerPixel",  // Compressed bits per pixel

        // user information
        0x927C : "MakerNote",               // Any desired information written by the manufacturer
        0x9286 : "UserComment",             // Comments by user

        // related file
        0xA004 : "RelatedSoundFile",        // Name of related sound file

        // date and time
        0x9003 : "DateTimeOriginal",        // Date and time when the original image was generated
        0x9004 : "DateTimeDigitized",       // Date and time when the image was stored digitally
        0x9290 : "SubsecTime",              // Fractions of seconds for DateTime
        0x9291 : "SubsecTimeOriginal",      // Fractions of seconds for DateTimeOriginal
        0x9292 : "SubsecTimeDigitized",     // Fractions of seconds for DateTimeDigitized

        // picture-taking conditions
        0x829A : "ExposureTime",            // Exposure time (in seconds)
        0x829D : "FNumber",                 // F number
        0x8822 : "ExposureProgram",         // Exposure program
        0x8824 : "SpectralSensitivity",     // Spectral sensitivity
        0x8827 : "ISOSpeedRatings",         // ISO speed rating
        0x8828 : "OECF",                    // Optoelectric conversion factor
        0x9201 : "ShutterSpeedValue",       // Shutter speed
        0x9202 : "ApertureValue",           // Lens aperture
        0x9203 : "BrightnessValue",         // Value of brightness
        0x9204 : "ExposureBias",            // Exposure bias
        0x9205 : "MaxApertureValue",        // Smallest F number of lens
        0x9206 : "SubjectDistance",         // Distance to subject in meters
        0x9207 : "MeteringMode",            // Metering mode
        0x9208 : "LightSource",             // Kind of light source
        0x9209 : "Flash",                   // Flash status
        0x9214 : "SubjectArea",             // Location and area of main subject
        0x920A : "FocalLength",             // Focal length of the lens in mm
        0xA20B : "FlashEnergy",             // Strobe energy in BCPS
        0xA20C : "SpatialFrequencyResponse",    //
        0xA20E : "FocalPlaneXResolution",   // Number of pixels in width direction per FocalPlaneResolutionUnit
        0xA20F : "FocalPlaneYResolution",   // Number of pixels in height direction per FocalPlaneResolutionUnit
        0xA210 : "FocalPlaneResolutionUnit",    // Unit for measuring FocalPlaneXResolution and FocalPlaneYResolution
        0xA214 : "SubjectLocation",         // Location of subject in image
        0xA215 : "ExposureIndex",           // Exposure index selected on camera
        0xA217 : "SensingMethod",           // Image sensor type
        0xA300 : "FileSource",              // Image source (3 == DSC)
        0xA301 : "SceneType",               // Scene type (1 == directly photographed)
        0xA302 : "CFAPattern",              // Color filter array geometric pattern
        0xA401 : "CustomRendered",          // Special processing
        0xA402 : "ExposureMode",            // Exposure mode
        0xA403 : "WhiteBalance",            // 1 = auto white balance, 2 = manual
        0xA404 : "DigitalZoomRation",       // Digital zoom ratio
        0xA405 : "FocalLengthIn35mmFilm",   // Equivalent foacl length assuming 35mm film camera (in mm)
        0xA406 : "SceneCaptureType",        // Type of scene
        0xA407 : "GainControl",             // Degree of overall image gain adjustment
        0xA408 : "Contrast",                // Direction of contrast processing applied by camera
        0xA409 : "Saturation",              // Direction of saturation processing applied by camera
        0xA40A : "Sharpness",               // Direction of sharpness processing applied by camera
        0xA40B : "DeviceSettingDescription",    //
        0xA40C : "SubjectDistanceRange",    // Distance to subject

        // other tags
        0xA005 : "InteroperabilityIFDPointer",
        0xA420 : "ImageUniqueID"            // Identifier assigned uniquely to each image
    };

    var TiffTags = EXIF.TiffTags = {
        0x0100 : "ImageWidth",
        0x0101 : "ImageHeight",
        0x8769 : "ExifIFDPointer",
        0x8825 : "GPSInfoIFDPointer",
        0xA005 : "InteroperabilityIFDPointer",
        0x0102 : "BitsPerSample",
        0x0103 : "Compression",
        0x0106 : "PhotometricInterpretation",
        0x0112 : "Orientation",
        0x0115 : "SamplesPerPixel",
        0x011C : "PlanarConfiguration",
        0x0212 : "YCbCrSubSampling",
        0x0213 : "YCbCrPositioning",
        0x011A : "XResolution",
        0x011B : "YResolution",
        0x0128 : "ResolutionUnit",
        0x0111 : "StripOffsets",
        0x0116 : "RowsPerStrip",
        0x0117 : "StripByteCounts",
        0x0201 : "JPEGInterchangeFormat",
        0x0202 : "JPEGInterchangeFormatLength",
        0x012D : "TransferFunction",
        0x013E : "WhitePoint",
        0x013F : "PrimaryChromaticities",
        0x0211 : "YCbCrCoefficients",
        0x0214 : "ReferenceBlackWhite",
        0x0132 : "DateTime",
        0x010E : "ImageDescription",
        0x010F : "Make",
        0x0110 : "Model",
        0x0131 : "Software",
        0x013B : "Artist",
        0x8298 : "Copyright"
    };

    var GPSTags = EXIF.GPSTags = {
        0x0000 : "GPSVersionID",
        0x0001 : "GPSLatitudeRef",
        0x0002 : "GPSLatitude",
        0x0003 : "GPSLongitudeRef",
        0x0004 : "GPSLongitude",
        0x0005 : "GPSAltitudeRef",
        0x0006 : "GPSAltitude",
        0x0007 : "GPSTimeStamp",
        0x0008 : "GPSSatellites",
        0x0009 : "GPSStatus",
        0x000A : "GPSMeasureMode",
        0x000B : "GPSDOP",
        0x000C : "GPSSpeedRef",
        0x000D : "GPSSpeed",
        0x000E : "GPSTrackRef",
        0x000F : "GPSTrack",
        0x0010 : "GPSImgDirectionRef",
        0x0011 : "GPSImgDirection",
        0x0012 : "GPSMapDatum",
        0x0013 : "GPSDestLatitudeRef",
        0x0014 : "GPSDestLatitude",
        0x0015 : "GPSDestLongitudeRef",
        0x0016 : "GPSDestLongitude",
        0x0017 : "GPSDestBearingRef",
        0x0018 : "GPSDestBearing",
        0x0019 : "GPSDestDistanceRef",
        0x001A : "GPSDestDistance",
        0x001B : "GPSProcessingMethod",
        0x001C : "GPSAreaInformation",
        0x001D : "GPSDateStamp",
        0x001E : "GPSDifferential"
    };

    var StringValues = EXIF.StringValues = {
        ExposureProgram : {
            0 : "Not defined",
            1 : "Manual",
            2 : "Normal program",
            3 : "Aperture priority",
            4 : "Shutter priority",
            5 : "Creative program",
            6 : "Action program",
            7 : "Portrait mode",
            8 : "Landscape mode"
        },
        MeteringMode : {
            0 : "Unknown",
            1 : "Average",
            2 : "CenterWeightedAverage",
            3 : "Spot",
            4 : "MultiSpot",
            5 : "Pattern",
            6 : "Partial",
            255 : "Other"
        },
        LightSource : {
            0 : "Unknown",
            1 : "Daylight",
            2 : "Fluorescent",
            3 : "Tungsten (incandescent light)",
            4 : "Flash",
            9 : "Fine weather",
            10 : "Cloudy weather",
            11 : "Shade",
            12 : "Daylight fluorescent (D 5700 - 7100K)",
            13 : "Day white fluorescent (N 4600 - 5400K)",
            14 : "Cool white fluorescent (W 3900 - 4500K)",
            15 : "White fluorescent (WW 3200 - 3700K)",
            17 : "Standard light A",
            18 : "Standard light B",
            19 : "Standard light C",
            20 : "D55",
            21 : "D65",
            22 : "D75",
            23 : "D50",
            24 : "ISO studio tungsten",
            255 : "Other"
        },
        Flash : {
            0x0000 : "Flash did not fire",
            0x0001 : "Flash fired",
            0x0005 : "Strobe return light not detected",
            0x0007 : "Strobe return light detected",
            0x0009 : "Flash fired, compulsory flash mode",
            0x000D : "Flash fired, compulsory flash mode, return light not detected",
            0x000F : "Flash fired, compulsory flash mode, return light detected",
            0x0010 : "Flash did not fire, compulsory flash mode",
            0x0018 : "Flash did not fire, auto mode",
            0x0019 : "Flash fired, auto mode",
            0x001D : "Flash fired, auto mode, return light not detected",
            0x001F : "Flash fired, auto mode, return light detected",
            0x0020 : "No flash function",
            0x0041 : "Flash fired, red-eye reduction mode",
            0x0045 : "Flash fired, red-eye reduction mode, return light not detected",
            0x0047 : "Flash fired, red-eye reduction mode, return light detected",
            0x0049 : "Flash fired, compulsory flash mode, red-eye reduction mode",
            0x004D : "Flash fired, compulsory flash mode, red-eye reduction mode, return light not detected",
            0x004F : "Flash fired, compulsory flash mode, red-eye reduction mode, return light detected",
            0x0059 : "Flash fired, auto mode, red-eye reduction mode",
            0x005D : "Flash fired, auto mode, return light not detected, red-eye reduction mode",
            0x005F : "Flash fired, auto mode, return light detected, red-eye reduction mode"
        },
        SensingMethod : {
            1 : "Not defined",
            2 : "One-chip color area sensor",
            3 : "Two-chip color area sensor",
            4 : "Three-chip color area sensor",
            5 : "Color sequential area sensor",
            7 : "Trilinear sensor",
            8 : "Color sequential linear sensor"
        },
        SceneCaptureType : {
            0 : "Standard",
            1 : "Landscape",
            2 : "Portrait",
            3 : "Night scene"
        },
        SceneType : {
            1 : "Directly photographed"
        },
        CustomRendered : {
            0 : "Normal process",
            1 : "Custom process"
        },
        WhiteBalance : {
            0 : "Auto white balance",
            1 : "Manual white balance"
        },
        GainControl : {
            0 : "None",
            1 : "Low gain up",
            2 : "High gain up",
            3 : "Low gain down",
            4 : "High gain down"
        },
        Contrast : {
            0 : "Normal",
            1 : "Soft",
            2 : "Hard"
        },
        Saturation : {
            0 : "Normal",
            1 : "Low saturation",
            2 : "High saturation"
        },
        Sharpness : {
            0 : "Normal",
            1 : "Soft",
            2 : "Hard"
        },
        SubjectDistanceRange : {
            0 : "Unknown",
            1 : "Macro",
            2 : "Close view",
            3 : "Distant view"
        },
        FileSource : {
            3 : "DSC"
        },

        Components : {
            0 : "",
            1 : "Y",
            2 : "Cb",
            3 : "Cr",
            4 : "R",
            5 : "G",
            6 : "B"
        }
    };

    function addEvent(element, event, handler) {
        if (element.addEventListener) {
            element.addEventListener(event, handler, false);
        } else if (element.attachEvent) {
            element.attachEvent("on" + event, handler);
        }
    }

    function imageHasData(img) {
        return !!(img.exifdata);
    }


    function base64ToArrayBuffer(base64, contentType) {
        contentType = contentType || base64.match(/^data\:([^\;]+)\;base64,/mi)[1] || ''; // e.g. 'data:image/jpeg;base64,...' => 'image/jpeg'
        base64 = base64.replace(/^data\:([^\;]+)\;base64,/gmi, '');
        var binary = atob(base64);
        var len = binary.length;
        var buffer = new ArrayBuffer(len);
        var view = new Uint8Array(buffer);
        for (var i = 0; i < len; i++) {
            view[i] = binary.charCodeAt(i);
        }
        return buffer;
    }

    function objectURLToBlob(url, callback) {
        var http = new XMLHttpRequest();
        http.open("GET", url, true);
        http.responseType = "blob";
        http.onload = function(e) {
            if (this.status == 200 || this.status === 0) {
                callback(this.response);
            }
        };
        http.send();
    }

    function getImageData(img, callback) {
        function handleBinaryFile(binFile) {
            var data = findEXIFinJPEG(binFile);
            var iptcdata = findIPTCinJPEG(binFile);
            img.exifdata = data || {};
            img.iptcdata = iptcdata || {};
            if (callback) {
                callback.call(img);
            }
        }

        if (img.src) {
            if (/^data\:/i.test(img.src)) { // Data URI
                var arrayBuffer = base64ToArrayBuffer(img.src);
                handleBinaryFile(arrayBuffer);

            } else if (/^blob\:/i.test(img.src)) { // Object URL
                var fileReader = new FileReader();
                fileReader.onload = function(e) {
                    handleBinaryFile(e.target.result);
                };
                objectURLToBlob(img.src, function (blob) {
                    fileReader.readAsArrayBuffer(blob);
                });
            } else {
                var http = new XMLHttpRequest();
                http.onload = function() {
                    if (this.status == 200 || this.status === 0) {
                        handleBinaryFile(http.response);
                    } else {
                        throw "Could not load image";
                    }
                    http = null;
                };
                http.open("GET", img.src, true);
                http.responseType = "arraybuffer";
                http.send(null);
            }
        } else if (window.FileReader && (img instanceof window.Blob || img instanceof window.File)) {
            var fileReader = new FileReader();
            fileReader.onload = function(e) {
                if (debug) console.log("Got file of length " + e.target.result.byteLength);
                handleBinaryFile(e.target.result);
            };

            fileReader.readAsArrayBuffer(img);
        }
    }

    function findEXIFinJPEG(file) {
        var dataView = new DataView(file);

        if (debug) console.log("Got file of length " + file.byteLength);
        if ((dataView.getUint8(0) != 0xFF) || (dataView.getUint8(1) != 0xD8)) {
            if (debug) console.log("Not a valid JPEG");
            return false; // not a valid jpeg
        }

        var offset = 2,
            length = file.byteLength,
            marker;

        while (offset < length) {
            if (dataView.getUint8(offset) != 0xFF) {
                if (debug) console.log("Not a valid marker at offset " + offset + ", found: " + dataView.getUint8(offset));
                return false; // not a valid marker, something is wrong
            }

            marker = dataView.getUint8(offset + 1);
            if (debug) console.log(marker);

            // we could implement handling for other markers here,
            // but we're only looking for 0xFFE1 for EXIF data

            if (marker == 225) {
                if (debug) console.log("Found 0xFFE1 marker");

                return readEXIFData(dataView, offset + 4, dataView.getUint16(offset + 2) - 2);

                // offset += 2 + file.getShortAt(offset+2, true);

            } else {
                offset += 2 + dataView.getUint16(offset+2);
            }

        }

    }

    function findIPTCinJPEG(file) {
        var dataView = new DataView(file);

        if (debug) console.log("Got file of length " + file.byteLength);
        if ((dataView.getUint8(0) != 0xFF) || (dataView.getUint8(1) != 0xD8)) {
            if (debug) console.log("Not a valid JPEG");
            return false; // not a valid jpeg
        }

        var offset = 2,
            length = file.byteLength;


        var isFieldSegmentStart = function(dataView, offset){
            return (
                dataView.getUint8(offset) === 0x38 &&
                dataView.getUint8(offset+1) === 0x42 &&
                dataView.getUint8(offset+2) === 0x49 &&
                dataView.getUint8(offset+3) === 0x4D &&
                dataView.getUint8(offset+4) === 0x04 &&
                dataView.getUint8(offset+5) === 0x04
            );
        };

        while (offset < length) {

            if ( isFieldSegmentStart(dataView, offset )){

                // Get the length of the name header (which is padded to an even number of bytes)
                var nameHeaderLength = dataView.getUint8(offset+7);
                if(nameHeaderLength % 2 !== 0) nameHeaderLength += 1;
                // Check for pre photoshop 6 format
                if(nameHeaderLength === 0) {
                    // Always 4
                    nameHeaderLength = 4;
                }

                var startOffset = offset + 8 + nameHeaderLength;
                var sectionLength = dataView.getUint16(offset + 6 + nameHeaderLength);

                return readIPTCData(file, startOffset, sectionLength);

                break;

            }


            // Not the marker, continue searching
            offset++;

        }

    }
    var IptcFieldMap = {
        0x78 : 'caption',
        0x6E : 'credit',
        0x19 : 'keywords',
        0x37 : 'dateCreated',
        0x50 : 'byline',
        0x55 : 'bylineTitle',
        0x7A : 'captionWriter',
        0x69 : 'headline',
        0x74 : 'copyright',
        0x0F : 'category'
    };
    function readIPTCData(file, startOffset, sectionLength){
        var dataView = new DataView(file);
        var data = {};
        var fieldValue, fieldName, dataSize, segmentType, segmentSize;
        var segmentStartPos = startOffset;
        while(segmentStartPos < startOffset+sectionLength) {
            if(dataView.getUint8(segmentStartPos) === 0x1C && dataView.getUint8(segmentStartPos+1) === 0x02){
                segmentType = dataView.getUint8(segmentStartPos+2);
                if(segmentType in IptcFieldMap) {
                    dataSize = dataView.getInt16(segmentStartPos+3);
                    segmentSize = dataSize + 5;
                    fieldName = IptcFieldMap[segmentType];
                    fieldValue = getStringFromDB(dataView, segmentStartPos+5, dataSize);
                    // Check if we already stored a value with this name
                    if(data.hasOwnProperty(fieldName)) {
                        // Value already stored with this name, create multivalue field
                        if(data[fieldName] instanceof Array) {
                            data[fieldName].push(fieldValue);
                        }
                        else {
                            data[fieldName] = [data[fieldName], fieldValue];
                        }
                    }
                    else {
                        data[fieldName] = fieldValue;
                    }
                }

            }
            segmentStartPos++;
        }
        return data;
    }



    function readTags(file, tiffStart, dirStart, strings, bigEnd) {
        var entries = file.getUint16(dirStart, !bigEnd),
            tags = {},
            entryOffset, tag,
            i;

        for (i=0;i<entries;i++) {
            entryOffset = dirStart + i*12 + 2;
            tag = strings[file.getUint16(entryOffset, !bigEnd)];
            if (!tag && debug) console.log("Unknown tag: " + file.getUint16(entryOffset, !bigEnd));
            tags[tag] = readTagValue(file, entryOffset, tiffStart, dirStart, bigEnd);
        }
        return tags;
    }


    function readTagValue(file, entryOffset, tiffStart, dirStart, bigEnd) {
        var type = file.getUint16(entryOffset+2, !bigEnd),
            numValues = file.getUint32(entryOffset+4, !bigEnd),
            valueOffset = file.getUint32(entryOffset+8, !bigEnd) + tiffStart,
            offset,
            vals, val, n,
            numerator, denominator;

        switch (type) {
            case 1: // byte, 8-bit unsigned int
            case 7: // undefined, 8-bit byte, value depending on field
                if (numValues == 1) {
                    return file.getUint8(entryOffset + 8, !bigEnd);
                } else {
                    offset = numValues > 4 ? valueOffset : (entryOffset + 8);
                    vals = [];
                    for (n=0;n<numValues;n++) {
                        vals[n] = file.getUint8(offset + n);
                    }
                    return vals;
                }

            case 2: // ascii, 8-bit byte
                offset = numValues > 4 ? valueOffset : (entryOffset + 8);
                return getStringFromDB(file, offset, numValues-1);

            case 3: // short, 16 bit int
                if (numValues == 1) {
                    return file.getUint16(entryOffset + 8, !bigEnd);
                } else {
                    offset = numValues > 2 ? valueOffset : (entryOffset + 8);
                    vals = [];
                    for (n=0;n<numValues;n++) {
                        vals[n] = file.getUint16(offset + 2*n, !bigEnd);
                    }
                    return vals;
                }

            case 4: // long, 32 bit int
                if (numValues == 1) {
                    return file.getUint32(entryOffset + 8, !bigEnd);
                } else {
                    vals = [];
                    for (n=0;n<numValues;n++) {
                        vals[n] = file.getUint32(valueOffset + 4*n, !bigEnd);
                    }
                    return vals;
                }

            case 5:    // rational = two long values, first is numerator, second is denominator
                if (numValues == 1) {
                    numerator = file.getUint32(valueOffset, !bigEnd);
                    denominator = file.getUint32(valueOffset+4, !bigEnd);
                    val = new Number(numerator / denominator);
                    val.numerator = numerator;
                    val.denominator = denominator;
                    return val;
                } else {
                    vals = [];
                    for (n=0;n<numValues;n++) {
                        numerator = file.getUint32(valueOffset + 8*n, !bigEnd);
                        denominator = file.getUint32(valueOffset+4 + 8*n, !bigEnd);
                        vals[n] = new Number(numerator / denominator);
                        vals[n].numerator = numerator;
                        vals[n].denominator = denominator;
                    }
                    return vals;
                }

            case 9: // slong, 32 bit signed int
                if (numValues == 1) {
                    return file.getInt32(entryOffset + 8, !bigEnd);
                } else {
                    vals = [];
                    for (n=0;n<numValues;n++) {
                        vals[n] = file.getInt32(valueOffset + 4*n, !bigEnd);
                    }
                    return vals;
                }

            case 10: // signed rational, two slongs, first is numerator, second is denominator
                if (numValues == 1) {
                    return file.getInt32(valueOffset, !bigEnd) / file.getInt32(valueOffset+4, !bigEnd);
                } else {
                    vals = [];
                    for (n=0;n<numValues;n++) {
                        vals[n] = file.getInt32(valueOffset + 8*n, !bigEnd) / file.getInt32(valueOffset+4 + 8*n, !bigEnd);
                    }
                    return vals;
                }
        }
    }

    function getStringFromDB(buffer, start, length) {
        var outstr = "";
        for (var n = start; n < start+length; n++) {
            outstr += String.fromCharCode(buffer.getUint8(n));
        }
        return outstr;
    }

    function readEXIFData(file, start) {
        if (getStringFromDB(file, start, 4) != "Exif") {
            if (debug) console.log("Not valid EXIF data! " + getStringFromDB(file, start, 4));
            return false;
        }

        var bigEnd,
            tags, tag,
            exifData, gpsData,
            tiffOffset = start + 6;

        // test for TIFF validity and endianness
        if (file.getUint16(tiffOffset) == 0x4949) {
            bigEnd = false;
        } else if (file.getUint16(tiffOffset) == 0x4D4D) {
            bigEnd = true;
        } else {
            if (debug) console.log("Not valid TIFF data! (no 0x4949 or 0x4D4D)");
            return false;
        }

        if (file.getUint16(tiffOffset+2, !bigEnd) != 0x002A) {
            if (debug) console.log("Not valid TIFF data! (no 0x002A)");
            return false;
        }

        var firstIFDOffset = file.getUint32(tiffOffset+4, !bigEnd);

        if (firstIFDOffset < 0x00000008) {
            if (debug) console.log("Not valid TIFF data! (First offset less than 8)", file.getUint32(tiffOffset+4, !bigEnd));
            return false;
        }

        tags = readTags(file, tiffOffset, tiffOffset + firstIFDOffset, TiffTags, bigEnd);

        if (tags.ExifIFDPointer) {
            exifData = readTags(file, tiffOffset, tiffOffset + tags.ExifIFDPointer, ExifTags, bigEnd);
            for (tag in exifData) {
                switch (tag) {
                    case "LightSource" :
                    case "Flash" :
                    case "MeteringMode" :
                    case "ExposureProgram" :
                    case "SensingMethod" :
                    case "SceneCaptureType" :
                    case "SceneType" :
                    case "CustomRendered" :
                    case "WhiteBalance" :
                    case "GainControl" :
                    case "Contrast" :
                    case "Saturation" :
                    case "Sharpness" :
                    case "SubjectDistanceRange" :
                    case "FileSource" :
                        exifData[tag] = StringValues[tag][exifData[tag]];
                        break;

                    case "ExifVersion" :
                    case "FlashpixVersion" :
                        exifData[tag] = String.fromCharCode(exifData[tag][0], exifData[tag][1], exifData[tag][2], exifData[tag][3]);
                        break;

                    case "ComponentsConfiguration" :
                        exifData[tag] =
                            StringValues.Components[exifData[tag][0]] +
                            StringValues.Components[exifData[tag][1]] +
                            StringValues.Components[exifData[tag][2]] +
                            StringValues.Components[exifData[tag][3]];
                        break;
                }
                tags[tag] = exifData[tag];
            }
        }

        if (tags.GPSInfoIFDPointer) {
            gpsData = readTags(file, tiffOffset, tiffOffset + tags.GPSInfoIFDPointer, GPSTags, bigEnd);
            for (tag in gpsData) {
                switch (tag) {
                    case "GPSVersionID" :
                        gpsData[tag] = gpsData[tag][0] +
                            "." + gpsData[tag][1] +
                            "." + gpsData[tag][2] +
                            "." + gpsData[tag][3];
                        break;
                }
                tags[tag] = gpsData[tag];
            }
        }

        return tags;
    }

    EXIF.getData = function(img, callback) {
        if ((img instanceof Image || img instanceof HTMLImageElement) && !img.complete) return false;

        if (!imageHasData(img)) {
            getImageData(img, callback);
        } else {
            if (callback) {
                callback.call(img);
            }
        }
        return true;
    }

    EXIF.getTag = function(img, tag) {
        if (!imageHasData(img)) return;
        return img.exifdata[tag];
    }

    EXIF.getAllTags = function(img) {
        if (!imageHasData(img)) return {};
        var a,
            data = img.exifdata,
            tags = {};
        for (a in data) {
            if (data.hasOwnProperty(a)) {
                tags[a] = data[a];
            }
        }
        return tags;
    }

    EXIF.pretty = function(img) {
        if (!imageHasData(img)) return "";
        var a,
            data = img.exifdata,
            strPretty = "";
        for (a in data) {
            if (data.hasOwnProperty(a)) {
                if (typeof data[a] == "object") {
                    if (data[a] instanceof Number) {
                        strPretty += a + " : " + data[a] + " [" + data[a].numerator + "/" + data[a].denominator + "]\r\n";
                    } else {
                        strPretty += a + " : [" + data[a].length + " values]\r\n";
                    }
                } else {
                    strPretty += a + " : " + data[a] + "\r\n";
                }
            }
        }
        return strPretty;
    }

    EXIF.readFromBinaryFile = function(file) {
        return findEXIFinJPEG(file);
    }

    if (typeof define === 'function' && define.amd) {
        define('exif-js', [], function() {
            return EXIF;
        });
    }
}.call(this));


if (!window.egret) {
    var egret_strings = {
        4001: "Abstract class can not be instantiated!",
        4002: "Unnamed data!",
        4003: "Nonsupport version!"
    };

    var Event = function(type, bubbles, cancelable, data) {
        this.type = type;
        this.bubbles = bubbles || false;
        this.cancelable = cancelable || false;
        this.data = data;
    };

    var EventDispatcher = function(target) {
        this._listenerDict = {};
    };

    EventDispatcher.prototype = {
        constructor: EventDispatcher,
        addEventListener: function(type, listener, thisObject, useCapture, priority, dispatchOnce) {
            if (!this._listenerDict[type]) {
                this._listenerDict[type] = [];
            }
            this._listenerDict[type].push({
                listener: listener,
                thisObject: thisObject,
                useCapture: useCapture,
                priority: priority,
                once: dispatchOnce
            });
        },
        once: function(type, listener, thisObject, useCapture, priority) {
            this.addEventListener(type, listener, thisObject, useCapture, priority, true);
        },
        removeEventListener: function(type, listener, thisObject, useCapture) {
            if (!type) {
                this._listenerDict = {};
            } else if (!listener) {
                if (this._listenerDict[type]) {
                    this._listenerDict[type].length = 0;
                }
            } else {
                var listeners = this._listenerDict[type];
                var index = listeners.indexOf(listener);
                if (index > -1) {
                    listeners.splice(index, 1);
                }
            }
        },
        hasEventListener: function(type) {
            return this._listenerDict[type];
        },
        dispatchEvent: function(event) {
            if (event && event.type && this._listenerDict[event.type]) {
                var listeners = this._listenerDict[event.type];
                var copyListeners = listeners.slice();
                for (var i = 0; i < copyListeners.length; i++) {
                    var listenerObj = copyListeners[i];
                    if (listenerObj.dispatchOnce) {
                        var index = listeners.indexOf(listenerObj);
                        if (index > -1) {
                            listeners.splice(index, 1);
                        }
                    }
                    if (listenerObj.listener) {
                        listenerObj.listener.call(listenerObj.thisObject || this, event);
                    }
                }
            }
        },
        willTrigger: function(type) {
            return this.hasEventListener(type);
        }
    };

    window.egret = {
        getString: function(code) {
            return egret_strings[code] || 'no string code';
        },
        Event: Event,
        EventDispatcher: EventDispatcher,
        registerClass: function(classDefinition, className, interfaceNames) {
            var prototype = classDefinition.prototype;
            prototype.__class__ = className;
            var types = [className];
            if (interfaceNames) {
                types = types.concat(interfaceNames);
            }
            var superTypes = prototype.__types__;
            if (prototype.__types__) {
                var length = superTypes.length;
                for (var i = 0; i < length; i++) {
                    var name = superTypes[i];
                    if (types.indexOf(name) == -1) {
                        types.push(name);
                    }
                }
            }
            prototype.__types__ = types;
        }
    };
}

window.__extends = window.__extends || function __extends(d, b, mixin) {
    for (var p in b)
        if (b.hasOwnProperty(p))
            d[p] = b[p];

    function __() {
        this.constructor = d;
    }
    __.prototype = b.prototype;
    d.prototype = new __();

    if(mixin){
        for(var key in mixin){
            d.prototype[key] = mixin[key];
        }
    }
};

window.__define = window.__define || function(o, p, g, s) {
    Object.defineProperty(o, p, {
        configurable: true,
        enumerable: true,
        get: g,
        set: s
    });
};
var dragonBones;
(function (dragonBones) {
    var DragonBones = (function () {
        function DragonBones() {
        }
        var d = __define,c=DragonBones,p=c.prototype;
        DragonBones.DATA_VERSION = "4.0";
        DragonBones.PARENT_COORDINATE_DATA_VERSION = "3.0";
        DragonBones.VERSION = "4.3.5";
        return DragonBones;
    })();
    dragonBones.DragonBones = DragonBones;
    egret.registerClass(DragonBones,'dragonBones.DragonBones');
})(dragonBones || (dragonBones = {}));
var dragonBones;
(function (dragonBones) {
    var Animation = (function () {
        function Animation(armature) {
            this._animationStateCount = 0;
            this._armature = armature;
            this._animationList = [];
            this._animationStateList = [];
            this._timeScale = 1;
            this._isPlaying = false;
            this.tweenEnabled = true;
        }
        var d = __define,c=Animation,p=c.prototype;
        p.dispose = function () {
            if (!this._armature) {
                return;
            }
            this._resetAnimationStateList();
            this._animationList.length = 0;
            this._armature = null;
            this._animationDataList = null;
            this._animationList = null;
            this._animationStateList = null;
        };
        p._resetAnimationStateList = function () {
            var i = this._animationStateList.length;
            var animationState;
            while (i--) {
                animationState = this._animationStateList[i];
                animationState._resetTimelineStateList();
                dragonBones.AnimationState._returnObject(animationState);
            }
            this._animationStateList.length = 0;
        };
        p.gotoAndPlay = function (animationName, fadeInTime, duration, playTimes, layer, group, fadeOutMode, pauseFadeOut, pauseFadeIn) {
            if (fadeInTime === void 0) { fadeInTime = -1; }
            if (duration === void 0) { duration = -1; }
            if (playTimes === void 0) { playTimes = NaN; }
            if (layer === void 0) { layer = 0; }
            if (group === void 0) { group = null; }
            if (fadeOutMode === void 0) { fadeOutMode = Animation.SAME_LAYER_AND_GROUP; }
            if (pauseFadeOut === void 0) { pauseFadeOut = true; }
            if (pauseFadeIn === void 0) { pauseFadeIn = true; }
            if (!this._animationDataList) {
                return null;
            }
            var i = this._animationDataList.length;
            var animationData;
            while (i--) {
                if (this._animationDataList[i].name == animationName) {
                    animationData = this._animationDataList[i];
                    break;
                }
            }
            if (!animationData) {
                return null;
            }
            var needUpdate = this._isPlaying == false;
            this._isPlaying = true;
            this._isFading = true;
            fadeInTime = fadeInTime < 0 ? (animationData.fadeTime < 0 ? 0.3 : animationData.fadeTime) : fadeInTime;
            var durationScale;
            if (duration < 0) {
                durationScale = animationData.scale < 0 ? 1 : animationData.scale;
            }
            else {
                durationScale = duration * 1000 / animationData.duration;
            }
            playTimes = isNaN(playTimes) ? animationData.playTimes : playTimes;
            var animationState;
            switch (fadeOutMode) {
                case Animation.NONE:
                    break;
                case Animation.SAME_LAYER:
                    i = this._animationStateList.length;
                    while (i--) {
                        animationState = this._animationStateList[i];
                        if (animationState.layer == layer) {
                            animationState.fadeOut(fadeInTime, pauseFadeOut);
                        }
                    }
                    break;
                case Animation.SAME_GROUP:
                    i = this._animationStateList.length;
                    while (i--) {
                        animationState = this._animationStateList[i];
                        if (animationState.group == group) {
                            animationState.fadeOut(fadeInTime, pauseFadeOut);
                        }
                    }
                    break;
                case Animation.ALL:
                    i = this._animationStateList.length;
                    while (i--) {
                        animationState = this._animationStateList[i];
                        animationState.fadeOut(fadeInTime, pauseFadeOut);
                    }
                    break;
                case Animation.SAME_LAYER_AND_GROUP:
                default:
                    i = this._animationStateList.length;
                    while (i--) {
                        animationState = this._animationStateList[i];
                        if (animationState.layer == layer && animationState.group == group) {
                            animationState.fadeOut(fadeInTime, pauseFadeOut);
                        }
                    }
                    break;
            }
            this._lastAnimationState = dragonBones.AnimationState._borrowObject();
            this._lastAnimationState._layer = layer;
            this._lastAnimationState._group = group;
            this._lastAnimationState.autoTween = this.tweenEnabled;
            this._lastAnimationState._fadeIn(this._armature, animationData, fadeInTime, 1 / durationScale, playTimes, pauseFadeIn);
            this.addState(this._lastAnimationState);
            var slotList = this._armature.getSlots(false);
            i = slotList.length;
            while (i--) {
                var slot = slotList[i];
                if (slot.childArmature) {
                    slot.childArmature.animation.gotoAndPlay(animationName, fadeInTime);
                }
            }
            if (needUpdate) {
                this._armature.advanceTime(0);
            }
            return this._lastAnimationState;
        };
        p.gotoAndStop = function (animationName, time, normalizedTime, fadeInTime, duration, layer, group, fadeOutMode) {
            if (normalizedTime === void 0) { normalizedTime = -1; }
            if (fadeInTime === void 0) { fadeInTime = 0; }
            if (duration === void 0) { duration = -1; }
            if (layer === void 0) { layer = 0; }
            if (group === void 0) { group = null; }
            if (fadeOutMode === void 0) { fadeOutMode = Animation.ALL; }
            var animationState = this.getState(animationName, layer);
            if (!animationState) {
                animationState = this.gotoAndPlay(animationName, fadeInTime, duration, NaN, layer, group, fadeOutMode);
            }
            if (normalizedTime >= 0) {
                animationState.setCurrentTime(animationState.totalTime * normalizedTime);
            }
            else {
                animationState.setCurrentTime(time);
            }
            animationState.stop();
            return animationState;
        };
        p.play = function () {
            if (!this._animationDataList || this._animationDataList.length == 0) {
                return;
            }
            if (!this._lastAnimationState) {
                this.gotoAndPlay(this._animationDataList[0].name);
            }
            else if (!this._isPlaying) {
                this._isPlaying = true;
            }
            else {
                this.gotoAndPlay(this._lastAnimationState.name);
            }
        };
        p.stop = function () {
            this._isPlaying = false;
        };
        p.getState = function (name, layer) {
            if (layer === void 0) { layer = 0; }
            var i = this._animationStateList.length;
            while (i--) {
                var animationState = this._animationStateList[i];
                if (animationState.name == name && animationState.layer == layer) {
                    return animationState;
                }
            }
            return null;
        };
        p.hasAnimation = function (animationName) {
            var i = this._animationDataList.length;
            while (i--) {
                if (this._animationDataList[i].name == animationName) {
                    return true;
                }
            }
            return false;
        };
        p._advanceTime = function (passedTime) {
            if (!this._isPlaying) {
                return;
            }
            var isFading = false;
            passedTime *= this._timeScale;
            var i = this._animationStateList.length;
            while (i--) {
                var animationState = this._animationStateList[i];
                if (animationState._advanceTime(passedTime)) {
                    this.removeState(animationState);
                }
                else if (animationState.fadeState != 1) {
                    isFading = true;
                }
            }
            this._isFading = isFading;
        };
        p._updateAnimationStates = function () {
            var i = this._animationStateList.length;
            while (i--) {
                this._animationStateList[i]._updateTimelineStates();
            }
        };
        p.addState = function (animationState) {
            if (this._animationStateList.indexOf(animationState) < 0) {
                this._animationStateList.unshift(animationState);
                this._animationStateCount = this._animationStateList.length;
            }
        };
        p.removeState = function (animationState) {
            var index = this._animationStateList.indexOf(animationState);
            if (index >= 0) {
                this._animationStateList.splice(index, 1);
                dragonBones.AnimationState._returnObject(animationState);
                if (this._lastAnimationState == animationState) {
                    if (this._animationStateList.length > 0) {
                        this._lastAnimationState = this._animationStateList[0];
                    }
                    else {
                        this._lastAnimationState = null;
                    }
                }
                this._animationStateCount = this._animationStateList.length;
            }
        };
        d(p, "movementList"
            ,function () {
                return this._animationList;
            }
        );
        d(p, "movementID"
            ,function () {
                return this.lastAnimationName;
            }
        );
        d(p, "lastAnimationState"
            ,function () {
                return this._lastAnimationState;
            }
        );
        d(p, "lastAnimationName"
            ,function () {
                return this._lastAnimationState ? this._lastAnimationState.name : null;
            }
        );
        d(p, "animationList"
            ,function () {
                return this._animationList;
            }
        );
        d(p, "isPlaying"
            ,function () {
                return this._isPlaying && !this.isComplete;
            }
        );
        d(p, "isComplete"
            ,function () {
                if (this._lastAnimationState) {
                    if (!this._lastAnimationState.isComplete) {
                        return false;
                    }
                    var i = this._animationStateList.length;
                    while (i--) {
                        if (!this._animationStateList[i].isComplete) {
                            return false;
                        }
                    }
                    return true;
                }
                return true;
            }
        );
        d(p, "timeScale"
            ,function () {
                return this._timeScale;
            }
            ,function (value) {
                if (isNaN(value) || value < 0) {
                    value = 1;
                }
                this._timeScale = value;
            }
        );
        d(p, "animationDataList"
            ,function () {
                return this._animationDataList;
            }
            ,function (value) {
                this._animationDataList = value;
                this._animationList.length = 0;
                for (var i = 0, len = this._animationDataList.length; i < len; i++) {
                    var animationData = this._animationDataList[i];
                    this._animationList[this._animationList.length] = animationData.name;
                }
            }
        );
        Animation.NONE = "none";
        Animation.SAME_LAYER = "sameLayer";
        Animation.SAME_GROUP = "sameGroup";
        Animation.SAME_LAYER_AND_GROUP = "sameLayerAndGroup";
        Animation.ALL = "all";
        return Animation;
    })();
    dragonBones.Animation = Animation;
    egret.registerClass(Animation,'dragonBones.Animation');
})(dragonBones || (dragonBones = {}));
var dragonBones;
(function (dragonBones) {
    var AnimationState = (function () {
        function AnimationState() {
            this._layer = 0;
            this._currentFrameIndex = 0;
            this._currentFramePosition = 0;
            this._currentFrameDuration = 0;
            this._currentPlayTimes = 0;
            this._totalTime = 0;
            this._currentTime = 0;
            this._lastTime = 0;
            this._fadeState = 0;
            this._playTimes = 0;
            this._timelineStateList = [];
            this._slotTimelineStateList = [];
            this._boneMasks = [];
        }
        var d = __define,c=AnimationState,p=c.prototype;
        AnimationState._borrowObject = function () {
            if (AnimationState._pool.length == 0) {
                return new AnimationState();
            }
            return AnimationState._pool.pop();
        };
        AnimationState._returnObject = function (animationState) {
            animationState.clear();
            if (AnimationState._pool.indexOf(animationState) < 0) {
                AnimationState._pool[AnimationState._pool.length] = animationState;
            }
        };
        AnimationState._clear = function () {
            var i = AnimationState._pool.length;
            while (i--) {
                AnimationState._pool[i].clear();
            }
            AnimationState._pool.length = 0;
            dragonBones.TimelineState._clear();
        };
        p.clear = function () {
            this._resetTimelineStateList();
            this._boneMasks.length = 0;
            this._armature = null;
            this._clip = null;
        };
        p._resetTimelineStateList = function () {
            var i = this._timelineStateList.length;
            while (i--) {
                dragonBones.TimelineState._returnObject(this._timelineStateList[i]);
            }
            this._timelineStateList.length = 0;
            i = this._slotTimelineStateList.length;
            while (i--) {
                dragonBones.SlotTimelineState._returnObject(this._slotTimelineStateList[i]);
            }
            this._slotTimelineStateList.length = 0;
        };
        p.containsBoneMask = function (boneName) {
            return this._boneMasks.length == 0 || this._boneMasks.indexOf(boneName) >= 0;
        };
        p.addBoneMask = function (boneName, ifInvolveChildBones) {
            if (ifInvolveChildBones === void 0) { ifInvolveChildBones = true; }
            this.addBoneToBoneMask(boneName);
            if (ifInvolveChildBones) {
                var currentBone = this._armature.getBone(boneName);
                if (currentBone) {
                    var boneList = this._armature.getBones(false);
                    var i = boneList.length;
                    while (i--) {
                        var tempBone = boneList[i];
                        if (currentBone.contains(tempBone)) {
                            this.addBoneToBoneMask(tempBone.name);
                        }
                    }
                }
            }
            this._updateTimelineStates();
            return this;
        };
        p.removeBoneMask = function (boneName, ifInvolveChildBones) {
            if (ifInvolveChildBones === void 0) { ifInvolveChildBones = true; }
            this.removeBoneFromBoneMask(boneName);
            if (ifInvolveChildBones) {
                var currentBone = this._armature.getBone(boneName);
                if (currentBone) {
                    var boneList = this._armature.getBones(false);
                    var i = boneList.length;
                    while (i--) {
                        var tempBone = boneList[i];
                        if (currentBone.contains(tempBone)) {
                            this.removeBoneFromBoneMask(tempBone.name);
                        }
                    }
                }
            }
            this._updateTimelineStates();
            return this;
        };
        p.removeAllMixingTransform = function () {
            this._boneMasks.length = 0;
            this._updateTimelineStates();
            return this;
        };
        p.addBoneToBoneMask = function (boneName) {
            if (this._clip.getTimeline(boneName) && this._boneMasks.indexOf(boneName) < 0) {
                this._boneMasks.push(boneName);
            }
        };
        p.removeBoneFromBoneMask = function (boneName) {
            var index = this._boneMasks.indexOf(boneName);
            if (index >= 0) {
                this._boneMasks.splice(index, 1);
            }
        };
        p._updateTimelineStates = function () {
            var timelineState;
            var slotTimelineState;
            var i = this._timelineStateList.length;
            var len;
            while (i--) {
                timelineState = this._timelineStateList[i];
                if (!this._armature.getBone(timelineState.name)) {
                    this.removeTimelineState(timelineState);
                }
            }
            i = this._slotTimelineStateList.length;
            while (i--) {
                slotTimelineState = this._slotTimelineStateList[i];
                if (!this._armature.getSlot(slotTimelineState.name)) {
                    this.removeSlotTimelineState(slotTimelineState);
                }
            }
            if (this._boneMasks.length > 0) {
                i = this._timelineStateList.length;
                while (i--) {
                    timelineState = this._timelineStateList[i];
                    if (this._boneMasks.indexOf(timelineState.name) < 0) {
                        this.removeTimelineState(timelineState);
                    }
                }
                for (i = 0, len = this._boneMasks.length; i < len; i++) {
                    var timelineName = this._boneMasks[i];
                    this.addTimelineState(timelineName);
                }
            }
            else {
                for (i = 0, len = this._clip.timelineList.length; i < len; i++) {
                    var timeline = this._clip.timelineList[i];
                    this.addTimelineState(timeline.name);
                }
            }
            for (i = 0, len = this._clip.slotTimelineList.length; i < len; i++) {
                var slotTimeline = this._clip.slotTimelineList[i];
                this.addSlotTimelineState(slotTimeline.name);
            }
        };
        p.addTimelineState = function (timelineName) {
            var bone = this._armature.getBone(timelineName);
            if (bone) {
                for (var i = 0, len = this._timelineStateList.length; i < len; i++) {
                    var eachState = this._timelineStateList[i];
                    if (eachState.name == timelineName) {
                        return;
                    }
                }
                var timelineState = dragonBones.TimelineState._borrowObject();
                timelineState._fadeIn(bone, this, this._clip.getTimeline(timelineName));
                this._timelineStateList.push(timelineState);
            }
        };
        p.removeTimelineState = function (timelineState) {
            var index = this._timelineStateList.indexOf(timelineState);
            this._timelineStateList.splice(index, 1);
            dragonBones.TimelineState._returnObject(timelineState);
        };
        p.addSlotTimelineState = function (timelineName) {
            var slot = this._armature.getSlot(timelineName);
            if (slot) {
                for (var i = 0, len = this._slotTimelineStateList.length; i < len; i++) {
                    var eachState = this._slotTimelineStateList[i];
                    if (eachState.name == timelineName) {
                        return;
                    }
                }
                var timelineState = dragonBones.SlotTimelineState._borrowObject();
                timelineState._fadeIn(slot, this, this._clip.getSlotTimeline(timelineName));
                this._slotTimelineStateList.push(timelineState);
            }
        };
        p.removeSlotTimelineState = function (timelineState) {
            var index = this._slotTimelineStateList.indexOf(timelineState);
            this._slotTimelineStateList.splice(index, 1);
            dragonBones.SlotTimelineState._returnObject(timelineState);
        };
        p.play = function () {
            this._isPlaying = true;
            return this;
        };
        p.stop = function () {
            this._isPlaying = false;
            return this;
        };
        p._fadeIn = function (armature, clip, fadeTotalTime, timeScale, playTimes, pausePlayhead) {
            this._armature = armature;
            this._clip = clip;
            this._pausePlayheadInFade = pausePlayhead;
            this._name = this._clip.name;
            this._totalTime = this._clip.duration;
            this.autoTween = this._clip.autoTween;
            this.setTimeScale(timeScale);
            this.setPlayTimes(playTimes);
            this._isComplete = false;
            this._currentFrameIndex = -1;
            this._currentPlayTimes = -1;
            if (Math.round(this._totalTime * this._clip.frameRate * 0.001) < 2 || timeScale == Infinity) {
                this._currentTime = this._totalTime;
            }
            else {
                this._currentTime = -1;
            }
            this._time = 0;
            this._boneMasks.length = 0;
            this._isFadeOut = false;
            this._fadeWeight = 0;
            this._fadeTotalWeight = 1;
            this._fadeState = -1;
            this._fadeCurrentTime = 0;
            this._fadeBeginTime = this._fadeCurrentTime;
            this._fadeTotalTime = fadeTotalTime * this._timeScale;
            this._isPlaying = true;
            this.displayControl = true;
            this.lastFrameAutoTween = true;
            this.additiveBlending = false;
            this.weight = 1;
            this.fadeOutTime = fadeTotalTime;
            this._updateTimelineStates();
            return this;
        };
        p.fadeOut = function (fadeTotalTime, pausePlayhead) {
            if (!this._armature) {
                return null;
            }
            if (isNaN(fadeTotalTime) || fadeTotalTime < 0) {
                fadeTotalTime = 0;
            }
            this._pausePlayheadInFade = pausePlayhead;
            if (this._isFadeOut) {
                if (fadeTotalTime > this._fadeTotalTime / this._timeScale - (this._fadeCurrentTime - this._fadeBeginTime)) {
                    return this;
                }
            }
            else {
                for (var i = 0, len = this._timelineStateList.length; i < len; i++) {
                    var timelineState = this._timelineStateList[i];
                    timelineState._fadeOut();
                }
            }
            this._isFadeOut = true;
            this._fadeTotalWeight = this._fadeWeight;
            this._fadeState = -1;
            this._fadeBeginTime = this._fadeCurrentTime;
            this._fadeTotalTime = this._fadeTotalWeight >= 0 ? fadeTotalTime * this._timeScale : 0;
            this.displayControl = false;
            return this;
        };
        p._advanceTime = function (passedTime) {
            passedTime *= this._timeScale;
            this.advanceFadeTime(passedTime);
            if (this._fadeWeight) {
                this.advanceTimelinesTime(passedTime);
            }
            return this._isFadeOut && this._fadeState == 1;
        };
        p.advanceFadeTime = function (passedTime) {
            var fadeStartFlg = false;
            var fadeCompleteFlg = false;
            if (this._fadeBeginTime >= 0) {
                var fadeState = this._fadeState;
                this._fadeCurrentTime += passedTime < 0 ? -passedTime : passedTime;
                if (this._fadeCurrentTime >= this._fadeBeginTime + this._fadeTotalTime) {
                    if (this._fadeWeight == 1 ||
                        this._fadeWeight == 0) {
                        fadeState = 1;
                        if (this._pausePlayheadInFade) {
                            this._pausePlayheadInFade = false;
                            this._currentTime = -1;
                        }
                    }
                    this._fadeWeight = this._isFadeOut ? 0 : 1;
                }
                else if (this._fadeCurrentTime >= this._fadeBeginTime) {
                    fadeState = 0;
                    this._fadeWeight = (this._fadeCurrentTime - this._fadeBeginTime) / this._fadeTotalTime * this._fadeTotalWeight;
                    if (this._isFadeOut) {
                        this._fadeWeight = this._fadeTotalWeight - this._fadeWeight;
                    }
                }
                else {
                    fadeState = -1;
                    this._fadeWeight = this._isFadeOut ? 1 : 0;
                }
                if (this._fadeState != fadeState) {
                    if (this._fadeState == -1) {
                        fadeStartFlg = true;
                    }
                    if (fadeState == 1) {
                        fadeCompleteFlg = true;
                    }
                    this._fadeState = fadeState;
                }
            }
            var event;
            if (fadeStartFlg) {
                if (this._isFadeOut) {
                    if (this._armature.hasEventListener(dragonBones.AnimationEvent.FADE_OUT)) {
                        event = new dragonBones.AnimationEvent(dragonBones.AnimationEvent.FADE_OUT);
                        event.animationState = this;
                        this._armature._eventList.push(event);
                    }
                }
                else {
                    this.hideBones();
                    if (this._armature.hasEventListener(dragonBones.AnimationEvent.FADE_IN)) {
                        event = new dragonBones.AnimationEvent(dragonBones.AnimationEvent.FADE_IN);
                        event.animationState = this;
                        this._armature._eventList.push(event);
                    }
                }
            }
            if (fadeCompleteFlg) {
                if (this._isFadeOut) {
                    if (this._armature.hasEventListener(dragonBones.AnimationEvent.FADE_OUT_COMPLETE)) {
                        event = new dragonBones.AnimationEvent(dragonBones.AnimationEvent.FADE_OUT_COMPLETE);
                        event.animationState = this;
                        this._armature._eventList.push(event);
                    }
                }
                else {
                    if (this._armature.hasEventListener(dragonBones.AnimationEvent.FADE_IN_COMPLETE)) {
                        event = new dragonBones.AnimationEvent(dragonBones.AnimationEvent.FADE_IN_COMPLETE);
                        event.animationState = this;
                        this._armature._eventList.push(event);
                    }
                }
            }
        };
        p.advanceTimelinesTime = function (passedTime) {
            if (this._isPlaying && !this._pausePlayheadInFade) {
                this._time += passedTime;
            }
            var startFlg = false;
            var completeFlg = false;
            var loopCompleteFlg = false;
            var isThisComplete = false;
            var currentPlayTimes = 0;
            var currentTime = this._time * 1000;
            if (this._playTimes == 0) {
                isThisComplete = false;
                currentPlayTimes = Math.ceil(Math.abs(currentTime) / this._totalTime) || 1;
                if (currentTime >= 0) {
                    currentTime -= Math.floor(currentTime / this._totalTime) * this._totalTime;
                }
                else {
                    currentTime -= Math.ceil(currentTime / this._totalTime) * this._totalTime;
                }
                if (currentTime < 0) {
                    currentTime += this._totalTime;
                }
            }
            else {
                var totalTimes = this._playTimes * this._totalTime;
                if (currentTime >= totalTimes) {
                    currentTime = totalTimes;
                    isThisComplete = true;
                }
                else if (currentTime <= -totalTimes) {
                    currentTime = -totalTimes;
                    isThisComplete = true;
                }
                else {
                    isThisComplete = false;
                }
                if (currentTime < 0) {
                    currentTime += totalTimes;
                }
                currentPlayTimes = Math.ceil(currentTime / this._totalTime) || 1;
                if (currentTime >= 0) {
                    currentTime -= Math.floor(currentTime / this._totalTime) * this._totalTime;
                }
                else {
                    currentTime -= Math.ceil(currentTime / this._totalTime) * this._totalTime;
                }
                if (isThisComplete) {
                    currentTime = this._totalTime;
                }
            }
            this._isComplete = isThisComplete;
            var progress = this._time * 1000 / this._totalTime;
            var i = 0;
            var len = 0;
            for (i = 0, len = this._timelineStateList.length; i < len; i++) {
                var timeline = this._timelineStateList[i];
                timeline._update(progress);
                this._isComplete = timeline._isComplete && this._isComplete;
            }
            for (i = 0, len = this._slotTimelineStateList.length; i < len; i++) {
                var slotTimeline = this._slotTimelineStateList[i];
                slotTimeline._update(progress);
                this._isComplete = timeline._isComplete && this._isComplete;
            }
            if (this._currentTime != currentTime) {
                if (this._currentPlayTimes != currentPlayTimes) {
                    if (this._currentPlayTimes > 0 && currentPlayTimes > 1) {
                        loopCompleteFlg = true;
                    }
                    this._currentPlayTimes = currentPlayTimes;
                }
                if (this._currentTime < 0) {
                    startFlg = true;
                }
                if (this._isComplete) {
                    completeFlg = true;
                }
                this._lastTime = this._currentTime;
                this._currentTime = currentTime;
                this.updateMainTimeline(isThisComplete);
            }
            var event;
            if (startFlg) {
                if (this._armature.hasEventListener(dragonBones.AnimationEvent.START)) {
                    event = new dragonBones.AnimationEvent(dragonBones.AnimationEvent.START);
                    event.animationState = this;
                    this._armature._eventList.push(event);
                }
            }
            if (completeFlg) {
                if (this._armature.hasEventListener(dragonBones.AnimationEvent.COMPLETE)) {
                    event = new dragonBones.AnimationEvent(dragonBones.AnimationEvent.COMPLETE);
                    event.animationState = this;
                    this._armature._eventList.push(event);
                }
                if (this.autoFadeOut) {
                    this.fadeOut(this.fadeOutTime, true);
                }
            }
            else if (loopCompleteFlg) {
                if (this._armature.hasEventListener(dragonBones.AnimationEvent.LOOP_COMPLETE)) {
                    event = new dragonBones.AnimationEvent(dragonBones.AnimationEvent.LOOP_COMPLETE);
                    event.animationState = this;
                    this._armature._eventList.push(event);
                }
            }
        };
        p.updateMainTimeline = function (isThisComplete) {
            var frameList = this._clip.frameList;
            if (frameList.length > 0) {
                var prevFrame;
                var currentFrame;
                for (var i = 0, l = this._clip.frameList.length; i < l; ++i) {
                    if (this._currentFrameIndex < 0) {
                        this._currentFrameIndex = 0;
                    }
                    else if (this._currentTime < this._currentFramePosition || this._currentTime >= this._currentFramePosition + this._currentFrameDuration || this._currentTime < this._lastTime) {
                        this._currentFrameIndex++;
                        this._lastTime = this._currentTime;
                        if (this._currentFrameIndex >= frameList.length) {
                            if (isThisComplete) {
                                this._currentFrameIndex--;
                                break;
                            }
                            else {
                                this._currentFrameIndex = 0;
                            }
                        }
                    }
                    else {
                        break;
                    }
                    currentFrame = frameList[this._currentFrameIndex];
                    if (prevFrame) {
                        this._armature._arriveAtFrame(prevFrame, null, this, true);
                    }
                    this._currentFrameDuration = currentFrame.duration;
                    this._currentFramePosition = currentFrame.position;
                    prevFrame = currentFrame;
                }
                if (currentFrame) {
                    this._armature._arriveAtFrame(currentFrame, null, this, false);
                }
            }
        };
        p.hideBones = function () {
            for (var i = 0, len = this._clip.hideTimelineNameMap.length; i < len; i++) {
                var timelineName = this._clip.hideTimelineNameMap[i];
                var bone = this._armature.getBone(timelineName);
                if (bone) {
                    bone._hideSlots();
                }
            }
            var slotTimelineName;
            for (i = 0, len = this._clip.hideSlotTimelineNameMap.length; i < len; i++) {
                slotTimelineName = this._clip.hideSlotTimelineNameMap[i];
                var slot = this._armature.getSlot(slotTimelineName);
                if (slot) {
                    slot._resetToOrigin();
                }
            }
        };
        p.setAdditiveBlending = function (value) {
            this.additiveBlending = value;
            return this;
        };
        p.setAutoFadeOut = function (value, fadeOutTime) {
            if (fadeOutTime === void 0) { fadeOutTime = -1; }
            this.autoFadeOut = value;
            if (fadeOutTime >= 0) {
                this.fadeOutTime = fadeOutTime * this._timeScale;
            }
            return this;
        };
        p.setWeight = function (value) {
            if (isNaN(value) || value < 0) {
                value = 1;
            }
            this.weight = value;
            return this;
        };
        p.setFrameTween = function (autoTween, lastFrameAutoTween) {
            this.autoTween = autoTween;
            this.lastFrameAutoTween = lastFrameAutoTween;
            return this;
        };
        p.setCurrentTime = function (value) {
            if (value < 0 || isNaN(value)) {
                value = 0;
            }
            this._time = value;
            this._currentTime = this._time * 1000;
            return this;
        };
        p.setTimeScale = function (value) {
            if (isNaN(value) || value == Infinity) {
                value = 1;
            }
            this._timeScale = value;
            return this;
        };
        p.setPlayTimes = function (value) {
            if (value === void 0) { value = 0; }
            if (Math.round(this._totalTime * 0.001 * this._clip.frameRate) < 2) {
                this._playTimes = value < 0 ? -1 : 1;
            }
            else {
                this._playTimes = value < 0 ? -value : value;
            }
            this.autoFadeOut = value < 0 ? true : false;
            return this;
        };
        d(p, "name"
            ,function () {
                return this._name;
            }
        );
        d(p, "layer"
            ,function () {
                return this._layer;
            }
        );
        d(p, "group"
            ,function () {
                return this._group;
            }
        );
        d(p, "clip"
            ,function () {
                return this._clip;
            }
        );
        d(p, "isComplete"
            ,function () {
                return this._isComplete;
            }
        );
        d(p, "isPlaying"
            ,function () {
                return (this._isPlaying && !this._isComplete);
            }
        );
        d(p, "currentPlayTimes"
            ,function () {
                return this._currentPlayTimes < 0 ? 0 : this._currentPlayTimes;
            }
        );
        d(p, "totalTime"
            ,function () {
                return this._totalTime * 0.001;
            }
        );
        d(p, "currentTime"
            ,function () {
                return this._currentTime < 0 ? 0 : this._currentTime * 0.001;
            }
        );
        d(p, "fadeWeight"
            ,function () {
                return this._fadeWeight;
            }
        );
        d(p, "fadeState"
            ,function () {
                return this._fadeState;
            }
        );
        d(p, "fadeTotalTime"
            ,function () {
                return this._fadeTotalTime;
            }
        );
        d(p, "timeScale"
            ,function () {
                return this._timeScale;
            }
        );
        d(p, "playTimes"
            ,function () {
                return this._playTimes;
            }
        );
        AnimationState._pool = [];
        return AnimationState;
    })();
    dragonBones.AnimationState = AnimationState;
    egret.registerClass(AnimationState,'dragonBones.AnimationState');
})(dragonBones || (dragonBones = {}));
var dragonBones;
(function (dragonBones) {
    var SlotTimelineState = (function () {
        function SlotTimelineState() {
            this._totalTime = 0;
            this._currentTime = 0;
            this._currentFrameIndex = 0;
            this._currentFramePosition = 0;
            this._currentFrameDuration = 0;
            this._updateMode = 0;
            this._durationColor = new dragonBones.ColorTransform();
        }
        var d = __define,c=SlotTimelineState,p=c.prototype;
        SlotTimelineState._borrowObject = function () {
            if (SlotTimelineState._pool.length == 0) {
                return new SlotTimelineState();
            }
            return SlotTimelineState._pool.pop();
        };
        SlotTimelineState._returnObject = function (timeline) {
            if (SlotTimelineState._pool.indexOf(timeline) < 0) {
                SlotTimelineState._pool[SlotTimelineState._pool.length] = timeline;
            }
            timeline.clear();
        };
        SlotTimelineState._clear = function () {
            var i = SlotTimelineState._pool.length;
            while (i--) {
                SlotTimelineState._pool[i].clear();
            }
            SlotTimelineState._pool.length = 0;
        };
        p.clear = function () {
            if (this._slot) {
                this._slot._removeState(this);
                this._slot = null;
            }
            this._armature = null;
            this._animation = null;
            this._animationState = null;
            this._timelineData = null;
        };
        p._fadeIn = function (slot, animationState, timelineData) {
            this._slot = slot;
            this._armature = this._slot.armature;
            this._animation = this._armature.animation;
            this._animationState = animationState;
            this._timelineData = timelineData;
            this.name = timelineData.name;
            this._totalTime = this._timelineData.duration;
            this._rawAnimationScale = this._animationState.clip.scale;
            this._isComplete = false;
            this._blendEnabled = false;
            this._tweenColor = false;
            this._currentFrameIndex = -1;
            this._currentTime = -1;
            this._tweenEasing = NaN;
            this._weight = 1;
            switch (this._timelineData.frameList.length) {
                case 0:
                    this._updateMode = 0;
                    break;
                case 1:
                    this._updateMode = 1;
                    break;
                default:
                    this._updateMode = -1;
                    break;
            }
            this._slot._addState(this);
        };
        p._fadeOut = function () {
        };
        p._update = function (progress) {
            if (this._updateMode == -1) {
                this.updateMultipleFrame(progress);
            }
            else if (this._updateMode == 1) {
                this._updateMode = 0;
                this.updateSingleFrame();
            }
        };
        p.updateMultipleFrame = function (progress) {
            var currentPlayTimes = 0;
            progress /= this._timelineData.scale;
            progress += this._timelineData.offset;
            var currentTime = this._totalTime * progress;
            var playTimes = this._animationState.playTimes;
            if (playTimes == 0) {
                this._isComplete = false;
                currentPlayTimes = Math.ceil(Math.abs(currentTime) / this._totalTime) || 1;
                if (currentTime >= 0) {
                    currentTime -= Math.floor(currentTime / this._totalTime) * this._totalTime;
                }
                else {
                    currentTime -= Math.ceil(currentTime / this._totalTime) * this._totalTime;
                }
                if (currentTime < 0) {
                    currentTime += this._totalTime;
                }
            }
            else {
                var totalTimes = playTimes * this._totalTime;
                if (currentTime >= totalTimes) {
                    currentTime = totalTimes;
                    this._isComplete = true;
                }
                else if (currentTime <= -totalTimes) {
                    currentTime = -totalTimes;
                    this._isComplete = true;
                }
                else {
                    this._isComplete = false;
                }
                if (currentTime < 0) {
                    currentTime += totalTimes;
                }
                currentPlayTimes = Math.ceil(currentTime / this._totalTime) || 1;
                if (this._isComplete) {
                    currentTime = this._totalTime;
                }
                else {
                    if (currentTime >= 0) {
                        currentTime -= Math.floor(currentTime / this._totalTime) * this._totalTime;
                    }
                    else {
                        currentTime -= Math.ceil(currentTime / this._totalTime) * this._totalTime;
                    }
                }
            }
            if (this._currentTime != currentTime) {
                this._currentTime = currentTime;
                var frameList = this._timelineData.frameList;
                var prevFrame;
                var currentFrame;
                for (var i = 0, l = this._timelineData.frameList.length; i < l; ++i) {
                    if (this._currentFrameIndex < 0) {
                        this._currentFrameIndex = 0;
                    }
                    else if (this._currentTime < this._currentFramePosition || this._currentTime >= this._currentFramePosition + this._currentFrameDuration) {
                        this._currentFrameIndex++;
                        if (this._currentFrameIndex >= frameList.length) {
                            if (this._isComplete) {
                                this._currentFrameIndex--;
                                break;
                            }
                            else {
                                this._currentFrameIndex = 0;
                            }
                        }
                    }
                    else {
                        break;
                    }
                    currentFrame = (frameList[this._currentFrameIndex]);
                    if (prevFrame) {
                        this._slot._arriveAtFrame(prevFrame, this, this._animationState, true);
                    }
                    this._currentFrameDuration = currentFrame.duration;
                    this._currentFramePosition = currentFrame.position;
                    prevFrame = currentFrame;
                }
                if (currentFrame) {
                    this._slot._arriveAtFrame(currentFrame, this, this._animationState, false);
                    this._blendEnabled = currentFrame.displayIndex >= 0;
                    if (this._blendEnabled) {
                        this.updateToNextFrame(currentPlayTimes);
                    }
                    else {
                        this._tweenEasing = NaN;
                        this._tweenColor = false;
                    }
                }
                if (this._blendEnabled) {
                    this.updateTween();
                }
            }
        };
        p.updateToNextFrame = function (currentPlayTimes) {
            if (currentPlayTimes === void 0) { currentPlayTimes = 0; }
            var nextFrameIndex = this._currentFrameIndex + 1;
            if (nextFrameIndex >= this._timelineData.frameList.length) {
                nextFrameIndex = 0;
            }
            var currentFrame = (this._timelineData.frameList[this._currentFrameIndex]);
            var nextFrame = (this._timelineData.frameList[nextFrameIndex]);
            var tweenEnabled = false;
            if (nextFrameIndex == 0 &&
                (!this._animationState.lastFrameAutoTween ||
                    (this._animationState.playTimes &&
                        this._animationState.currentPlayTimes >= this._animationState.playTimes &&
                        ((this._currentFramePosition + this._currentFrameDuration) / this._totalTime + currentPlayTimes - this._timelineData.offset) * this._timelineData.scale > 0.999999))) {
                this._tweenEasing = NaN;
                tweenEnabled = false;
            }
            else if (currentFrame.displayIndex < 0 || nextFrame.displayIndex < 0) {
                this._tweenEasing = NaN;
                tweenEnabled = false;
            }
            else if (this._animationState.autoTween) {
                this._tweenEasing = this._animationState.clip.tweenEasing;
                if (isNaN(this._tweenEasing)) {
                    this._tweenEasing = currentFrame.tweenEasing;
                    this._tweenCurve = currentFrame.curve;
                    if (isNaN(this._tweenEasing) && this._tweenCurve == null) {
                        tweenEnabled = false;
                    }
                    else {
                        if (this._tweenEasing == 10) {
                            this._tweenEasing = 0;
                        }
                        tweenEnabled = true;
                    }
                }
                else {
                    tweenEnabled = true;
                }
            }
            else {
                this._tweenEasing = currentFrame.tweenEasing;
                this._tweenCurve = currentFrame.curve;
                if ((isNaN(this._tweenEasing) || this._tweenEasing == 10) && this._tweenCurve == null) {
                    this._tweenEasing = NaN;
                    tweenEnabled = false;
                }
                else {
                    tweenEnabled = true;
                }
            }
            if (tweenEnabled) {
                if (currentFrame.color && nextFrame.color) {
                    this._durationColor.alphaOffset = nextFrame.color.alphaOffset - currentFrame.color.alphaOffset;
                    this._durationColor.redOffset = nextFrame.color.redOffset - currentFrame.color.redOffset;
                    this._durationColor.greenOffset = nextFrame.color.greenOffset - currentFrame.color.greenOffset;
                    this._durationColor.blueOffset = nextFrame.color.blueOffset - currentFrame.color.blueOffset;
                    this._durationColor.alphaMultiplier = nextFrame.color.alphaMultiplier - currentFrame.color.alphaMultiplier;
                    this._durationColor.redMultiplier = nextFrame.color.redMultiplier - currentFrame.color.redMultiplier;
                    this._durationColor.greenMultiplier = nextFrame.color.greenMultiplier - currentFrame.color.greenMultiplier;
                    this._durationColor.blueMultiplier = nextFrame.color.blueMultiplier - currentFrame.color.blueMultiplier;
                    if (this._durationColor.alphaOffset ||
                        this._durationColor.redOffset ||
                        this._durationColor.greenOffset ||
                        this._durationColor.blueOffset ||
                        this._durationColor.alphaMultiplier ||
                        this._durationColor.redMultiplier ||
                        this._durationColor.greenMultiplier ||
                        this._durationColor.blueMultiplier) {
                        this._tweenColor = true;
                    }
                    else {
                        this._tweenColor = false;
                    }
                }
                else if (currentFrame.color) {
                    this._tweenColor = true;
                    this._durationColor.alphaOffset = -currentFrame.color.alphaOffset;
                    this._durationColor.redOffset = -currentFrame.color.redOffset;
                    this._durationColor.greenOffset = -currentFrame.color.greenOffset;
                    this._durationColor.blueOffset = -currentFrame.color.blueOffset;
                    this._durationColor.alphaMultiplier = 1 - currentFrame.color.alphaMultiplier;
                    this._durationColor.redMultiplier = 1 - currentFrame.color.redMultiplier;
                    this._durationColor.greenMultiplier = 1 - currentFrame.color.greenMultiplier;
                    this._durationColor.blueMultiplier = 1 - currentFrame.color.blueMultiplier;
                }
                else if (nextFrame.color) {
                    this._tweenColor = true;
                    this._durationColor.alphaOffset = nextFrame.color.alphaOffset;
                    this._durationColor.redOffset = nextFrame.color.redOffset;
                    this._durationColor.greenOffset = nextFrame.color.greenOffset;
                    this._durationColor.blueOffset = nextFrame.color.blueOffset;
                    this._durationColor.alphaMultiplier = nextFrame.color.alphaMultiplier - 1;
                    this._durationColor.redMultiplier = nextFrame.color.redMultiplier - 1;
                    this._durationColor.greenMultiplier = nextFrame.color.greenMultiplier - 1;
                    this._durationColor.blueMultiplier = nextFrame.color.blueMultiplier - 1;
                }
                else {
                    this._tweenColor = false;
                }
            }
            else {
                this._tweenColor = false;
            }
            if (!this._tweenColor && this._animationState.displayControl) {
                if (currentFrame.color) {
                    this._slot._updateDisplayColor(currentFrame.color.alphaOffset, currentFrame.color.redOffset, currentFrame.color.greenOffset, currentFrame.color.blueOffset, currentFrame.color.alphaMultiplier, currentFrame.color.redMultiplier, currentFrame.color.greenMultiplier, currentFrame.color.blueMultiplier, true);
                }
                else if (this._slot._isColorChanged) {
                    this._slot._updateDisplayColor(0, 0, 0, 0, 1, 1, 1, 1, false);
                }
            }
        };
        p.updateTween = function () {
            var currentFrame = (this._timelineData.frameList[this._currentFrameIndex]);
            if (this._tweenColor && this._animationState.displayControl) {
                var progress = (this._currentTime - this._currentFramePosition) / this._currentFrameDuration;
                if (this._tweenCurve != null) {
                    progress = this._tweenCurve.getValueByProgress(progress);
                }
                else if (this._tweenEasing) {
                    progress = dragonBones.MathUtil.getEaseValue(progress, this._tweenEasing);
                }
                if (currentFrame.color) {
                    this._slot._updateDisplayColor(currentFrame.color.alphaOffset + this._durationColor.alphaOffset * progress, currentFrame.color.redOffset + this._durationColor.redOffset * progress, currentFrame.color.greenOffset + this._durationColor.greenOffset * progress, currentFrame.color.blueOffset + this._durationColor.blueOffset * progress, currentFrame.color.alphaMultiplier + this._durationColor.alphaMultiplier * progress, currentFrame.color.redMultiplier + this._durationColor.redMultiplier * progress, currentFrame.color.greenMultiplier + this._durationColor.greenMultiplier * progress, currentFrame.color.blueMultiplier + this._durationColor.blueMultiplier * progress, true);
                }
                else {
                    this._slot._updateDisplayColor(this._durationColor.alphaOffset * progress, this._durationColor.redOffset * progress, this._durationColor.greenOffset * progress, this._durationColor.blueOffset * progress, 1 + this._durationColor.alphaMultiplier * progress, 1 + this._durationColor.redMultiplier * progress, 1 + this._durationColor.greenMultiplier * progress, 1 + this._durationColor.blueMultiplier * progress, true);
                }
            }
        };
        p.updateSingleFrame = function () {
            var currentFrame = (this._timelineData.frameList[0]);
            this._slot._arriveAtFrame(currentFrame, this, this._animationState, false);
            this._isComplete = true;
            this._tweenEasing = NaN;
            this._tweenColor = false;
            this._blendEnabled = currentFrame.displayIndex >= 0;
            if (this._blendEnabled) {
                if (this._animationState.displayControl) {
                    if (currentFrame.color) {
                        this._slot._updateDisplayColor(currentFrame.color.alphaOffset, currentFrame.color.redOffset, currentFrame.color.greenOffset, currentFrame.color.blueOffset, currentFrame.color.alphaMultiplier, currentFrame.color.redMultiplier, currentFrame.color.greenMultiplier, currentFrame.color.blueMultiplier, true);
                    }
                    else if (this._slot._isColorChanged) {
                        this._slot._updateDisplayColor(0, 0, 0, 0, 1, 1, 1, 1, false);
                    }
                }
            }
        };
        SlotTimelineState.HALF_PI = Math.PI * 0.5;
        SlotTimelineState.DOUBLE_PI = Math.PI * 2;
        SlotTimelineState._pool = [];
        return SlotTimelineState;
    })();
    dragonBones.SlotTimelineState = SlotTimelineState;
    egret.registerClass(SlotTimelineState,'dragonBones.SlotTimelineState');
})(dragonBones || (dragonBones = {}));
var dragonBones;
(function (dragonBones) {
    var TimelineState = (function () {
        function TimelineState() {
            this._totalTime = 0;
            this._currentTime = 0;
            this._lastTime = 0;
            this._currentFrameIndex = 0;
            this._currentFramePosition = 0;
            this._currentFrameDuration = 0;
            this._updateMode = 0;
            this._transform = new dragonBones.DBTransform();
            this._pivot = new dragonBones.Point();
            this._durationTransform = new dragonBones.DBTransform();
            this._durationPivot = new dragonBones.Point();
            this._durationColor = new dragonBones.ColorTransform();
        }
        var d = __define,c=TimelineState,p=c.prototype;
        TimelineState._borrowObject = function () {
            if (TimelineState._pool.length == 0) {
                return new TimelineState();
            }
            return TimelineState._pool.pop();
        };
        TimelineState._returnObject = function (timeline) {
            if (TimelineState._pool.indexOf(timeline) < 0) {
                TimelineState._pool[TimelineState._pool.length] = timeline;
            }
            timeline.clear();
        };
        TimelineState._clear = function () {
            var i = TimelineState._pool.length;
            while (i--) {
                TimelineState._pool[i].clear();
            }
            TimelineState._pool.length = 0;
        };
        p.clear = function () {
            if (this._bone) {
                this._bone._removeState(this);
                this._bone = null;
            }
            this._armature = null;
            this._animation = null;
            this._animationState = null;
            this._timelineData = null;
            this._originTransform = null;
            this._originPivot = null;
        };
        p._fadeIn = function (bone, animationState, timelineData) {
            this._bone = bone;
            this._armature = this._bone.armature;
            this._animation = this._armature.animation;
            this._animationState = animationState;
            this._timelineData = timelineData;
            this._originTransform = this._timelineData.originTransform;
            this._originPivot = this._timelineData.originPivot;
            this.name = timelineData.name;
            this._totalTime = this._timelineData.duration;
            this._rawAnimationScale = this._animationState.clip.scale;
            this._isComplete = false;
            this._tweenTransform = false;
            this._tweenScale = false;
            this._currentFrameIndex = -1;
            this._currentTime = -1;
            this._tweenEasing = NaN;
            this._weight = 1;
            this._transform.x = 0;
            this._transform.y = 0;
            this._transform.scaleX = 1;
            this._transform.scaleY = 1;
            this._transform.skewX = 0;
            this._transform.skewY = 0;
            this._pivot.x = 0;
            this._pivot.y = 0;
            this._durationTransform.x = 0;
            this._durationTransform.y = 0;
            this._durationTransform.scaleX = 1;
            this._durationTransform.scaleY = 1;
            this._durationTransform.skewX = 0;
            this._durationTransform.skewY = 0;
            this._durationPivot.x = 0;
            this._durationPivot.y = 0;
            switch (this._timelineData.frameList.length) {
                case 0:
                    this._updateMode = 0;
                    break;
                case 1:
                    this._updateMode = 1;
                    break;
                default:
                    this._updateMode = -1;
                    break;
            }
            this._bone._addState(this);
        };
        p._fadeOut = function () {
            this._transform.skewX = dragonBones.TransformUtil.formatRadian(this._transform.skewX);
            this._transform.skewY = dragonBones.TransformUtil.formatRadian(this._transform.skewY);
        };
        p._update = function (progress) {
            if (this._updateMode == -1) {
                this.updateMultipleFrame(progress);
            }
            else if (this._updateMode == 1) {
                this._updateMode = 0;
                this.updateSingleFrame();
            }
        };
        p.updateMultipleFrame = function (progress) {
            var currentPlayTimes = 0;
            progress /= this._timelineData.scale;
            progress += this._timelineData.offset;
            var currentTime = this._totalTime * progress;
            var playTimes = this._animationState.playTimes;
            if (playTimes == 0) {
                this._isComplete = false;
                currentPlayTimes = Math.ceil(Math.abs(currentTime) / this._totalTime) || 1;
                if (currentTime >= 0) {
                    currentTime -= Math.floor(currentTime / this._totalTime) * this._totalTime;
                }
                else {
                    currentTime -= Math.ceil(currentTime / this._totalTime) * this._totalTime;
                }
                if (currentTime < 0) {
                    currentTime += this._totalTime;
                }
            }
            else {
                var totalTimes = playTimes * this._totalTime;
                if (currentTime >= totalTimes) {
                    currentTime = totalTimes;
                    this._isComplete = true;
                }
                else if (currentTime <= -totalTimes) {
                    currentTime = -totalTimes;
                    this._isComplete = true;
                }
                else {
                    this._isComplete = false;
                }
                if (currentTime < 0) {
                    currentTime += totalTimes;
                }
                currentPlayTimes = Math.ceil(currentTime / this._totalTime) || 1;
                if (this._isComplete) {
                    currentTime = this._totalTime;
                }
                else {
                    if (currentTime >= 0) {
                        currentTime -= Math.floor(currentTime / this._totalTime) * this._totalTime;
                    }
                    else {
                        currentTime -= Math.ceil(currentTime / this._totalTime) * this._totalTime;
                    }
                }
            }
            if (this._currentTime != currentTime) {
                this._lastTime = this._currentTime;
                this._currentTime = currentTime;
                var frameList = this._timelineData.frameList;
                var prevFrame;
                var currentFrame;
                for (var i = 0, l = this._timelineData.frameList.length; i < l; ++i) {
                    if (this._currentFrameIndex < 0) {
                        this._currentFrameIndex = 0;
                    }
                    else if (this._currentTime < this._currentFramePosition || this._currentTime >= this._currentFramePosition + this._currentFrameDuration || this._currentTime < this._lastTime) {
                        this._currentFrameIndex++;
                        this._lastTime = this._currentTime;
                        if (this._currentFrameIndex >= frameList.length) {
                            if (this._isComplete) {
                                this._currentFrameIndex--;
                                break;
                            }
                            else {
                                this._currentFrameIndex = 0;
                            }
                        }
                    }
                    else {
                        break;
                    }
                    currentFrame = (frameList[this._currentFrameIndex]);
                    if (prevFrame) {
                        this._bone._arriveAtFrame(prevFrame, this, this._animationState, true);
                    }
                    this._currentFrameDuration = currentFrame.duration;
                    this._currentFramePosition = currentFrame.position;
                    prevFrame = currentFrame;
                }
                if (currentFrame) {
                    this._bone._arriveAtFrame(currentFrame, this, this._animationState, false);
                    this.updateToNextFrame(currentPlayTimes);
                }
                this.updateTween();
            }
        };
        p.updateToNextFrame = function (currentPlayTimes) {
            if (currentPlayTimes === void 0) { currentPlayTimes = 0; }
            var nextFrameIndex = this._currentFrameIndex + 1;
            if (nextFrameIndex >= this._timelineData.frameList.length) {
                nextFrameIndex = 0;
            }
            var currentFrame = (this._timelineData.frameList[this._currentFrameIndex]);
            var nextFrame = (this._timelineData.frameList[nextFrameIndex]);
            var tweenEnabled = false;
            if (nextFrameIndex == 0 &&
                (!this._animationState.lastFrameAutoTween ||
                    (this._animationState.playTimes &&
                        this._animationState.currentPlayTimes >= this._animationState.playTimes &&
                        ((this._currentFramePosition + this._currentFrameDuration) / this._totalTime + currentPlayTimes - this._timelineData.offset) * this._timelineData.scale > 0.999999))) {
                this._tweenEasing = NaN;
                tweenEnabled = false;
            }
            else if (currentFrame.displayIndex < 0 || nextFrame.displayIndex < 0) {
                this._tweenEasing = NaN;
                tweenEnabled = false;
            }
            else if (this._animationState.autoTween) {
                this._tweenEasing = this._animationState.clip.tweenEasing;
                if (isNaN(this._tweenEasing)) {
                    this._tweenEasing = currentFrame.tweenEasing;
                    this._tweenCurve = currentFrame.curve;
                    if (isNaN(this._tweenEasing) && this._tweenCurve == null) {
                        tweenEnabled = false;
                    }
                    else {
                        if (this._tweenEasing == 10) {
                            this._tweenEasing = 0;
                        }
                        tweenEnabled = true;
                    }
                }
                else {
                    tweenEnabled = true;
                }
            }
            else {
                this._tweenEasing = currentFrame.tweenEasing;
                this._tweenCurve = currentFrame.curve;
                if ((isNaN(this._tweenEasing) || this._tweenEasing == 10) && this._tweenCurve == null) {
                    this._tweenEasing = NaN;
                    tweenEnabled = false;
                }
                else {
                    tweenEnabled = true;
                }
            }
            if (tweenEnabled) {
                this._durationTransform.x = nextFrame.transform.x - currentFrame.transform.x;
                this._durationTransform.y = nextFrame.transform.y - currentFrame.transform.y;
                this._durationTransform.skewX = nextFrame.transform.skewX - currentFrame.transform.skewX;
                this._durationTransform.skewY = nextFrame.transform.skewY - currentFrame.transform.skewY;
                this._durationTransform.scaleX = nextFrame.transform.scaleX - currentFrame.transform.scaleX + nextFrame.scaleOffset.x;
                this._durationTransform.scaleY = nextFrame.transform.scaleY - currentFrame.transform.scaleY + nextFrame.scaleOffset.y;
                this._durationTransform.normalizeRotation();
                if (nextFrameIndex == 0) {
                    this._durationTransform.skewX = dragonBones.TransformUtil.formatRadian(this._durationTransform.skewX);
                    this._durationTransform.skewY = dragonBones.TransformUtil.formatRadian(this._durationTransform.skewY);
                }
                this._durationPivot.x = nextFrame.pivot.x - currentFrame.pivot.x;
                this._durationPivot.y = nextFrame.pivot.y - currentFrame.pivot.y;
                if (this._durationTransform.x ||
                    this._durationTransform.y ||
                    this._durationTransform.skewX ||
                    this._durationTransform.skewY ||
                    this._durationTransform.scaleX ||
                    this._durationTransform.scaleY ||
                    this._durationPivot.x ||
                    this._durationPivot.y) {
                    this._tweenTransform = true;
                    this._tweenScale = currentFrame.tweenScale;
                }
                else {
                    this._tweenTransform = false;
                    this._tweenScale = false;
                }
            }
            else {
                this._tweenTransform = false;
                this._tweenScale = false;
            }
            if (!this._tweenTransform) {
                if (this._animationState.additiveBlending) {
                    this._transform.x = currentFrame.transform.x;
                    this._transform.y = currentFrame.transform.y;
                    this._transform.skewX = currentFrame.transform.skewX;
                    this._transform.skewY = currentFrame.transform.skewY;
                    this._transform.scaleX = currentFrame.transform.scaleX;
                    this._transform.scaleY = currentFrame.transform.scaleY;
                    this._pivot.x = currentFrame.pivot.x;
                    this._pivot.y = currentFrame.pivot.y;
                }
                else {
                    this._transform.x = this._originTransform.x + currentFrame.transform.x;
                    this._transform.y = this._originTransform.y + currentFrame.transform.y;
                    this._transform.skewX = this._originTransform.skewX + currentFrame.transform.skewX;
                    this._transform.skewY = this._originTransform.skewY + currentFrame.transform.skewY;
                    this._transform.scaleX = this._originTransform.scaleX * currentFrame.transform.scaleX;
                    this._transform.scaleY = this._originTransform.scaleY * currentFrame.transform.scaleY;
                    this._pivot.x = this._originPivot.x + currentFrame.pivot.x;
                    this._pivot.y = this._originPivot.y + currentFrame.pivot.y;
                }
                this._bone.invalidUpdate();
            }
            else if (!this._tweenScale) {
                if (this._animationState.additiveBlending) {
                    this._transform.scaleX = currentFrame.transform.scaleX;
                    this._transform.scaleY = currentFrame.transform.scaleY;
                }
                else {
                    this._transform.scaleX = this._originTransform.scaleX * currentFrame.transform.scaleX;
                    this._transform.scaleY = this._originTransform.scaleY * currentFrame.transform.scaleY;
                }
            }
        };
        p.updateTween = function () {
            var currentFrame = (this._timelineData.frameList[this._currentFrameIndex]);
            if (this._tweenTransform) {
                var progress = (this._currentTime - this._currentFramePosition) / this._currentFrameDuration;
                if (this._tweenCurve != null) {
                    progress = this._tweenCurve.getValueByProgress(progress);
                }
                else if (this._tweenEasing) {
                    progress = dragonBones.MathUtil.getEaseValue(progress, this._tweenEasing);
                }
                var currentTransform = currentFrame.transform;
                var currentPivot = currentFrame.pivot;
                if (this._animationState.additiveBlending) {
                    this._transform.x = currentTransform.x + this._durationTransform.x * progress;
                    this._transform.y = currentTransform.y + this._durationTransform.y * progress;
                    this._transform.skewX = currentTransform.skewX + this._durationTransform.skewX * progress;
                    this._transform.skewY = currentTransform.skewY + this._durationTransform.skewY * progress;
                    if (this._tweenScale) {
                        this._transform.scaleX = currentTransform.scaleX + this._durationTransform.scaleX * progress;
                        this._transform.scaleY = currentTransform.scaleY + this._durationTransform.scaleY * progress;
                    }
                    this._pivot.x = currentPivot.x + this._durationPivot.x * progress;
                    this._pivot.y = currentPivot.y + this._durationPivot.y * progress;
                }
                else {
                    this._transform.x = this._originTransform.x + currentTransform.x + this._durationTransform.x * progress;
                    this._transform.y = this._originTransform.y + currentTransform.y + this._durationTransform.y * progress;
                    this._transform.skewX = this._originTransform.skewX + currentTransform.skewX + this._durationTransform.skewX * progress;
                    this._transform.skewY = this._originTransform.skewY + currentTransform.skewY + this._durationTransform.skewY * progress;
                    if (this._tweenScale) {
                        this._transform.scaleX = this._originTransform.scaleX * currentTransform.scaleX + this._durationTransform.scaleX * progress;
                        this._transform.scaleY = this._originTransform.scaleY * currentTransform.scaleY + this._durationTransform.scaleY * progress;
                    }
                    this._pivot.x = this._originPivot.x + currentPivot.x + this._durationPivot.x * progress;
                    this._pivot.y = this._originPivot.y + currentPivot.y + this._durationPivot.y * progress;
                }
                this._bone.invalidUpdate();
            }
        };
        p.updateSingleFrame = function () {
            var currentFrame = (this._timelineData.frameList[0]);
            this._bone._arriveAtFrame(currentFrame, this, this._animationState, false);
            this._isComplete = true;
            this._tweenEasing = NaN;
            this._tweenTransform = false;
            this._tweenScale = false;
            this._tweenColor = false;
            if (this._animationState.additiveBlending) {
                this._transform.x = currentFrame.transform.x;
                this._transform.y = currentFrame.transform.y;
                this._transform.skewX = currentFrame.transform.skewX;
                this._transform.skewY = currentFrame.transform.skewY;
                this._transform.scaleX = currentFrame.transform.scaleX;
                this._transform.scaleY = currentFrame.transform.scaleY;
                this._pivot.x = currentFrame.pivot.x;
                this._pivot.y = currentFrame.pivot.y;
            }
            else {
                this._transform.x = this._originTransform.x + currentFrame.transform.x;
                this._transform.y = this._originTransform.y + currentFrame.transform.y;
                this._transform.skewX = this._originTransform.skewX + currentFrame.transform.skewX;
                this._transform.skewY = this._originTransform.skewY + currentFrame.transform.skewY;
                this._transform.scaleX = this._originTransform.scaleX * currentFrame.transform.scaleX;
                this._transform.scaleY = this._originTransform.scaleY * currentFrame.transform.scaleY;
                this._pivot.x = this._originPivot.x + currentFrame.pivot.x;
                this._pivot.y = this._originPivot.y + currentFrame.pivot.y;
            }
            this._bone.invalidUpdate();
        };
        TimelineState.HALF_PI = Math.PI * 0.5;
        TimelineState.DOUBLE_PI = Math.PI * 2;
        TimelineState._pool = [];
        return TimelineState;
    })();
    dragonBones.TimelineState = TimelineState;
    egret.registerClass(TimelineState,'dragonBones.TimelineState');
})(dragonBones || (dragonBones = {}));
var dragonBones;
(function (dragonBones) {
    var WorldClock = (function () {
        function WorldClock(time, timeScale) {
            if (time === void 0) { time = -1; }
            if (timeScale === void 0) { timeScale = 1; }
            this._time = time >= 0 ? time : new Date().getTime() * 0.001;
            this._timeScale = isNaN(timeScale) ? 1 : timeScale;
            this._animatableList = [];
        }
        var d = __define,c=WorldClock,p=c.prototype;
        d(p, "time"
            ,function () {
                return this._time;
            }
        );
        d(p, "timeScale"
            ,function () {
                return this._timeScale;
            }
            ,function (value) {
                if (isNaN(value) || value < 0) {
                    value = 1;
                }
                this._timeScale = value;
            }
        );
        p.contains = function (animatable) {
            return this._animatableList.indexOf(animatable) >= 0;
        };
        p.add = function (animatable) {
            if (animatable && this._animatableList.indexOf(animatable) == -1) {
                this._animatableList.push(animatable);
            }
        };
        p.remove = function (animatable) {
            var index = this._animatableList.indexOf(animatable);
            if (index >= 0) {
                this._animatableList[index] = null;
            }
        };
        p.clear = function () {
            this._animatableList.length = 0;
        };
        p.advanceTime = function (passedTime) {
            if (passedTime === void 0) { passedTime = -1; }
            if (passedTime < 0) {
                passedTime = new Date().getTime() * 0.001 - this._time;
            }
            passedTime *= this._timeScale;
            this._time += passedTime;
            var length = this._animatableList.length;
            if (length == 0) {
                return;
            }
            var currentIndex = 0;
            for (var i = 0; i < length; i++) {
                var animatable = this._animatableList[i];
                if (animatable) {
                    if (currentIndex != i) {
                        this._animatableList[currentIndex] = animatable;
                        this._animatableList[i] = null;
                    }
                    animatable.advanceTime(passedTime);
                    currentIndex++;
                }
            }
            if (currentIndex != i) {
                length = this._animatableList.length;
                while (i < length) {
                    this._animatableList[currentIndex++] = this._animatableList[i++];
                }
                this._animatableList.length = currentIndex;
            }
        };
        WorldClock.clock = new WorldClock();
        return WorldClock;
    })();
    dragonBones.WorldClock = WorldClock;
    egret.registerClass(WorldClock,'dragonBones.WorldClock',["dragonBones.IAnimatable"]);
})(dragonBones || (dragonBones = {}));
var dragonBones;
(function (dragonBones) {
    var EventDispatcher = (function (_super) {
        __extends(EventDispatcher, _super);
        function EventDispatcher(target) {
            if (target === void 0) { target = null; }
            _super.call(this, target);
        }
        var d = __define,c=EventDispatcher,p=c.prototype;
        return EventDispatcher;
    })(egret.EventDispatcher);
    dragonBones.EventDispatcher = EventDispatcher;
    egret.registerClass(EventDispatcher,'dragonBones.EventDispatcher');
})(dragonBones || (dragonBones = {}));
var dragonBones;
(function (dragonBones) {
    var SoundEventManager = (function (_super) {
        __extends(SoundEventManager, _super);
        function SoundEventManager() {
            _super.call(this);
            if (SoundEventManager._instance) {
                throw new Error("Singleton already constructed!");
            }
        }
        var d = __define,c=SoundEventManager,p=c.prototype;
        SoundEventManager.getInstance = function () {
            if (!SoundEventManager._instance) {
                SoundEventManager._instance = new SoundEventManager();
            }
            return SoundEventManager._instance;
        };
        return SoundEventManager;
    })(dragonBones.EventDispatcher);
    dragonBones.SoundEventManager = SoundEventManager;
    egret.registerClass(SoundEventManager,'dragonBones.SoundEventManager');
})(dragonBones || (dragonBones = {}));
var dragonBones;
(function (dragonBones) {
    var Armature = (function (_super) {
        __extends(Armature, _super);
        function Armature(display) {
            _super.call(this);
            this._display = display;
            this._animation = new dragonBones.Animation(this);
            this._slotsZOrderChanged = false;
            this._slotList = [];
            this._boneList = [];
            this._eventList = [];
            this._delayDispose = false;
            this._lockDispose = false;
            this._armatureData = null;
        }
        var d = __define,c=Armature,p=c.prototype;
        d(p, "armatureData"
            ,function () {
                return this._armatureData;
            }
        );
        d(p, "display"
            ,function () {
                return this._display;
            }
        );
        p.getDisplay = function () {
            return this._display;
        };
        d(p, "animation"
            ,function () {
                return this._animation;
            }
        );
        p.dispose = function () {
            this._delayDispose = true;
            if (!this._animation || this._lockDispose) {
                return;
            }
            this.userData = null;
            this._animation.dispose();
            var i = this._slotList.length;
            while (i--) {
                this._slotList[i].dispose();
            }
            i = this._boneList.length;
            while (i--) {
                this._boneList[i].dispose();
            }
            this._armatureData = null;
            this._animation = null;
            this._slotList = null;
            this._boneList = null;
            this._eventList = null;
        };
        p.invalidUpdate = function (boneName) {
            if (boneName === void 0) { boneName = null; }
            if (boneName) {
                var bone = this.getBone(boneName);
                if (bone) {
                    bone.invalidUpdate();
                }
            }
            else {
                var i = this._boneList.length;
                while (i--) {
                    this._boneList[i].invalidUpdate();
                }
            }
        };
        p.advanceTime = function (passedTime) {
            this._lockDispose = true;
            this._animation._advanceTime(passedTime);
            passedTime *= this._animation.timeScale;
            var isFading = this._animation._isFading;
            var i = this._boneList.length;
            while (i--) {
                var bone = this._boneList[i];
                bone._update(isFading);
            }
            i = this._slotList.length;
            while (i--) {
                var slot = this._slotList[i];
                slot._update();
                if (slot._isShowDisplay) {
                    var childArmature = slot.childArmature;
                    if (childArmature) {
                        childArmature.advanceTime(passedTime);
                    }
                }
            }
            if (this._slotsZOrderChanged) {
                this.updateSlotsZOrder();
                if (this.hasEventListener(dragonBones.ArmatureEvent.Z_ORDER_UPDATED)) {
                    this.dispatchEvent(new dragonBones.ArmatureEvent(dragonBones.ArmatureEvent.Z_ORDER_UPDATED));
                }
            }
            if (this._eventList.length > 0) {
                for (var i = 0, len = this._eventList.length; i < len; i++) {
                    var event = this._eventList[i];
                    this.dispatchEvent(event);
                }
                this._eventList.length = 0;
            }
            this._lockDispose = false;
            if (this._delayDispose) {
                this.dispose();
            }
        };
        p.resetAnimation = function () {
            this.animation.stop();
            this.animation._resetAnimationStateList();
            for (var i = 0, len = this._boneList.length; i < len; i++) {
                this._boneList[i]._removeAllStates();
            }
        };
        p.getSlots = function (returnCopy) {
            if (returnCopy === void 0) { returnCopy = true; }
            return returnCopy ? this._slotList.concat() : this._slotList;
        };
        p.getSlot = function (slotName) {
            var length = this._slotList.length;
            for (var i = 0; i < length; i++) {
                var slot = this._slotList[i];
                if (slot.name == slotName) {
                    return slot;
                }
            }
            return null;
        };
        p.getSlotByDisplay = function (displayObj) {
            if (displayObj) {
                var length = this._slotList.length;
                for (var i = 0; i < length; i++) {
                    var slot = this._slotList[i];
                    if (slot.display == displayObj) {
                        return slot;
                    }
                }
            }
            return null;
        };
        p.addSlot = function (slot, boneName) {
            var bone = this.getBone(boneName);
            if (bone) {
                bone.addSlot(slot);
            }
            else {
                throw new Error();
            }
        };
        p.removeSlot = function (slot) {
            if (!slot || slot.armature != this) {
                throw new Error();
            }
            slot.parent.removeSlot(slot);
        };
        p.removeSlotByName = function (slotName) {
            var slot = this.getSlot(slotName);
            if (slot) {
                this.removeSlot(slot);
            }
            return slot;
        };
        p.getBones = function (returnCopy) {
            if (returnCopy === void 0) { returnCopy = true; }
            return returnCopy ? this._boneList.concat() : this._boneList;
        };
        p.getBone = function (boneName) {
            var length = this._boneList.length;
            for (var i = 0; i < length; i++) {
                var bone = this._boneList[i];
                if (bone.name == boneName) {
                    return bone;
                }
            }
            return null;
        };
        p.getBoneByDisplay = function (display) {
            var slot = this.getSlotByDisplay(display);
            return slot ? slot.parent : null;
        };
        p.addBone = function (bone, parentName, updateLater) {
            if (parentName === void 0) { parentName = null; }
            if (updateLater === void 0) { updateLater = false; }
            var parentBone;
            if (parentName) {
                parentBone = this.getBone(parentName);
                if (!parentBone) {
                    throw new Error();
                }
            }
            if (parentBone) {
                parentBone.addChildBone(bone, updateLater);
            }
            else {
                if (bone.parent) {
                    bone.parent.removeChildBone(bone, updateLater);
                }
                bone._setArmature(this);
                if (!updateLater) {
                    this._updateAnimationAfterBoneListChanged();
                }
            }
        };
        p.removeBone = function (bone, updateLater) {
            if (updateLater === void 0) { updateLater = false; }
            if (!bone || bone.armature != this) {
                throw new Error();
            }
            if (bone.parent) {
                bone.parent.removeChildBone(bone, updateLater);
            }
            else {
                bone._setArmature(null);
                if (!updateLater) {
                    this._updateAnimationAfterBoneListChanged(false);
                }
            }
        };
        p.removeBoneByName = function (boneName) {
            var bone = this.getBone(boneName);
            if (bone) {
                this.removeBone(bone);
            }
            return bone;
        };
        p._addBoneToBoneList = function (bone) {
            if (this._boneList.indexOf(bone) < 0) {
                this._boneList[this._boneList.length] = bone;
            }
        };
        p._removeBoneFromBoneList = function (bone) {
            var index = this._boneList.indexOf(bone);
            if (index >= 0) {
                this._boneList.splice(index, 1);
            }
        };
        p._addSlotToSlotList = function (slot) {
            if (this._slotList.indexOf(slot) < 0) {
                this._slotList[this._slotList.length] = slot;
            }
        };
        p._removeSlotFromSlotList = function (slot) {
            var index = this._slotList.indexOf(slot);
            if (index >= 0) {
                this._slotList.splice(index, 1);
            }
        };
        p.updateSlotsZOrder = function () {
            this._slotList.sort(this.sortSlot);
            var i = this._slotList.length;
            while (i--) {
                var slot = this._slotList[i];
                if (slot._isShowDisplay) {
                    slot._addDisplayToContainer(this._display);
                }
            }
            this._slotsZOrderChanged = false;
        };
        p._updateAnimationAfterBoneListChanged = function (ifNeedSortBoneList) {
            if (ifNeedSortBoneList === void 0) { ifNeedSortBoneList = true; }
            if (ifNeedSortBoneList) {
                this.sortBoneList();
            }
            this._animation._updateAnimationStates();
        };
        p.sortBoneList = function () {
            var i = this._boneList.length;
            if (i == 0) {
                return;
            }
            var helpArray = [];
            while (i--) {
                var level = 0;
                var bone = this._boneList[i];
                var boneParent = bone;
                while (boneParent) {
                    level++;
                    boneParent = boneParent.parent;
                }
                helpArray[i] = [level, bone];
            }
            helpArray.sort(dragonBones.ArmatureData.sortBoneDataHelpArrayDescending);
            i = helpArray.length;
            while (i--) {
                this._boneList[i] = helpArray[i][1];
            }
            helpArray.length = 0;
        };
        p._arriveAtFrame = function (frame, timelineState, animationState, isCross) {
            if (frame.event && this.hasEventListener(dragonBones.FrameEvent.ANIMATION_FRAME_EVENT)) {
                var frameEvent = new dragonBones.FrameEvent(dragonBones.FrameEvent.ANIMATION_FRAME_EVENT);
                frameEvent.animationState = animationState;
                frameEvent.frameLabel = frame.event;
                this._eventList.push(frameEvent);
            }
            if (frame.sound && Armature._soundManager.hasEventListener(dragonBones.SoundEvent.SOUND)) {
                var soundEvent = new dragonBones.SoundEvent(dragonBones.SoundEvent.SOUND);
                soundEvent.armature = this;
                soundEvent.animationState = animationState;
                soundEvent.sound = frame.sound;
                Armature._soundManager.dispatchEvent(soundEvent);
            }
            if (frame.action) {
                if (animationState.displayControl) {
                    this.animation.gotoAndPlay(frame.action);
                }
            }
        };
        p.sortSlot = function (slot1, slot2) {
            return slot1.zOrder < slot2.zOrder ? 1 : -1;
        };
        p.getAnimation = function () {
            return this._animation;
        };
        Armature._soundManager = dragonBones.SoundEventManager.getInstance();
        return Armature;
    })(dragonBones.EventDispatcher);
    dragonBones.Armature = Armature;
    egret.registerClass(Armature,'dragonBones.Armature',["dragonBones.IAnimatable"]);
})(dragonBones || (dragonBones = {}));
var dragonBones;
(function (dragonBones) {
    var Matrix = (function () {
        function Matrix() {
            this.a = 1;
            this.b = 0;
            this.c = 0;
            this.d = 1;
            this.tx = 0;
            this.ty = 0;
        }
        var d = __define,c=Matrix,p=c.prototype;
        p.invert = function () {
            var a1 = this.a;
            var b1 = this.b;
            var c1 = this.c;
            var d1 = this.d;
            var tx1 = this.tx;
            var n = a1 * d1 - b1 * c1;
            this.a = d1 / n;
            this.b = -b1 / n;
            this.c = -c1 / n;
            this.d = a1 / n;
            this.tx = (c1 * this.ty - d1 * tx1) / n;
            this.ty = -(a1 * this.ty - b1 * tx1) / n;
        };
        p.concat = function (m) {
            var ma = m.a;
            var mb = m.b;
            var mc = m.c;
            var md = m.d;
            var tx1 = this.tx;
            var ty1 = this.ty;
            if (ma != 1 || mb != 0 || mc != 0 || md != 1) {
                var a1 = this.a;
                var b1 = this.b;
                var c1 = this.c;
                var d1 = this.d;
                this.a = a1 * ma + b1 * mc;
                this.b = a1 * mb + b1 * md;
                this.c = c1 * ma + d1 * mc;
                this.d = c1 * mb + d1 * md;
            }
            this.tx = tx1 * ma + ty1 * mc + m.tx;
            this.ty = tx1 * mb + ty1 * md + m.ty;
        };
        p.copyFrom = function (m) {
            this.tx = m.tx;
            this.ty = m.ty;
            this.a = m.a;
            this.b = m.b;
            this.c = m.c;
            this.d = m.d;
        };
        return Matrix;
    })();
    dragonBones.Matrix = Matrix;
    egret.registerClass(Matrix,'dragonBones.Matrix');
})(dragonBones || (dragonBones = {}));
var dragonBones;
(function (dragonBones) {
    var DBTransform = (function () {
        function DBTransform() {
            this.x = 0;
            this.y = 0;
            this.skewX = 0;
            this.skewY = 0;
            this.scaleX = 1;
            this.scaleY = 1;
        }
        var d = __define,c=DBTransform,p=c.prototype;
        d(p, "rotation"
            ,function () {
                return this.skewX;
            }
            ,function (value) {
                this.skewX = this.skewY = value;
            }
        );
        p.copy = function (transform) {
            this.x = transform.x;
            this.y = transform.y;
            this.skewX = transform.skewX;
            this.skewY = transform.skewY;
            this.scaleX = transform.scaleX;
            this.scaleY = transform.scaleY;
        };
        p.add = function (transform) {
            this.x += transform.x;
            this.y += transform.y;
            this.skewX += transform.skewX;
            this.skewY += transform.skewY;
            this.scaleX *= transform.scaleX;
            this.scaleY *= transform.scaleY;
        };
        p.minus = function (transform) {
            this.x -= transform.x;
            this.y -= transform.y;
            this.skewX -= transform.skewX;
            this.skewY -= transform.skewY;
            this.scaleX /= transform.scaleX;
            this.scaleY /= transform.scaleY;
        };
        p.normalizeRotation = function () {
            this.skewX = dragonBones.TransformUtil.normalizeRotation(this.skewX);
            this.skewY = dragonBones.TransformUtil.normalizeRotation(this.skewY);
        };
        p.toString = function () {
            var string = "x:" + this.x + " y:" + this.y + " skewX:" + this.skewX + " skewY:" + this.skewY + " scaleX:" + this.scaleX + " scaleY:" + this.scaleY;
            return string;
        };
        return DBTransform;
    })();
    dragonBones.DBTransform = DBTransform;
    egret.registerClass(DBTransform,'dragonBones.DBTransform');
})(dragonBones || (dragonBones = {}));
var dragonBones;
(function (dragonBones) {
    var DBObject = (function () {
        function DBObject() {
            this._globalTransformMatrix = new dragonBones.Matrix();
            this._global = new dragonBones.DBTransform();
            this._origin = new dragonBones.DBTransform();
            this._offset = new dragonBones.DBTransform();
            this._offset.scaleX = this._offset.scaleY = 1;
            this._visible = true;
            this._armature = null;
            this._parent = null;
            this.userData = null;
            this.inheritRotation = true;
            this.inheritScale = true;
            this.inheritTranslation = true;
        }
        var d = __define,c=DBObject,p=c.prototype;
        d(p, "global"
            ,function () {
                return this._global;
            }
        );
        d(p, "origin"
            ,function () {
                return this._origin;
            }
        );
        d(p, "offset"
            ,function () {
                return this._offset;
            }
        );
        d(p, "armature"
            ,function () {
                return this._armature;
            }
        );
        p._setArmature = function (value) {
            this._armature = value;
        };
        d(p, "parent"
            ,function () {
                return this._parent;
            }
        );
        p._setParent = function (value) {
            this._parent = value;
        };
        p.dispose = function () {
            this.userData = null;
            this._globalTransformMatrix = null;
            this._global = null;
            this._origin = null;
            this._offset = null;
            this._armature = null;
            this._parent = null;
        };
        p._calculateRelativeParentTransform = function () {
        };
        p._calculateParentTransform = function () {
            if (this.parent && (this.inheritTranslation || this.inheritRotation || this.inheritScale)) {
                var parentGlobalTransform = this._parent._globalTransformForChild;
                var parentGlobalTransformMatrix = this._parent._globalTransformMatrixForChild;
                if (!this.inheritTranslation || !this.inheritRotation || !this.inheritScale) {
                    parentGlobalTransform = DBObject._tempParentGlobalTransform;
                    parentGlobalTransform.copy(this._parent._globalTransformForChild);
                    if (!this.inheritTranslation) {
                        parentGlobalTransform.x = 0;
                        parentGlobalTransform.y = 0;
                    }
                    if (!this.inheritScale) {
                        parentGlobalTransform.scaleX = 1;
                        parentGlobalTransform.scaleY = 1;
                    }
                    if (!this.inheritRotation) {
                        parentGlobalTransform.skewX = 0;
                        parentGlobalTransform.skewY = 0;
                    }
                    parentGlobalTransformMatrix = DBObject._tempParentGlobalTransformMatrix;
                    dragonBones.TransformUtil.transformToMatrix(parentGlobalTransform, parentGlobalTransformMatrix, true);
                }
                return { parentGlobalTransform: parentGlobalTransform, parentGlobalTransformMatrix: parentGlobalTransformMatrix };
            }
            return null;
        };
        p._updateGlobal = function () {
            this._calculateRelativeParentTransform();
            var output = this._calculateParentTransform();
            if (output != null) {
                var parentMatrix = output.parentGlobalTransformMatrix;
                var parentGlobalTransform = output.parentGlobalTransform;
                var x = this._global.x;
                var y = this._global.y;
                this._global.x = parentMatrix.a * x + parentMatrix.c * y + parentMatrix.tx;
                this._global.y = parentMatrix.d * y + parentMatrix.b * x + parentMatrix.ty;
                if (this.inheritRotation) {
                    this._global.skewX += parentGlobalTransform.skewX;
                    this._global.skewY += parentGlobalTransform.skewY;
                }
                if (this.inheritScale) {
                    this._global.scaleX *= parentGlobalTransform.scaleX;
                    this._global.scaleY *= parentGlobalTransform.scaleY;
                }
            }
            dragonBones.TransformUtil.transformToMatrix(this._global, this._globalTransformMatrix, true);
            return output;
        };
        DBObject._tempParentGlobalTransformMatrix = new dragonBones.Matrix();
        DBObject._tempParentGlobalTransform = new dragonBones.DBTransform();
        return DBObject;
    })();
    dragonBones.DBObject = DBObject;
    egret.registerClass(DBObject,'dragonBones.DBObject');
})(dragonBones || (dragonBones = {}));
var dragonBones;
(function (dragonBones) {
    var Bone = (function (_super) {
        __extends(Bone, _super);
        function Bone() {
            _super.call(this);
            this.applyOffsetTranslationToChild = true;
            this.applyOffsetRotationToChild = true;
            this.applyOffsetScaleToChild = false;
            this._needUpdate = 0;
            this._tween = new dragonBones.DBTransform();
            this._tweenPivot = new dragonBones.Point();
            this._tween.scaleX = this._tween.scaleY = 1;
            this._boneList = [];
            this._slotList = [];
            this._timelineStateList = [];
            this._needUpdate = 2;
            this._isColorChanged = false;
        }
        var d = __define,c=Bone,p=c.prototype;
        Bone.initWithBoneData = function (boneData) {
            var outputBone = new Bone();
            outputBone.name = boneData.name;
            outputBone.inheritRotation = boneData.inheritRotation;
            outputBone.inheritScale = boneData.inheritScale;
            outputBone.origin.copy(boneData.transform);
            return outputBone;
        };
        p.dispose = function () {
            if (!this._boneList) {
                return;
            }
            _super.prototype.dispose.call(this);
            var i = this._boneList.length;
            while (i--) {
                this._boneList[i].dispose();
            }
            i = this._slotList.length;
            while (i--) {
                this._slotList[i].dispose();
            }
            this._tween = null;
            this._tweenPivot = null;
            this._boneList = null;
            this._slotList = null;
            this._timelineStateList = null;
        };
        p.contains = function (child) {
            if (!child) {
                throw new Error();
            }
            if (child == this) {
                return false;
            }
            var ancestor = child;
            while (!(ancestor == this || ancestor == null)) {
                ancestor = ancestor.parent;
            }
            return ancestor == this;
        };
        p.addChildBone = function (childBone, updateLater) {
            if (updateLater === void 0) { updateLater = false; }
            if (!childBone) {
                throw new Error();
            }
            if (childBone == this || childBone.contains(this)) {
                throw new Error();
            }
            if (childBone.parent == this) {
                return;
            }
            if (childBone.parent) {
                childBone.parent.removeChildBone(childBone, updateLater);
            }
            this._boneList[this._boneList.length] = childBone;
            childBone._setParent(this);
            childBone._setArmature(this._armature);
            if (this._armature && !updateLater) {
                this._armature._updateAnimationAfterBoneListChanged();
            }
        };
        p.removeChildBone = function (childBone, updateLater) {
            if (updateLater === void 0) { updateLater = false; }
            if (!childBone) {
                throw new Error();
            }
            var index = this._boneList.indexOf(childBone);
            if (index < 0) {
                throw new Error();
            }
            this._boneList.splice(index, 1);
            childBone._setParent(null);
            childBone._setArmature(null);
            if (this._armature && !updateLater) {
                this._armature._updateAnimationAfterBoneListChanged(false);
            }
        };
        p.addSlot = function (childSlot) {
            if (!childSlot) {
                throw new Error();
            }
            if (childSlot.parent) {
                childSlot.parent.removeSlot(childSlot);
            }
            this._slotList[this._slotList.length] = childSlot;
            childSlot._setParent(this);
            childSlot.setArmature(this._armature);
        };
        p.removeSlot = function (childSlot) {
            if (!childSlot) {
                throw new Error();
            }
            var index = this._slotList.indexOf(childSlot);
            if (index < 0) {
                throw new Error();
            }
            this._slotList.splice(index, 1);
            childSlot._setParent(null);
            childSlot.setArmature(null);
        };
        p._setArmature = function (value) {
            if (this._armature == value) {
                return;
            }
            if (this._armature) {
                this._armature._removeBoneFromBoneList(this);
                this._armature._updateAnimationAfterBoneListChanged(false);
            }
            this._armature = value;
            if (this._armature) {
                this._armature._addBoneToBoneList(this);
            }
            var i = this._boneList.length;
            while (i--) {
                this._boneList[i]._setArmature(this._armature);
            }
            i = this._slotList.length;
            while (i--) {
                this._slotList[i].setArmature(this._armature);
            }
        };
        p.getBones = function (returnCopy) {
            if (returnCopy === void 0) { returnCopy = true; }
            return returnCopy ? this._boneList.concat() : this._boneList;
        };
        p.getSlots = function (returnCopy) {
            if (returnCopy === void 0) { returnCopy = true; }
            return returnCopy ? this._slotList.concat() : this._slotList;
        };
        p.invalidUpdate = function () {
            this._needUpdate = 2;
        };
        p._calculateRelativeParentTransform = function () {
            this._global.scaleX = this._origin.scaleX * this._tween.scaleX * this._offset.scaleX;
            this._global.scaleY = this._origin.scaleY * this._tween.scaleY * this._offset.scaleY;
            this._global.skewX = this._origin.skewX + this._tween.skewX + this._offset.skewX;
            this._global.skewY = this._origin.skewY + this._tween.skewY + this._offset.skewY;
            this._global.x = this._origin.x + this._tween.x + this._offset.x;
            this._global.y = this._origin.y + this._tween.y + this._offset.y;
        };
        p._update = function (needUpdate) {
            if (needUpdate === void 0) { needUpdate = false; }
            this._needUpdate--;
            if (needUpdate || this._needUpdate > 0 || (this._parent && this._parent._needUpdate > 0)) {
                this._needUpdate = 1;
            }
            else {
                return;
            }
            this.blendingTimeline();
            var result = this._updateGlobal();
            var parentGlobalTransform = result ? result.parentGlobalTransform : null;
            var parentGlobalTransformMatrix = result ? result.parentGlobalTransformMatrix : null;
            var ifExistOffsetTranslation = this._offset.x != 0 || this._offset.y != 0;
            var ifExistOffsetScale = this._offset.scaleX != 0 || this._offset.scaleY != 0;
            var ifExistOffsetRotation = this._offset.skewX != 0 || this._offset.skewY != 0;
            if ((!ifExistOffsetTranslation || this.applyOffsetTranslationToChild) &&
                (!ifExistOffsetScale || this.applyOffsetScaleToChild) &&
                (!ifExistOffsetRotation || this.applyOffsetRotationToChild)) {
                this._globalTransformForChild = this._global;
                this._globalTransformMatrixForChild = this._globalTransformMatrix;
            }
            else {
                if (!this._tempGlobalTransformForChild) {
                    this._tempGlobalTransformForChild = new dragonBones.DBTransform();
                }
                this._globalTransformForChild = this._tempGlobalTransformForChild;
                if (!this._tempGlobalTransformMatrixForChild) {
                    this._tempGlobalTransformMatrixForChild = new dragonBones.Matrix();
                }
                this._globalTransformMatrixForChild = this._tempGlobalTransformMatrixForChild;
                this._globalTransformForChild.x = this._origin.x + this._tween.x;
                this._globalTransformForChild.y = this._origin.y + this._tween.y;
                this._globalTransformForChild.scaleX = this._origin.scaleX * this._tween.scaleX;
                this._globalTransformForChild.scaleY = this._origin.scaleY * this._tween.scaleY;
                this._globalTransformForChild.skewX = this._origin.skewX + this._tween.skewX;
                this._globalTransformForChild.skewY = this._origin.skewY + this._tween.skewY;
                if (this.applyOffsetTranslationToChild) {
                    this._globalTransformForChild.x += this._offset.x;
                    this._globalTransformForChild.y += this._offset.y;
                }
                if (this.applyOffsetScaleToChild) {
                    this._globalTransformForChild.scaleX *= this._offset.scaleX;
                    this._globalTransformForChild.scaleY *= this._offset.scaleY;
                }
                if (this.applyOffsetRotationToChild) {
                    this._globalTransformForChild.skewX += this._offset.skewX;
                    this._globalTransformForChild.skewY += this._offset.skewY;
                }
                dragonBones.TransformUtil.transformToMatrix(this._globalTransformForChild, this._globalTransformMatrixForChild, true);
                if (parentGlobalTransformMatrix) {
                    this._globalTransformMatrixForChild.concat(parentGlobalTransformMatrix);
                    dragonBones.TransformUtil.matrixToTransform(this._globalTransformMatrixForChild, this._globalTransformForChild, this._globalTransformForChild.scaleX * parentGlobalTransform.scaleX >= 0, this._globalTransformForChild.scaleY * parentGlobalTransform.scaleY >= 0);
                }
            }
        };
        p._updateColor = function (aOffset, rOffset, gOffset, bOffset, aMultiplier, rMultiplier, gMultiplier, bMultiplier, colorChanged) {
            var length = this._slotList.length;
            for (var i = 0; i < length; i++) {
                var childSlot = this._slotList[i];
                childSlot._updateDisplayColor(aOffset, rOffset, gOffset, bOffset, aMultiplier, rMultiplier, gMultiplier, bMultiplier);
            }
            this._isColorChanged = colorChanged;
        };
        p._hideSlots = function () {
            var length = this._slotList.length;
            for (var i = 0; i < length; i++) {
                var childSlot = this._slotList[i];
                childSlot._changeDisplay(-1);
            }
        };
        p._arriveAtFrame = function (frame, timelineState, animationState, isCross) {
            var displayControl = animationState.displayControl &&
                (!this.displayController || this.displayController == animationState.name) &&
                animationState.containsBoneMask(this.name);
            if (displayControl) {
                var tansformFrame = frame;
                var displayIndex = tansformFrame.displayIndex;
                var childSlot;
                if (frame.event && this._armature.hasEventListener(dragonBones.FrameEvent.BONE_FRAME_EVENT)) {
                    var frameEvent = new dragonBones.FrameEvent(dragonBones.FrameEvent.BONE_FRAME_EVENT);
                    frameEvent.bone = this;
                    frameEvent.animationState = animationState;
                    frameEvent.frameLabel = frame.event;
                    this._armature._eventList.push(frameEvent);
                }
                if (frame.sound && Bone._soundManager.hasEventListener(dragonBones.SoundEvent.SOUND)) {
                    var soundEvent = new dragonBones.SoundEvent(dragonBones.SoundEvent.SOUND);
                    soundEvent.armature = this._armature;
                    soundEvent.animationState = animationState;
                    soundEvent.sound = frame.sound;
                    Bone._soundManager.dispatchEvent(soundEvent);
                }
                if (frame.action) {
                    var length1 = this._slotList.length;
                    for (var i1 = 0; i1 < length1; i1++) {
                        childSlot = this._slotList[i1];
                        var childArmature = childSlot.childArmature;
                        if (childArmature) {
                            childArmature.animation.gotoAndPlay(frame.action);
                        }
                    }
                }
            }
        };
        p._addState = function (timelineState) {
            if (this._timelineStateList.indexOf(timelineState) < 0) {
                this._timelineStateList.push(timelineState);
                this._timelineStateList.sort(this.sortState);
            }
        };
        p._removeState = function (timelineState) {
            var index = this._timelineStateList.indexOf(timelineState);
            if (index >= 0) {
                this._timelineStateList.splice(index, 1);
            }
        };
        p._removeAllStates = function () {
            this._timelineStateList.length = 0;
        };
        p.blendingTimeline = function () {
            var timelineState;
            var transform;
            var pivot;
            var weight;
            var i = this._timelineStateList.length;
            if (i == 1) {
                timelineState = this._timelineStateList[0];
                weight = timelineState._animationState.weight * timelineState._animationState.fadeWeight;
                timelineState._weight = weight;
                transform = timelineState._transform;
                pivot = timelineState._pivot;
                this._tween.x = transform.x * weight;
                this._tween.y = transform.y * weight;
                this._tween.skewX = transform.skewX * weight;
                this._tween.skewY = transform.skewY * weight;
                this._tween.scaleX = 1 + (transform.scaleX - 1) * weight;
                this._tween.scaleY = 1 + (transform.scaleY - 1) * weight;
                this._tweenPivot.x = pivot.x * weight;
                this._tweenPivot.y = pivot.y * weight;
            }
            else if (i > 1) {
                var x = 0;
                var y = 0;
                var skewX = 0;
                var skewY = 0;
                var scaleX = 1;
                var scaleY = 1;
                var pivotX = 0;
                var pivotY = 0;
                var weigthLeft = 1;
                var layerTotalWeight = 0;
                var prevLayer = this._timelineStateList[i - 1]._animationState.layer;
                var currentLayer = 0;
                while (i--) {
                    timelineState = this._timelineStateList[i];
                    currentLayer = timelineState._animationState.layer;
                    if (prevLayer != currentLayer) {
                        if (layerTotalWeight >= weigthLeft) {
                            timelineState._weight = 0;
                            break;
                        }
                        else {
                            weigthLeft -= layerTotalWeight;
                        }
                    }
                    prevLayer = currentLayer;
                    weight = timelineState._animationState.weight * timelineState._animationState.fadeWeight * weigthLeft;
                    timelineState._weight = weight;
                    if (weight) {
                        transform = timelineState._transform;
                        pivot = timelineState._pivot;
                        x += transform.x * weight;
                        y += transform.y * weight;
                        skewX += transform.skewX * weight;
                        skewY += transform.skewY * weight;
                        scaleX += (transform.scaleX - 1) * weight;
                        scaleY += (transform.scaleY - 1) * weight;
                        pivotX += pivot.x * weight;
                        pivotY += pivot.y * weight;
                        layerTotalWeight += weight;
                    }
                }
                this._tween.x = x;
                this._tween.y = y;
                this._tween.skewX = skewX;
                this._tween.skewY = skewY;
                this._tween.scaleX = scaleX;
                this._tween.scaleY = scaleY;
                this._tweenPivot.x = pivotX;
                this._tweenPivot.y = pivotY;
            }
        };
        p.sortState = function (state1, state2) {
            return state1._animationState.layer < state2._animationState.layer ? -1 : 1;
        };
        d(p, "childArmature"
            ,function () {
                if (this.slot) {
                    return this.slot.childArmature;
                }
                return null;
            }
        );
        d(p, "display"
            ,function () {
                if (this.slot) {
                    return this.slot.display;
                }
                return null;
            }
            ,function (value) {
                if (this.slot) {
                    this.slot.display = value;
                }
            }
        );
        d(p, "node"
            ,function () {
                return this._offset;
            }
        );
        d(p, "visible",undefined
            ,function (value) {
                if (this._visible != value) {
                    this._visible = value;
                    var length = this._slotList.length;
                    for (var i = 0; i < length; i++) {
                        var childSlot = this._slotList[i];
                        childSlot._updateDisplayVisible(this._visible);
                    }
                }
            }
        );
        d(p, "slot"
            ,function () {
                return this._slotList.length > 0 ? this._slotList[0] : null;
            }
        );
        Bone._soundManager = dragonBones.SoundEventManager.getInstance();
        return Bone;
    })(dragonBones.DBObject);
    dragonBones.Bone = Bone;
    egret.registerClass(Bone,'dragonBones.Bone');
})(dragonBones || (dragonBones = {}));
var dragonBones;
(function (dragonBones) {
    var Slot = (function (_super) {
        __extends(Slot, _super);
        function Slot(self) {
            _super.call(this);
            this._currentDisplayIndex = 0;
            if (self != this) {
                throw new Error(egret.getString(4001));
            }
            this._displayList = [];
            this._timelineStateList = [];
            this._currentDisplayIndex = -1;
            this._originZOrder = 0;
            this._tweenZOrder = 0;
            this._offsetZOrder = 0;
            this._isShowDisplay = false;
            this._colorTransform = new dragonBones.ColorTransform();
            this._displayDataList = null;
            this._currentDisplay = null;
            this.inheritRotation = true;
            this.inheritScale = true;
        }
        var d = __define,c=Slot,p=c.prototype;
        p.initWithSlotData = function (slotData) {
            this.name = slotData.name;
            this.blendMode = slotData.blendMode;
            this._originZOrder = slotData.zOrder;
            this._displayDataList = slotData.displayDataList;
            this._originDisplayIndex = slotData.displayIndex;
        };
        p.dispose = function () {
            if (!this._displayList) {
                return;
            }
            _super.prototype.dispose.call(this);
            this._displayList.length = 0;
            this._displayDataList = null;
            this._displayList = null;
            this._currentDisplay = null;
        };
        p.sortState = function (state1, state2) {
            return state1._animationState.layer < state2._animationState.layer ? -1 : 1;
        };
        p._addState = function (timelineState) {
            if (this._timelineStateList.indexOf(timelineState) < 0) {
                this._timelineStateList.push(timelineState);
                this._timelineStateList.sort(this.sortState);
            }
        };
        p._removeState = function (timelineState) {
            var index = this._timelineStateList.indexOf(timelineState);
            if (index >= 0) {
                this._timelineStateList.splice(index, 1);
            }
        };
        p.setArmature = function (value) {
            if (this._armature == value) {
                return;
            }
            if (this._armature) {
                this._armature._removeSlotFromSlotList(this);
            }
            this._armature = value;
            if (this._armature) {
                this._armature._addSlotToSlotList(this);
                this._armature._slotsZOrderChanged = true;
                this._addDisplayToContainer(this._armature.display);
            }
            else {
                this._removeDisplayFromContainer();
            }
        };
        p._update = function () {
            if (this._parent._needUpdate <= 0 && !this._needUpdate) {
                return;
            }
            this._updateGlobal();
            this._updateTransform();
            this._needUpdate = false;
        };
        p._calculateRelativeParentTransform = function () {
            this._global.scaleX = this._origin.scaleX * this._offset.scaleX;
            this._global.scaleY = this._origin.scaleY * this._offset.scaleY;
            this._global.skewX = this._origin.skewX + this._offset.skewX;
            this._global.skewY = this._origin.skewY + this._offset.skewY;
            this._global.x = this._origin.x + this._offset.x + this._parent._tweenPivot.x;
            this._global.y = this._origin.y + this._offset.y + this._parent._tweenPivot.y;
        };
        p.updateChildArmatureAnimation = function () {
            if (this.childArmature) {
                if (this._isShowDisplay) {
                    if (this._armature &&
                        this._armature.animation.lastAnimationState &&
                        this.childArmature.animation.hasAnimation(this._armature.animation.lastAnimationState.name)) {
                        this.childArmature.animation.gotoAndPlay(this._armature.animation.lastAnimationState.name);
                    }
                    else {
                        this.childArmature.animation.play();
                    }
                }
                else {
                    this.childArmature.animation.stop();
                    this.childArmature.animation._lastAnimationState = null;
                }
            }
        };
        p._changeDisplay = function (displayIndex) {
            if (displayIndex === void 0) { displayIndex = 0; }
            if (displayIndex < 0) {
                if (this._isShowDisplay) {
                    this._isShowDisplay = false;
                    this._removeDisplayFromContainer();
                    this.updateChildArmatureAnimation();
                }
            }
            else if (this._displayList.length > 0) {
                var length = this._displayList.length;
                if (displayIndex >= length) {
                    displayIndex = length - 1;
                }
                if (this._currentDisplayIndex != displayIndex) {
                    this._isShowDisplay = true;
                    this._currentDisplayIndex = displayIndex;
                    this._updateSlotDisplay();
                    this.updateChildArmatureAnimation();
                    if (this._displayDataList &&
                        this._displayDataList.length > 0 &&
                        this._currentDisplayIndex < this._displayDataList.length) {
                        this._origin.copy(this._displayDataList[this._currentDisplayIndex].transform);
                    }
                    this._needUpdate = true;
                }
                else if (!this._isShowDisplay) {
                    this._isShowDisplay = true;
                    if (this._armature) {
                        this._armature._slotsZOrderChanged = true;
                        this._addDisplayToContainer(this._armature.display);
                    }
                    this.updateChildArmatureAnimation();
                }
            }
        };
        p._updateSlotDisplay = function () {
            var currentDisplayIndex = -1;
            if (this._currentDisplay) {
                currentDisplayIndex = this._getDisplayIndex();
                this._removeDisplayFromContainer();
            }
            var displayObj = this._displayList[this._currentDisplayIndex];
            if (displayObj) {
                if (displayObj instanceof dragonBones.Armature) {
                    this._currentDisplay = displayObj.display;
                }
                else {
                    this._currentDisplay = displayObj;
                }
            }
            else {
                this._currentDisplay = null;
            }
            this._updateDisplay(this._currentDisplay);
            if (this._currentDisplay) {
                if (this._armature && this._isShowDisplay) {
                    if (currentDisplayIndex < 0) {
                        this._armature._slotsZOrderChanged = true;
                        this._addDisplayToContainer(this._armature.display);
                    }
                    else {
                        this._addDisplayToContainer(this._armature.display, currentDisplayIndex);
                    }
                }
                this._updateDisplayBlendMode(this._blendMode);
                this._updateDisplayColor(this._colorTransform.alphaOffset, this._colorTransform.redOffset, this._colorTransform.greenOffset, this._colorTransform.blueOffset, this._colorTransform.alphaMultiplier, this._colorTransform.redMultiplier, this._colorTransform.greenMultiplier, this._colorTransform.blueMultiplier, true);
                this._updateDisplayVisible(this._visible);
                this._updateTransform();
            }
        };
        d(p, "visible",undefined
            ,function (value) {
                if (this._visible != value) {
                    this._visible = value;
                    this._updateDisplayVisible(this._visible);
                }
            }
        );
        d(p, "displayList"
            ,function () {
                return this._displayList;
            }
            ,function (value) {
                if (!value) {
                    throw new Error();
                }
                if (this._currentDisplayIndex < 0) {
                    this._currentDisplayIndex = 0;
                }
                var i = this._displayList.length = value.length;
                while (i--) {
                    this._displayList[i] = value[i];
                }
                var displayIndexBackup = this._currentDisplayIndex;
                this._currentDisplayIndex = -1;
                this._changeDisplay(displayIndexBackup);
            }
        );
        d(p, "display"
            ,function () {
                return this._currentDisplay;
            }
            ,function (value) {
                if (this._currentDisplayIndex < 0) {
                    this._currentDisplayIndex = 0;
                }
                if (this._displayList[this._currentDisplayIndex] == value) {
                    return;
                }
                this._displayList[this._currentDisplayIndex] = value;
                this._updateSlotDisplay();
                this.updateChildArmatureAnimation();
                this._updateTransform();
            }
        );
        p.getDisplay = function () {
            return this.display;
        };
        p.setDisplay = function (value) {
            this.display = value;
        };
        d(p, "childArmature"
            ,function () {
                if (this._displayList[this._currentDisplayIndex] instanceof dragonBones.Armature) {
                    return (this._displayList[this._currentDisplayIndex]);
                }
                return null;
            }
            ,function (value) {
                this.display = value;
            }
        );
        d(p, "zOrder"
            ,function () {
                return this._originZOrder + this._tweenZOrder + this._offsetZOrder;
            }
            ,function (value) {
                if (this.zOrder != value) {
                    this._offsetZOrder = value - this._originZOrder - this._tweenZOrder;
                    if (this._armature) {
                        this._armature._slotsZOrderChanged = true;
                    }
                }
            }
        );
        d(p, "blendMode"
            ,function () {
                return this._blendMode;
            }
            ,function (value) {
                if (this._blendMode != value) {
                    this._blendMode = value;
                    this._updateDisplayBlendMode(this._blendMode);
                }
            }
        );
        p._updateDisplay = function (value) {
            throw new Error("");
        };
        p._getDisplayIndex = function () {
            throw new Error(egret.getString(4001));
        };
        p._addDisplayToContainer = function (container, index) {
            if (index === void 0) { index = -1; }
            throw new Error(egret.getString(4001));
        };
        p._removeDisplayFromContainer = function () {
            throw new Error(egret.getString(4001));
        };
        p._updateTransform = function () {
            throw new Error(egret.getString(4001));
        };
        p._updateDisplayVisible = function (value) {
            throw new Error(egret.getString(4001));
        };
        p._updateDisplayColor = function (aOffset, rOffset, gOffset, bOffset, aMultiplier, rMultiplier, gMultiplier, bMultiplier, colorChanged) {
            if (colorChanged === void 0) { colorChanged = false; }
            this._colorTransform.alphaOffset = aOffset;
            this._colorTransform.redOffset = rOffset;
            this._colorTransform.greenOffset = gOffset;
            this._colorTransform.blueOffset = bOffset;
            this._colorTransform.alphaMultiplier = aMultiplier;
            this._colorTransform.redMultiplier = rMultiplier;
            this._colorTransform.greenMultiplier = gMultiplier;
            this._colorTransform.blueMultiplier = bMultiplier;
            this._isColorChanged = colorChanged;
        };
        p._updateDisplayBlendMode = function (value) {
            throw new Error("Abstract method needs to be implemented in subclass!");
        };
        p._arriveAtFrame = function (frame, timelineState, animationState, isCross) {
            var displayControl = animationState.displayControl &&
                animationState.containsBoneMask(this.parent.name);
            if (displayControl) {
                var slotFrame = frame;
                var displayIndex = slotFrame.displayIndex;
                var childSlot;
                this._changeDisplay(displayIndex);
                this._updateDisplayVisible(slotFrame.visible);
                if (displayIndex >= 0) {
                    if (!isNaN(slotFrame.zOrder) && slotFrame.zOrder != this._tweenZOrder) {
                        this._tweenZOrder = slotFrame.zOrder;
                        this._armature._slotsZOrderChanged = true;
                    }
                }
                if (frame.action) {
                    if (this.childArmature) {
                        this.childArmature.animation.gotoAndPlay(frame.action);
                    }
                }
            }
        };
        p._updateGlobal = function () {
            this._calculateRelativeParentTransform();
            dragonBones.TransformUtil.transformToMatrix(this._global, this._globalTransformMatrix, true);
            var output = this._calculateParentTransform();
            if (output) {
                this._globalTransformMatrix.concat(output.parentGlobalTransformMatrix);
                dragonBones.TransformUtil.matrixToTransform(this._globalTransformMatrix, this._global, this._global.scaleX * output.parentGlobalTransform.scaleX >= 0, this._global.scaleY * output.parentGlobalTransform.scaleY >= 0);
            }
            return output;
        };
        p._resetToOrigin = function () {
            this._changeDisplay(this._originDisplayIndex);
            this._updateDisplayColor(0, 0, 0, 0, 1, 1, 1, 1, true);
        };
        return Slot;
    })(dragonBones.DBObject);
    dragonBones.Slot = Slot;
    egret.registerClass(Slot,'dragonBones.Slot');
})(dragonBones || (dragonBones = {}));
var dragonBones;
(function (dragonBones) {
    var AnimationCache = (function () {
        function AnimationCache() {
            this.slotTimelineCacheList = [];
            this.slotTimelineCacheDic = {};
            this.frameNum = 0;
        }
        var d = __define,c=AnimationCache,p=c.prototype;
        AnimationCache.initWithAnimationData = function (animationData, armatureData) {
            var output = new AnimationCache();
            output.name = animationData.name;
            var boneTimelineList = animationData.timelineList;
            var boneName;
            var boneData;
            var slotData;
            var slotTimelineCache;
            var slotName;
            for (var i = 0, length = boneTimelineList.length; i < length; i++) {
                boneName = boneTimelineList[i].name;
                for (var j = 0, jlen = armatureData.slotDataList.length; j < jlen; j++) {
                    slotData = armatureData.slotDataList[j];
                    slotName = slotData.name;
                    if (slotData.parent == boneName) {
                        if (output.slotTimelineCacheDic[slotName] == null) {
                            slotTimelineCache = new dragonBones.SlotTimelineCache();
                            slotTimelineCache.name = slotName;
                            output.slotTimelineCacheList.push(slotTimelineCache);
                            output.slotTimelineCacheDic[slotName] = slotTimelineCache;
                        }
                    }
                }
            }
            return output;
        };
        p.initSlotTimelineCacheDic = function (slotCacheGeneratorDic, slotFrameCacheDic) {
            var name;
            for (var k in this.slotTimelineCacheDic) {
                var slotTimelineCache = this.slotTimelineCacheDic[k];
                name = slotTimelineCache.name;
                slotTimelineCache.cacheGenerator = slotCacheGeneratorDic[name];
                slotTimelineCache.currentFrameCache = slotFrameCacheDic[name];
            }
        };
        p.bindCacheUserSlotDic = function (slotDic) {
            for (var name in slotDic) {
                (this.slotTimelineCacheDic[name]).bindCacheUser(slotDic[name]);
            }
        };
        p.addFrame = function () {
            this.frameNum++;
            var slotTimelineCache;
            for (var i = 0, length = this.slotTimelineCacheList.length; i < length; i++) {
                slotTimelineCache = this.slotTimelineCacheList[i];
                slotTimelineCache.addFrame();
            }
        };
        p.update = function (progress) {
            var frameIndex = Math.floor(progress * (this.frameNum - 1));
            var slotTimelineCache;
            for (var i = 0, length = this.slotTimelineCacheList.length; i < length; i++) {
                slotTimelineCache = this.slotTimelineCacheList[i];
                slotTimelineCache.update(frameIndex);
            }
        };
        return AnimationCache;
    })();
    dragonBones.AnimationCache = AnimationCache;
    egret.registerClass(AnimationCache,'dragonBones.AnimationCache');
})(dragonBones || (dragonBones = {}));
var dragonBones;
(function (dragonBones) {
    var AnimationCacheManager = (function () {
        function AnimationCacheManager() {
            this.animationCacheDic = {};
            this.slotFrameCacheDic = {};
        }
        var d = __define,c=AnimationCacheManager,p=c.prototype;
        AnimationCacheManager.initWithArmatureData = function (armatureData, frameRate) {
            if (frameRate === void 0) { frameRate = 0; }
            var output = new AnimationCacheManager();
            output.armatureData = armatureData;
            if (frameRate <= 0) {
                var animationData = armatureData.animationDataList[0];
                if (animationData) {
                    output.frameRate = animationData.frameRate;
                }
            }
            else {
                output.frameRate = frameRate;
            }
            return output;
        };
        p.initAllAnimationCache = function () {
            var length = this.armatureData.animationDataList.length;
            for (var i = 0; i < length; i++) {
                var animationData = this.armatureData.animationDataList[i];
                this.animationCacheDic[animationData.name] = dragonBones.AnimationCache.initWithAnimationData(animationData, this.armatureData);
            }
        };
        p.initAnimationCache = function (animationName) {
            this.animationCacheDic[animationName] = dragonBones.AnimationCache.initWithAnimationData(this.armatureData.getAnimationData(animationName), this.armatureData);
        };
        p.bindCacheUserArmatures = function (armatures) {
            var length = armatures.length;
            for (var i = 0; i < length; i++) {
                var armature = armatures[i];
                this.bindCacheUserArmature(armature);
            }
        };
        p.bindCacheUserArmature = function (armature) {
            armature.animation.animationCacheManager = this;
            var cacheUser;
            for (var k in armature._slotDic) {
                cacheUser = armature._slotDic[k];
                cacheUser.frameCache = this.slotFrameCacheDic[cacheUser.name];
            }
        };
        p.setCacheGeneratorArmature = function (armature) {
            this.cacheGeneratorArmature = armature;
            var cacheUser;
            for (var slot in armature._slotDic) {
                cacheUser = armature._slotDic[slot];
                this.slotFrameCacheDic[cacheUser.name] = new dragonBones.SlotFrameCache();
            }
            for (var anim in this.animationCacheDic) {
                var animationCache = this.animationCacheDic[anim];
                animationCache.initSlotTimelineCacheDic(armature._slotDic, this.slotFrameCacheDic);
            }
        };
        p.generateAllAnimationCache = function (loop) {
            for (var anim in this.animationCacheDic) {
                var animationCache = this.animationCacheDic[anim];
                this.generateAnimationCache(animationCache.name, loop);
            }
        };
        p.generateAnimationCache = function (animationName, loop) {
            var temp = this.cacheGeneratorArmature.enableCache;
            this.cacheGeneratorArmature.enableCache = false;
            var animationCache = this.animationCacheDic[animationName];
            if (!animationCache) {
                return;
            }
            var animationState = this.cacheGeneratorArmature.getAnimation().animationState;
            var passTime = 1 / this.frameRate;
            if (loop) {
                this.cacheGeneratorArmature.getAnimation().gotoAndPlay(animationName, 0, -1, 0);
            }
            else {
                this.cacheGeneratorArmature.getAnimation().gotoAndPlay(animationName, 0, -1, 1);
            }
            var tempEnableEventDispatch = this.cacheGeneratorArmature.enableEventDispatch;
            this.cacheGeneratorArmature.enableEventDispatch = false;
            var lastProgress;
            do {
                lastProgress = animationState.progress;
                this.cacheGeneratorArmature.advanceTime(passTime);
                animationCache.addFrame();
            } while (animationState.progress >= lastProgress && animationState.progress < 1);
            this.cacheGeneratorArmature.enableEventDispatch = tempEnableEventDispatch;
            this.resetCacheGeneratorArmature();
            this.cacheGeneratorArmature.enableCache = temp;
        };
        p.resetCacheGeneratorArmature = function () {
            this.cacheGeneratorArmature.resetAnimation();
        };
        p.getAnimationCache = function (animationName) {
            return this.animationCacheDic[animationName];
        };
        return AnimationCacheManager;
    })();
    dragonBones.AnimationCacheManager = AnimationCacheManager;
    egret.registerClass(AnimationCacheManager,'dragonBones.AnimationCacheManager');
})(dragonBones || (dragonBones = {}));
var dragonBones;
(function (dragonBones) {
    var FrameCache = (function () {
        function FrameCache() {
            this.globalTransform = new dragonBones.DBTransform();
            this.globalTransformMatrix = new dragonBones.Matrix();
        }
        var d = __define,c=FrameCache,p=c.prototype;
        p.copy = function (frameCache) {
            this.globalTransform = frameCache.globalTransform;
            this.globalTransformMatrix = frameCache.globalTransformMatrix;
        };
        p.clear = function () {
            this.globalTransform = FrameCache.ORIGIN_TRAMSFORM;
            this.globalTransformMatrix = FrameCache.ORIGIN_MATRIX;
        };
        FrameCache.ORIGIN_TRAMSFORM = new dragonBones.DBTransform();
        FrameCache.ORIGIN_MATRIX = new dragonBones.Matrix();
        return FrameCache;
    })();
    dragonBones.FrameCache = FrameCache;
    egret.registerClass(FrameCache,'dragonBones.FrameCache');
})(dragonBones || (dragonBones = {}));
var dragonBones;
(function (dragonBones) {
    var SlotFrameCache = (function (_super) {
        __extends(SlotFrameCache, _super);
        function SlotFrameCache() {
            _super.call(this);
            this.displayIndex = -1;
        }
        var d = __define,c=SlotFrameCache,p=c.prototype;
        p.copy = function (frameCache) {
            _super.prototype.copy.call(this, frameCache);
            this.colorTransform = frameCache.colorTransform;
            this.displayIndex = frameCache.displayIndex;
        };
        p.clear = function () {
            _super.prototype.clear.call(this);
            this.colorTransform = null;
            this.displayIndex = -1;
        };
        return SlotFrameCache;
    })(dragonBones.FrameCache);
    dragonBones.SlotFrameCache = SlotFrameCache;
    egret.registerClass(SlotFrameCache,'dragonBones.SlotFrameCache');
})(dragonBones || (dragonBones = {}));
var dragonBones;
(function (dragonBones) {
    var TimelineCache = (function () {
        function TimelineCache() {
            this.frameCacheList = new Array();
        }
        var d = __define,c=TimelineCache,p=c.prototype;
        p.addFrame = function () {
        };
        p.update = function (frameIndex) {
            if (frameIndex === void 0) { frameIndex = 0; }
            this.currentFrameCache.copy(this.frameCacheList[frameIndex]);
        };
        p.bindCacheUser = function (cacheUser) {
            cacheUser.frameCache = this.currentFrameCache;
        };
        return TimelineCache;
    })();
    dragonBones.TimelineCache = TimelineCache;
    egret.registerClass(TimelineCache,'dragonBones.TimelineCache');
})(dragonBones || (dragonBones = {}));
var dragonBones;
(function (dragonBones) {
    var SlotTimelineCache = (function (_super) {
        __extends(SlotTimelineCache, _super);
        function SlotTimelineCache() {
            _super.call(this);
        }
        var d = __define,c=SlotTimelineCache,p=c.prototype;
        p.addFrame = function () {
            var cache = new dragonBones.SlotFrameCache();
            cache.globalTransform.copy(this.cacheGenerator.global);
            cache.globalTransformMatrix.copyFrom(this.cacheGenerator.globalTransformMatrix);
            if (this.cacheGenerator.colorChanged) {
                cache.colorTransform = dragonBones.ColorTransformUtil.cloneColor(this.cacheGenerator.colorTransform);
            }
            cache.displayIndex = this.cacheGenerator.displayIndex;
            this.frameCacheList.push(cache);
        };
        return SlotTimelineCache;
    })(dragonBones.TimelineCache);
    dragonBones.SlotTimelineCache = SlotTimelineCache;
    egret.registerClass(SlotTimelineCache,'dragonBones.SlotTimelineCache');
})(dragonBones || (dragonBones = {}));
var dragonBones;
(function (dragonBones) {
    var Event = (function (_super) {
        __extends(Event, _super);
        function Event(type, bubbles, cancelable) {
            if (bubbles === void 0) { bubbles = false; }
            if (cancelable === void 0) { cancelable = false; }
            _super.call(this, type, bubbles, cancelable);
        }
        var d = __define,c=Event,p=c.prototype;
        return Event;
    })(egret.Event);
    dragonBones.Event = Event;
    egret.registerClass(Event,'dragonBones.Event');
})(dragonBones || (dragonBones = {}));
var dragonBones;
(function (dragonBones) {
    var AnimationEvent = (function (_super) {
        __extends(AnimationEvent, _super);
        function AnimationEvent(type, cancelable) {
            if (cancelable === void 0) { cancelable = false; }
            _super.call(this, type);
        }
        var d = __define,c=AnimationEvent,p=c.prototype;
        d(AnimationEvent, "MOVEMENT_CHANGE"
            ,function () {
                return AnimationEvent.FADE_IN;
            }
        );
        d(p, "movementID"
            ,function () {
                return this.animationName;
            }
        );
        d(p, "armature"
            ,function () {
                return (this.target);
            }
        );
        d(p, "animationName"
            ,function () {
                return this.animationState.name;
            }
        );
        AnimationEvent.FADE_IN = "fadeIn";
        AnimationEvent.FADE_OUT = "fadeOut";
        AnimationEvent.START = "start";
        AnimationEvent.COMPLETE = "complete";
        AnimationEvent.LOOP_COMPLETE = "loopComplete";
        AnimationEvent.FADE_IN_COMPLETE = "fadeInComplete";
        AnimationEvent.FADE_OUT_COMPLETE = "fadeOutComplete";
        return AnimationEvent;
    })(dragonBones.Event);
    dragonBones.AnimationEvent = AnimationEvent;
    egret.registerClass(AnimationEvent,'dragonBones.AnimationEvent');
})(dragonBones || (dragonBones = {}));
var dragonBones;
(function (dragonBones) {
    var ArmatureEvent = (function (_super) {
        __extends(ArmatureEvent, _super);
        function ArmatureEvent(type) {
            _super.call(this, type);
        }
        var d = __define,c=ArmatureEvent,p=c.prototype;
        ArmatureEvent.Z_ORDER_UPDATED = "zOrderUpdated";
        return ArmatureEvent;
    })(dragonBones.Event);
    dragonBones.ArmatureEvent = ArmatureEvent;
    egret.registerClass(ArmatureEvent,'dragonBones.ArmatureEvent');
})(dragonBones || (dragonBones = {}));
var dragonBones;
(function (dragonBones) {
    var FrameEvent = (function (_super) {
        __extends(FrameEvent, _super);
        function FrameEvent(type, cancelable) {
            if (cancelable === void 0) { cancelable = false; }
            _super.call(this, type);
        }
        var d = __define,c=FrameEvent,p=c.prototype;
        d(FrameEvent, "MOVEMENT_FRAME_EVENT"
            ,function () {
                return FrameEvent.ANIMATION_FRAME_EVENT;
            }
        );
        d(p, "armature"
            ,function () {
                return (this.target);
            }
        );
        FrameEvent.ANIMATION_FRAME_EVENT = "animationFrameEvent";
        FrameEvent.BONE_FRAME_EVENT = "boneFrameEvent";
        return FrameEvent;
    })(dragonBones.Event);
    dragonBones.FrameEvent = FrameEvent;
    egret.registerClass(FrameEvent,'dragonBones.FrameEvent');
})(dragonBones || (dragonBones = {}));
var dragonBones;
(function (dragonBones) {
    var SoundEvent = (function (_super) {
        __extends(SoundEvent, _super);
        function SoundEvent(type, cancelable) {
            if (cancelable === void 0) { cancelable = false; }
            _super.call(this, type);
        }
        var d = __define,c=SoundEvent,p=c.prototype;
        SoundEvent.SOUND = "sound";
        return SoundEvent;
    })(dragonBones.Event);
    dragonBones.SoundEvent = SoundEvent;
    egret.registerClass(SoundEvent,'dragonBones.SoundEvent');
})(dragonBones || (dragonBones = {}));
var dragonBones;
(function (dragonBones) {
    var BaseFactory = (function (_super) {
        __extends(BaseFactory, _super);
        function BaseFactory(self) {
            _super.call(this);
            this.dragonBonesDataDic = {};
            this.textureAtlasDic = {};
            if (self != this) {
                throw new Error(egret.getString(4001));
            }
        }
        var d = __define,c=BaseFactory,p=c.prototype;
        p.dispose = function (disposeData) {
            if (disposeData === void 0) { disposeData = true; }
            if (disposeData) {
                for (var skeletonName in this.dragonBonesDataDic) {
                    (this.dragonBonesDataDic[skeletonName]).dispose();
                    delete this.dragonBonesDataDic[skeletonName];
                }
                for (var textureAtlasName in this.textureAtlasDic) {
                    var textureAtlasArr = this.textureAtlasDic[textureAtlasName];
                    if (textureAtlasArr) {
                        for (var i = 0, len = textureAtlasArr.length; i < len; i++) {
                            textureAtlasArr[i].dispose();
                        }
                    }
                    delete this.textureAtlasDic[textureAtlasName];
                }
            }
            this.dragonBonesDataDic = null;
            this.textureAtlasDic = null;
        };
        p.getDragonBonesData = function (name) {
            return this.dragonBonesDataDic[name];
        };
        p.getSkeletonData = function (name) {
            return this.getDragonBonesData(name);
        };
        p.addDragonBonesData = function (data, name) {
            if (name === void 0) { name = null; }
            if (!data) {
                throw new Error();
            }
            name = name || data.name;
            if (!name) {
                throw new Error(egret.getString(4002));
            }
            this.dragonBonesDataDic[name] = data;
        };
        p.addSkeletonData = function (data, name) {
            if (name === void 0) { name = null; }
            this.addDragonBonesData(data, name);
        };
        p.removeDragonBonesData = function (name) {
            delete this.dragonBonesDataDic[name];
        };
        p.removeSkeletonData = function (name) {
            delete this.dragonBonesDataDic[name];
        };
        p.getTextureAtlas = function (name) {
            return this.textureAtlasDic[name];
        };
        p.addTextureAtlas = function (textureAtlas, name) {
            if (name === void 0) { name = null; }
            if (!textureAtlas) {
                throw new Error();
            }
            if (!name && textureAtlas.hasOwnProperty("name")) {
                name = textureAtlas.name;
            }
            if (!name) {
                throw new Error(egret.getString(4002));
            }
            var textureAtlasArr = this.textureAtlasDic[name];
            if (textureAtlasArr == null) {
                textureAtlasArr = [];
                this.textureAtlasDic[name] = textureAtlasArr;
            }
            if (textureAtlasArr.indexOf(textureAtlas) != -1) {
                return;
            }
            textureAtlasArr.push(textureAtlas);
        };
        p.removeTextureAtlas = function (name) {
            delete this.textureAtlasDic[name];
        };
        p.getTextureDisplay = function (textureName, textureAtlasName, pivotX, pivotY) {
            if (textureAtlasName === void 0) { textureAtlasName = null; }
            if (pivotX === void 0) { pivotX = NaN; }
            if (pivotY === void 0) { pivotY = NaN; }
            var targetTextureAtlas;
            var textureAtlasArr;
            var i;
            var len;
            if (textureAtlasName) {
                textureAtlasArr = this.textureAtlasDic[textureAtlasName];
                if (textureAtlasArr) {
                    for (i = 0, len = textureAtlasArr.length; i < len; i++) {
                        targetTextureAtlas = textureAtlasArr[i];
                        if (targetTextureAtlas.getRegion(textureName)) {
                            break;
                        }
                        targetTextureAtlas = null;
                    }
                }
            }
            else {
                for (textureAtlasName in this.textureAtlasDic) {
                    textureAtlasArr = this.textureAtlasDic[textureAtlasName];
                    if (textureAtlasArr) {
                        for (i = 0, len = textureAtlasArr.length; i < len; i++) {
                            targetTextureAtlas = textureAtlasArr[i];
                            if (targetTextureAtlas.getRegion(textureName)) {
                                break;
                            }
                            targetTextureAtlas = null;
                        }
                        if (targetTextureAtlas != null) {
                            break;
                        }
                    }
                }
            }
            if (!targetTextureAtlas) {
                return null;
            }
            if (isNaN(pivotX) || isNaN(pivotY)) {
                var data = this.dragonBonesDataDic[textureAtlasName];
                data = data ? data : this.findFirstDragonBonesData();
                if (data) {
                    var displayData = data.getDisplayDataByName(textureName);
                    if (displayData) {
                        pivotX = displayData.pivot.x;
                        pivotY = displayData.pivot.y;
                    }
                }
            }
            return this._generateDisplay(targetTextureAtlas, textureName, pivotX, pivotY);
        };
        p.buildArmature = function (armatureName, fromDragonBonesDataName, fromTextureAtlasName, skinName) {
            if (fromDragonBonesDataName === void 0) { fromDragonBonesDataName = null; }
            if (fromTextureAtlasName === void 0) { fromTextureAtlasName = null; }
            if (skinName === void 0) { skinName = null; }
            var buildArmatureDataPackage = {};
            this.fillBuildArmatureDataPackageArmatureInfo(armatureName, fromDragonBonesDataName, buildArmatureDataPackage);
            if (fromTextureAtlasName == null) {
                fromTextureAtlasName = buildArmatureDataPackage.dragonBonesDataName;
            }
            var dragonBonesData = buildArmatureDataPackage.dragonBonesData;
            var armatureData = buildArmatureDataPackage.armatureData;
            if (!armatureData) {
                return null;
            }
            return this.buildArmatureUsingArmatureDataFromTextureAtlas(dragonBonesData, armatureData, fromTextureAtlasName, skinName);
        };
        p.buildFastArmature = function (armatureName, fromDragonBonesDataName, fromTextureAtlasName, skinName) {
            if (fromDragonBonesDataName === void 0) { fromDragonBonesDataName = null; }
            if (fromTextureAtlasName === void 0) { fromTextureAtlasName = null; }
            if (skinName === void 0) { skinName = null; }
            var buildArmatureDataPackage = new BuildArmatureDataPackage();
            this.fillBuildArmatureDataPackageArmatureInfo(armatureName, fromDragonBonesDataName, buildArmatureDataPackage);
            if (fromTextureAtlasName == null) {
                fromTextureAtlasName = buildArmatureDataPackage.dragonBonesDataName;
            }
            var dragonBonesData = buildArmatureDataPackage.dragonBonesData;
            var armatureData = buildArmatureDataPackage.armatureData;
            if (!armatureData) {
                return null;
            }
            return this.buildFastArmatureUsingArmatureDataFromTextureAtlas(dragonBonesData, armatureData, fromTextureAtlasName, skinName);
        };
        p.buildArmatureUsingArmatureDataFromTextureAtlas = function (dragonBonesData, armatureData, textureAtlasName, skinName) {
            if (skinName === void 0) { skinName = null; }
            var outputArmature = this._generateArmature();
            outputArmature.name = armatureData.name;
            outputArmature.__dragonBonesData = dragonBonesData;
            outputArmature._armatureData = armatureData;
            outputArmature.animation.animationDataList = armatureData.animationDataList;
            this._buildBones(outputArmature);
            this._buildSlots(outputArmature, skinName, textureAtlasName);
            outputArmature.advanceTime(0);
            return outputArmature;
        };
        p.buildFastArmatureUsingArmatureDataFromTextureAtlas = function (dragonBonesData, armatureData, textureAtlasName, skinName) {
            if (skinName === void 0) { skinName = null; }
            var outputArmature = this._generateFastArmature();
            outputArmature.name = armatureData.name;
            outputArmature.__dragonBonesData = dragonBonesData;
            outputArmature._armatureData = armatureData;
            outputArmature.animation.animationDataList = armatureData.animationDataList;
            this._buildFastBones(outputArmature);
            this._buildFastSlots(outputArmature, skinName, textureAtlasName);
            outputArmature.advanceTime(0);
            return outputArmature;
        };
        p.copyAnimationsToArmature = function (toArmature, fromArmatreName, fromDragonBonesDataName, ifRemoveOriginalAnimationList) {
            if (fromDragonBonesDataName === void 0) { fromDragonBonesDataName = null; }
            if (ifRemoveOriginalAnimationList === void 0) { ifRemoveOriginalAnimationList = true; }
            var buildArmatureDataPackage = {};
            if (!this.fillBuildArmatureDataPackageArmatureInfo(fromArmatreName, fromDragonBonesDataName, buildArmatureDataPackage)) {
                return false;
            }
            var fromArmatureData = buildArmatureDataPackage.armatureData;
            toArmature.animation.animationDataList = fromArmatureData.animationDataList;
            var fromSkinData = fromArmatureData.getSkinData("");
            var fromSlotData;
            var fromDisplayData;
            var toSlotList = toArmature.getSlots(false);
            var toSlot;
            var toSlotDisplayList;
            var toSlotDisplayListLength = 0;
            var toDisplayObject;
            var toChildArmature;
            var length1 = toSlotList.length;
            for (var i1 = 0; i1 < length1; i1++) {
                toSlot = toSlotList[i1];
                toSlotDisplayList = toSlot.displayList;
                toSlotDisplayListLength = toSlotDisplayList.length;
                for (var i = 0; i < toSlotDisplayListLength; i++) {
                    toDisplayObject = toSlotDisplayList[i];
                    if (toDisplayObject instanceof dragonBones.Armature) {
                        toChildArmature = toDisplayObject;
                        fromSlotData = fromSkinData.getSlotData(toSlot.name);
                        fromDisplayData = fromSlotData.displayDataList[i];
                        if (fromDisplayData.type == dragonBones.DisplayData.ARMATURE) {
                            this.copyAnimationsToArmature(toChildArmature, fromDisplayData.name, buildArmatureDataPackage.dragonBonesDataName, ifRemoveOriginalAnimationList);
                        }
                    }
                }
            }
            return true;
        };
        p.fillBuildArmatureDataPackageArmatureInfo = function (armatureName, dragonBonesDataName, outputBuildArmatureDataPackage) {
            if (dragonBonesDataName) {
                outputBuildArmatureDataPackage.dragonBonesDataName = dragonBonesDataName;
                outputBuildArmatureDataPackage.dragonBonesData = this.dragonBonesDataDic[dragonBonesDataName];
                outputBuildArmatureDataPackage.armatureData = outputBuildArmatureDataPackage.dragonBonesData.getArmatureDataByName(armatureName);
                return true;
            }
            else {
                for (dragonBonesDataName in this.dragonBonesDataDic) {
                    outputBuildArmatureDataPackage.dragonBonesData = this.dragonBonesDataDic[dragonBonesDataName];
                    outputBuildArmatureDataPackage.armatureData = outputBuildArmatureDataPackage.dragonBonesData.getArmatureDataByName(armatureName);
                    if (outputBuildArmatureDataPackage.armatureData) {
                        outputBuildArmatureDataPackage.dragonBonesDataName = dragonBonesDataName;
                        return true;
                    }
                }
            }
            return false;
        };
        p.fillBuildArmatureDataPackageTextureInfo = function (fromTextureAtlasName, outputBuildArmatureDataPackage) {
            outputBuildArmatureDataPackage.textureAtlas = this.textureAtlasDic[fromTextureAtlasName ? fromTextureAtlasName : outputBuildArmatureDataPackage.dragonBonesDataName];
        };
        p.findFirstDragonBonesData = function () {
            for (var key in this.dragonBonesDataDic) {
                var outputDragonBonesData = this.dragonBonesDataDic[key];
                if (outputDragonBonesData) {
                    return outputDragonBonesData;
                }
            }
            return null;
        };
        p.findFirstTextureAtlas = function () {
            for (var key in this.textureAtlasDic) {
                var outputTextureAtlas = this.textureAtlasDic[key];
                if (outputTextureAtlas) {
                    return outputTextureAtlas;
                }
            }
            return null;
        };
        p._buildBones = function (armature) {
            var boneDataList = armature.armatureData.boneDataList;
            var boneData;
            var bone;
            var parent;
            for (var i = 0; i < boneDataList.length; i++) {
                boneData = boneDataList[i];
                bone = dragonBones.Bone.initWithBoneData(boneData);
                parent = boneData.parent;
                if (parent && armature.armatureData.getBoneData(parent) == null) {
                    parent = null;
                }
                armature.addBone(bone, parent, true);
            }
            armature._updateAnimationAfterBoneListChanged();
        };
        p._buildSlots = function (armature, skinName, textureAtlasName) {
            var skinData = armature.armatureData.getSkinData(skinName);
            if (!skinData) {
                return;
            }
            armature.armatureData.setSkinData(skinName);
            var displayList = [];
            var slotDataList = armature.armatureData.slotDataList;
            var slotData;
            var slot;
            var bone;
            for (var i = 0; i < slotDataList.length; i++) {
                slotData = slotDataList[i];
                bone = armature.getBone(slotData.parent);
                if (!bone) {
                    continue;
                }
                slot = this._generateSlot();
                slot.initWithSlotData(slotData);
                bone.addSlot(slot);
                displayList.length = 0;
                var l = slotData.displayDataList.length;
                while (l--) {
                    var displayData = slotData.displayDataList[l];
                    switch (displayData.type) {
                        case dragonBones.DisplayData.ARMATURE:
                            var childArmature = this.buildArmatureUsingArmatureDataFromTextureAtlas(armature.__dragonBonesData, armature.__dragonBonesData.getArmatureDataByName(displayData.name), textureAtlasName, skinName);
                            displayList[l] = childArmature;
                            break;
                        case dragonBones.DisplayData.IMAGE:
                        default:
                            displayList[l] = this.getTextureDisplay(displayData.name, textureAtlasName, displayData.pivot.x, displayData.pivot.y);
                            break;
                    }
                }
                for (var j = 0, jLen = displayList.length; j < jLen; j++) {
                    var displayObject = displayList[j];
                    if (!displayObject) {
                        continue;
                    }
                    if (displayObject instanceof dragonBones.Armature) {
                        displayObject = displayObject.display;
                    }
                    if (displayObject.hasOwnProperty("name")) {
                        try {
                            displayObject["name"] = slot.name;
                        }
                        catch (err) {
                        }
                    }
                }
                slot.displayList = displayList;
                slot._changeDisplay(slotData.displayIndex);
            }
        };
        p._buildFastBones = function (armature) {
            var boneDataList = armature.armatureData.boneDataList;
            var boneData;
            var bone;
            for (var i = 0; i < boneDataList.length; i++) {
                boneData = boneDataList[i];
                bone = dragonBones.FastBone.initWithBoneData(boneData);
                armature.addBone(bone, boneData.parent);
            }
        };
        p._buildFastSlots = function (armature, skinName, textureAtlasName) {
            var skinData = armature.armatureData.getSkinData(skinName);
            if (!skinData) {
                return;
            }
            armature.armatureData.setSkinData(skinName);
            var displayList = [];
            var slotDataList = armature.armatureData.slotDataList;
            var slotData;
            var slot;
            for (var i = 0; i < slotDataList.length; i++) {
                displayList.length = 0;
                slotData = slotDataList[i];
                slot = this._generateFastSlot();
                slot.initWithSlotData(slotData);
                var l = slotData.displayDataList.length;
                while (l--) {
                    var displayData = slotData.displayDataList[l];
                    switch (displayData.type) {
                        case dragonBones.DisplayData.ARMATURE:
                            var childArmature = this.buildFastArmatureUsingArmatureDataFromTextureAtlas(armature.__dragonBonesData, armature.__dragonBonesData.getArmatureDataByName(displayData.name), textureAtlasName, skinName);
                            displayList[l] = childArmature;
                            slot.hasChildArmature = true;
                            break;
                        case dragonBones.DisplayData.IMAGE:
                        default:
                            displayList[l] = this.getTextureDisplay(displayData.name, textureAtlasName, displayData.pivot.x, displayData.pivot.y);
                            break;
                    }
                }
                var length1 = displayList.length;
                for (var i1 = 0; i1 < length1; i1++) {
                    var displayObject = displayList[i1];
                    if (!displayObject) {
                        continue;
                    }
                    if (displayObject instanceof dragonBones.FastArmature) {
                        displayObject = displayObject.display;
                    }
                    if (displayObject.hasOwnProperty("name")) {
                        try {
                            displayObject["name"] = slot.name;
                        }
                        catch (err) {
                        }
                    }
                }
                slot.initDisplayList(displayList.concat());
                armature.addSlot(slot, slotData.parent);
                slot._changeDisplayIndex(slotData.displayIndex);
            }
        };
        p._generateArmature = function () {
            return null;
        };
        p._generateSlot = function () {
            return null;
        };
        p._generateFastArmature = function () {
            return null;
        };
        p._generateFastSlot = function () {
            return null;
        };
        p._generateDisplay = function (textureAtlas, fullName, pivotX, pivotY) {
            return null;
        };
        BaseFactory._helpMatrix = new dragonBones.Matrix();
        return BaseFactory;
    })(dragonBones.EventDispatcher);
    dragonBones.BaseFactory = BaseFactory;
    egret.registerClass(BaseFactory,'dragonBones.BaseFactory');
    var BuildArmatureDataPackage = (function () {
        function BuildArmatureDataPackage() {
        }
        var d = __define,c=BuildArmatureDataPackage,p=c.prototype;
        return BuildArmatureDataPackage;
    })();
    dragonBones.BuildArmatureDataPackage = BuildArmatureDataPackage;
    egret.registerClass(BuildArmatureDataPackage,'dragonBones.BuildArmatureDataPackage');
})(dragonBones || (dragonBones = {}));
var dragonBones;
(function (dragonBones) {
    var FastArmature = (function (_super) {
        __extends(FastArmature, _super);
        function FastArmature(display) {
            _super.call(this);
            this.isCacheManagerExclusive = false;
            this._enableEventDispatch = true;
            this.useCache = true;
            this._display = display;
            this._animation = new dragonBones.FastAnimation(this);
            this._slotsZOrderChanged = false;
            this._armatureData = null;
            this.boneList = [];
            this._boneDic = {};
            this.slotList = [];
            this._slotDic = {};
            this.slotHasChildArmatureList = [];
            this._eventList = [];
            this._delayDispose = false;
            this._lockDispose = false;
        }
        var d = __define,c=FastArmature,p=c.prototype;
        p.dispose = function () {
            this._delayDispose = true;
            if (!this._animation || this._lockDispose) {
                return;
            }
            this.userData = null;
            this._animation.dispose();
            var i = this.slotList.length;
            while (i--) {
                this.slotList[i].dispose();
            }
            i = this.boneList.length;
            while (i--) {
                this.boneList[i].dispose();
            }
            this.slotList.length = 0;
            this.boneList.length = 0;
            this._armatureData = null;
            this._animation = null;
            this.slotList = null;
            this.boneList = null;
            this._eventList = null;
        };
        p.advanceTime = function (passedTime) {
            this._lockDispose = true;
            this._animation.advanceTime(passedTime);
            var bone;
            var slot;
            var i = 0;
            if (this._animation.animationState.isUseCache()) {
                if (!this.useCache) {
                    this.useCache = true;
                }
                i = this.slotList.length;
                while (i--) {
                    slot = this.slotList[i];
                    slot.updateByCache();
                }
            }
            else {
                if (this.useCache) {
                    this.useCache = false;
                    i = this.slotList.length;
                    while (i--) {
                        slot = this.slotList[i];
                        slot.switchTransformToBackup();
                    }
                }
                i = this.boneList.length;
                while (i--) {
                    bone = this.boneList[i];
                    bone.update();
                }
                i = this.slotList.length;
                while (i--) {
                    slot = this.slotList[i];
                    slot._update();
                }
            }
            i = this.slotHasChildArmatureList.length;
            while (i--) {
                slot = this.slotHasChildArmatureList[i];
                var childArmature = slot.childArmature;
                if (childArmature) {
                    childArmature.advanceTime(passedTime);
                }
            }
            if (this._slotsZOrderChanged) {
                this.updateSlotsZOrder();
            }
            while (this._eventList.length > 0) {
                this.dispatchEvent(this._eventList.shift());
            }
            this._lockDispose = false;
            if (this._delayDispose) {
                this.dispose();
            }
        };
        p.enableAnimationCache = function (frameRate, animationList, loop) {
            if (animationList === void 0) { animationList = null; }
            if (loop === void 0) { loop = true; }
            var animationCacheManager = dragonBones.AnimationCacheManager.initWithArmatureData(this.armatureData, frameRate);
            if (animationList) {
                var length = animationList.length;
                for (var i = 0; i < length; i++) {
                    var animationName = animationList[i];
                    animationCacheManager.initAnimationCache(animationName);
                }
            }
            else {
                animationCacheManager.initAllAnimationCache();
            }
            animationCacheManager.setCacheGeneratorArmature(this);
            animationCacheManager.generateAllAnimationCache(loop);
            animationCacheManager.bindCacheUserArmature(this);
            this.enableCache = true;
            return animationCacheManager;
        };
        p.getBone = function (boneName) {
            return this._boneDic[boneName];
        };
        p.getSlot = function (slotName) {
            return this._slotDic[slotName];
        };
        p.getBoneByDisplay = function (display) {
            var slot = this.getSlotByDisplay(display);
            return slot ? slot.parent : null;
        };
        p.getSlotByDisplay = function (displayObj) {
            if (displayObj) {
                for (var i = 0, len = this.slotList.length; i < len; i++) {
                    if (this.slotList[i].display == displayObj) {
                        return this.slotList[i];
                    }
                }
            }
            return null;
        };
        p.getSlots = function (returnCopy) {
            if (returnCopy === void 0) { returnCopy = true; }
            return returnCopy ? this.slotList.concat() : this.slotList;
        };
        p._updateBonesByCache = function () {
            var i = this.boneList.length;
            var bone;
            while (i--) {
                bone = this.boneList[i];
                bone.update();
            }
        };
        p.addBone = function (bone, parentName) {
            if (parentName === void 0) { parentName = null; }
            var parentBone;
            if (parentName) {
                parentBone = this.getBone(parentName);
                parentBone.boneList.push(bone);
            }
            bone.armature = this;
            bone.setParent(parentBone);
            this.boneList.unshift(bone);
            this._boneDic[bone.name] = bone;
        };
        p.addSlot = function (slot, parentBoneName) {
            var bone = this.getBone(parentBoneName);
            if (bone) {
                slot.armature = this;
                slot.setParent(bone);
                bone.slotList.push(slot);
                slot._addDisplayToContainer(this.display);
                this.slotList.push(slot);
                this._slotDic[slot.name] = slot;
                if (slot.hasChildArmature) {
                    this.slotHasChildArmatureList.push(slot);
                }
            }
            else {
                throw new Error();
            }
        };
        p.updateSlotsZOrder = function () {
            this.slotList.sort(this.sortSlot);
            var i = this.slotList.length;
            while (i--) {
                var slot = this.slotList[i];
                if ((slot._frameCache && (slot._frameCache).displayIndex >= 0)
                    || (!slot._frameCache && slot.displayIndex >= 0)) {
                    slot._addDisplayToContainer(this._display);
                }
            }
            this._slotsZOrderChanged = false;
        };
        p.sortBoneList = function () {
            var i = this.boneList.length;
            if (i == 0) {
                return;
            }
            var helpArray = [];
            while (i--) {
                var level = 0;
                var bone = this.boneList[i];
                var boneParent = bone;
                while (boneParent) {
                    level++;
                    boneParent = boneParent.parent;
                }
                helpArray[i] = [level, bone];
            }
            helpArray.sort(dragonBones.ArmatureData.sortBoneDataHelpArrayDescending);
            i = helpArray.length;
            while (i--) {
                this.boneList[i] = helpArray[i][1];
            }
            helpArray.length = 0;
        };
        p.arriveAtFrame = function (frame, animationState) {
            if (frame.event && this.hasEventListener(dragonBones.FrameEvent.ANIMATION_FRAME_EVENT)) {
                var frameEvent = new dragonBones.FrameEvent(dragonBones.FrameEvent.ANIMATION_FRAME_EVENT);
                frameEvent.animationState = animationState;
                frameEvent.frameLabel = frame.event;
                this._addEvent(frameEvent);
            }
            if (frame.action) {
                this.animation.gotoAndPlay(frame.action);
            }
        };
        p.invalidUpdate = function (boneName) {
            if (boneName === void 0) { boneName = null; }
            if (boneName) {
                var bone = this.getBone(boneName);
                if (bone) {
                    bone.invalidUpdate();
                }
            }
            else {
                var i = this.boneList.length;
                while (i--) {
                    this.boneList[i].invalidUpdate();
                }
            }
        };
        p.resetAnimation = function () {
            this.animation.animationState._resetTimelineStateList();
            var length = this.boneList.length;
            for (var i = 0; i < length; i++) {
                var boneItem = this.boneList[i];
                boneItem._timelineState = null;
            }
            this.animation.stop();
        };
        p.sortSlot = function (slot1, slot2) {
            return slot1.zOrder < slot2.zOrder ? 1 : -1;
        };
        p.getAnimation = function () {
            return this._animation;
        };
        d(p, "armatureData"
            ,function () {
                return this._armatureData;
            }
        );
        d(p, "animation"
            ,function () {
                return this._animation;
            }
        );
        d(p, "display"
            ,function () {
                return this._display;
            }
        );
        d(p, "enableCache"
            ,function () {
                return this._enableCache;
            }
            ,function (value) {
                this._enableCache = value;
            }
        );
        d(p, "enableEventDispatch"
            ,function () {
                return this._enableEventDispatch;
            }
            ,function (value) {
                this._enableEventDispatch = value;
            }
        );
        p._addEvent = function (event) {
            if (this._enableEventDispatch) {
                this._eventList.push(event);
            }
        };
        return FastArmature;
    })(dragonBones.EventDispatcher);
    dragonBones.FastArmature = FastArmature;
    egret.registerClass(FastArmature,'dragonBones.FastArmature',["dragonBones.ICacheableArmature","dragonBones.IArmature","dragonBones.IAnimatable"]);
})(dragonBones || (dragonBones = {}));
var dragonBones;
(function (dragonBones) {
    var FastDBObject = (function () {
        function FastDBObject() {
            this._globalTransformMatrix = new dragonBones.Matrix();
            this._global = new dragonBones.DBTransform();
            this._origin = new dragonBones.DBTransform();
            this._visible = true;
            this.armature = null;
            this._parent = null;
            this.userData = null;
            this.inheritRotation = true;
            this.inheritScale = true;
            this.inheritTranslation = true;
        }
        var d = __define,c=FastDBObject,p=c.prototype;
        p.updateByCache = function () {
            this._global = this._frameCache.globalTransform;
            this._globalTransformMatrix = this._frameCache.globalTransformMatrix;
        };
        p.switchTransformToBackup = function () {
            if (!this._globalBackup) {
                this._globalBackup = new dragonBones.DBTransform();
                this._globalTransformMatrixBackup = new dragonBones.Matrix();
            }
            this._global = this._globalBackup;
            this._globalTransformMatrix = this._globalTransformMatrixBackup;
        };
        p.setParent = function (value) {
            this._parent = value;
        };
        p.dispose = function () {
            this.userData = null;
            this._globalTransformMatrix = null;
            this._global = null;
            this._origin = null;
            this.armature = null;
            this._parent = null;
        };
        p._calculateParentTransform = function () {
            if (this.parent && (this.inheritTranslation || this.inheritRotation || this.inheritScale)) {
                var parentGlobalTransform = this._parent._global;
                var parentGlobalTransformMatrix = this._parent._globalTransformMatrix;
                if (!this.inheritTranslation && (parentGlobalTransform.x != 0 || parentGlobalTransform.y != 0) ||
                    !this.inheritRotation && (parentGlobalTransform.skewX != 0 || parentGlobalTransform.skewY != 0) ||
                    !this.inheritScale && (parentGlobalTransform.scaleX != 1 || parentGlobalTransform.scaleY != 1)) {
                    parentGlobalTransform = FastDBObject._tempParentGlobalTransform;
                    parentGlobalTransform.copy(this._parent._global);
                    if (!this.inheritTranslation) {
                        parentGlobalTransform.x = 0;
                        parentGlobalTransform.y = 0;
                    }
                    if (!this.inheritScale) {
                        parentGlobalTransform.scaleX = 1;
                        parentGlobalTransform.scaleY = 1;
                    }
                    if (!this.inheritRotation) {
                        parentGlobalTransform.skewX = 0;
                        parentGlobalTransform.skewY = 0;
                    }
                    parentGlobalTransformMatrix = dragonBones.DBObject._tempParentGlobalTransformMatrix;
                    dragonBones.TransformUtil.transformToMatrix(parentGlobalTransform, parentGlobalTransformMatrix);
                }
                FastDBObject.tempOutputObj.parentGlobalTransform = parentGlobalTransform;
                FastDBObject.tempOutputObj.parentGlobalTransformMatrix = parentGlobalTransformMatrix;
                return FastDBObject.tempOutputObj;
            }
            return null;
        };
        p._updateGlobal = function () {
            this._calculateRelativeParentTransform();
            var output = this._calculateParentTransform();
            if (output != null) {
                var parentMatrix = output.parentGlobalTransformMatrix;
                var parentGlobalTransform = output.parentGlobalTransform;
                var x = this._global.x;
                var y = this._global.y;
                this._global.x = parentMatrix.a * x + parentMatrix.c * y + parentMatrix.tx;
                this._global.y = parentMatrix.d * y + parentMatrix.b * x + parentMatrix.ty;
                if (this.inheritRotation) {
                    this._global.skewX += parentGlobalTransform.skewX;
                    this._global.skewY += parentGlobalTransform.skewY;
                }
                if (this.inheritScale) {
                    this._global.scaleX *= parentGlobalTransform.scaleX;
                    this._global.scaleY *= parentGlobalTransform.scaleY;
                }
            }
            dragonBones.TransformUtil.transformToMatrix(this._global, this._globalTransformMatrix, true);
            return output;
        };
        p._calculateRelativeParentTransform = function () {
        };
        d(p, "name"
            ,function () {
                return this._name;
            }
            ,function (value) {
                this._name = value;
            }
        );
        d(p, "global"
            ,function () {
                return this._global;
            }
        );
        d(p, "globalTransformMatrix"
            ,function () {
                return this._globalTransformMatrix;
            }
        );
        d(p, "origin"
            ,function () {
                return this._origin;
            }
        );
        d(p, "parent"
            ,function () {
                return this._parent;
            }
        );
        d(p, "visible"
            ,function () {
                return this._visible;
            }
            ,function (value) {
                this._visible = value;
            }
        );
        d(p, "frameCache",undefined
            ,function (cache) {
                this._frameCache = cache;
            }
        );
        FastDBObject._tempParentGlobalTransform = new dragonBones.DBTransform();
        FastDBObject.tempOutputObj = {};
        return FastDBObject;
    })();
    dragonBones.FastDBObject = FastDBObject;
    egret.registerClass(FastDBObject,'dragonBones.FastDBObject');
})(dragonBones || (dragonBones = {}));
var dragonBones;
(function (dragonBones) {
    var FastBone = (function (_super) {
        __extends(FastBone, _super);
        function FastBone() {
            _super.call(this);
            this.slotList = [];
            this.boneList = [];
            this._needUpdate = 0;
            this._needUpdate = 2;
            this._tweenPivot = new dragonBones.Point();
        }
        var d = __define,c=FastBone,p=c.prototype;
        FastBone.initWithBoneData = function (boneData) {
            var outputBone = new FastBone();
            outputBone.name = boneData.name;
            outputBone.inheritRotation = boneData.inheritRotation;
            outputBone.inheritScale = boneData.inheritScale;
            outputBone.origin.copy(boneData.transform);
            return outputBone;
        };
        p.getBones = function (returnCopy) {
            if (returnCopy === void 0) { returnCopy = true; }
            return returnCopy ? this.boneList.concat() : this.boneList;
        };
        p.getSlots = function (returnCopy) {
            if (returnCopy === void 0) { returnCopy = true; }
            return returnCopy ? this.slotList.concat() : this.slotList;
        };
        p.dispose = function () {
            _super.prototype.dispose.call(this);
            this._timelineState = null;
            this._tweenPivot = null;
        };
        p.invalidUpdate = function () {
            this._needUpdate = 2;
        };
        p._calculateRelativeParentTransform = function () {
            this._global.copy(this._origin);
            if (this._timelineState) {
                this._global.add(this._timelineState._transform);
            }
        };
        p.updateByCache = function () {
            _super.prototype.updateByCache.call(this);
            this._global = this._frameCache.globalTransform;
            this._globalTransformMatrix = this._frameCache.globalTransformMatrix;
        };
        p.update = function (needUpdate) {
            if (needUpdate === void 0) { needUpdate = false; }
            this._needUpdate--;
            if (needUpdate || this._needUpdate > 0 || (this._parent && this._parent._needUpdate > 0)) {
                this._needUpdate = 1;
            }
            else {
                return;
            }
            this.blendingTimeline();
            this._updateGlobal();
        };
        p._hideSlots = function () {
            var length = this.slotList.length;
            for (var i = 0; i < length; i++) {
                var childSlot = this.slotList[i];
                childSlot.hideSlots();
            }
        };
        p.blendingTimeline = function () {
            if (this._timelineState) {
                this._tweenPivot.x = this._timelineState._pivot.x;
                this._tweenPivot.y = this._timelineState._pivot.y;
            }
        };
        p.arriveAtFrame = function (frame, animationState) {
            var childSlot;
            if (frame.event && this.armature.hasEventListener(dragonBones.FrameEvent.BONE_FRAME_EVENT)) {
                var frameEvent = new dragonBones.FrameEvent(dragonBones.FrameEvent.BONE_FRAME_EVENT);
                frameEvent.bone = this;
                frameEvent.animationState = animationState;
                frameEvent.frameLabel = frame.event;
                this.armature._addEvent(frameEvent);
            }
        };
        d(p, "childArmature"
            ,function () {
                var s = this.slot;
                if (s) {
                    return s.childArmature;
                }
                return null;
            }
        );
        d(p, "display"
            ,function () {
                var s = this.slot;
                if (s) {
                    return s.display;
                }
                return null;
            }
            ,function (value) {
                var s = this.slot;
                if (s) {
                    s.display = value;
                }
            }
        );
        d(p, "visible",undefined
            ,function (value) {
                if (this._visible != value) {
                    this._visible = value;
                    for (var i = 0, len = this.armature.slotList.length; i < len; i++) {
                        if (this.armature.slotList[i].parent == this) {
                            this.armature.slotList[i]._updateDisplayVisible(this._visible);
                        }
                    }
                }
            }
        );
        d(p, "slot"
            ,function () {
                return this.slotList.length > 0 ? this.slotList[0] : null;
            }
        );
        return FastBone;
    })(dragonBones.FastDBObject);
    dragonBones.FastBone = FastBone;
    egret.registerClass(FastBone,'dragonBones.FastBone');
})(dragonBones || (dragonBones = {}));
var dragonBones;
(function (dragonBones) {
    var FastSlot = (function (_super) {
        __extends(FastSlot, _super);
        function FastSlot(self) {
            _super.call(this);
            this._currentDisplayIndex = 0;
            if (self != this) {
                throw new Error("Abstract class can not be instantiated!");
            }
            this.hasChildArmature = false;
            this._currentDisplayIndex = -1;
            this._originZOrder = 0;
            this._tweenZOrder = 0;
            this._offsetZOrder = 0;
            this._colorTransform = new dragonBones.ColorTransform();
            this._isColorChanged = false;
            this._displayDataList = null;
            this._currentDisplay = null;
            this.inheritRotation = true;
            this.inheritScale = true;
        }
        var d = __define,c=FastSlot,p=c.prototype;
        p.initWithSlotData = function (slotData) {
            this.name = slotData.name;
            this.blendMode = slotData.blendMode;
            this._originZOrder = slotData.zOrder;
            this._displayDataList = slotData.displayDataList;
            this._originDisplayIndex = slotData.displayIndex;
        };
        p.dispose = function () {
            if (!this._displayList) {
                return;
            }
            _super.prototype.dispose.call(this);
            this._displayDataList = null;
            this._displayList = null;
            this._currentDisplay = null;
        };
        p.updateByCache = function () {
            _super.prototype.updateByCache.call(this);
            this._updateTransform();
            var cacheColor = (this._frameCache).colorTransform;
            var cacheColorChanged = cacheColor != null;
            if (this.colorChanged != cacheColorChanged ||
                (this.colorChanged && cacheColorChanged && !dragonBones.ColorTransformUtil.isEqual(this._colorTransform, cacheColor))) {
                cacheColor = cacheColor || dragonBones.ColorTransformUtil.originalColor;
                this._updateDisplayColor(cacheColor.alphaOffset, cacheColor.redOffset, cacheColor.greenOffset, cacheColor.blueOffset, cacheColor.alphaMultiplier, cacheColor.redMultiplier, cacheColor.greenMultiplier, cacheColor.blueMultiplier, cacheColorChanged);
            }
            this._changeDisplayIndex((this._frameCache).displayIndex);
        };
        p._update = function () {
            if (this._parent._needUpdate <= 0) {
                return;
            }
            this._updateGlobal();
            this._updateTransform();
        };
        p._calculateRelativeParentTransform = function () {
            this._global.copy(this._origin);
            this._global.x += this._parent._tweenPivot.x;
            this._global.y += this._parent._tweenPivot.y;
        };
        p.initDisplayList = function (newDisplayList) {
            this._displayList = newDisplayList;
        };
        p.clearCurrentDisplay = function () {
            if (this.hasChildArmature) {
                var targetArmature = this.childArmature;
                if (targetArmature) {
                    targetArmature.resetAnimation();
                }
            }
            var slotIndex = this._getDisplayIndex();
            this._removeDisplayFromContainer();
            return slotIndex;
        };
        p._changeDisplayIndex = function (displayIndex) {
            if (displayIndex === void 0) { displayIndex = 0; }
            if (this._currentDisplayIndex == displayIndex) {
                return;
            }
            var slotIndex = -1;
            if (this._currentDisplayIndex >= 0) {
                slotIndex = this.clearCurrentDisplay();
            }
            this._currentDisplayIndex = displayIndex;
            if (this._currentDisplayIndex >= 0) {
                this._origin.copy(this._displayDataList[this._currentDisplayIndex].transform);
                this.initCurrentDisplay(slotIndex);
            }
        };
        p.changeSlotDisplay = function (value) {
            var slotIndex = this.clearCurrentDisplay();
            this._displayList[this._currentDisplayIndex] = value;
            this.initCurrentDisplay(slotIndex);
        };
        p.initCurrentDisplay = function (slotIndex) {
            if (slotIndex === void 0) { slotIndex = 0; }
            var display = this._displayList[this._currentDisplayIndex];
            if (display) {
                if (display instanceof dragonBones.FastArmature) {
                    this._currentDisplay = display.display;
                }
                else {
                    this._currentDisplay = display;
                }
            }
            else {
                this._currentDisplay = null;
            }
            this._updateDisplay(this._currentDisplay);
            if (this._currentDisplay) {
                if (slotIndex != -1) {
                    this._addDisplayToContainer(this.armature.display, slotIndex);
                }
                else {
                    this.armature._slotsZOrderChanged = true;
                    this._addDisplayToContainer(this.armature.display);
                }
                if (this._blendMode) {
                    this._updateDisplayBlendMode(this._blendMode);
                }
                if (this._isColorChanged) {
                    this._updateDisplayColor(this._colorTransform.alphaOffset, this._colorTransform.redOffset, this._colorTransform.greenOffset, this._colorTransform.blueOffset, this._colorTransform.alphaMultiplier, this._colorTransform.redMultiplier, this._colorTransform.greenMultiplier, this._colorTransform.blueMultiplier, true);
                }
                this._updateTransform();
                if (display instanceof dragonBones.FastArmature) {
                    var targetArmature = (display);
                    if (this.armature &&
                        this.armature.animation.animationState &&
                        targetArmature.animation.hasAnimation(this.armature.animation.animationState.name)) {
                        targetArmature.animation.gotoAndPlay(this.armature.animation.animationState.name);
                    }
                    else {
                        targetArmature.animation.play();
                    }
                }
            }
        };
        d(p, "visible",undefined
            ,function (value) {
                if (this._visible != value) {
                    this._visible = value;
                    this._updateDisplayVisible(this._visible);
                }
            }
        );
        d(p, "displayList"
            ,function () {
                return this._displayList;
            }
            ,function (value) {
                if (!value) {
                    throw new Error();
                }
                var newDisplay = value[this._currentDisplayIndex];
                var displayChanged = this._currentDisplayIndex >= 0 && this._displayList[this._currentDisplayIndex] != newDisplay;
                this._displayList = value;
                if (displayChanged) {
                    this.changeSlotDisplay(newDisplay);
                }
            }
        );
        d(p, "display"
            ,function () {
                return this._currentDisplay;
            }
            ,function (value) {
                if (this._currentDisplayIndex < 0) {
                    return;
                }
                if (this._displayList[this._currentDisplayIndex] == value) {
                    return;
                }
                this.changeSlotDisplay(value);
            }
        );
        d(p, "childArmature"
            ,function () {
                return (this._displayList[this._currentDisplayIndex] instanceof dragonBones.Armature
                    || this._displayList[this._currentDisplayIndex] instanceof dragonBones.FastArmature) ? this._displayList[this._currentDisplayIndex] : null;
            }
            ,function (value) {
                this.display = value;
            }
        );
        d(p, "zOrder"
            ,function () {
                return this._originZOrder + this._tweenZOrder + this._offsetZOrder;
            }
            ,function (value) {
                if (this.zOrder != value) {
                    this._offsetZOrder = value - this._originZOrder - this._tweenZOrder;
                    if (this.armature) {
                        this.armature._slotsZOrderChanged = true;
                    }
                }
            }
        );
        d(p, "blendMode"
            ,function () {
                return this._blendMode;
            }
            ,function (value) {
                if (this._blendMode != value) {
                    this._blendMode = value;
                    this._updateDisplayBlendMode(this._blendMode);
                }
            }
        );
        d(p, "colorTransform"
            ,function () {
                return this._colorTransform;
            }
        );
        d(p, "displayIndex"
            ,function () {
                return this._currentDisplayIndex;
            }
        );
        d(p, "colorChanged"
            ,function () {
                return this._isColorChanged;
            }
        );
        p._updateDisplay = function (value) {
            throw new Error("Abstract method needs to be implemented in subclass!");
        };
        p._getDisplayIndex = function () {
            throw new Error("Abstract method needs to be implemented in subclass!");
        };
        p._addDisplayToContainer = function (container, index) {
            if (index === void 0) { index = -1; }
            throw new Error("Abstract method needs to be implemented in subclass!");
        };
        p._removeDisplayFromContainer = function () {
            throw new Error("Abstract method needs to be implemented in subclass!");
        };
        p._updateTransform = function () {
            throw new Error("Abstract method needs to be implemented in subclass!");
        };
        p._updateDisplayVisible = function (value) {
            throw new Error("Abstract method needs to be implemented in subclass!");
        };
        p._updateDisplayColor = function (aOffset, rOffset, gOffset, bOffset, aMultiplier, rMultiplier, gMultiplier, bMultiplier, colorChanged) {
            if (colorChanged === void 0) { colorChanged = false; }
            this._colorTransform.alphaOffset = aOffset;
            this._colorTransform.redOffset = rOffset;
            this._colorTransform.greenOffset = gOffset;
            this._colorTransform.blueOffset = bOffset;
            this._colorTransform.alphaMultiplier = aMultiplier;
            this._colorTransform.redMultiplier = rMultiplier;
            this._colorTransform.greenMultiplier = gMultiplier;
            this._colorTransform.blueMultiplier = bMultiplier;
            this._isColorChanged = colorChanged;
        };
        p._updateDisplayBlendMode = function (value) {
            throw new Error("Abstract method needs to be implemented in subclass!");
        };
        p._arriveAtFrame = function (frame, animationState) {
            var slotFrame = frame;
            var displayIndex = slotFrame.displayIndex;
            this._changeDisplayIndex(displayIndex);
            this._updateDisplayVisible(slotFrame.visible);
            if (displayIndex >= 0) {
                if (!isNaN(slotFrame.zOrder) && slotFrame.zOrder != this._tweenZOrder) {
                    this._tweenZOrder = slotFrame.zOrder;
                    this.armature._slotsZOrderChanged = true;
                }
            }
            if (frame.action) {
                var targetArmature = this.childArmature;
                if (targetArmature) {
                    targetArmature.getAnimation().gotoAndPlay(frame.action);
                }
            }
        };
        p.hideSlots = function () {
            this._changeDisplayIndex(-1);
            this._removeDisplayFromContainer();
            if (this._frameCache) {
                this._frameCache.clear();
            }
        };
        p._updateGlobal = function () {
            this._calculateRelativeParentTransform();
            dragonBones.TransformUtil.transformToMatrix(this._global, this._globalTransformMatrix, true);
            var output = this._calculateParentTransform();
            if (output) {
                this._globalTransformMatrix.concat(output.parentGlobalTransformMatrix);
                dragonBones.TransformUtil.matrixToTransform(this._globalTransformMatrix, this._global, this._global.scaleX * output.parentGlobalTransform.scaleX >= 0, this._global.scaleY * output.parentGlobalTransform.scaleY >= 0);
            }
            return output;
        };
        p._resetToOrigin = function () {
            this._changeDisplayIndex(this._originDisplayIndex);
            this._updateDisplayColor(0, 0, 0, 0, 1, 1, 1, 1, true);
        };
        return FastSlot;
    })(dragonBones.FastDBObject);
    dragonBones.FastSlot = FastSlot;
    egret.registerClass(FastSlot,'dragonBones.FastSlot',["dragonBones.ISlotCacheGenerator","dragonBones.ICacheUser"]);
})(dragonBones || (dragonBones = {}));
var dragonBones;
(function (dragonBones) {
    var Point = (function () {
        function Point(x, y) {
            if (x === void 0) { x = 0; }
            if (y === void 0) { y = 0; }
            this.x = x;
            this.y = y;
        }
        var d = __define,c=Point,p=c.prototype;
        p.toString = function () {
            return "[Point (x=" + this.x + " y=" + this.y + ")]";
        };
        return Point;
    })();
    dragonBones.Point = Point;
    egret.registerClass(Point,'dragonBones.Point');
})(dragonBones || (dragonBones = {}));
var dragonBones;
(function (dragonBones) {
    var Rectangle = (function () {
        function Rectangle(x, y, width, height) {
            if (x === void 0) { x = 0; }
            if (y === void 0) { y = 0; }
            if (width === void 0) { width = 0; }
            if (height === void 0) { height = 0; }
            this.x = x;
            this.y = y;
            this.width = width;
            this.height = height;
        }
        var d = __define,c=Rectangle,p=c.prototype;
        return Rectangle;
    })();
    dragonBones.Rectangle = Rectangle;
    egret.registerClass(Rectangle,'dragonBones.Rectangle');
})(dragonBones || (dragonBones = {}));
var dragonBones;
(function (dragonBones) {
    var Data3Parser = (function () {
        function Data3Parser() {
        }
        var d = __define,c=Data3Parser,p=c.prototype;
        Data3Parser.parseDragonBonesData = function (rawDataToParse) {
            if (!rawDataToParse) {
                throw new Error();
            }
            var version = rawDataToParse[dragonBones.ConstValues.A_VERSION];
            version = version.toString();
            if (version.toString() != dragonBones.DragonBones.DATA_VERSION &&
                version.toString() != dragonBones.DragonBones.PARENT_COORDINATE_DATA_VERSION &&
                version.toString() != "2.3") {
                throw new Error("Nonsupport version!");
            }
            var frameRate = Data3Parser.getNumber(rawDataToParse, dragonBones.ConstValues.A_FRAME_RATE, 0) || 0;
            var outputDragonBonesData = new dragonBones.DragonBonesData();
            outputDragonBonesData.name = rawDataToParse[dragonBones.ConstValues.A_NAME];
            outputDragonBonesData.isGlobal = rawDataToParse[dragonBones.ConstValues.A_IS_GLOBAL] == "0" ? false : true;
            Data3Parser.tempDragonBonesData = outputDragonBonesData;
            var armatureList = rawDataToParse[dragonBones.ConstValues.ARMATURE];
            for (var i = 0, len = armatureList.length; i < len; i++) {
                var armatureObject = armatureList[i];
                outputDragonBonesData.addArmatureData(Data3Parser.parseArmatureData(armatureObject, frameRate));
            }
            Data3Parser.tempDragonBonesData = null;
            return outputDragonBonesData;
        };
        Data3Parser.parseArmatureData = function (armatureDataToParse, frameRate) {
            var outputArmatureData = new dragonBones.ArmatureData();
            outputArmatureData.name = armatureDataToParse[dragonBones.ConstValues.A_NAME];
            var i;
            var len;
            var boneList = armatureDataToParse[dragonBones.ConstValues.BONE];
            for (i = 0, len = boneList.length; i < len; i++) {
                var boneObject = boneList[i];
                outputArmatureData.addBoneData(Data3Parser.parseBoneData(boneObject));
            }
            var skinList = armatureDataToParse[dragonBones.ConstValues.SKIN];
            for (i = 0, len = skinList.length; i < len; i++) {
                var skinSlotList = skinList[i];
                var skinSlotObject = skinSlotList[dragonBones.ConstValues.SLOT];
                for (var j = 0, jLen = skinSlotObject.length; j < jLen; j++) {
                    var slotObject = skinSlotObject[j];
                    outputArmatureData.addSlotData(Data3Parser.parseSlotData(slotObject));
                }
            }
            for (i = 0, len = skinList.length; i < len; i++) {
                var skinObject = skinList[i];
                outputArmatureData.addSkinData(Data3Parser.parseSkinData(skinObject));
            }
            if (Data3Parser.tempDragonBonesData.isGlobal) {
                dragonBones.DBDataUtil.transformArmatureData(outputArmatureData);
            }
            outputArmatureData.sortBoneDataList();
            var animationList = armatureDataToParse[dragonBones.ConstValues.ANIMATION];
            for (i = 0, len = animationList.length; i < len; i++) {
                var animationObject = animationList[i];
                var animationData = Data3Parser.parseAnimationData(animationObject, frameRate);
                dragonBones.DBDataUtil.addHideTimeline(animationData, outputArmatureData);
                dragonBones.DBDataUtil.transformAnimationData(animationData, outputArmatureData, Data3Parser.tempDragonBonesData.isGlobal);
                outputArmatureData.addAnimationData(animationData);
            }
            return outputArmatureData;
        };
        Data3Parser.parseBoneData = function (boneObject) {
            var boneData = new dragonBones.BoneData();
            boneData.name = boneObject[dragonBones.ConstValues.A_NAME];
            boneData.parent = boneObject[dragonBones.ConstValues.A_PARENT];
            boneData.length = Number(boneObject[dragonBones.ConstValues.A_LENGTH]) || 0;
            boneData.inheritRotation = Data3Parser.getBoolean(boneObject, dragonBones.ConstValues.A_INHERIT_ROTATION, true);
            boneData.inheritScale = Data3Parser.getBoolean(boneObject, dragonBones.ConstValues.A_INHERIT_SCALE, true);
            Data3Parser.parseTransform(boneObject[dragonBones.ConstValues.TRANSFORM], boneData.transform);
            if (Data3Parser.tempDragonBonesData.isGlobal) {
                boneData.global.copy(boneData.transform);
            }
            return boneData;
        };
        Data3Parser.parseSkinData = function (skinObject) {
            var skinData = new dragonBones.SkinData();
            skinData.name = skinObject[dragonBones.ConstValues.A_NAME];
            var slotList = skinObject[dragonBones.ConstValues.SLOT];
            for (var i = 0, len = slotList.length; i < len; i++) {
                var slotObject = slotList[i];
                skinData.addSlotData(Data3Parser.parseSkinSlotData(slotObject));
            }
            return skinData;
        };
        Data3Parser.parseSkinSlotData = function (slotObject) {
            var slotData = new dragonBones.SlotData();
            slotData.name = slotObject[dragonBones.ConstValues.A_NAME];
            slotData.parent = slotObject[dragonBones.ConstValues.A_PARENT];
            slotData.zOrder = (slotObject[dragonBones.ConstValues.A_Z_ORDER]);
            slotData.zOrder = Data3Parser.getNumber(slotObject, dragonBones.ConstValues.A_Z_ORDER, 0) || 0;
            slotData.blendMode = slotObject[dragonBones.ConstValues.A_BLENDMODE];
            var displayList = slotObject[dragonBones.ConstValues.DISPLAY];
            if (displayList) {
                for (var i = 0, len = displayList.length; i < len; i++) {
                    var displayObject = displayList[i];
                    slotData.addDisplayData(Data3Parser.parseDisplayData(displayObject));
                }
            }
            return slotData;
        };
        Data3Parser.parseSlotData = function (slotObject) {
            var slotData = new dragonBones.SlotData();
            slotData.name = slotObject[dragonBones.ConstValues.A_NAME];
            slotData.parent = slotObject[dragonBones.ConstValues.A_PARENT];
            slotData.zOrder = (slotObject[dragonBones.ConstValues.A_Z_ORDER]);
            slotData.zOrder = Data3Parser.getNumber(slotObject, dragonBones.ConstValues.A_Z_ORDER, 0) || 0;
            slotData.blendMode = slotObject[dragonBones.ConstValues.A_BLENDMODE];
            slotData.displayIndex = 0;
            return slotData;
        };
        Data3Parser.parseDisplayData = function (displayObject) {
            var displayData = new dragonBones.DisplayData();
            displayData.name = displayObject[dragonBones.ConstValues.A_NAME];
            displayData.type = displayObject[dragonBones.ConstValues.A_TYPE];
            Data3Parser.parseTransform(displayObject[dragonBones.ConstValues.TRANSFORM], displayData.transform, displayData.pivot);
            if (Data3Parser.tempDragonBonesData != null) {
                Data3Parser.tempDragonBonesData.addDisplayData(displayData);
            }
            return displayData;
        };
        Data3Parser.parseAnimationData = function (animationObject, frameRate) {
            var animationData = new dragonBones.AnimationData();
            animationData.name = animationObject[dragonBones.ConstValues.A_NAME];
            animationData.frameRate = frameRate;
            animationData.duration = Math.round((Data3Parser.getNumber(animationObject, dragonBones.ConstValues.A_DURATION, 1) || 1) * 1000 / frameRate);
            animationData.playTimes = Data3Parser.getNumber(animationObject, dragonBones.ConstValues.A_LOOP, 1);
            animationData.playTimes = animationData.playTimes != NaN ? animationData.playTimes : 1;
            animationData.fadeTime = Data3Parser.getNumber(animationObject, dragonBones.ConstValues.A_FADE_IN_TIME, 0) || 0;
            animationData.scale = Data3Parser.getNumber(animationObject, dragonBones.ConstValues.A_SCALE, 1) || 0;
            animationData.tweenEasing = Data3Parser.getNumber(animationObject, dragonBones.ConstValues.A_TWEEN_EASING, NaN);
            animationData.autoTween = Data3Parser.getBoolean(animationObject, dragonBones.ConstValues.A_AUTO_TWEEN, true);
            var frameObjectList = animationObject[dragonBones.ConstValues.FRAME];
            var i = 0;
            var len = 0;
            if (frameObjectList) {
                for (i = 0, len = frameObjectList.length; i < len; i++) {
                    var frameObject = frameObjectList[i];
                    var frame = Data3Parser.parseTransformFrame(frameObject, null, frameRate);
                    animationData.addFrame(frame);
                }
            }
            Data3Parser.parseTimeline(animationObject, animationData);
            var lastFrameDuration = animationData.duration;
            var displayIndexChangeSlotTimelines = [];
            var displayIndexChangeTimelines = [];
            var timelineObjectList = animationObject[dragonBones.ConstValues.TIMELINE];
            var displayIndexChange;
            if (timelineObjectList) {
                for (i = 0, len = timelineObjectList.length; i < len; i++) {
                    var timelineObject = timelineObjectList[i];
                    var timeline = Data3Parser.parseTransformTimeline(timelineObject, animationData.duration, frameRate);
                    timeline = Data3Parser.parseTransformTimeline(timelineObject, animationData.duration, frameRate);
                    lastFrameDuration = Math.min(lastFrameDuration, timeline.frameList[timeline.frameList.length - 1].duration);
                    animationData.addTimeline(timeline);
                    var slotTimeline = Data3Parser.parseSlotTimeline(timelineObject, animationData.duration, frameRate);
                    animationData.addSlotTimeline(slotTimeline);
                    if (animationData.autoTween && !displayIndexChange) {
                        var slotFrame;
                        for (var j = 0, jlen = slotTimeline.frameList.length; j < jlen; j++) {
                            slotFrame = slotTimeline.frameList[j];
                            if (slotFrame && slotFrame.displayIndex < 0) {
                                displayIndexChange = true;
                                break;
                            }
                        }
                    }
                }
                var animationTween = animationData.tweenEasing;
                if (displayIndexChange) {
                    len = animationData.slotTimelineList.length;
                    for (i = 0; i < len; i++) {
                        slotTimeline = animationData.slotTimelineList[i];
                        timeline = animationData.timelineList[i];
                        var curFrame;
                        var curSlotFrame;
                        var nextSlotFrame;
                        for (j = 0, jlen = slotTimeline.frameList.length; j < jlen; j++) {
                            curSlotFrame = slotTimeline.frameList[j];
                            curFrame = timeline.frameList[j];
                            nextSlotFrame = (j == jlen - 1) ? slotTimeline.frameList[0] : slotTimeline.frameList[j + 1];
                            if (curSlotFrame.displayIndex < 0 || nextSlotFrame.displayIndex < 0) {
                                curFrame.tweenEasing = curSlotFrame.tweenEasing = NaN;
                            }
                            else if (animationTween == 10) {
                                curFrame.tweenEasing = curSlotFrame.tweenEasing = 0;
                            }
                            else if (!isNaN(animationTween)) {
                                curFrame.tweenEasing = curSlotFrame.tweenEasing = animationTween;
                            }
                            else if (curFrame.tweenEasing == 10) {
                                curFrame.tweenEasing = 0;
                            }
                        }
                    }
                    animationData.autoTween = false;
                }
            }
            if (animationData.frameList.length > 0) {
                lastFrameDuration = Math.min(lastFrameDuration, animationData.frameList[animationData.frameList.length - 1].duration);
            }
            animationData.lastFrameDuration = lastFrameDuration;
            return animationData;
        };
        Data3Parser.parseSlotTimeline = function (timelineObject, duration, frameRate) {
            var outputTimeline = new dragonBones.SlotTimeline();
            outputTimeline.name = timelineObject[dragonBones.ConstValues.A_NAME];
            outputTimeline.scale = Data3Parser.getNumber(timelineObject, dragonBones.ConstValues.A_SCALE, 1) || 0;
            outputTimeline.offset = Data3Parser.getNumber(timelineObject, dragonBones.ConstValues.A_OFFSET, 0) || 0;
            outputTimeline.duration = duration;
            var frameList = timelineObject[dragonBones.ConstValues.FRAME];
            for (var i = 0, len = frameList.length; i < len; i++) {
                var frameObject = frameList[i];
                var frame = Data3Parser.parseSlotFrame(frameObject, frameRate);
                outputTimeline.addFrame(frame);
            }
            Data3Parser.parseTimeline(timelineObject, outputTimeline);
            return outputTimeline;
        };
        Data3Parser.parseSlotFrame = function (frameObject, frameRate) {
            var outputFrame = new dragonBones.SlotFrame();
            Data3Parser.parseFrame(frameObject, outputFrame, frameRate);
            outputFrame.visible = !Data3Parser.getBoolean(frameObject, dragonBones.ConstValues.A_HIDE, false);
            outputFrame.tweenEasing = Data3Parser.getNumber(frameObject, dragonBones.ConstValues.A_TWEEN_EASING, 10);
            outputFrame.displayIndex = Math.floor(Data3Parser.getNumber(frameObject, dragonBones.ConstValues.A_DISPLAY_INDEX, 0) || 0);
            outputFrame.zOrder = Data3Parser.getNumber(frameObject, dragonBones.ConstValues.A_Z_ORDER, Data3Parser.tempDragonBonesData.isGlobal ? NaN : 0);
            var colorTransformObject = frameObject[dragonBones.ConstValues.COLOR_TRANSFORM];
            if (colorTransformObject) {
                outputFrame.color = new dragonBones.ColorTransform();
                Data3Parser.parseColorTransform(colorTransformObject, outputFrame.color);
            }
            return outputFrame;
        };
        Data3Parser.parseTransformTimeline = function (timelineObject, duration, frameRate) {
            var outputTimeline = new dragonBones.TransformTimeline();
            outputTimeline.name = timelineObject[dragonBones.ConstValues.A_NAME];
            outputTimeline.scale = Data3Parser.getNumber(timelineObject, dragonBones.ConstValues.A_SCALE, 1) || 0;
            outputTimeline.offset = Data3Parser.getNumber(timelineObject, dragonBones.ConstValues.A_OFFSET, 0) || 0;
            outputTimeline.originPivot.x = Data3Parser.getNumber(timelineObject, dragonBones.ConstValues.A_PIVOT_X, 0) || 0;
            outputTimeline.originPivot.y = Data3Parser.getNumber(timelineObject, dragonBones.ConstValues.A_PIVOT_Y, 0) || 0;
            outputTimeline.duration = duration;
            var frameList = timelineObject[dragonBones.ConstValues.FRAME];
            var nextFrameObject;
            for (var i = 0, len = frameList.length; i < len; i++) {
                var frameObject = frameList[i];
                if (i < len - 1) {
                    nextFrameObject = frameList[i + 1];
                }
                else if (i != 0) {
                    nextFrameObject = frameList[0];
                }
                else {
                    nextFrameObject = null;
                }
                var frame = Data3Parser.parseTransformFrame(frameObject, nextFrameObject, frameRate);
                outputTimeline.addFrame(frame);
            }
            Data3Parser.parseTimeline(timelineObject, outputTimeline);
            return outputTimeline;
        };
        Data3Parser.parseTransformFrame = function (frameObject, nextFrameObject, frameRate) {
            var outputFrame = new dragonBones.TransformFrame();
            Data3Parser.parseFrame(frameObject, outputFrame, frameRate);
            outputFrame.visible = !Data3Parser.getBoolean(frameObject, dragonBones.ConstValues.A_HIDE, false);
            outputFrame.tweenEasing = Data3Parser.getNumber(frameObject, dragonBones.ConstValues.A_TWEEN_EASING, 10);
            outputFrame.tweenRotate = Math.floor(Data3Parser.getNumber(frameObject, dragonBones.ConstValues.A_TWEEN_ROTATE, 0) || 0);
            outputFrame.tweenScale = Data3Parser.getBoolean(frameObject, dragonBones.ConstValues.A_TWEEN_SCALE, true);
            if (nextFrameObject && Math.floor(Data3Parser.getNumber(nextFrameObject, dragonBones.ConstValues.A_DISPLAY_INDEX, 0) || 0) == -1) {
                outputFrame.tweenEasing = NaN;
            }
            Data3Parser.parseTransform(frameObject[dragonBones.ConstValues.TRANSFORM], outputFrame.transform, outputFrame.pivot);
            if (Data3Parser.tempDragonBonesData.isGlobal) {
                outputFrame.global.copy(outputFrame.transform);
            }
            outputFrame.scaleOffset.x = Data3Parser.getNumber(frameObject, dragonBones.ConstValues.A_SCALE_X_OFFSET, 0) || 0;
            outputFrame.scaleOffset.y = Data3Parser.getNumber(frameObject, dragonBones.ConstValues.A_SCALE_Y_OFFSET, 0) || 0;
            return outputFrame;
        };
        Data3Parser.parseTimeline = function (timelineObject, outputTimeline) {
            var position = 0;
            var frame;
            var frameList = outputTimeline.frameList;
            for (var i = 0, len = frameList.length; i < len; i++) {
                frame = frameList[i];
                frame.position = position;
                position += frame.duration;
            }
            if (frame) {
                frame.duration = outputTimeline.duration - frame.position;
            }
        };
        Data3Parser.parseFrame = function (frameObject, outputFrame, frameRate) {
            if (frameRate === void 0) { frameRate = 0; }
            outputFrame.duration = Math.round(((frameObject[dragonBones.ConstValues.A_DURATION]) || 1) * 1000 / frameRate);
            outputFrame.action = frameObject[dragonBones.ConstValues.A_ACTION];
            outputFrame.event = frameObject[dragonBones.ConstValues.A_EVENT];
            outputFrame.sound = frameObject[dragonBones.ConstValues.A_SOUND];
        };
        Data3Parser.parseTransform = function (transformObject, transform, pivot) {
            if (pivot === void 0) { pivot = null; }
            if (transformObject) {
                if (transform) {
                    transform.x = Data3Parser.getNumber(transformObject, dragonBones.ConstValues.A_X, 0) || 0;
                    transform.y = Data3Parser.getNumber(transformObject, dragonBones.ConstValues.A_Y, 0) || 0;
                    transform.skewX = Data3Parser.getNumber(transformObject, dragonBones.ConstValues.A_SKEW_X, 0) * dragonBones.ConstValues.ANGLE_TO_RADIAN || 0;
                    transform.skewY = Data3Parser.getNumber(transformObject, dragonBones.ConstValues.A_SKEW_Y, 0) * dragonBones.ConstValues.ANGLE_TO_RADIAN || 0;
                    transform.scaleX = Data3Parser.getNumber(transformObject, dragonBones.ConstValues.A_SCALE_X, 1) || 0;
                    transform.scaleY = Data3Parser.getNumber(transformObject, dragonBones.ConstValues.A_SCALE_Y, 1) || 0;
                }
                if (pivot) {
                    pivot.x = Data3Parser.getNumber(transformObject, dragonBones.ConstValues.A_PIVOT_X, 0) || 0;
                    pivot.y = Data3Parser.getNumber(transformObject, dragonBones.ConstValues.A_PIVOT_Y, 0) || 0;
                }
            }
        };
        Data3Parser.parseColorTransform = function (colorTransformObject, colorTransform) {
            if (colorTransformObject) {
                if (colorTransform) {
                    colorTransform.alphaOffset = Data3Parser.getNumber(colorTransformObject, dragonBones.ConstValues.A_ALPHA_OFFSET, 0);
                    colorTransform.redOffset = Data3Parser.getNumber(colorTransformObject, dragonBones.ConstValues.A_RED_OFFSET, 0);
                    colorTransform.greenOffset = Data3Parser.getNumber(colorTransformObject, dragonBones.ConstValues.A_GREEN_OFFSET, 0);
                    colorTransform.blueOffset = Data3Parser.getNumber(colorTransformObject, dragonBones.ConstValues.A_BLUE_OFFSET, 0);
                    colorTransform.alphaMultiplier = Data3Parser.getNumber(colorTransformObject, dragonBones.ConstValues.A_ALPHA_MULTIPLIER, 100) * 0.01;
                    colorTransform.redMultiplier = Data3Parser.getNumber(colorTransformObject, dragonBones.ConstValues.A_RED_MULTIPLIER, 100) * 0.01;
                    colorTransform.greenMultiplier = Data3Parser.getNumber(colorTransformObject, dragonBones.ConstValues.A_GREEN_MULTIPLIER, 100) * 0.01;
                    colorTransform.blueMultiplier = Data3Parser.getNumber(colorTransformObject, dragonBones.ConstValues.A_BLUE_MULTIPLIER, 100) * 0.01;
                }
            }
        };
        Data3Parser.getBoolean = function (data, key, defaultValue) {
            if (data && key in data) {
                switch (String(data[key])) {
                    case "0":
                    case "NaN":
                    case "":
                    case "false":
                    case "null":
                    case "undefined":
                        return false;
                    case "1":
                    case "true":
                    default:
                        return true;
                }
            }
            return defaultValue;
        };
        Data3Parser.getNumber = function (data, key, defaultValue) {
            if (data && key in data) {
                switch (String(data[key])) {
                    case "NaN":
                    case "":
                    case "false":
                    case "null":
                    case "undefined":
                        return NaN;
                    default:
                        return Number(data[key]);
                }
            }
            return defaultValue;
        };
        return Data3Parser;
    })();
    dragonBones.Data3Parser = Data3Parser;
    egret.registerClass(Data3Parser,'dragonBones.Data3Parser');
})(dragonBones || (dragonBones = {}));
var dragonBones;
(function (dragonBones) {
    var DataParser = (function () {
        function DataParser() {
        }
        var d = __define,c=DataParser,p=c.prototype;
        DataParser.parseTextureAtlasData = function (rawData, scale) {
            if (scale === void 0) { scale = 1; }
            var textureAtlasData = {};
            var subTextureFrame;
            var subTextureList = rawData[dragonBones.ConstValues.SUB_TEXTURE];
            for (var i = 0, len = subTextureList.length; i < len; i++) {
                var subTextureObject = subTextureList[i];
                var subTextureName = subTextureObject[dragonBones.ConstValues.A_NAME];
                var subTextureRegion = new dragonBones.Rectangle();
                subTextureRegion.x = DataParser.getNumber(subTextureObject, dragonBones.ConstValues.A_X, 0) / scale;
                subTextureRegion.y = DataParser.getNumber(subTextureObject, dragonBones.ConstValues.A_Y, 0) / scale;
                subTextureRegion.width = DataParser.getNumber(subTextureObject, dragonBones.ConstValues.A_WIDTH, 0) / scale;
                subTextureRegion.height = DataParser.getNumber(subTextureObject, dragonBones.ConstValues.A_HEIGHT, 0) / scale;
                var rotated = subTextureObject[dragonBones.ConstValues.A_ROTATED] == "true";
                var frameWidth = DataParser.getNumber(subTextureObject, dragonBones.ConstValues.A_FRAME_WIDTH, 0) / scale;
                var frameHeight = DataParser.getNumber(subTextureObject, dragonBones.ConstValues.A_FRAME_HEIGHT, 0) / scale;
                if (frameWidth > 0 && frameHeight > 0) {
                    subTextureFrame = new dragonBones.Rectangle();
                    subTextureFrame.x = DataParser.getNumber(subTextureObject, dragonBones.ConstValues.A_FRAME_X, 0) / scale;
                    subTextureFrame.y = DataParser.getNumber(subTextureObject, dragonBones.ConstValues.A_FRAME_Y, 0) / scale;
                    subTextureFrame.width = frameWidth;
                    subTextureFrame.height = frameHeight;
                }
                else {
                    subTextureFrame = null;
                }
                textureAtlasData[subTextureName] = new dragonBones.TextureData(subTextureRegion, subTextureFrame, rotated);
            }
            return textureAtlasData;
        };
        DataParser.parseDragonBonesData = function (rawDataToParse) {
            if (!rawDataToParse) {
                throw new Error();
            }
            var version = rawDataToParse[dragonBones.ConstValues.A_VERSION];
            version = version.toString();
            if (version.toString() == dragonBones.DragonBones.PARENT_COORDINATE_DATA_VERSION ||
                version.toString() == "2.3") {
                return dragonBones.Data3Parser.parseDragonBonesData(rawDataToParse);
            }
            var frameRate = DataParser.getNumber(rawDataToParse, dragonBones.ConstValues.A_FRAME_RATE, 0) || 0;
            var outputDragonBonesData = new dragonBones.DragonBonesData();
            outputDragonBonesData.name = rawDataToParse[dragonBones.ConstValues.A_NAME];
            outputDragonBonesData.isGlobal = rawDataToParse[dragonBones.ConstValues.A_IS_GLOBAL] == "0" ? false : true;
            DataParser.tempDragonBonesData = outputDragonBonesData;
            var armatureList = rawDataToParse[dragonBones.ConstValues.ARMATURE];
            for (var i = 0, len = armatureList.length; i < len; i++) {
                var armatureObject = armatureList[i];
                outputDragonBonesData.addArmatureData(DataParser.parseArmatureData(armatureObject, frameRate));
            }
            DataParser.tempDragonBonesData = null;
            return outputDragonBonesData;
        };
        DataParser.parseArmatureData = function (armatureDataToParse, frameRate) {
            var outputArmatureData = new dragonBones.ArmatureData();
            outputArmatureData.name = armatureDataToParse[dragonBones.ConstValues.A_NAME];
            var boneList = armatureDataToParse[dragonBones.ConstValues.BONE];
            var i;
            var len;
            for (i = 0, len = boneList.length; i < len; i++) {
                var boneObject = boneList[i];
                outputArmatureData.addBoneData(DataParser.parseBoneData(boneObject));
            }
            var slotList = armatureDataToParse[dragonBones.ConstValues.SLOT];
            for (i = 0, len = slotList.length; i < len; i++) {
                var slotObject = slotList[i];
                outputArmatureData.addSlotData(DataParser.parseSlotData(slotObject));
            }
            var skinList = armatureDataToParse[dragonBones.ConstValues.SKIN];
            for (i = 0, len = skinList.length; i < len; i++) {
                var skinObject = skinList[i];
                outputArmatureData.addSkinData(DataParser.parseSkinData(skinObject));
            }
            if (DataParser.tempDragonBonesData.isGlobal) {
                dragonBones.DBDataUtil.transformArmatureData(outputArmatureData);
            }
            outputArmatureData.sortBoneDataList();
            var animationList = armatureDataToParse[dragonBones.ConstValues.ANIMATION];
            for (i = 0, len = animationList.length; i < len; i++) {
                var animationObject = animationList[i];
                var animationData = DataParser.parseAnimationData(animationObject, frameRate);
                dragonBones.DBDataUtil.addHideTimeline(animationData, outputArmatureData, true);
                dragonBones.DBDataUtil.transformAnimationData(animationData, outputArmatureData, DataParser.tempDragonBonesData.isGlobal);
                outputArmatureData.addAnimationData(animationData);
            }
            return outputArmatureData;
        };
        DataParser.parseBoneData = function (boneObject) {
            var boneData = new dragonBones.BoneData();
            boneData.name = boneObject[dragonBones.ConstValues.A_NAME];
            boneData.parent = boneObject[dragonBones.ConstValues.A_PARENT];
            boneData.length = Number(boneObject[dragonBones.ConstValues.A_LENGTH]) || 0;
            boneData.inheritRotation = DataParser.getBoolean(boneObject, dragonBones.ConstValues.A_INHERIT_ROTATION, true);
            boneData.inheritScale = DataParser.getBoolean(boneObject, dragonBones.ConstValues.A_INHERIT_SCALE, true);
            DataParser.parseTransform(boneObject[dragonBones.ConstValues.TRANSFORM], boneData.transform);
            if (DataParser.tempDragonBonesData.isGlobal) {
                boneData.global.copy(boneData.transform);
            }
            return boneData;
        };
        DataParser.parseSkinData = function (skinObject) {
            var skinData = new dragonBones.SkinData();
            skinData.name = skinObject[dragonBones.ConstValues.A_NAME];
            var slotList = skinObject[dragonBones.ConstValues.SLOT];
            for (var i = 0, len = slotList.length; i < len; i++) {
                var slotObject = slotList[i];
                skinData.addSlotData(DataParser.parseSlotDisplayData(slotObject));
            }
            return skinData;
        };
        DataParser.parseSlotData = function (slotObject) {
            var slotData = new dragonBones.SlotData();
            slotData.name = slotObject[dragonBones.ConstValues.A_NAME];
            slotData.parent = slotObject[dragonBones.ConstValues.A_PARENT];
            slotData.zOrder = DataParser.getNumber(slotObject, dragonBones.ConstValues.A_Z_ORDER, 0) || 0;
            slotData.displayIndex = DataParser.getNumber(slotObject, dragonBones.ConstValues.A_DISPLAY_INDEX, 0);
            slotData.blendMode = slotObject[dragonBones.ConstValues.A_BLENDMODE];
            return slotData;
        };
        DataParser.parseSlotDisplayData = function (slotObject) {
            var slotData = new dragonBones.SlotData();
            slotData.name = slotObject[dragonBones.ConstValues.A_NAME];
            slotData.parent = slotObject[dragonBones.ConstValues.A_PARENT];
            slotData.zOrder = DataParser.getNumber(slotObject, dragonBones.ConstValues.A_Z_ORDER, 0) || 0;
            var displayList = slotObject[dragonBones.ConstValues.DISPLAY];
            if (displayList) {
                for (var i = 0, len = displayList.length; i < len; i++) {
                    var displayObject = displayList[i];
                    slotData.addDisplayData(DataParser.parseDisplayData(displayObject));
                }
            }
            return slotData;
        };
        DataParser.parseDisplayData = function (displayObject) {
            var displayData = new dragonBones.DisplayData();
            displayData.name = displayObject[dragonBones.ConstValues.A_NAME];
            displayData.type = displayObject[dragonBones.ConstValues.A_TYPE];
            DataParser.parseTransform(displayObject[dragonBones.ConstValues.TRANSFORM], displayData.transform, displayData.pivot);
            displayData.pivot.x = NaN;
            displayData.pivot.y = NaN;
            if (DataParser.tempDragonBonesData != null) {
                DataParser.tempDragonBonesData.addDisplayData(displayData);
            }
            return displayData;
        };
        DataParser.parseAnimationData = function (animationObject, frameRate) {
            var animationData = new dragonBones.AnimationData();
            animationData.name = animationObject[dragonBones.ConstValues.A_NAME];
            animationData.frameRate = frameRate;
            animationData.duration = Math.ceil((DataParser.getNumber(animationObject, dragonBones.ConstValues.A_DURATION, 1) || 1) * 1000 / frameRate);
            animationData.playTimes = DataParser.getNumber(animationObject, dragonBones.ConstValues.A_PLAY_TIMES, 1);
            animationData.playTimes = animationData.playTimes != NaN ? animationData.playTimes : 1;
            animationData.fadeTime = DataParser.getNumber(animationObject, dragonBones.ConstValues.A_FADE_IN_TIME, 0) || 0;
            animationData.scale = DataParser.getNumber(animationObject, dragonBones.ConstValues.A_SCALE, 1) || 0;
            animationData.tweenEasing = DataParser.getNumber(animationObject, dragonBones.ConstValues.A_TWEEN_EASING, NaN);
            animationData.autoTween = DataParser.getBoolean(animationObject, dragonBones.ConstValues.A_AUTO_TWEEN, true);
            var frameObjectList = animationObject[dragonBones.ConstValues.FRAME];
            var i = 0;
            var len = 0;
            if (frameObjectList) {
                for (i = 0, len = frameObjectList.length; i < len; i++) {
                    var frameObject = frameObjectList[i];
                    var frame = DataParser.parseTransformFrame(frameObject, frameRate);
                    animationData.addFrame(frame);
                }
            }
            DataParser.parseTimeline(animationObject, animationData);
            var lastFrameDuration = animationData.duration;
            var timelineObjectList = animationObject[dragonBones.ConstValues.BONE];
            if (timelineObjectList) {
                for (i = 0, len = timelineObjectList.length; i < len; i++) {
                    var timelineObject = timelineObjectList[i];
                    if (timelineObject) {
                        var timeline = DataParser.parseTransformTimeline(timelineObject, animationData.duration, frameRate);
                        if (timeline.frameList.length > 0) {
                            lastFrameDuration = Math.min(lastFrameDuration, timeline.frameList[timeline.frameList.length - 1].duration);
                        }
                        animationData.addTimeline(timeline);
                    }
                }
            }
            var slotTimelineObjectList = animationObject[dragonBones.ConstValues.SLOT];
            if (slotTimelineObjectList) {
                for (i = 0, len = slotTimelineObjectList.length; i < len; i++) {
                    var slotTimelineObject = slotTimelineObjectList[i];
                    if (slotTimelineObject) {
                        var slotTimeline = DataParser.parseSlotTimeline(slotTimelineObject, animationData.duration, frameRate);
                        if (slotTimeline.frameList.length > 0) {
                            lastFrameDuration = Math.min(lastFrameDuration, slotTimeline.frameList[slotTimeline.frameList.length - 1].duration);
                            animationData.addSlotTimeline(slotTimeline);
                        }
                    }
                }
            }
            if (animationData.frameList.length > 0) {
                lastFrameDuration = Math.min(lastFrameDuration, animationData.frameList[animationData.frameList.length - 1].duration);
            }
            animationData.lastFrameDuration = lastFrameDuration;
            return animationData;
        };
        DataParser.parseTransformTimeline = function (timelineObject, duration, frameRate) {
            var outputTimeline = new dragonBones.TransformTimeline();
            outputTimeline.name = timelineObject[dragonBones.ConstValues.A_NAME];
            outputTimeline.scale = DataParser.getNumber(timelineObject, dragonBones.ConstValues.A_SCALE, 1) || 0;
            outputTimeline.offset = DataParser.getNumber(timelineObject, dragonBones.ConstValues.A_OFFSET, 0) || 0;
            outputTimeline.originPivot.x = DataParser.getNumber(timelineObject, dragonBones.ConstValues.A_PIVOT_X, 0) || 0;
            outputTimeline.originPivot.y = DataParser.getNumber(timelineObject, dragonBones.ConstValues.A_PIVOT_Y, 0) || 0;
            outputTimeline.duration = duration;
            var frameList = timelineObject[dragonBones.ConstValues.FRAME];
            for (var i = 0, len = frameList.length; i < len; i++) {
                var frameObject = frameList[i];
                var frame = DataParser.parseTransformFrame(frameObject, frameRate);
                outputTimeline.addFrame(frame);
            }
            DataParser.parseTimeline(timelineObject, outputTimeline);
            return outputTimeline;
        };
        DataParser.parseSlotTimeline = function (timelineObject, duration, frameRate) {
            var outputTimeline = new dragonBones.SlotTimeline();
            outputTimeline.name = timelineObject[dragonBones.ConstValues.A_NAME];
            outputTimeline.scale = DataParser.getNumber(timelineObject, dragonBones.ConstValues.A_SCALE, 1) || 0;
            outputTimeline.offset = DataParser.getNumber(timelineObject, dragonBones.ConstValues.A_OFFSET, 0) || 0;
            outputTimeline.duration = duration;
            var frameList = timelineObject[dragonBones.ConstValues.FRAME];
            for (var i = 0, len = frameList.length; i < len; i++) {
                var frameObject = frameList[i];
                var frame = DataParser.parseSlotFrame(frameObject, frameRate);
                outputTimeline.addFrame(frame);
            }
            DataParser.parseTimeline(timelineObject, outputTimeline);
            return outputTimeline;
        };
        DataParser.parseTransformFrame = function (frameObject, frameRate) {
            var outputFrame = new dragonBones.TransformFrame();
            DataParser.parseFrame(frameObject, outputFrame, frameRate);
            outputFrame.visible = !DataParser.getBoolean(frameObject, dragonBones.ConstValues.A_HIDE, false);
            outputFrame.tweenEasing = DataParser.getNumber(frameObject, dragonBones.ConstValues.A_TWEEN_EASING, 10);
            outputFrame.tweenRotate = Math.floor(DataParser.getNumber(frameObject, dragonBones.ConstValues.A_TWEEN_ROTATE, 0) || 0);
            outputFrame.tweenScale = DataParser.getBoolean(frameObject, dragonBones.ConstValues.A_TWEEN_SCALE, true);
            outputFrame.displayIndex = Math.floor(DataParser.getNumber(frameObject, dragonBones.ConstValues.A_DISPLAY_INDEX, 0) || 0);
            DataParser.parseTransform(frameObject[dragonBones.ConstValues.TRANSFORM], outputFrame.transform, outputFrame.pivot);
            if (DataParser.tempDragonBonesData.isGlobal) {
                outputFrame.global.copy(outputFrame.transform);
            }
            outputFrame.scaleOffset.x = DataParser.getNumber(frameObject, dragonBones.ConstValues.A_SCALE_X_OFFSET, 0) || 0;
            outputFrame.scaleOffset.y = DataParser.getNumber(frameObject, dragonBones.ConstValues.A_SCALE_Y_OFFSET, 0) || 0;
            return outputFrame;
        };
        DataParser.parseSlotFrame = function (frameObject, frameRate) {
            var outputFrame = new dragonBones.SlotFrame();
            DataParser.parseFrame(frameObject, outputFrame, frameRate);
            outputFrame.visible = !DataParser.getBoolean(frameObject, dragonBones.ConstValues.A_HIDE, false);
            outputFrame.tweenEasing = DataParser.getNumber(frameObject, dragonBones.ConstValues.A_TWEEN_EASING, 10);
            outputFrame.displayIndex = Math.floor(DataParser.getNumber(frameObject, dragonBones.ConstValues.A_DISPLAY_INDEX, 0) || 0);
            outputFrame.zOrder = DataParser.getNumber(frameObject, dragonBones.ConstValues.A_Z_ORDER, DataParser.tempDragonBonesData.isGlobal ? NaN : 0);
            var colorTransformObject = frameObject[dragonBones.ConstValues.COLOR];
            if (colorTransformObject) {
                outputFrame.color = new dragonBones.ColorTransform();
                DataParser.parseColorTransform(colorTransformObject, outputFrame.color);
            }
            return outputFrame;
        };
        DataParser.parseTimeline = function (timelineObject, outputTimeline) {
            var position = 0;
            var frame;
            var frameList = outputTimeline.frameList;
            for (var i = 0, len = frameList.length; i < len; i++) {
                frame = frameList[i];
                frame.position = position;
                position += frame.duration;
            }
            if (frame) {
                frame.duration = outputTimeline.duration - frame.position;
            }
        };
        DataParser.parseFrame = function (frameObject, outputFrame, frameRate) {
            if (frameRate === void 0) { frameRate = 0; }
            outputFrame.duration = Math.round(((frameObject[dragonBones.ConstValues.A_DURATION]) || 1) * 1000 / frameRate);
            outputFrame.action = frameObject[dragonBones.ConstValues.A_ACTION];
            outputFrame.event = frameObject[dragonBones.ConstValues.A_EVENT];
            outputFrame.sound = frameObject[dragonBones.ConstValues.A_SOUND];
            var curve = frameObject[dragonBones.ConstValues.A_CURVE];
            if (curve != null && curve.length == 4) {
                outputFrame.curve = new dragonBones.CurveData();
                outputFrame.curve.pointList = [new dragonBones.Point(curve[0], curve[1]),
                    new dragonBones.Point(curve[2], curve[3])];
            }
        };
        DataParser.parseTransform = function (transformObject, transform, pivot) {
            if (pivot === void 0) { pivot = null; }
            if (transformObject) {
                if (transform) {
                    transform.x = DataParser.getNumber(transformObject, dragonBones.ConstValues.A_X, 0) || 0;
                    transform.y = DataParser.getNumber(transformObject, dragonBones.ConstValues.A_Y, 0) || 0;
                    transform.skewX = DataParser.getNumber(transformObject, dragonBones.ConstValues.A_SKEW_X, 0) * dragonBones.ConstValues.ANGLE_TO_RADIAN || 0;
                    transform.skewY = DataParser.getNumber(transformObject, dragonBones.ConstValues.A_SKEW_Y, 0) * dragonBones.ConstValues.ANGLE_TO_RADIAN || 0;
                    transform.scaleX = DataParser.getNumber(transformObject, dragonBones.ConstValues.A_SCALE_X, 1) || 0;
                    transform.scaleY = DataParser.getNumber(transformObject, dragonBones.ConstValues.A_SCALE_Y, 1) || 0;
                }
                if (pivot) {
                    pivot.x = DataParser.getNumber(transformObject, dragonBones.ConstValues.A_PIVOT_X, 0) || 0;
                    pivot.y = DataParser.getNumber(transformObject, dragonBones.ConstValues.A_PIVOT_Y, 0) || 0;
                }
            }
        };
        DataParser.parseColorTransform = function (colorTransformObject, colorTransform) {
            if (colorTransform) {
                colorTransform.alphaOffset = DataParser.getNumber(colorTransformObject, dragonBones.ConstValues.A_ALPHA_OFFSET, 0);
                colorTransform.redOffset = DataParser.getNumber(colorTransformObject, dragonBones.ConstValues.A_RED_OFFSET, 0);
                colorTransform.greenOffset = DataParser.getNumber(colorTransformObject, dragonBones.ConstValues.A_GREEN_OFFSET, 0);
                colorTransform.blueOffset = DataParser.getNumber(colorTransformObject, dragonBones.ConstValues.A_BLUE_OFFSET, 0);
                colorTransform.alphaMultiplier = DataParser.getNumber(colorTransformObject, dragonBones.ConstValues.A_ALPHA_MULTIPLIER, 100) * 0.01;
                colorTransform.redMultiplier = DataParser.getNumber(colorTransformObject, dragonBones.ConstValues.A_RED_MULTIPLIER, 100) * 0.01;
                colorTransform.greenMultiplier = DataParser.getNumber(colorTransformObject, dragonBones.ConstValues.A_GREEN_MULTIPLIER, 100) * 0.01;
                colorTransform.blueMultiplier = DataParser.getNumber(colorTransformObject, dragonBones.ConstValues.A_BLUE_MULTIPLIER, 100) * 0.01;
            }
        };
        DataParser.getBoolean = function (data, key, defaultValue) {
            if (data && key in data) {
                switch (String(data[key])) {
                    case "0":
                    case "NaN":
                    case "":
                    case "false":
                    case "null":
                    case "undefined":
                        return false;
                    case "1":
                    case "true":
                    default:
                        return true;
                }
            }
            return defaultValue;
        };
        DataParser.getNumber = function (data, key, defaultValue) {
            if (data && key in data) {
                switch (String(data[key])) {
                    case "NaN":
                    case "":
                    case "false":
                    case "null":
                    case "undefined":
                        return NaN;
                    default:
                        return Number(data[key]);
                }
            }
            return defaultValue;
        };
        return DataParser;
    })();
    dragonBones.DataParser = DataParser;
    egret.registerClass(DataParser,'dragonBones.DataParser');
})(dragonBones || (dragonBones = {}));
var dragonBones;
(function (dragonBones) {
    var Timeline = (function () {
        function Timeline() {
            this.duration = 0;
            this._frameList = [];
            this.duration = 0;
            this.scale = 1;
        }
        var d = __define,c=Timeline,p=c.prototype;
        p.dispose = function () {
            var i = this._frameList.length;
            while (i--) {
                this._frameList[i].dispose();
            }
            this._frameList = null;
        };
        p.addFrame = function (frame) {
            if (!frame) {
                throw new Error();
            }
            if (this._frameList.indexOf(frame) < 0) {
                this._frameList[this._frameList.length] = frame;
            }
            else {
                throw new Error();
            }
        };
        d(p, "frameList"
            ,function () {
                return this._frameList;
            }
        );
        return Timeline;
    })();
    dragonBones.Timeline = Timeline;
    egret.registerClass(Timeline,'dragonBones.Timeline');
})(dragonBones || (dragonBones = {}));
var dragonBones;
(function (dragonBones) {
    var AnimationData = (function (_super) {
        __extends(AnimationData, _super);
        function AnimationData() {
            _super.call(this);
            this.frameRate = 0;
            this.playTimes = 0;
            this.lastFrameDuration = 0;
            this.fadeTime = 0;
            this.playTimes = 0;
            this.autoTween = true;
            this.tweenEasing = NaN;
            this.hideTimelineNameMap = [];
            this.hideSlotTimelineNameMap = [];
            this._timelineList = [];
            this._slotTimelineList = [];
        }
        var d = __define,c=AnimationData,p=c.prototype;
        d(p, "timelineList"
            ,function () {
                return this._timelineList;
            }
        );
        d(p, "slotTimelineList"
            ,function () {
                return this._slotTimelineList;
            }
        );
        p.dispose = function () {
            _super.prototype.dispose.call(this);
            this.hideTimelineNameMap = null;
            var i = 0;
            var len = 0;
            for (i = 0, len = this._timelineList.length; i < len; i++) {
                var timeline = this._timelineList[i];
                timeline.dispose();
            }
            this._timelineList = null;
            for (i = 0, len = this._slotTimelineList.length; i < len; i++) {
                var slotTimeline = this._slotTimelineList[i];
                slotTimeline.dispose();
            }
            this._slotTimelineList = null;
        };
        p.getTimeline = function (timelineName) {
            var i = this._timelineList.length;
            while (i--) {
                if (this._timelineList[i].name == timelineName) {
                    return this._timelineList[i];
                }
            }
            return null;
        };
        p.addTimeline = function (timeline) {
            if (!timeline) {
                throw new Error();
            }
            if (this._timelineList.indexOf(timeline) < 0) {
                this._timelineList[this._timelineList.length] = timeline;
            }
        };
        p.getSlotTimeline = function (timelineName) {
            var i = this._slotTimelineList.length;
            while (i--) {
                if (this._slotTimelineList[i].name == timelineName) {
                    return this._slotTimelineList[i];
                }
            }
            return null;
        };
        p.addSlotTimeline = function (timeline) {
            if (!timeline) {
                throw new Error();
            }
            if (this._slotTimelineList.indexOf(timeline) < 0) {
                this._slotTimelineList[this._slotTimelineList.length] = timeline;
            }
        };
        return AnimationData;
    })(dragonBones.Timeline);
    dragonBones.AnimationData = AnimationData;
    egret.registerClass(AnimationData,'dragonBones.AnimationData');
})(dragonBones || (dragonBones = {}));
var dragonBones;
(function (dragonBones) {
    var ArmatureData = (function () {
        function ArmatureData() {
            this._boneDataList = [];
            this._skinDataList = [];
            this._slotDataList = [];
            this._animationDataList = [];
        }
        var d = __define,c=ArmatureData,p=c.prototype;
        ArmatureData.sortBoneDataHelpArray = function (object1, object2) {
            return object1[0] > object2[0] ? 1 : -1;
        };
        ArmatureData.sortBoneDataHelpArrayDescending = function (object1, object2) {
            return object1[0] > object2[0] ? -1 : 1;
        };
        p.setSkinData = function (skinName) {
            var i = 0;
            var len = this._slotDataList.length;
            for (i = 0; i < len; i++) {
                this._slotDataList[i].dispose();
            }
            var skinData;
            if (!skinName && this._skinDataList.length > 0) {
                skinData = this._skinDataList[0];
            }
            else {
                i = 0,
                    len = this._skinDataList.length;
                for (; i < len; i++) {
                    if (this._skinDataList[i].name == skinName) {
                        skinData = this._skinDataList[i];
                        break;
                    }
                }
            }
            if (skinData) {
                var slotData;
                i = 0, len = skinData.slotDataList.length;
                for (i = 0; i < len; i++) {
                    slotData = this.getSlotData(skinData.slotDataList[i].name);
                    if (slotData) {
                        var j = 0;
                        var jLen = skinData.slotDataList[i].displayDataList.length;
                        for (j = 0; j < jLen; j++) {
                            slotData.addDisplayData(skinData.slotDataList[i].displayDataList[j]);
                        }
                    }
                }
            }
        };
        p.dispose = function () {
            var i = this._boneDataList.length;
            while (i--) {
                this._boneDataList[i].dispose();
            }
            i = this._skinDataList.length;
            while (i--) {
                this._skinDataList[i].dispose();
            }
            i = this._slotDataList.length;
            while (i--) {
                this._slotDataList[i].dispose();
            }
            i = this._animationDataList.length;
            while (i--) {
                this._animationDataList[i].dispose();
            }
            this._boneDataList = null;
            this._slotDataList = null;
            this._skinDataList = null;
            this._animationDataList = null;
        };
        p.getBoneData = function (boneName) {
            var i = this._boneDataList.length;
            while (i--) {
                if (this._boneDataList[i].name == boneName) {
                    return this._boneDataList[i];
                }
            }
            return null;
        };
        p.getSlotData = function (slotName) {
            var i = this._slotDataList.length;
            while (i--) {
                if (this._slotDataList[i].name == slotName) {
                    return this._slotDataList[i];
                }
            }
            return null;
        };
        p.getSkinData = function (skinName) {
            if (!skinName && this._skinDataList.length > 0) {
                return this._skinDataList[0];
            }
            var i = this._skinDataList.length;
            while (i--) {
                if (this._skinDataList[i].name == skinName) {
                    return this._skinDataList[i];
                }
            }
            return null;
        };
        p.getAnimationData = function (animationName) {
            var i = this._animationDataList.length;
            while (i--) {
                if (this._animationDataList[i].name == animationName) {
                    return this._animationDataList[i];
                }
            }
            return null;
        };
        p.addBoneData = function (boneData) {
            if (!boneData) {
                throw new Error();
            }
            if (this._boneDataList.indexOf(boneData) < 0) {
                this._boneDataList[this._boneDataList.length] = boneData;
            }
            else {
                throw new Error();
            }
        };
        p.addSlotData = function (slotData) {
            if (!slotData) {
                throw new Error();
            }
            if (this._slotDataList.indexOf(slotData) < 0) {
                this._slotDataList[this._slotDataList.length] = slotData;
            }
            else {
                throw new Error();
            }
        };
        p.addSkinData = function (skinData) {
            if (!skinData) {
                throw new Error();
            }
            if (this._skinDataList.indexOf(skinData) < 0) {
                this._skinDataList[this._skinDataList.length] = skinData;
            }
            else {
                throw new Error();
            }
        };
        p.addAnimationData = function (animationData) {
            if (!animationData) {
                throw new Error();
            }
            if (this._animationDataList.indexOf(animationData) < 0) {
                this._animationDataList[this._animationDataList.length] = animationData;
            }
        };
        p.sortBoneDataList = function () {
            var i = this._boneDataList.length;
            if (i == 0) {
                return;
            }
            var helpArray = [];
            while (i--) {
                var boneData = this._boneDataList[i];
                var level = 0;
                var parentData = boneData;
                while (parentData) {
                    level++;
                    parentData = this.getBoneData(parentData.parent);
                }
                helpArray[i] = [level, boneData];
            }
            helpArray.sort(ArmatureData.sortBoneDataHelpArray);
            i = helpArray.length;
            while (i--) {
                this._boneDataList[i] = helpArray[i][1];
            }
        };
        d(p, "boneDataList"
            ,function () {
                return this._boneDataList;
            }
        );
        d(p, "slotDataList"
            ,function () {
                return this._slotDataList;
            }
        );
        d(p, "skinDataList"
            ,function () {
                return this._skinDataList;
            }
        );
        d(p, "animationDataList"
            ,function () {
                return this._animationDataList;
            }
        );
        return ArmatureData;
    })();
    dragonBones.ArmatureData = ArmatureData;
    egret.registerClass(ArmatureData,'dragonBones.ArmatureData');
})(dragonBones || (dragonBones = {}));
var dragonBones;
(function (dragonBones) {
    var BoneData = (function () {
        function BoneData() {
            this.length = 0;
            this.global = new dragonBones.DBTransform();
            this.transform = new dragonBones.DBTransform();
            this.inheritRotation = true;
            this.inheritScale = false;
        }
        var d = __define,c=BoneData,p=c.prototype;
        p.dispose = function () {
            this.global = null;
            this.transform = null;
        };
        return BoneData;
    })();
    dragonBones.BoneData = BoneData;
    egret.registerClass(BoneData,'dragonBones.BoneData');
})(dragonBones || (dragonBones = {}));
var dragonBones;
(function (dragonBones) {
    var ColorTransform = (function () {
        function ColorTransform() {
            this.alphaMultiplier = 1;
            this.alphaOffset = 0;
            this.blueMultiplier = 1;
            this.blueOffset = 0;
            this.greenMultiplier = 1;
            this.greenOffset = 0;
            this.redMultiplier = 1;
            this.redOffset = 0;
        }
        var d = __define,c=ColorTransform,p=c.prototype;
        return ColorTransform;
    })();
    dragonBones.ColorTransform = ColorTransform;
    egret.registerClass(ColorTransform,'dragonBones.ColorTransform');
})(dragonBones || (dragonBones = {}));
var dragonBones;
(function (dragonBones) {
    var CurveData = (function () {
        function CurveData() {
            this._dataChanged = false;
            this._pointList = [];
            this.sampling = new Array(CurveData.SamplingTimes);
            for (var i = 0; i < CurveData.SamplingTimes - 1; i++) {
                this.sampling[i] = new dragonBones.Point();
            }
        }
        var d = __define,c=CurveData,p=c.prototype;
        p.getValueByProgress = function (progress) {
            if (this._dataChanged) {
                this.refreshSampling();
            }
            for (var i = 0; i < CurveData.SamplingTimes - 1; i++) {
                var point = this.sampling[i];
                if (point.x >= progress) {
                    if (i == 0) {
                        return point.y * progress / point.x;
                    }
                    else {
                        var prevPoint = this.sampling[i - 1];
                        return prevPoint.y + (point.y - prevPoint.y) * (progress - prevPoint.x) / (point.x - prevPoint.x);
                    }
                }
            }
            return point.y + (1 - point.y) * (progress - point.x) / (1 - point.x);
        };
        p.refreshSampling = function () {
            for (var i = 0; i < CurveData.SamplingTimes - 1; i++) {
                this.bezierCurve(CurveData.SamplingStep * (i + 1), this.sampling[i]);
            }
            this._dataChanged = false;
        };
        p.bezierCurve = function (t, outputPoint) {
            var l_t = 1 - t;
            outputPoint.x = 3 * this.point1.x * t * l_t * l_t + 3 * this.point2.x * t * t * l_t + Math.pow(t, 3);
            outputPoint.y = 3 * this.point1.y * t * l_t * l_t + 3 * this.point2.y * t * t * l_t + Math.pow(t, 3);
        };
        d(p, "pointList"
            ,function () {
                return this._pointList;
            }
            ,function (value) {
                this._pointList = value;
                this._dataChanged = true;
            }
        );
        p.isCurve = function () {
            return this.point1.x != 0 || this.point1.y != 0 || this.point2.x != 1 || this.point2.y != 1;
        };
        d(p, "point1"
            ,function () {
                return this.pointList[0];
            }
        );
        d(p, "point2"
            ,function () {
                return this.pointList[1];
            }
        );
        CurveData.SamplingTimes = 20;
        CurveData.SamplingStep = 0.05;
        return CurveData;
    })();
    dragonBones.CurveData = CurveData;
    egret.registerClass(CurveData,'dragonBones.CurveData');
})(dragonBones || (dragonBones = {}));
var dragonBones;
(function (dragonBones) {
    var DisplayData = (function () {
        function DisplayData() {
            this.transform = new dragonBones.DBTransform();
            this.pivot = new dragonBones.Point();
        }
        var d = __define,c=DisplayData,p=c.prototype;
        p.dispose = function () {
            this.transform = null;
            this.pivot = null;
        };
        DisplayData.ARMATURE = "armature";
        DisplayData.IMAGE = "image";
        return DisplayData;
    })();
    dragonBones.DisplayData = DisplayData;
    egret.registerClass(DisplayData,'dragonBones.DisplayData');
})(dragonBones || (dragonBones = {}));
var dragonBones;
(function (dragonBones) {
    var DragonBonesData = (function () {
        function DragonBonesData() {
            this._armatureDataList = [];
            this._displayDataDictionary = {};
        }
        var d = __define,c=DragonBonesData,p=c.prototype;
        p.dispose = function () {
            for (var i = 0, len = this._armatureDataList.length; i < len; i++) {
                var armatureData = this._armatureDataList[i];
                armatureData.dispose();
            }
            this._armatureDataList = null;
            this.removeAllDisplayData();
            this._displayDataDictionary = null;
        };
        d(p, "armatureDataList"
            ,function () {
                return this._armatureDataList;
            }
        );
        p.getArmatureDataByName = function (armatureName) {
            var i = this._armatureDataList.length;
            while (i--) {
                if (this._armatureDataList[i].name == armatureName) {
                    return this._armatureDataList[i];
                }
            }
            return null;
        };
        p.addArmatureData = function (armatureData) {
            if (!armatureData) {
                throw new Error();
            }
            if (this._armatureDataList.indexOf(armatureData) < 0) {
                this._armatureDataList[this._armatureDataList.length] = armatureData;
            }
            else {
                throw new Error();
            }
        };
        p.removeArmatureData = function (armatureData) {
            var index = this._armatureDataList.indexOf(armatureData);
            if (index >= 0) {
                this._armatureDataList.splice(index, 1);
            }
        };
        p.removeArmatureDataByName = function (armatureName) {
            var i = this._armatureDataList.length;
            while (i--) {
                if (this._armatureDataList[i].name == armatureName) {
                    this._armatureDataList.splice(i, 1);
                }
            }
        };
        p.getDisplayDataByName = function (name) {
            return this._displayDataDictionary[name];
        };
        p.addDisplayData = function (displayData) {
            this._displayDataDictionary[displayData.name] = displayData;
        };
        p.removeDisplayDataByName = function (name) {
            delete this._displayDataDictionary[name];
        };
        p.removeAllDisplayData = function () {
            for (var name in this._displayDataDictionary) {
                delete this._displayDataDictionary[name];
            }
        };
        return DragonBonesData;
    })();
    dragonBones.DragonBonesData = DragonBonesData;
    egret.registerClass(DragonBonesData,'dragonBones.DragonBonesData');
})(dragonBones || (dragonBones = {}));
var dragonBones;
(function (dragonBones) {
    var Frame = (function () {
        function Frame() {
            this.position = 0;
            this.duration = 0;
            this.position = 0;
            this.duration = 0;
        }
        var d = __define,c=Frame,p=c.prototype;
        p.dispose = function () {
        };
        return Frame;
    })();
    dragonBones.Frame = Frame;
    egret.registerClass(Frame,'dragonBones.Frame');
})(dragonBones || (dragonBones = {}));
var dragonBones;
(function (dragonBones) {
    var SkinData = (function () {
        function SkinData() {
            this._slotDataList = [];
        }
        var d = __define,c=SkinData,p=c.prototype;
        p.dispose = function () {
            var i = this._slotDataList.length;
            while (i--) {
                this._slotDataList[i].dispose();
            }
            this._slotDataList = null;
        };
        p.getSlotData = function (slotName) {
            var i = this._slotDataList.length;
            while (i--) {
                if (this._slotDataList[i].name == slotName) {
                    return this._slotDataList[i];
                }
            }
            return null;
        };
        p.addSlotData = function (slotData) {
            if (!slotData) {
                throw new Error();
            }
            if (this._slotDataList.indexOf(slotData) < 0) {
                this._slotDataList[this._slotDataList.length] = slotData;
            }
            else {
                throw new Error();
            }
        };
        d(p, "slotDataList"
            ,function () {
                return this._slotDataList;
            }
        );
        return SkinData;
    })();
    dragonBones.SkinData = SkinData;
    egret.registerClass(SkinData,'dragonBones.SkinData');
})(dragonBones || (dragonBones = {}));
var dragonBones;
(function (dragonBones) {
    var SlotData = (function () {
        function SlotData() {
            this._displayDataList = [];
            this.zOrder = 0;
        }
        var d = __define,c=SlotData,p=c.prototype;
        p.dispose = function () {
            this._displayDataList.length = 0;
        };
        p.addDisplayData = function (displayData) {
            if (!displayData) {
                throw new Error();
            }
            if (this._displayDataList.indexOf(displayData) < 0) {
                this._displayDataList[this._displayDataList.length] = displayData;
            }
            else {
                throw new Error();
            }
        };
        p.getDisplayData = function (displayName) {
            var i = this._displayDataList.length;
            while (i--) {
                if (this._displayDataList[i].name == displayName) {
                    return this._displayDataList[i];
                }
            }
            return null;
        };
        d(p, "displayDataList"
            ,function () {
                return this._displayDataList;
            }
        );
        return SlotData;
    })();
    dragonBones.SlotData = SlotData;
    egret.registerClass(SlotData,'dragonBones.SlotData');
})(dragonBones || (dragonBones = {}));
var dragonBones;
(function (dragonBones) {
    var SlotFrame = (function (_super) {
        __extends(SlotFrame, _super);
        function SlotFrame() {
            _super.call(this);
            this.displayIndex = 0;
            this.tweenEasing = 10;
            this.displayIndex = 0;
            this.visible = true;
            this.zOrder = NaN;
        }
        var d = __define,c=SlotFrame,p=c.prototype;
        p.dispose = function () {
            _super.prototype.dispose.call(this);
            this.color = null;
        };
        return SlotFrame;
    })(dragonBones.Frame);
    dragonBones.SlotFrame = SlotFrame;
    egret.registerClass(SlotFrame,'dragonBones.SlotFrame');
})(dragonBones || (dragonBones = {}));
var dragonBones;
(function (dragonBones) {
    var SlotTimeline = (function (_super) {
        __extends(SlotTimeline, _super);
        function SlotTimeline() {
            _super.call(this);
            this.offset = 0;
        }
        var d = __define,c=SlotTimeline,p=c.prototype;
        p.dispose = function () {
            _super.prototype.dispose.call(this);
        };
        return SlotTimeline;
    })(dragonBones.Timeline);
    dragonBones.SlotTimeline = SlotTimeline;
    egret.registerClass(SlotTimeline,'dragonBones.SlotTimeline');
})(dragonBones || (dragonBones = {}));
var dragonBones;
(function (dragonBones) {
    var TransformFrame = (function (_super) {
        __extends(TransformFrame, _super);
        function TransformFrame() {
            _super.call(this);
            this.tweenRotate = 0;
            this.displayIndex = 0;
            this.tweenEasing = 10;
            this.tweenRotate = 0;
            this.tweenScale = true;
            this.displayIndex = 0;
            this.visible = true;
            this.zOrder = NaN;
            this.global = new dragonBones.DBTransform();
            this.transform = new dragonBones.DBTransform();
            this.pivot = new dragonBones.Point();
            this.scaleOffset = new dragonBones.Point();
        }
        var d = __define,c=TransformFrame,p=c.prototype;
        p.dispose = function () {
            _super.prototype.dispose.call(this);
            this.global = null;
            this.transform = null;
            this.pivot = null;
            this.scaleOffset = null;
            this.color = null;
        };
        return TransformFrame;
    })(dragonBones.Frame);
    dragonBones.TransformFrame = TransformFrame;
    egret.registerClass(TransformFrame,'dragonBones.TransformFrame');
})(dragonBones || (dragonBones = {}));
var dragonBones;
(function (dragonBones) {
    var TransformTimeline = (function (_super) {
        __extends(TransformTimeline, _super);
        function TransformTimeline() {
            _super.call(this);
            this.originTransform = new dragonBones.DBTransform();
            this.originTransform.scaleX = 1;
            this.originTransform.scaleY = 1;
            this.originPivot = new dragonBones.Point();
            this.offset = 0;
        }
        var d = __define,c=TransformTimeline,p=c.prototype;
        p.dispose = function () {
            _super.prototype.dispose.call(this);
            this.originTransform = null;
            this.originPivot = null;
        };
        return TransformTimeline;
    })(dragonBones.Timeline);
    dragonBones.TransformTimeline = TransformTimeline;
    egret.registerClass(TransformTimeline,'dragonBones.TransformTimeline');
})(dragonBones || (dragonBones = {}));
var dragonBones;
(function (dragonBones) {
    var TextureData = (function () {
        function TextureData(region, frame, rotated) {
            this.region = region;
            this.frame = frame;
            this.rotated = rotated;
        }
        var d = __define,c=TextureData,p=c.prototype;
        return TextureData;
    })();
    dragonBones.TextureData = TextureData;
    egret.registerClass(TextureData,'dragonBones.TextureData');
})(dragonBones || (dragonBones = {}));
var dragonBones;
(function (dragonBones) {
    var ColorTransformUtil = (function () {
        function ColorTransformUtil() {
        }
        var d = __define,c=ColorTransformUtil,p=c.prototype;
        ColorTransformUtil.cloneColor = function (color) {
            var c = new dragonBones.ColorTransform();
            c.redMultiplier = color.redMultiplier;
            c.greenMultiplier = color.greenMultiplier;
            c.blueMultiplier = color.blueMultiplier;
            c.alphaMultiplier = color.alphaMultiplier;
            c.redOffset = color.redOffset;
            c.greenOffset = color.greenOffset;
            c.blueOffset = color.blueOffset;
            c.alphaOffset = color.alphaOffset;
            return c;
        };
        ColorTransformUtil.isEqual = function (color1, color2) {
            return color1.alphaOffset == color2.alphaOffset &&
                color1.redOffset == color2.redOffset &&
                color1.greenOffset == color2.greenOffset &&
                color1.blueOffset == color2.blueOffset &&
                color1.alphaMultiplier == color2.alphaMultiplier &&
                color1.redMultiplier == color2.redMultiplier &&
                color1.greenMultiplier == color2.greenMultiplier &&
                color1.blueMultiplier == color2.blueMultiplier;
        };
        ColorTransformUtil.minus = function (color1, color2, outputColor) {
            outputColor.alphaOffset = color1.alphaOffset - color2.alphaOffset;
            outputColor.redOffset = color1.redOffset - color2.redOffset;
            outputColor.greenOffset = color1.greenOffset - color2.greenOffset;
            outputColor.blueOffset = color1.blueOffset - color2.blueOffset;
            outputColor.alphaMultiplier = color1.alphaMultiplier - color2.alphaMultiplier;
            outputColor.redMultiplier = color1.redMultiplier - color2.redMultiplier;
            outputColor.greenMultiplier = color1.greenMultiplier - color2.greenMultiplier;
            outputColor.blueMultiplier = color1.blueMultiplier - color2.blueMultiplier;
        };
        ColorTransformUtil.originalColor = new dragonBones.ColorTransform();
        return ColorTransformUtil;
    })();
    dragonBones.ColorTransformUtil = ColorTransformUtil;
    egret.registerClass(ColorTransformUtil,'dragonBones.ColorTransformUtil');
})(dragonBones || (dragonBones = {}));
var dragonBones;
(function (dragonBones) {
    var ConstValues = (function () {
        function ConstValues() {
        }
        var d = __define,c=ConstValues,p=c.prototype;
        ConstValues.ANGLE_TO_RADIAN = Math.PI / 180;
        ConstValues.RADIAN_TO_ANGLE = 180 / Math.PI;
        ConstValues.DRAGON_BONES = "dragonBones";
        ConstValues.ARMATURE = "armature";
        ConstValues.SKIN = "skin";
        ConstValues.BONE = "bone";
        ConstValues.SLOT = "slot";
        ConstValues.DISPLAY = "display";
        ConstValues.ANIMATION = "animation";
        ConstValues.TIMELINE = "timeline";
        ConstValues.FRAME = "frame";
        ConstValues.TRANSFORM = "transform";
        ConstValues.COLOR_TRANSFORM = "colorTransform";
        ConstValues.COLOR = "color";
        ConstValues.RECTANGLE = "rectangle";
        ConstValues.ELLIPSE = "ellipse";
        ConstValues.TEXTURE_ATLAS = "TextureAtlas";
        ConstValues.SUB_TEXTURE = "SubTexture";
        ConstValues.A_ROTATED = "rotated";
        ConstValues.A_FRAME_X = "frameX";
        ConstValues.A_FRAME_Y = "frameY";
        ConstValues.A_FRAME_WIDTH = "frameWidth";
        ConstValues.A_FRAME_HEIGHT = "frameHeight";
        ConstValues.A_VERSION = "version";
        ConstValues.A_IMAGE_PATH = "imagePath";
        ConstValues.A_FRAME_RATE = "frameRate";
        ConstValues.A_NAME = "name";
        ConstValues.A_IS_GLOBAL = "isGlobal";
        ConstValues.A_PARENT = "parent";
        ConstValues.A_LENGTH = "length";
        ConstValues.A_TYPE = "type";
        ConstValues.A_FADE_IN_TIME = "fadeInTime";
        ConstValues.A_DURATION = "duration";
        ConstValues.A_SCALE = "scale";
        ConstValues.A_OFFSET = "offset";
        ConstValues.A_LOOP = "loop";
        ConstValues.A_PLAY_TIMES = "playTimes";
        ConstValues.A_EVENT = "event";
        ConstValues.A_EVENT_PARAMETERS = "eventParameters";
        ConstValues.A_SOUND = "sound";
        ConstValues.A_ACTION = "action";
        ConstValues.A_HIDE = "hide";
        ConstValues.A_AUTO_TWEEN = "autoTween";
        ConstValues.A_TWEEN_EASING = "tweenEasing";
        ConstValues.A_TWEEN_ROTATE = "tweenRotate";
        ConstValues.A_TWEEN_SCALE = "tweenScale";
        ConstValues.A_DISPLAY_INDEX = "displayIndex";
        ConstValues.A_Z_ORDER = "z";
        ConstValues.A_BLENDMODE = "blendMode";
        ConstValues.A_WIDTH = "width";
        ConstValues.A_HEIGHT = "height";
        ConstValues.A_INHERIT_SCALE = "inheritScale";
        ConstValues.A_INHERIT_ROTATION = "inheritRotation";
        ConstValues.A_X = "x";
        ConstValues.A_Y = "y";
        ConstValues.A_SKEW_X = "skX";
        ConstValues.A_SKEW_Y = "skY";
        ConstValues.A_SCALE_X = "scX";
        ConstValues.A_SCALE_Y = "scY";
        ConstValues.A_PIVOT_X = "pX";
        ConstValues.A_PIVOT_Y = "pY";
        ConstValues.A_ALPHA_OFFSET = "aO";
        ConstValues.A_RED_OFFSET = "rO";
        ConstValues.A_GREEN_OFFSET = "gO";
        ConstValues.A_BLUE_OFFSET = "bO";
        ConstValues.A_ALPHA_MULTIPLIER = "aM";
        ConstValues.A_RED_MULTIPLIER = "rM";
        ConstValues.A_GREEN_MULTIPLIER = "gM";
        ConstValues.A_BLUE_MULTIPLIER = "bM";
        ConstValues.A_CURVE = "curve";
        ConstValues.A_SCALE_X_OFFSET = "scXOffset";
        ConstValues.A_SCALE_Y_OFFSET = "scYOffset";
        ConstValues.A_SCALE_MODE = "scaleMode";
        ConstValues.A_FIXED_ROTATION = "fixedRotation";
        return ConstValues;
    })();
    dragonBones.ConstValues = ConstValues;
    egret.registerClass(ConstValues,'dragonBones.ConstValues');
})(dragonBones || (dragonBones = {}));
var dragonBones;
(function (dragonBones) {
    var DBDataUtil = (function () {
        function DBDataUtil() {
        }
        var d = __define,c=DBDataUtil,p=c.prototype;
        DBDataUtil.transformArmatureData = function (armatureData) {
            var boneDataList = armatureData.boneDataList;
            var i = boneDataList.length;
            while (i--) {
                var boneData = boneDataList[i];
                if (boneData.parent) {
                    var parentBoneData = armatureData.getBoneData(boneData.parent);
                    if (parentBoneData) {
                        boneData.transform.copy(boneData.global);
                        dragonBones.TransformUtil.globalToLocal(boneData.transform, parentBoneData.global);
                    }
                }
            }
        };
        DBDataUtil.transformArmatureDataAnimations = function (armatureData) {
            var animationDataList = armatureData.animationDataList;
            var i = animationDataList.length;
            while (i--) {
                DBDataUtil.transformAnimationData(animationDataList[i], armatureData, false);
            }
        };
        DBDataUtil.transformRelativeAnimationData = function (animationData, armatureData) {
        };
        DBDataUtil.transformAnimationData = function (animationData, armatureData, isGlobalData) {
            if (!isGlobalData) {
                DBDataUtil.transformRelativeAnimationData(animationData, armatureData);
                return;
            }
            var skinData = armatureData.getSkinData(null);
            var boneDataList = armatureData.boneDataList;
            var slotDataList;
            if (skinData) {
                slotDataList = skinData.slotDataList;
            }
            for (var i = 0; i < boneDataList.length; i++) {
                var boneData = boneDataList[i];
                var timeline = animationData.getTimeline(boneData.name);
                var slotTimeline = animationData.getSlotTimeline(boneData.name);
                if (!timeline && !slotTimeline) {
                    continue;
                }
                var slotData = null;
                if (slotDataList) {
                    for (var j = 0, jLen = slotDataList.length; j < jLen; j++) {
                        slotData = slotDataList[j];
                        if (slotData.parent == boneData.name) {
                            break;
                        }
                    }
                }
                var frameList = timeline.frameList;
                if (slotTimeline) {
                    var slotFrameList = slotTimeline.frameList;
                }
                var originTransform = null;
                var originPivot = null;
                var prevFrame = null;
                var frameListLength = frameList.length;
                for (var j = 0; j < frameListLength; j++) {
                    var frame = (frameList[j]);
                    DBDataUtil.setFrameTransform(animationData, armatureData, boneData, frame);
                    frame.transform.x -= boneData.transform.x;
                    frame.transform.y -= boneData.transform.y;
                    frame.transform.skewX -= boneData.transform.skewX;
                    frame.transform.skewY -= boneData.transform.skewY;
                    frame.transform.scaleX /= boneData.transform.scaleX;
                    frame.transform.scaleY /= boneData.transform.scaleY;
                    if (prevFrame) {
                        var dLX = frame.transform.skewX - prevFrame.transform.skewX;
                        if (prevFrame.tweenRotate) {
                            if (prevFrame.tweenRotate > 0) {
                                if (dLX < 0) {
                                    frame.transform.skewX += Math.PI * 2;
                                    frame.transform.skewY += Math.PI * 2;
                                }
                                if (prevFrame.tweenRotate > 1) {
                                    frame.transform.skewX += Math.PI * 2 * (prevFrame.tweenRotate - 1);
                                    frame.transform.skewY += Math.PI * 2 * (prevFrame.tweenRotate - 1);
                                }
                            }
                            else {
                                if (dLX > 0) {
                                    frame.transform.skewX -= Math.PI * 2;
                                    frame.transform.skewY -= Math.PI * 2;
                                }
                                if (prevFrame.tweenRotate < 1) {
                                    frame.transform.skewX += Math.PI * 2 * (prevFrame.tweenRotate + 1);
                                    frame.transform.skewY += Math.PI * 2 * (prevFrame.tweenRotate + 1);
                                }
                            }
                        }
                        else {
                            frame.transform.skewX = prevFrame.transform.skewX + dragonBones.TransformUtil.formatRadian(frame.transform.skewX - prevFrame.transform.skewX);
                            frame.transform.skewY = prevFrame.transform.skewY + dragonBones.TransformUtil.formatRadian(frame.transform.skewY - prevFrame.transform.skewY);
                        }
                    }
                    prevFrame = frame;
                }
                if (slotTimeline && slotFrameList) {
                    frameListLength = slotFrameList.length;
                    for (var j = 0; j < frameListLength; j++) {
                        var slotFrame = slotFrameList[j];
                        if (!slotTimeline.transformed) {
                            if (slotData) {
                                slotFrame.zOrder -= slotData.zOrder;
                            }
                        }
                    }
                    slotTimeline.transformed = true;
                }
                timeline.transformed = true;
            }
        };
        DBDataUtil.setFrameTransform = function (animationData, armatureData, boneData, frame) {
            frame.transform.copy(frame.global);
            var parentData = armatureData.getBoneData(boneData.parent);
            if (parentData) {
                var parentTimeline = animationData.getTimeline(parentData.name);
                if (parentTimeline) {
                    var parentTimelineList = [];
                    var parentDataList = [];
                    while (parentTimeline) {
                        parentTimelineList.push(parentTimeline);
                        parentDataList.push(parentData);
                        parentData = armatureData.getBoneData(parentData.parent);
                        if (parentData) {
                            parentTimeline = animationData.getTimeline(parentData.name);
                        }
                        else {
                            parentTimeline = null;
                        }
                    }
                    var i = parentTimelineList.length;
                    var globalTransform;
                    var globalTransformMatrix = new dragonBones.Matrix();
                    var currentTransform = new dragonBones.DBTransform();
                    var currentTransformMatrix = new dragonBones.Matrix();
                    while (i--) {
                        parentTimeline = parentTimelineList[i];
                        parentData = parentDataList[i];
                        DBDataUtil.getTimelineTransform(parentTimeline, frame.position, currentTransform, !globalTransform);
                        if (!globalTransform) {
                            globalTransform = new dragonBones.DBTransform();
                            globalTransform.copy(currentTransform);
                        }
                        else {
                            currentTransform.x += parentTimeline.originTransform.x + parentData.transform.x;
                            currentTransform.y += parentTimeline.originTransform.y + parentData.transform.y;
                            currentTransform.skewX += parentTimeline.originTransform.skewX + parentData.transform.skewX;
                            currentTransform.skewY += parentTimeline.originTransform.skewY + parentData.transform.skewY;
                            currentTransform.scaleX *= parentTimeline.originTransform.scaleX * parentData.transform.scaleX;
                            currentTransform.scaleY *= parentTimeline.originTransform.scaleY * parentData.transform.scaleY;
                            dragonBones.TransformUtil.transformToMatrix(currentTransform, currentTransformMatrix, true);
                            currentTransformMatrix.concat(globalTransformMatrix);
                            dragonBones.TransformUtil.matrixToTransform(currentTransformMatrix, globalTransform, currentTransform.scaleX * globalTransform.scaleX >= 0, currentTransform.scaleY * globalTransform.scaleY >= 0);
                        }
                        dragonBones.TransformUtil.transformToMatrix(globalTransform, globalTransformMatrix, true);
                    }
                    dragonBones.TransformUtil.globalToLocal(frame.transform, globalTransform);
                }
            }
        };
        DBDataUtil.getTimelineTransform = function (timeline, position, retult, isGlobal) {
            var frameList = timeline.frameList;
            var i = frameList.length;
            while (i--) {
                var currentFrame = (frameList[i]);
                if (currentFrame.position <= position && currentFrame.position + currentFrame.duration > position) {
                    if (i == frameList.length - 1 || position == currentFrame.position) {
                        retult.copy(isGlobal ? currentFrame.global : currentFrame.transform);
                    }
                    else {
                        var tweenEasing = currentFrame.tweenEasing;
                        var progress = (position - currentFrame.position) / currentFrame.duration;
                        if (tweenEasing && tweenEasing != 10) {
                            progress = dragonBones.MathUtil.getEaseValue(progress, tweenEasing);
                        }
                        var nextFrame = frameList[i + 1];
                        var currentTransform = isGlobal ? currentFrame.global : currentFrame.transform;
                        var nextTransform = isGlobal ? nextFrame.global : nextFrame.transform;
                        retult.x = currentTransform.x + (nextTransform.x - currentTransform.x) * progress;
                        retult.y = currentTransform.y + (nextTransform.y - currentTransform.y) * progress;
                        retult.skewX = dragonBones.TransformUtil.formatRadian(currentTransform.skewX + (nextTransform.skewX - currentTransform.skewX) * progress);
                        retult.skewY = dragonBones.TransformUtil.formatRadian(currentTransform.skewY + (nextTransform.skewY - currentTransform.skewY) * progress);
                        retult.scaleX = currentTransform.scaleX + (nextTransform.scaleX - currentTransform.scaleX) * progress;
                        retult.scaleY = currentTransform.scaleY + (nextTransform.scaleY - currentTransform.scaleY) * progress;
                    }
                    break;
                }
            }
        };
        DBDataUtil.addHideTimeline = function (animationData, armatureData, addHideSlot) {
            if (addHideSlot === void 0) { addHideSlot = false; }
            var boneDataList = armatureData.boneDataList;
            var slotDataList = armatureData.slotDataList;
            var i = boneDataList.length;
            while (i--) {
                var boneData = boneDataList[i];
                var boneName = boneData.name;
                if (!animationData.getTimeline(boneName)) {
                    if (animationData.hideTimelineNameMap.indexOf(boneName) < 0) {
                        animationData.hideTimelineNameMap.push(boneName);
                    }
                }
            }
            if (addHideSlot) {
                i = slotDataList.length;
                var slotData;
                var slotName;
                while (i--) {
                    slotData = slotDataList[i];
                    slotName = slotData.name;
                    if (!animationData.getSlotTimeline(slotName)) {
                        if (animationData.hideSlotTimelineNameMap.indexOf(slotName) < 0) {
                            animationData.hideSlotTimelineNameMap.push(slotName);
                        }
                    }
                }
            }
        };
        return DBDataUtil;
    })();
    dragonBones.DBDataUtil = DBDataUtil;
    egret.registerClass(DBDataUtil,'dragonBones.DBDataUtil');
})(dragonBones || (dragonBones = {}));
var dragonBones;
(function (dragonBones) {
    var MathUtil = (function () {
        function MathUtil() {
        }
        var d = __define,c=MathUtil,p=c.prototype;
        MathUtil.getEaseValue = function (value, easing) {
            var valueEase = 1;
            if (easing > 1) {
                valueEase = 0.5 * (1 - MathUtil.cos(value * Math.PI));
                easing -= 1;
            }
            else if (easing > 0) {
                valueEase = 1 - Math.pow(1 - value, 2);
            }
            else if (easing < 0) {
                easing *= -1;
                valueEase = Math.pow(value, 2);
            }
            return (valueEase - value) * easing + value;
        };
        MathUtil.isNumber = function (value) {
            return typeof (value) === "number" && !isNaN(value);
        };
        MathUtil.sin = function (value) {
            value *= MathUtil.RADIAN_TO_ANGLE;
            var valueFloor = Math.floor(value);
            var valueCeil = valueFloor + 1;
            var resultFloor = MathUtil.sinInt(valueFloor);
            var resultCeil = MathUtil.sinInt(valueCeil);
            return (value - valueFloor) * resultCeil + (valueCeil - value) * resultFloor;
        };
        MathUtil.sinInt = function (value) {
            value = value % 360;
            if (value < 0) {
                value += 360;
            }
            if (value < 90) {
                return db_sin_map[value];
            }
            if (value < 180) {
                return db_sin_map[180 - value];
            }
            if (value < 270) {
                return -db_sin_map[value - 180];
            }
            return -db_sin_map[360 - value];
        };
        MathUtil.cos = function (value) {
            return MathUtil.sin(Math.PI / 2 - value);
        };
        MathUtil.ANGLE_TO_RADIAN = Math.PI / 180;
        MathUtil.RADIAN_TO_ANGLE = 180 / Math.PI;
        return MathUtil;
    })();
    dragonBones.MathUtil = MathUtil;
    egret.registerClass(MathUtil,'dragonBones.MathUtil');
})(dragonBones || (dragonBones = {}));
var db_sin_map = {};
for (var dbMathIndex = 0; dbMathIndex <= 90; dbMathIndex++) {
    db_sin_map[dbMathIndex] = Math.sin(dbMathIndex * dragonBones.MathUtil.ANGLE_TO_RADIAN);
}
var dragonBones;
(function (dragonBones) {
    var TransformUtil = (function () {
        function TransformUtil() {
        }
        var d = __define,c=TransformUtil,p=c.prototype;
        TransformUtil.globalToLocal = function (transform, parent) {
            TransformUtil.transformToMatrix(transform, TransformUtil._helpTransformMatrix, true);
            TransformUtil.transformToMatrix(parent, TransformUtil._helpParentTransformMatrix, true);
            TransformUtil._helpParentTransformMatrix.invert();
            TransformUtil._helpTransformMatrix.concat(TransformUtil._helpParentTransformMatrix);
            TransformUtil.matrixToTransform(TransformUtil._helpTransformMatrix, transform, transform.scaleX * parent.scaleX >= 0, transform.scaleY * parent.scaleY >= 0);
        };
        TransformUtil.transformToMatrix = function (transform, matrix, keepScale) {
            if (keepScale === void 0) { keepScale = false; }
            if (keepScale) {
                matrix.a = transform.scaleX * dragonBones.MathUtil.cos(transform.skewY);
                matrix.b = transform.scaleX * dragonBones.MathUtil.sin(transform.skewY);
                matrix.c = -transform.scaleY * dragonBones.MathUtil.sin(transform.skewX);
                matrix.d = transform.scaleY * dragonBones.MathUtil.cos(transform.skewX);
                matrix.tx = transform.x;
                matrix.ty = transform.y;
            }
            else {
                matrix.a = dragonBones.MathUtil.cos(transform.skewY);
                matrix.b = dragonBones.MathUtil.sin(transform.skewY);
                matrix.c = -dragonBones.MathUtil.sin(transform.skewX);
                matrix.d = dragonBones.MathUtil.cos(transform.skewX);
                matrix.tx = transform.x;
                matrix.ty = transform.y;
            }
        };
        TransformUtil.matrixToTransform = function (matrix, transform, scaleXF, scaleYF) {
            transform.x = matrix.tx;
            transform.y = matrix.ty;
            transform.scaleX = Math.sqrt(matrix.a * matrix.a + matrix.b * matrix.b) * (scaleXF ? 1 : -1);
            transform.scaleY = Math.sqrt(matrix.d * matrix.d + matrix.c * matrix.c) * (scaleYF ? 1 : -1);
            var skewXArray = [];
            skewXArray[0] = Math.acos(matrix.d / transform.scaleY);
            skewXArray[1] = -skewXArray[0];
            skewXArray[2] = Math.asin(-matrix.c / transform.scaleY);
            skewXArray[3] = skewXArray[2] >= 0 ? Math.PI - skewXArray[2] : skewXArray[2] - Math.PI;
            if (Number(skewXArray[0]).toFixed(4) == Number(skewXArray[2]).toFixed(4) || Number(skewXArray[0]).toFixed(4) == Number(skewXArray[3]).toFixed(4)) {
                transform.skewX = skewXArray[0];
            }
            else {
                transform.skewX = skewXArray[1];
            }
            var skewYArray = [];
            skewYArray[0] = Math.acos(matrix.a / transform.scaleX);
            skewYArray[1] = -skewYArray[0];
            skewYArray[2] = Math.asin(matrix.b / transform.scaleX);
            skewYArray[3] = skewYArray[2] >= 0 ? Math.PI - skewYArray[2] : skewYArray[2] - Math.PI;
            if (Number(skewYArray[0]).toFixed(4) == Number(skewYArray[2]).toFixed(4) || Number(skewYArray[0]).toFixed(4) == Number(skewYArray[3]).toFixed(4)) {
                transform.skewY = skewYArray[0];
            }
            else {
                transform.skewY = skewYArray[1];
            }
        };
        TransformUtil.formatRadian = function (radian) {
            if (radian > Math.PI) {
                radian -= TransformUtil.DOUBLE_PI;
            }
            if (radian < -Math.PI) {
                radian += TransformUtil.DOUBLE_PI;
            }
            return radian;
        };
        TransformUtil.normalizeRotation = function (rotation) {
            rotation = (rotation + Math.PI) % (2 * Math.PI);
            rotation = rotation > 0 ? rotation : 2 * Math.PI + rotation;
            return rotation - Math.PI;
        };
        TransformUtil.HALF_PI = Math.PI * 0.5;
        TransformUtil.DOUBLE_PI = Math.PI * 2;
        TransformUtil._helpTransformMatrix = new dragonBones.Matrix();
        TransformUtil._helpParentTransformMatrix = new dragonBones.Matrix();
        return TransformUtil;
    })();
    dragonBones.TransformUtil = TransformUtil;
    egret.registerClass(TransformUtil,'dragonBones.TransformUtil');
})(dragonBones || (dragonBones = {}));
var dragonBones;
(function (dragonBones) {
    var FastAnimation = (function () {
        function FastAnimation(armature) {
            this.animationState = new dragonBones.FastAnimationState();
            this._armature = armature;
            this.animationState._armature = armature;
            this.animationList = [];
            this._animationDataObj = {};
            this._isPlaying = false;
            this._timeScale = 1;
        }
        var d = __define,c=FastAnimation,p=c.prototype;
        p.dispose = function () {
            if (!this._armature) {
                return;
            }
            this._armature = null;
            this._animationDataList = null;
            this.animationList = null;
            this.animationState = null;
        };
        p.gotoAndPlay = function (animationName, fadeInTime, duration, playTimes) {
            if (fadeInTime === void 0) { fadeInTime = -1; }
            if (duration === void 0) { duration = -1; }
            if (playTimes === void 0) { playTimes = NaN; }
            if (!this._animationDataList) {
                return null;
            }
            var animationData = this._animationDataObj[animationName];
            if (!animationData) {
                return null;
            }
            this._isPlaying = true;
            fadeInTime = fadeInTime < 0 ? (animationData.fadeTime < 0 ? 0.3 : animationData.fadeTime) : fadeInTime;
            var durationScale;
            if (duration < 0) {
                durationScale = animationData.scale < 0 ? 1 : animationData.scale;
            }
            else {
                durationScale = duration * 1000 / animationData.duration;
            }
            playTimes = isNaN(playTimes) ? animationData.playTimes : playTimes;
            this.animationState._fadeIn(animationData, playTimes, 1 / durationScale, fadeInTime);
            if (this._armature.enableCache && this.animationCacheManager) {
                this.animationState.animationCache = this.animationCacheManager.getAnimationCache(animationName);
            }
            var i = this._armature.slotHasChildArmatureList.length;
            while (i--) {
                var slot = this._armature.slotHasChildArmatureList[i];
                var childArmature = slot.childArmature;
                if (childArmature) {
                    childArmature.getAnimation().gotoAndPlay(animationName);
                }
            }
            return this.animationState;
        };
        p.gotoAndStop = function (animationName, time, normalizedTime, fadeInTime, duration) {
            if (normalizedTime === void 0) { normalizedTime = -1; }
            if (fadeInTime === void 0) { fadeInTime = 0; }
            if (duration === void 0) { duration = -1; }
            if (this.animationState.name != animationName) {
                this.gotoAndPlay(animationName, fadeInTime, duration);
            }
            if (normalizedTime >= 0) {
                this.animationState.setCurrentTime(this.animationState.totalTime * normalizedTime);
            }
            else {
                this.animationState.setCurrentTime(time);
            }
            this.animationState.stop();
            return this.animationState;
        };
        p.play = function () {
            if (!this._animationDataList) {
                return;
            }
            if (!this.animationState.name) {
                this.gotoAndPlay(this._animationDataList[0].name);
            }
            else if (!this._isPlaying) {
                this._isPlaying = true;
            }
            else {
                this.gotoAndPlay(this.animationState.name);
            }
        };
        p.stop = function () {
            this._isPlaying = false;
        };
        p.advanceTime = function (passedTime) {
            if (!this._isPlaying) {
                return;
            }
            this.animationState._advanceTime(passedTime * this._timeScale);
        };
        p.hasAnimation = function (animationName) {
            return this._animationDataObj[animationName] != null;
        };
        d(p, "timeScale"
            ,function () {
                return this._timeScale;
            }
            ,function (value) {
                if (isNaN(value) || value < 0) {
                    value = 1;
                }
                this._timeScale = value;
            }
        );
        d(p, "animationDataList"
            ,function () {
                return this._animationDataList;
            }
            ,function (value) {
                this._animationDataList = value;
                this.animationList.length = 0;
                var length = this._animationDataList.length;
                for (var i = 0; i < length; i++) {
                    var animationData = this._animationDataList[i];
                    this.animationList.push(animationData.name);
                    this._animationDataObj[animationData.name] = animationData;
                }
            }
        );
        d(p, "movementList"
            ,function () {
                return this.animationList;
            }
        );
        d(p, "movementID"
            ,function () {
                return this.lastAnimationName;
            }
        );
        p.isPlaying = function () {
            return this._isPlaying && !this.isComplete;
        };
        d(p, "isComplete"
            ,function () {
                return this.animationState.isComplete;
            }
        );
        d(p, "lastAnimationState"
            ,function () {
                return this.animationState;
            }
        );
        d(p, "lastAnimationName"
            ,function () {
                return this.animationState ? this.animationState.name : null;
            }
        );
        return FastAnimation;
    })();
    dragonBones.FastAnimation = FastAnimation;
    egret.registerClass(FastAnimation,'dragonBones.FastAnimation');
})(dragonBones || (dragonBones = {}));
var dragonBones;
(function (dragonBones) {
    var FastAnimationState = (function () {
        function FastAnimationState() {
            this._boneTimelineStateList = [];
            this._slotTimelineStateList = [];
            this._currentFrameIndex = 0;
            this._currentFramePosition = 0;
            this._currentFrameDuration = 0;
            this._currentPlayTimes = 0;
            this._totalTime = 0;
            this._currentTime = 0;
            this._lastTime = 0;
            this._playTimes = 0;
            this._fading = false;
        }
        var d = __define,c=FastAnimationState,p=c.prototype;
        p.dispose = function () {
            this._resetTimelineStateList();
            this._armature = null;
        };
        p.play = function () {
            this._isPlaying = true;
            return this;
        };
        p.stop = function () {
            this._isPlaying = false;
            return this;
        };
        p.setCurrentTime = function (value) {
            if (value < 0 || isNaN(value)) {
                value = 0;
            }
            this._time = value;
            this._currentTime = this._time * 1000;
            return this;
        };
        p._resetTimelineStateList = function () {
            var i = this._boneTimelineStateList.length;
            while (i--) {
                dragonBones.FastBoneTimelineState.returnObject(this._boneTimelineStateList[i]);
            }
            this._boneTimelineStateList.length = 0;
            i = this._slotTimelineStateList.length;
            while (i--) {
                dragonBones.FastSlotTimelineState.returnObject(this._slotTimelineStateList[i]);
            }
            this._slotTimelineStateList.length = 0;
            this.name = null;
        };
        p._fadeIn = function (aniData, playTimes, timeScale, fadeTotalTime) {
            this.animationData = aniData;
            this.name = this.animationData.name;
            this._totalTime = this.animationData.duration;
            this.autoTween = aniData.autoTween;
            this.setTimeScale(timeScale);
            this.setPlayTimes(playTimes);
            this._isComplete = false;
            this._currentFrameIndex = -1;
            this._currentPlayTimes = -1;
            if (Math.round(this._totalTime * this.animationData.frameRate * 0.001) < 2) {
                this._currentTime = this._totalTime;
            }
            else {
                this._currentTime = -1;
            }
            this._fadeTotalTime = fadeTotalTime * this._timeScale;
            this._fading = this._fadeTotalTime > 0;
            this._isPlaying = true;
            if (this._armature.enableCache && this.animationCache && this._fading && this._boneTimelineStateList) {
                this.updateTransformTimeline(this.progress);
            }
            this._time = 0;
            this._progress = 0;
            this._updateTimelineStateList();
            this.hideBones();
            return;
        };
        p._updateTimelineStateList = function () {
            this._resetTimelineStateList();
            var timelineName;
            var length = this.animationData.timelineList.length;
            for (var i = 0; i < length; i++) {
                var boneTimeline = this.animationData.timelineList[i];
                timelineName = boneTimeline.name;
                var bone = this._armature.getBone(timelineName);
                if (bone) {
                    var boneTimelineState = dragonBones.FastBoneTimelineState.borrowObject();
                    boneTimelineState.fadeIn(bone, this, boneTimeline);
                    this._boneTimelineStateList.push(boneTimelineState);
                }
            }
            var length1 = this.animationData.slotTimelineList.length;
            for (var i1 = 0; i1 < length1; i1++) {
                var slotTimeline = this.animationData.slotTimelineList[i1];
                timelineName = slotTimeline.name;
                var slot = this._armature.getSlot(timelineName);
                if (slot && slot.displayList.length > 0) {
                    var slotTimelineState = dragonBones.FastSlotTimelineState.borrowObject();
                    slotTimelineState.fadeIn(slot, this, slotTimeline);
                    this._slotTimelineStateList.push(slotTimelineState);
                }
            }
        };
        p._advanceTime = function (passedTime) {
            passedTime *= this._timeScale;
            if (this._fading) {
                this._time += passedTime;
                this._progress = this._time / this._fadeTotalTime;
                if (this._progress >= 1) {
                    this._progress = 0;
                    this._time = 0;
                    this._fading = false;
                }
            }
            if (this._fading) {
                var length = this._boneTimelineStateList.length;
                for (var i = 0; i < length; i++) {
                    var timeline = this._boneTimelineStateList[i];
                    timeline.updateFade(this.progress);
                }
                var length1 = this._slotTimelineStateList.length;
                for (var i1 = 0; i1 < length1; i1++) {
                    var slotTimeline = this._slotTimelineStateList[i1];
                    slotTimeline.updateFade(this.progress);
                }
            }
            else {
                this.advanceTimelinesTime(passedTime);
            }
        };
        p.advanceTimelinesTime = function (passedTime) {
            if (this._isPlaying) {
                this._time += passedTime;
            }
            var startFlg = false;
            var loopCompleteFlg = false;
            var completeFlg = false;
            var isThisComplete = false;
            var currentPlayTimes = 0;
            var currentTime = this._time * 1000;
            if (this._playTimes == 0 ||
                currentTime < this._playTimes * this._totalTime) {
                isThisComplete = false;
                this._progress = currentTime / this._totalTime;
                currentPlayTimes = Math.ceil(this.progress) || 1;
                this._progress -= Math.floor(this.progress);
                currentTime %= this._totalTime;
            }
            else {
                currentPlayTimes = this._playTimes;
                currentTime = this._totalTime;
                isThisComplete = true;
                this._progress = 1;
            }
            this._isComplete = isThisComplete;
            if (this.isUseCache()) {
                this.animationCache.update(this.progress);
            }
            else {
                this.updateTransformTimeline(this.progress);
            }
            if (this._currentTime != currentTime) {
                if (this._currentPlayTimes != currentPlayTimes) {
                    if (this._currentPlayTimes > 0 && currentPlayTimes > 1) {
                        loopCompleteFlg = true;
                    }
                    this._currentPlayTimes = currentPlayTimes;
                }
                if (this._currentTime < 0) {
                    startFlg = true;
                }
                if (this._isComplete) {
                    completeFlg = true;
                }
                this._lastTime = this._currentTime;
                this._currentTime = currentTime;
                this.updateMainTimeline(isThisComplete);
            }
            var event;
            if (startFlg) {
                if (this._armature.hasEventListener(dragonBones.AnimationEvent.START)) {
                    event = new dragonBones.AnimationEvent(dragonBones.AnimationEvent.START);
                    event.animationState = this;
                    this._armature._addEvent(event);
                }
            }
            if (completeFlg) {
                if (this._armature.hasEventListener(dragonBones.AnimationEvent.COMPLETE)) {
                    event = new dragonBones.AnimationEvent(dragonBones.AnimationEvent.COMPLETE);
                    event.animationState = this;
                    this._armature._addEvent(event);
                }
            }
            else if (loopCompleteFlg) {
                if (this._armature.hasEventListener(dragonBones.AnimationEvent.LOOP_COMPLETE)) {
                    event = new dragonBones.AnimationEvent(dragonBones.AnimationEvent.LOOP_COMPLETE);
                    event.animationState = this;
                    this._armature._addEvent(event);
                }
            }
        };
        p.updateTransformTimeline = function (progress) {
            var i = this._boneTimelineStateList.length;
            var boneTimeline;
            var slotTimeline;
            if (this._isComplete) {
                while (i--) {
                    boneTimeline = this._boneTimelineStateList[i];
                    boneTimeline.update(progress);
                    this._isComplete = boneTimeline._isComplete && this._isComplete;
                }
                i = this._slotTimelineStateList.length;
                while (i--) {
                    slotTimeline = this._slotTimelineStateList[i];
                    slotTimeline.update(progress);
                    this._isComplete = slotTimeline._isComplete && this._isComplete;
                }
            }
            else {
                while (i--) {
                    boneTimeline = this._boneTimelineStateList[i];
                    boneTimeline.update(progress);
                }
                i = this._slotTimelineStateList.length;
                while (i--) {
                    slotTimeline = this._slotTimelineStateList[i];
                    slotTimeline.update(progress);
                }
            }
        };
        p.updateMainTimeline = function (isThisComplete) {
            var frameList = this.animationData.frameList;
            if (frameList.length > 0) {
                var prevFrame;
                var currentFrame;
                for (var i = 0, l = this.animationData.frameList.length; i < l; ++i) {
                    if (this._currentFrameIndex < 0) {
                        this._currentFrameIndex = 0;
                    }
                    else if (this._currentTime < this._currentFramePosition || this._currentTime >= this._currentFramePosition + this._currentFrameDuration || this._currentTime < this._lastTime) {
                        this._lastTime = this._currentTime;
                        this._currentFrameIndex++;
                        if (this._currentFrameIndex >= frameList.length) {
                            if (isThisComplete) {
                                this._currentFrameIndex--;
                                break;
                            }
                            else {
                                this._currentFrameIndex = 0;
                            }
                        }
                    }
                    else {
                        break;
                    }
                    currentFrame = frameList[this._currentFrameIndex];
                    if (prevFrame) {
                        this._armature.arriveAtFrame(prevFrame, this);
                    }
                    this._currentFrameDuration = currentFrame.duration;
                    this._currentFramePosition = currentFrame.position;
                    prevFrame = currentFrame;
                }
                if (currentFrame) {
                    this._armature.arriveAtFrame(currentFrame, this);
                }
            }
        };
        p.setTimeScale = function (value) {
            if (isNaN(value) || value == Infinity) {
                value = 1;
            }
            this._timeScale = value;
            return this;
        };
        p.setPlayTimes = function (value) {
            if (value === void 0) { value = 0; }
            if (Math.round(this._totalTime * 0.001 * this.animationData.frameRate) < 2) {
                this._playTimes = 1;
            }
            else {
                this._playTimes = value;
            }
            return this;
        };
        d(p, "playTimes"
            ,function () {
                return this._playTimes;
            }
        );
        d(p, "currentPlayTimes"
            ,function () {
                return this._currentPlayTimes < 0 ? 0 : this._currentPlayTimes;
            }
        );
        d(p, "isComplete"
            ,function () {
                return this._isComplete;
            }
        );
        d(p, "isPlaying"
            ,function () {
                return (this._isPlaying && !this._isComplete);
            }
        );
        d(p, "totalTime"
            ,function () {
                return this._totalTime * 0.001;
            }
        );
        d(p, "currentTime"
            ,function () {
                return this._currentTime < 0 ? 0 : this._currentTime * 0.001;
            }
        );
        p.isUseCache = function () {
            return this._armature.enableCache && this.animationCache && !this._fading;
        };
        p.hideBones = function () {
            var length = this.animationData.hideTimelineNameMap.length;
            for (var i = 0; i < length; i++) {
                var timelineName = this.animationData.hideTimelineNameMap[i];
                var bone = this._armature.getBone(timelineName);
                if (bone) {
                    bone._hideSlots();
                }
            }
            var slotTimelineName;
            for (i = 0, length = this.animationData.hideSlotTimelineNameMap.length; i < length; i++) {
                slotTimelineName = this.animationData.hideSlotTimelineNameMap[i];
                var slot = this._armature.getSlot(slotTimelineName);
                if (slot) {
                    slot._resetToOrigin();
                }
            }
        };
        d(p, "progress"
            ,function () {
                return this._progress;
            }
        );
        return FastAnimationState;
    })();
    dragonBones.FastAnimationState = FastAnimationState;
    egret.registerClass(FastAnimationState,'dragonBones.FastAnimationState',["dragonBones.IAnimationState"]);
})(dragonBones || (dragonBones = {}));
var dragonBones;
(function (dragonBones) {
    var FastBoneTimelineState = (function () {
        function FastBoneTimelineState() {
            this._totalTime = 0;
            this._currentTime = 0;
            this._lastTime = 0;
            this._currentFrameIndex = 0;
            this._currentFramePosition = 0;
            this._currentFrameDuration = 0;
            this._updateMode = 0;
            this._transform = new dragonBones.DBTransform();
            this._durationTransform = new dragonBones.DBTransform();
            this._transformToFadein = new dragonBones.DBTransform();
            this._pivot = new dragonBones.Point();
            this._durationPivot = new dragonBones.Point();
        }
        var d = __define,c=FastBoneTimelineState,p=c.prototype;
        FastBoneTimelineState.borrowObject = function () {
            if (FastBoneTimelineState._pool.length == 0) {
                return new FastBoneTimelineState();
            }
            return FastBoneTimelineState._pool.pop();
        };
        FastBoneTimelineState.returnObject = function (timeline) {
            if (FastBoneTimelineState._pool.indexOf(timeline) < 0) {
                FastBoneTimelineState._pool[FastBoneTimelineState._pool.length] = timeline;
            }
            timeline.clear();
        };
        FastBoneTimelineState.clear = function () {
            var i = FastBoneTimelineState._pool.length;
            while (i--) {
                FastBoneTimelineState._pool[i].clear();
            }
            FastBoneTimelineState._pool.length = 0;
        };
        p.clear = function () {
            if (this._bone) {
                this._bone._timelineState = null;
                this._bone = null;
            }
            this._animationState = null;
            this._timelineData = null;
            this._originPivot = null;
        };
        p.fadeIn = function (bone, animationState, timelineData) {
            this._bone = bone;
            this._animationState = animationState;
            this._timelineData = timelineData;
            this.name = timelineData.name;
            this._totalTime = this._timelineData.duration;
            this._isComplete = false;
            this._tweenTransform = false;
            this._currentFrameIndex = -1;
            this._currentTime = -1;
            this._tweenEasing = NaN;
            this._durationPivot.x = 0;
            this._durationPivot.y = 0;
            this._pivot.x = 0;
            this._pivot.y = 0;
            this._originPivot = this._timelineData.originPivot;
            switch (this._timelineData.frameList.length) {
                case 0:
                    this._updateMode = 0;
                    break;
                case 1:
                    this._updateMode = 1;
                    break;
                default:
                    this._updateMode = -1;
                    break;
            }
            if (animationState._fadeTotalTime > 0) {
                var pivotToFadein;
                if (this._bone._timelineState) {
                    this._transformToFadein.copy(this._bone._timelineState._transform);
                }
                else {
                    this._transformToFadein = new dragonBones.DBTransform();
                }
                var firstFrame = (this._timelineData.frameList[0]);
                this._durationTransform.copy(firstFrame.transform);
                this._durationTransform.minus(this._transformToFadein);
            }
            this._bone._timelineState = this;
        };
        p.updateFade = function (progress) {
            this._transform.x = this._transformToFadein.x + this._durationTransform.x * progress;
            this._transform.y = this._transformToFadein.y + this._durationTransform.y * progress;
            this._transform.scaleX = this._transformToFadein.scaleX * (1 + (this._durationTransform.scaleX - 1) * progress);
            this._transform.scaleY = this._transformToFadein.scaleX * (1 + (this._durationTransform.scaleY - 1) * progress);
            this._transform.rotation = this._transformToFadein.rotation + this._durationTransform.rotation * progress;
            this._bone.invalidUpdate();
        };
        p.update = function (progress) {
            if (this._updateMode == 1) {
                this._updateMode = 0;
                this.updateSingleFrame();
            }
            else if (this._updateMode == -1) {
                this.updateMultipleFrame(progress);
            }
        };
        p.updateSingleFrame = function () {
            var currentFrame = (this._timelineData.frameList[0]);
            this._bone.arriveAtFrame(currentFrame, this._animationState);
            this._isComplete = true;
            this._tweenEasing = NaN;
            this._tweenTransform = false;
            this._pivot.x = this._originPivot.x + currentFrame.pivot.x;
            this._pivot.y = this._originPivot.y + currentFrame.pivot.y;
            this._transform.copy(currentFrame.transform);
            this._bone.invalidUpdate();
        };
        p.updateMultipleFrame = function (progress) {
            var currentPlayTimes = 0;
            progress /= this._timelineData.scale;
            progress += this._timelineData.offset;
            var currentTime = this._totalTime * progress;
            var playTimes = this._animationState.playTimes;
            if (playTimes == 0) {
                this._isComplete = false;
                currentPlayTimes = Math.ceil(Math.abs(currentTime) / this._totalTime) || 1;
                currentTime -= Math.floor(currentTime / this._totalTime) * this._totalTime;
                if (currentTime < 0) {
                    currentTime += this._totalTime;
                }
            }
            else {
                var totalTimes = playTimes * this._totalTime;
                if (currentTime >= totalTimes) {
                    currentTime = totalTimes;
                    this._isComplete = true;
                }
                else if (currentTime <= -totalTimes) {
                    currentTime = -totalTimes;
                    this._isComplete = true;
                }
                else {
                    this._isComplete = false;
                }
                if (currentTime < 0) {
                    currentTime += totalTimes;
                }
                currentPlayTimes = Math.ceil(currentTime / this._totalTime) || 1;
                if (this._isComplete) {
                    currentTime = this._totalTime;
                }
                else {
                    currentTime -= Math.floor(currentTime / this._totalTime) * this._totalTime;
                }
            }
            if (this._currentTime != currentTime) {
                this._lastTime = this._currentTime;
                this._currentTime = currentTime;
                var frameList = this._timelineData.frameList;
                var prevFrame;
                var currentFrame;
                for (var i = 0, l = this._timelineData.frameList.length; i < l; ++i) {
                    if (this._currentFrameIndex < 0) {
                        this._currentFrameIndex = 0;
                    }
                    else if (this._currentTime < this._currentFramePosition || this._currentTime >= this._currentFramePosition + this._currentFrameDuration || this._currentTime < this._lastTime) {
                        this._currentFrameIndex++;
                        this._lastTime = this._currentTime;
                        if (this._currentFrameIndex >= frameList.length) {
                            if (this._isComplete) {
                                this._currentFrameIndex--;
                                break;
                            }
                            else {
                                this._currentFrameIndex = 0;
                            }
                        }
                    }
                    else {
                        break;
                    }
                    currentFrame = (frameList[this._currentFrameIndex]);
                    if (prevFrame) {
                        this._bone.arriveAtFrame(prevFrame, this._animationState);
                    }
                    this._currentFrameDuration = currentFrame.duration;
                    this._currentFramePosition = currentFrame.position;
                    prevFrame = currentFrame;
                }
                if (currentFrame) {
                    this._bone.arriveAtFrame(currentFrame, this._animationState);
                    this.updateToNextFrame(currentPlayTimes);
                }
                if (this._tweenTransform) {
                    this.updateTween();
                }
            }
        };
        p.updateToNextFrame = function (currentPlayTimes) {
            if (currentPlayTimes === void 0) { currentPlayTimes = 0; }
            var nextFrameIndex = this._currentFrameIndex + 1;
            if (nextFrameIndex >= this._timelineData.frameList.length) {
                nextFrameIndex = 0;
            }
            var currentFrame = (this._timelineData.frameList[this._currentFrameIndex]);
            var nextFrame = (this._timelineData.frameList[nextFrameIndex]);
            var tweenEnabled = false;
            if (nextFrameIndex == 0 && (this._animationState.playTimes &&
                this._animationState.currentPlayTimes >= this._animationState.playTimes &&
                ((this._currentFramePosition + this._currentFrameDuration) / this._totalTime + currentPlayTimes - this._timelineData.offset) * this._timelineData.scale > 0.999999)) {
                this._tweenEasing = NaN;
                tweenEnabled = false;
            }
            else if (this._animationState.autoTween) {
                this._tweenEasing = this._animationState.animationData.tweenEasing;
                if (isNaN(this._tweenEasing)) {
                    this._tweenEasing = currentFrame.tweenEasing;
                    this._tweenCurve = currentFrame.curve;
                    if (isNaN(this._tweenEasing) && this._tweenCurve == null) {
                        tweenEnabled = false;
                    }
                    else {
                        if (this._tweenEasing == 10) {
                            this._tweenEasing = 0;
                        }
                        tweenEnabled = true;
                    }
                }
                else {
                    tweenEnabled = true;
                }
            }
            else {
                this._tweenEasing = currentFrame.tweenEasing;
                this._tweenCurve = currentFrame.curve;
                if ((isNaN(this._tweenEasing) || this._tweenEasing == 10) && this._tweenCurve == null) {
                    this._tweenEasing = NaN;
                    tweenEnabled = false;
                }
                else {
                    tweenEnabled = true;
                }
            }
            if (tweenEnabled) {
                this._durationTransform.x = nextFrame.transform.x - currentFrame.transform.x;
                this._durationTransform.y = nextFrame.transform.y - currentFrame.transform.y;
                this._durationTransform.skewX = nextFrame.transform.skewX - currentFrame.transform.skewX;
                this._durationTransform.skewY = nextFrame.transform.skewY - currentFrame.transform.skewY;
                this._durationTransform.scaleX = nextFrame.transform.scaleX - currentFrame.transform.scaleX + nextFrame.scaleOffset.x;
                this._durationTransform.scaleY = nextFrame.transform.scaleY - currentFrame.transform.scaleY + nextFrame.scaleOffset.y;
                this._durationPivot.x = nextFrame.pivot.x - currentFrame.pivot.x;
                this._durationPivot.y = nextFrame.pivot.y - currentFrame.pivot.y;
                this._durationTransform.normalizeRotation();
                if (nextFrameIndex == 0) {
                    this._durationTransform.skewX = dragonBones.TransformUtil.formatRadian(this._durationTransform.skewX);
                    this._durationTransform.skewY = dragonBones.TransformUtil.formatRadian(this._durationTransform.skewY);
                }
                if (this._durationTransform.x ||
                    this._durationTransform.y ||
                    this._durationTransform.skewX ||
                    this._durationTransform.skewY ||
                    this._durationTransform.scaleX != 1 ||
                    this._durationTransform.scaleY != 1 ||
                    this._durationPivot.x ||
                    this._durationPivot.y) {
                    this._tweenTransform = true;
                }
                else {
                    this._tweenTransform = false;
                }
            }
            else {
                this._tweenTransform = false;
            }
            if (!this._tweenTransform) {
                this._transform.copy(currentFrame.transform);
                this._pivot.x = this._originPivot.x + currentFrame.pivot.x;
                this._pivot.y = this._originPivot.y + currentFrame.pivot.y;
                this._bone.invalidUpdate();
            }
        };
        p.updateTween = function () {
            var progress = (this._currentTime - this._currentFramePosition) / this._currentFrameDuration;
            if (this._tweenCurve) {
                progress = this._tweenCurve.getValueByProgress(progress);
            }
            else if (this._tweenEasing) {
                progress = dragonBones.MathUtil.getEaseValue(progress, this._tweenEasing);
            }
            var currentFrame = (this._timelineData.frameList[this._currentFrameIndex]);
            var currentTransform = currentFrame.transform;
            var currentPivot = currentFrame.pivot;
            this._transform.x = currentTransform.x + this._durationTransform.x * progress;
            this._transform.y = currentTransform.y + this._durationTransform.y * progress;
            this._transform.skewX = currentTransform.skewX + this._durationTransform.skewX * progress;
            this._transform.skewY = currentTransform.skewY + this._durationTransform.skewY * progress;
            this._transform.scaleX = currentTransform.scaleX + this._durationTransform.scaleX * progress;
            this._transform.scaleY = currentTransform.scaleY + this._durationTransform.scaleY * progress;
            this._pivot.x = currentPivot.x + this._durationPivot.x * progress;
            this._pivot.y = currentPivot.y + this._durationPivot.y * progress;
            this._bone.invalidUpdate();
        };
        FastBoneTimelineState._pool = [];
        return FastBoneTimelineState;
    })();
    dragonBones.FastBoneTimelineState = FastBoneTimelineState;
    egret.registerClass(FastBoneTimelineState,'dragonBones.FastBoneTimelineState');
})(dragonBones || (dragonBones = {}));
var dragonBones;
(function (dragonBones) {
    var FastSlotTimelineState = (function () {
        function FastSlotTimelineState() {
            this._totalTime = 0;
            this._currentTime = 0;
            this._currentFrameIndex = 0;
            this._currentFramePosition = 0;
            this._currentFrameDuration = 0;
            this._updateMode = 0;
            this._durationColor = new dragonBones.ColorTransform();
        }
        var d = __define,c=FastSlotTimelineState,p=c.prototype;
        FastSlotTimelineState.borrowObject = function () {
            if (FastSlotTimelineState._pool.length == 0) {
                return new FastSlotTimelineState();
            }
            return FastSlotTimelineState._pool.pop();
        };
        FastSlotTimelineState.returnObject = function (timeline) {
            if (FastSlotTimelineState._pool.indexOf(timeline) < 0) {
                FastSlotTimelineState._pool[FastSlotTimelineState._pool.length] = timeline;
            }
            timeline.clear();
        };
        FastSlotTimelineState.clear = function () {
            var i = FastSlotTimelineState._pool.length;
            while (i--) {
                FastSlotTimelineState._pool[i].clear();
            }
            FastSlotTimelineState._pool.length = 0;
        };
        p.clear = function () {
            this._slot = null;
            this._armature = null;
            this._animation = null;
            this._animationState = null;
            this._timelineData = null;
        };
        p.fadeIn = function (slot, animationState, timelineData) {
            this._slot = slot;
            this._armature = this._slot.armature;
            this._animation = this._armature.animation;
            this._animationState = animationState;
            this._timelineData = timelineData;
            this.name = timelineData.name;
            this._totalTime = this._timelineData.duration;
            this._isComplete = false;
            this._blendEnabled = false;
            this._tweenColor = false;
            this._currentFrameIndex = -1;
            this._currentTime = -1;
            this._tweenEasing = NaN;
            this._weight = 1;
            switch (this._timelineData.frameList.length) {
                case 0:
                    this._updateMode = 0;
                    break;
                case 1:
                    this._updateMode = 1;
                    break;
                default:
                    this._updateMode = -1;
                    break;
            }
        };
        p.updateFade = function (progress) {
        };
        p.update = function (progress) {
            if (this._updateMode == -1) {
                this.updateMultipleFrame(progress);
            }
            else if (this._updateMode == 1) {
                this._updateMode = 0;
                this.updateSingleFrame();
            }
        };
        p.updateMultipleFrame = function (progress) {
            var currentPlayTimes = 0;
            progress /= this._timelineData.scale;
            progress += this._timelineData.offset;
            var currentTime = this._totalTime * progress;
            var playTimes = this._animationState.playTimes;
            if (playTimes == 0) {
                this._isComplete = false;
                currentPlayTimes = Math.ceil(Math.abs(currentTime) / this._totalTime) || 1;
                currentTime -= Math.floor(currentTime / this._totalTime) * this._totalTime;
                if (currentTime < 0) {
                    currentTime += this._totalTime;
                }
            }
            else {
                var totalTimes = playTimes * this._totalTime;
                if (currentTime >= totalTimes) {
                    currentTime = totalTimes;
                    this._isComplete = true;
                }
                else if (currentTime <= -totalTimes) {
                    currentTime = -totalTimes;
                    this._isComplete = true;
                }
                else {
                    this._isComplete = false;
                }
                if (currentTime < 0) {
                    currentTime += totalTimes;
                }
                currentPlayTimes = Math.ceil(currentTime / this._totalTime) || 1;
                if (this._isComplete) {
                    currentTime = this._totalTime;
                }
                else {
                    currentTime -= Math.floor(currentTime / this._totalTime) * this._totalTime;
                }
            }
            if (this._currentTime != currentTime) {
                this._currentTime = currentTime;
                var frameList = this._timelineData.frameList;
                var prevFrame;
                var currentFrame;
                for (var i = 0, l = this._timelineData.frameList.length; i < l; ++i) {
                    if (this._currentFrameIndex < 0) {
                        this._currentFrameIndex = 0;
                    }
                    else if (this._currentTime < this._currentFramePosition || this._currentTime >= this._currentFramePosition + this._currentFrameDuration) {
                        this._currentFrameIndex++;
                        if (this._currentFrameIndex >= frameList.length) {
                            if (this._isComplete) {
                                this._currentFrameIndex--;
                                break;
                            }
                            else {
                                this._currentFrameIndex = 0;
                            }
                        }
                    }
                    else {
                        break;
                    }
                    currentFrame = (frameList[this._currentFrameIndex]);
                    if (prevFrame) {
                        this._slot._arriveAtFrame(prevFrame, this._animationState);
                    }
                    this._currentFrameDuration = currentFrame.duration;
                    this._currentFramePosition = currentFrame.position;
                    prevFrame = currentFrame;
                }
                if (currentFrame) {
                    this._slot._arriveAtFrame(currentFrame, this._animationState);
                    this._blendEnabled = currentFrame.displayIndex >= 0;
                    if (this._blendEnabled) {
                        this.updateToNextFrame(currentPlayTimes);
                    }
                    else {
                        this._tweenEasing = NaN;
                        this._tweenColor = false;
                    }
                }
                if (this._blendEnabled) {
                    this.updateTween();
                }
            }
        };
        p.updateToNextFrame = function (currentPlayTimes) {
            if (currentPlayTimes === void 0) { currentPlayTimes = 0; }
            var nextFrameIndex = this._currentFrameIndex + 1;
            if (nextFrameIndex >= this._timelineData.frameList.length) {
                nextFrameIndex = 0;
            }
            var currentFrame = (this._timelineData.frameList[this._currentFrameIndex]);
            var nextFrame = (this._timelineData.frameList[nextFrameIndex]);
            var tweenEnabled = false;
            if (nextFrameIndex == 0 &&
                (this._animationState.playTimes &&
                    this._animationState.currentPlayTimes >= this._animationState.playTimes &&
                    ((this._currentFramePosition + this._currentFrameDuration) / this._totalTime + currentPlayTimes - this._timelineData.offset) * this._timelineData.scale > 0.999999)) {
                this._tweenEasing = NaN;
                tweenEnabled = false;
            }
            else if (currentFrame.displayIndex < 0 || nextFrame.displayIndex < 0) {
                this._tweenEasing = NaN;
                tweenEnabled = false;
            }
            else if (this._animationState.autoTween) {
                this._tweenEasing = this._animationState.animationData.tweenEasing;
                if (isNaN(this._tweenEasing)) {
                    this._tweenEasing = currentFrame.tweenEasing;
                    this._tweenCurve = currentFrame.curve;
                    if (isNaN(this._tweenEasing) && this._tweenCurve == null) {
                        tweenEnabled = false;
                    }
                    else {
                        if (this._tweenEasing == 10) {
                            this._tweenEasing = 0;
                        }
                        tweenEnabled = true;
                    }
                }
                else {
                    tweenEnabled = true;
                }
            }
            else {
                this._tweenEasing = currentFrame.tweenEasing;
                this._tweenCurve = currentFrame.curve;
                if ((isNaN(this._tweenEasing) || this._tweenEasing == 10) && this._tweenCurve == null) {
                    this._tweenEasing = NaN;
                    tweenEnabled = false;
                }
                else {
                    tweenEnabled = true;
                }
            }
            if (tweenEnabled) {
                if (currentFrame.color || nextFrame.color) {
                    dragonBones.ColorTransformUtil.minus(nextFrame.color || dragonBones.ColorTransformUtil.originalColor, currentFrame.color || dragonBones.ColorTransformUtil.originalColor, this._durationColor);
                    this._tweenColor = this._durationColor.alphaOffset != 0 ||
                        this._durationColor.redOffset != 0 ||
                        this._durationColor.greenOffset != 0 ||
                        this._durationColor.blueOffset != 0 ||
                        this._durationColor.alphaMultiplier != 0 ||
                        this._durationColor.redMultiplier != 0 ||
                        this._durationColor.greenMultiplier != 0 ||
                        this._durationColor.blueMultiplier != 0;
                }
                else {
                    this._tweenColor = false;
                }
            }
            else {
                this._tweenColor = false;
            }
            if (!this._tweenColor) {
                var targetColor;
                var colorChanged;
                if (currentFrame.color) {
                    targetColor = currentFrame.color;
                    colorChanged = true;
                }
                else {
                    targetColor = dragonBones.ColorTransformUtil.originalColor;
                    colorChanged = false;
                }
                if ((this._slot._isColorChanged || colorChanged)) {
                    if (!dragonBones.ColorTransformUtil.isEqual(this._slot._colorTransform, targetColor)) {
                        this._slot._updateDisplayColor(targetColor.alphaOffset, targetColor.redOffset, targetColor.greenOffset, targetColor.blueOffset, targetColor.alphaMultiplier, targetColor.redMultiplier, targetColor.greenMultiplier, targetColor.blueMultiplier, colorChanged);
                    }
                }
            }
        };
        p.updateTween = function () {
            var currentFrame = (this._timelineData.frameList[this._currentFrameIndex]);
            if (this._tweenColor) {
                var progress = (this._currentTime - this._currentFramePosition) / this._currentFrameDuration;
                if (this._tweenCurve != null) {
                    progress = this._tweenCurve.getValueByProgress(progress);
                }
                else if (this._tweenEasing) {
                    progress = dragonBones.MathUtil.getEaseValue(progress, this._tweenEasing);
                }
                if (currentFrame.color) {
                    this._slot._updateDisplayColor(currentFrame.color.alphaOffset + this._durationColor.alphaOffset * progress, currentFrame.color.redOffset + this._durationColor.redOffset * progress, currentFrame.color.greenOffset + this._durationColor.greenOffset * progress, currentFrame.color.blueOffset + this._durationColor.blueOffset * progress, currentFrame.color.alphaMultiplier + this._durationColor.alphaMultiplier * progress, currentFrame.color.redMultiplier + this._durationColor.redMultiplier * progress, currentFrame.color.greenMultiplier + this._durationColor.greenMultiplier * progress, currentFrame.color.blueMultiplier + this._durationColor.blueMultiplier * progress, true);
                }
                else {
                    this._slot._updateDisplayColor(this._durationColor.alphaOffset * progress, this._durationColor.redOffset * progress, this._durationColor.greenOffset * progress, this._durationColor.blueOffset * progress, this._durationColor.alphaMultiplier * progress + 1, this._durationColor.redMultiplier * progress + 1, this._durationColor.greenMultiplier * progress + 1, this._durationColor.blueMultiplier * progress + 1, true);
                }
            }
        };
        p.updateSingleFrame = function () {
            var currentFrame = (this._timelineData.frameList[0]);
            this._slot._arriveAtFrame(currentFrame, this._animationState);
            this._isComplete = true;
            this._tweenEasing = NaN;
            this._tweenColor = false;
            this._blendEnabled = currentFrame.displayIndex >= 0;
            if (this._blendEnabled) {
                var targetColor;
                var colorChanged;
                if (currentFrame.color) {
                    targetColor = currentFrame.color;
                    colorChanged = true;
                }
                else {
                    targetColor = dragonBones.ColorTransformUtil.originalColor;
                    colorChanged = false;
                }
                if ((this._slot._isColorChanged || colorChanged)) {
                    if (!dragonBones.ColorTransformUtil.isEqual(this._slot._colorTransform, targetColor)) {
                        this._slot._updateDisplayColor(targetColor.alphaOffset, targetColor.redOffset, targetColor.greenOffset, targetColor.blueOffset, targetColor.alphaMultiplier, targetColor.redMultiplier, targetColor.greenMultiplier, targetColor.blueMultiplier, colorChanged);
                    }
                }
            }
        };
        FastSlotTimelineState.HALF_PI = Math.PI * 0.5;
        FastSlotTimelineState.DOUBLE_PI = Math.PI * 2;
        FastSlotTimelineState._pool = [];
        return FastSlotTimelineState;
    })();
    dragonBones.FastSlotTimelineState = FastSlotTimelineState;
    egret.registerClass(FastSlotTimelineState,'dragonBones.FastSlotTimelineState');
})(dragonBones || (dragonBones = {}));

(function(){
    var DataParser = dragonBones.DataParser;
    var TextureData = dragonBones.TextureData;

    var TextureAtlas = function(texture, textureAtlasRawData, scale){
        this._textureDatas = {};
        this.scale = scale||1;
        this.texture = texture;
        this.name = textureAtlasRawData.name;

        this.parseData(textureAtlasRawData);
    };

    TextureAtlas.rotatedDic = {};

    TextureAtlas.prototype = {
        constructor:TextureAtlas,
        getTexture:function(fullName){
            var data = this._textureDatas[fullName];
            if(data){
                data.texture = this.texture;
                if(data.rotated)
                {
                    TextureAtlas.rotatedDic[fullName] = 1;
                }
            }
            return data;
        },
        dispose:function(){
            this.texture = null;
            this._textureDatas = {};
        },
        getRegion:function(subTextureName){
            var textureData = this._textureDatas[subTextureName];
            if(textureData && textureData instanceof TextureData){
                return textureData.region;
            }
            return null;
        },
        getFrame:function(subTextureName){
            var textureData = this._textureDatas[subTextureName];
            if(textureData && textureData instanceof TextureData)
            {
                return textureData.frame;
            }
            return null;
        },
        parseData:function(textureAtlasRawData){
            this._textureDatas = DataParser.parseTextureAtlasData(textureAtlasRawData, this.scale);
        }
    };
    dragonBones.TextureAtlas = TextureAtlas;
})();
/**
 * PixiSlot
 */
(function(superClass) {
    var RAD2DEG = 180/Math.PI;
    var TextureAtlas = dragonBones.TextureAtlas;
    var PixiSlot = function() {
        superClass.call(this, this);
        this._display = null;
    };

    __extends(PixiSlot, superClass, {
        dispose: function() {
            if (this._displayList) {
                var length = this._displayList.length;
                for (var i = 0; i < length; i++) {
                    var content = this._displayList[i];
					if(typeof content.dispose === "function") content.dispose();
					/*if (content instanceof Armature) {
                        content.dispose();
                    }*/
                }
            }

            superClass.prototype.dispose();
            this._display = null;
        },
        _updateDisplay: function(value) {
            this._display = value;
        },
        _getDisplayIndex: function() {
            if (this._display && this._display.parent) {
                return this._display.parent.getChildIndex(this._display);
            }
            return -1;
        },
        _addDisplayToContainer: function(container, index) {
            if (this._display && container) {
                if(index){
                    container.addChildAt(this._display, index);
                }
                else{
                    container.addChild(this._display);
                }
            }
        },
        _removeDisplayFromContainer: function() {
            if (this._display && this._display.parent) {
                this._display.parent.removeChild(this._display);
            }
        },
        _updateTransform: function() {
            if (this._display) {
                this._display.position.x = this._global.x;
                this._display.position.y = this._global.y;
                this._display.scale.x = this._global.scaleX;
                this._display.scale.y = this._global.scaleY;
                this._display.rotation = this._global.skewX;
            }
        },
        _updateDisplayVisible: function(value) {
            if (this._display && this._parent) {
                this._display.visible = this._parent._visible && this._visible && value;
            }
        },
        _updateDisplayColor: function(aOffset, rOffset, gOffset, bOffset, aMultiplier, rMultiplier, gMultiplier, bMultiplier, colorChange) {
            superClass.prototype._updateDisplayColor.call(this, aOffset, rOffset, gOffset, bOffset, aMultiplier, rMultiplier, gMultiplier, bMultiplier, colorChange);
            if (this._display) {
                this._display.alpha = aMultiplier;
            }
        },
        _updateDisplayBlendMode: function(value) {
            // if (this._display && value) {
            //     this._display.blendMode = value;
            // }
        },
        _calculateRelativeParentTransform: function() {
            this._global.scaleX = this._origin.scaleX * this._offset.scaleX;
            this._global.scaleY = this._origin.scaleY * this._offset.scaleY;
            this._global.skewX = this._origin.skewX + this._offset.skewX;
            this._global.skewY = this._origin.skewY + this._offset.skewY;
            this._global.x = this._origin.x + this._offset.x + this._parent._tweenPivot.x;
            this._global.y = this._origin.y + this._offset.y + this._parent._tweenPivot.y;

            if (this._displayDataList &&
                this._currentDisplayIndex >= 0 &&
                this._displayDataList[this._currentDisplayIndex] &&
                TextureAtlas.rotatedDic[this._displayDataList[this._currentDisplayIndex].name] == 1) {
                this._global.skewX -= 1.57;
                this._global.skewY -= 1.57;
            }
        }
    });

    dragonBones.PixiSlot = PixiSlot;
})(dragonBones.Slot);

/**
 * PixiFactory
 */
(function(superClass){
    var Armature = dragonBones.Armature;
    var PixiSlot = dragonBones.PixiSlot;

    var PixiFactory = function(){
        superClass.call(this, this);
    };
    __extends(PixiFactory, superClass, {
        _generateArmature:function(){
            var armature = new Armature(new PIXI.Container);
            return armature;
        },
        _generateSlot:function(){
            var slot = new PixiSlot();
            return slot;
        },
        _generateDisplay:function(textureAtlas, fullName, pivotX, pivotY){
            var texture = textureAtlas.getTexture(fullName);
            var region = texture.region;

            this._textureCache = this._textureCache || {};
            if(!this._textureCache[textureAtlas.texture.src]){
                this._textureCache[textureAtlas.texture.src] = new PIXI.BaseTexture(textureAtlas.texture);
            }
            var pixiTexture = new PIXI.Texture(
                this._textureCache[textureAtlas.texture.src],
                new PIXI.Rectangle(region.x, region.y, region.width, region.height)
            );
            var bitmap = new PIXI.Sprite(pixiTexture);

            if(isNaN(pivotX)||isNaN(pivotY))
            {
                var subTextureFrame = textureAtlas.getFrame(fullName);
                if(subTextureFrame != null)
                {
                    pivotX = subTextureFrame.width/2;
                    pivotY = subTextureFrame.height/2;
                }
                else
                {
                    pivotX = texture.region.width/2;
                    pivotY = texture.region.height/2;
                }
            }
            bitmap.pivot.x = pivotX;
            bitmap.pivot.y = pivotY;
            return bitmap;
        }
    });

    dragonBones.PixiFactory = PixiFactory;
}(dragonBones.BaseFactory));
/**
 * @desc initial EHDIJS Library
 */

//GET OR INITIALIZE EHDI
var EHDI = EHDI || Object.create(null);

//PIXI.JS ALIASES
EHDI.aka = {
	AutoDetectRenderer: PIXI.autoDetectRenderer,
	CanvasRenderer: PIXI.CanvasRenderer, 
	GLRenderer: PIXI.WebGLRenderer,
	AbstractFilter: PIXI.Filter,
	Container: PIXI.Container,
	Sprite: PIXI.Sprite,
	AnimatedSprite : PIXI.extras.AnimatedSprite,
	PixiText: PIXI.Text,
	PixiFilters: PIXI.filters,
	TextureCache: PIXI.utils.TextureCache,
	Loader: PIXI.loader,
	Graphics : PIXI.Graphics,
	Ticker: PIXI.ticker,
	Rectangle: PIXI.Rectangle,
	TilingSprite: PIXI.extras.TilingSprite
}

//EHDI Library config
EHDI.config = {
    isTransition : false
}

//PIXI DisplayObject Mod - pivot and scale
Object.defineProperties(PIXI.DisplayObject.prototype, 
{   
	'pivotX': {        
        get: function () { 
            return this.pivot.x; 
        },        
        set: function (v) { 
            this.pivot.x = v; 
        }    
	},    
	'pivotY': {        
		get: function () { 
			return this.pivot.y; 
		},        
		set: function (v) { 
			this.pivot.y = v; 
		}    
	},
	'scaleX': {        
        get: function () { 
            return this.scale.x; 
        },        
        set: function (v) { 
            this.scale.x = v; 
        }    
	},    
	'scaleY': {        
		get: function () { 
			return this.scale.y; 
		},        
		set: function (v) { 
			this.scale.y = v; 
		}    
	}
});
var EHDI = EHDI || Object.create(null);

EHDI.displays = EHDI.displays || Object.create(null);
/**
 * @param (PIXI.Texture) pointerUp
 * @param (PIXI.Texture) pointerDown/undefined
 * @param (PIXI.Texture) mouseOver/undefined
 * @param (PIXI.Texture) disabledTexture/undefined
 * @param (Float) scaleOnPointerDown/undefined
 * @desc Set onclick function by elem.setOnclickFunction();
 */
EHDI.displays.Button = function (pointerUp) {
    this.pointerUp = pointerUp;
    this.pointerDown = arguments.length <= 1 || arguments[1] === undefined ? undefined : arguments[1];
    this.mouseOver = arguments.length <= 2 || arguments[2] === undefined ? undefined : arguments[2];
    this.disabledTexture = arguments.length <= 3 || arguments[3] === undefined ? undefined : arguments[3];
    this.scaleOnPointerDown = arguments.length <= 4 || arguments[4] === undefined ? undefined : arguments[4];
    var disabled = false;
    this.onClickFunction = null;
    this.baseScale = {x : 1, y: 1};
    PIXI.Sprite.call(this, pointerUp);
    this.sfx = null;
    this.isDisabled = function() {
        //console.log(disabled);
        return disabled;
    }

    this.setDisabled = function(disabool) {
        disabled = disabool;
        //console.log(disabled);
    }

    this.interactive = true;

    this.anchor.x = 0.5;
    this.anchor.y = 0.5;
    
    this.hitArea = new PIXI.Rectangle(-this.width * 0.5, -this.height * 0.5, this.width, this.height);
    
};

EHDI.displays.Button.prototype = Object.create(EHDI.aka.Sprite.prototype);

EHDI.displays.Button.prototype.touchstart = function(touchData) {
    if(this.isDisabled() === true)
        return;
    this.isTouched = true;
    this.touchID = touchData.data.identifier;
    if(this.pointerDown) {
        this.texture = this.pointerDown;
    }
    if(this.customScale) {
        this.baseScale.x = this.scale.x;
        this.baseScale.y = this.scale.y;
        this.scale.x = this.customScale.x;
        this.scale.y = this.customScale.y;
    } else if(this.scaleOnPointerDown) {
        this.baseScale.x = this.scale.x;
        this.baseScale.y = this.scale.y;
        this.scale.x = this.scaleOnPointerDown;
        this.scale.y = this.scaleOnPointerDown;
    }
};

EHDI.displays.Button.prototype.touchend = function(touchData) {
    if(this.isDisabled() === true)
        return;
    if(this.pointerUp)
        this.texture = this.pointerUp;
    if(this.scaleOnPointerDown) {
        this.scale.x = this.baseScale.x;
        this.scale.y = this.baseScale.y;
    }
};

EHDI.displays.Button.prototype.touchendoutside = function(touchData) {
    if(this.touchID !== touchData.data.identifier)
        return;
    if(this.isDisabled() === true)
        return;
    if(this.pointerUp)
        this.texture = this.pointerUp;
    if(this.customScale || this.scaleOnPointerDown) {
        this.scale.x = this.baseScale.x;
        this.scale.y = this.baseScale.y;
    }
    this.isTouched = false;
}

EHDI.displays.Button.prototype.tap = function(touchData) {
    if(this.isDisabled() === true || EHDI.config.isTransition === true)
        return;
    if(this.onClickFunction && this.isTouched)
        this.onClickFunction.apply(null, this.onClickArgs);
    this.isTouched = false;
};

EHDI.displays.Button.prototype.mouseover = function(mouseData) {
    if(this.isDisabled() === true)
        return;
    if(this.mouseOver)
        this.texture = this.mouseOver;
};

EHDI.displays.Button.prototype.mouseout = function(mouseData) {
    if(this.isDisabled() === true)
        return;
    if(this.pointerUp)
        this.texture = this.pointerUp;
    if(this.customScale || this.scaleOnPointerDown) {
        this.scale.x = this.baseScale.x;
        this.scale.y = this.baseScale.y;
    }
};

EHDI.displays.Button.prototype.mousedown = function(mouseData) {
    if(this.isDisabled() === true)
        return;
    if(this.pointerDown) {
        this.texture = this.pointerDown;
        //console.log("onClick");
    }
    if(this.customScale) {
        this.baseScale.x = this.scale.x;
        this.baseScale.y = this.scale.y;
        this.scale.x = this.customScale.x;
        this.scale.y = this.customScale.y;
    } else if(this.scaleOnPointerDown) {
        this.baseScale.x = this.scale.x;
        this.baseScale.y = this.scale.y;
        this.scale.x = this.scaleOnPointerDown;
        this.scale.y = this.scaleOnPointerDown;
    }
};

EHDI.displays.Button.prototype.mouseup = function(mouseData) {
    if(this.isDisabled() === true)
        return;
    if(this.pointerUp)
        this.texture = this.pointerUp;
    if(this.customScale || this.scaleOnPointerDown) {
        this.scale.x = this.baseScale.x;
        this.scale.y = this.baseScale.y;
    }
};

EHDI.displays.Button.prototype.click = function(mouseData) {
    if(this.isDisabled() === true || EHDI.config.isTransition === true)
        return;
    if(this.onClickFunction)
        this.onClickFunction.apply(null, this.onClickArgs);
};

EHDI.displays.Button.prototype.mouseupoutside = function(mouseData) {
    if(this.isDisabled() === true)
        return;
    if(this.pointerUp)
        this.texture = this.pointerUp;
    if(this.scaleOnPointerDown) {
        this.scale.x = this.baseScale.x;
        this.scale.y = this.baseScale.y;
    }
}

EHDI.displays.Button.prototype.disable = function(disabool) {
    this.setDisabled(disabool);
    if(this.disabledTexture && disabool) {
        this.texture = this.disabledTexture;
        if(this.scaleOnPointerDown) {
            this.scale.x = this.baseScale.x;
            this.scale.y = this.baseScale.y;
        }
    } else if(this.pointerUp && !disabool) {
        this.texture = this.pointerUp;
        if(this.scaleOnPointerDown) {
            this.scale.x = this.baseScale.x;
            this.scale.y = this.baseScale.y;
        }
    }
}

 /**
 * @static
 * @value (STRING)- store string value of the sfx and let it be played in the createjs.Sound
 */
EHDI.displays.Button.defaultSFX = null;

/**
 * @param (STRING) - store string value of the sfx and let it be played in the createjs.Sound
 */
EHDI.displays.Button.prototype.setSFX = function(sfx){
    this.sfx = sfx;
}

/**
 * @param (FUNCTION) onClickFunction
 */
EHDI.displays.Button.prototype.setOnClickFunction = function(finishFunction) {
    this.onClickFunction = finishFunction;
    this.onClickArgs = arguments.length <= 1 || arguments[1] === undefined ? [] : arguments[1];
}

/**
 * @desc destroys all button props and methods
 */
EHDI.displays.Button.prototype.destroy = function(){
	delete this.pointerUp;
	delete this.pointerDown;
	delete this.mouseOver;
	delete this.disabledTexture;
	delete this.onClickFunction;
	delete this.baseScale;
	EHDI.aka.Sprite.prototype.destroy.apply(this, arguments);
}

/**
 * @deprecated dispose function included in the destroy
 * @desc dispose and clear all refenrences to the button object
 */
 EHDI.displays.Button.prototype.dispose = function(){
   delete this.pointerUp;
   delete this.pointerDown;
   delete this.mouseOver;
   delete this.disabledTexture;
   delete this.onClickFunction;
   delete this.baseScale;
   this.destroy({children: true});
 }

//GET OR INITIALIZE EHDI
var EHDI = EHDI || Object.create(null);

EHDI.displays = EHDI.displays || Object.create(null);

/**
 * @param (OBJECT) locale{"TEXT":"the text to be created", "STYLE":"The style to be implemented"}
 * @return (EHDI.aka.PixiText) returns a new pixi text object
 */
/**
* to use
* var txt = new EHDI.displays.TextSprite(JSONManager.getLocale("LBL_TITLE_HEADER");
*/
EHDI.displays.TextSprite = function(locale){
  EHDI.aka.PixiText.call(this, locale.TEXT, locale.STYLE);
};

EHDI.displays.TextSprite.prototype = Object.create(EHDI.aka.PixiText.prototype);

var EHDI = EHDI || Object.create(null);

EHDI.displays = EHDI.displays || Object.create(null);

EHDI.displays.TextureRectangle = function(color, width, height) {
    
    var graphics = new PIXI.Graphics();
    graphics._sprite = null;
    graphics._width = width;
    graphics._height = height;
    graphics._color = color;
    
    var draw = function(width, height, fillStyle) {
        graphics.clear();
        graphics.beginFill(fillStyle);
        graphics.drawRect(0,0,width, height);
        graphics.endFill();
    };
    
    draw(graphics._width, graphics._height, graphics._color);
    
    var texture = graphics.generateCanvasTexture(1);
    graphics.destroy();
    return texture;
};

EHDI.displays.TextureCircle = function(color, radius) {
    
    var graphics = new PIXI.Graphics();
    graphics._sprite = null;
    graphics._radius = radius;
    graphics._color = color;
    
    var draw = function(radius, fillStyle) {
        graphics.clear();
        graphics.beginFill(fillStyle);
        graphics.drawCircle(radius, radius,radius);
        graphics.endFill();
    };
    
    draw(graphics._radius, graphics._color);
    
    var texture = graphics.generateCanvasTexture(1);
    return texture;
};


var EHDI = EHDI || Object.create(null);

EHDI.displays = EHDI.displays || Object.create(null);

EHDI.displays.ToggleButton = function (inactivePointerUp, inactivePointerDown, activePointerUp, activePointerDown) {
    this.active = arguments.length <= 4 || arguments[4] === undefined ? false : arguments[4];
    this.scaleOnPointerDown = arguments.length <= 5 || arguments[5] === undefined ? 1 : arguments[5]; 
    this.baseScale = {x : 1, y:1};
    this.inactivePointerUp = inactivePointerUp;
    this.inactivePointerDown = inactivePointerDown;
    this.activePointerUp = activePointerUp;
    this.activePointerDown = activePointerDown;
    this.onClickFunction = null;
    if(this.active === false) {
        PIXI.Sprite.call(this, inactivePointerUp);
    } else {
        PIXI.Sprite.call(this, activePointerUp);
    }
    this.interactive = true;


    this.anchor.x = 0.5;
    this.anchor.y = 0.5;
};

EHDI.displays.ToggleButton.prototype = Object.create(PIXI.Sprite.prototype);

EHDI.displays.ToggleButton.prototype.touchstart = function(touchData) {
    if(this.active === false)
        this.texture = this.inactivePointerDown;
    else
        this.texture = this.activePointerDown;
    if(this.scaleOnPointerDown) {
        this.baseScale.x = this.scale.x;
        this.baseScale.y = this.scale.y;
        this.scale.x = this.scaleOnPointerDown;
        this.scale.y = this.scaleOnPointerDown;
    }
};

EHDI.displays.ToggleButton.prototype.touchend = function(touchData) {
    if(this.active === false)
        this.texture = this.inactivePointerUp;
    else
        this.texture = this.activePointerUp;
    if(this.scaleOnPointerDown) {
         this.scale.x = this.baseScale.x;
        this.scale.y = this.baseScale.y;
    }
};

EHDI.displays.ToggleButton.prototype.touchendoutside = function(touchData) {
    if(this.active === false)
        this.texture = this.inactivePointerUp;
    else
        this.texture = this.activePointerUp;
   if(this.scaleOnPointerDown) {
        this.scale.x = this.baseScale.x;
        this.scale.y = this.baseScale.y;
   }
}

EHDI.displays.ToggleButton.prototype.tap = function(touchData) {
    this.active = !this.active;
    if(this.active === false)
        this.texture = this.inactivePointerUp;
    else
        this.texture = this.activePointerUp;
    if(this.scaleOnPointerDown) {
        this.scale.x = this.baseScale.x;
        this.scale.y = this.baseScale.y;
    }
    if(this.onClickFunction)
        this.onClickFunction(this.active);
};

EHDI.displays.ToggleButton.prototype.mouseout = function(mouseData) {
    if(this.active === false)
        this.texture = this.inactivePointerUp;
    else
        this.texture = this.activePointerUp;
    if(this.scaleOnPointerDown) {
        this.scale.x = this.baseScale.x;
        this.scale.y = this.baseScale.y;
    }
};

EHDI.displays.ToggleButton.prototype.mousedown = function(mouseData) {
    if(this.active === false)
        this.texture = this.inactivePointerDown;
    else
        this.texture = this.activePointerDown;
    if(this.scaleOnPointerDown) {
        this.baseScale.x = this.scale.x;
        this.baseScale.y = this.scale.y;
        this.scale.x = this.scaleOnPointerDown;
        this.scale.y = this.scaleOnPointerDown;
    }
};

EHDI.displays.ToggleButton.prototype.mouseup = function(mouseData) {
    if(this.active === false)
        this.texture = this.inactivePointerUp;
    else
        this.texture = this.activePointerUp;
    if(this.scaleOnPointerDown) {
        this.scale.x = this.baseScale.x;
        this.scale.y = this.baseScale.y;
    }
};

EHDI.displays.ToggleButton.prototype.click = function(mouseData) {
    this.active = !this.active;
    if(this.active === false)
        this.texture = this.inactivePointerUp;
    else
        this.texture = this.activePointerUp;
    if(this.scaleOnPointerDown) {
        this.scale.x = this.baseScale.x;
        this.scale.y = this.baseScale.y;
    }
     if(this.onClickFunction)
        this.onClickFunction(this.active);
};

EHDI.displays.ToggleButton.prototype.mouseupoutside = function(mouseData) {
    if(this.active === false)
        this.texture = this.inactivePointerUp;
    else
        this.texture = this.activePointerUp;
    if(this.scaleOnPointerDown) {
        this.scale.x = this.baseScale.x;
        this.scale.y = this.baseScale.y;
    }
}

/**
 * @desc destroys all button props and methods
 */
EHDI.displays.Button.prototype.destroy = function(){
	delete this.pointerUp;
	delete this.pointerDown;
	delete this.mouseOver;
	delete this.disabledTexture;
	delete this.onClickFunction;
	delete this.baseScale;
	EHDI.aka.Sprite.prototype.destroy.apply(this, arguments);
}

/**
 * @deprecated dispose function included in the destroy
 * @desc dispose and clear all refenrences to the button object
 */
EHDI.displays.ToggleButton.prototype.dispose = function() {
  delete this.inactivePointerUp;
  delete this.inactivePointerDown;
  delete this.activePointerUp;
  delete this.activePointerDown;
  delete this.onClickFunction;
  delete this.baseScale;
  this.destroy({children: true});

}

EHDI.displays.ToggleButton.prototype.setOnClickFunction = function(finishFunction) {
    this.onClickFunction = finishFunction;
}

var EHDI = EHDI || Object.create(null);

/**
 * @desc manages taking photos with the phone camera or webcam
 *
 *		 ```
 *       requires in the index:
 *       <input id="photo" style="display: none;" type="file" accept="image/*" capture="camera">
 *       <div id="vidiv"></div>
 *       before
 *       <canvas id="game-canvas" width="" height="100%"></canvas>
 *       ```
 */
EHDI.CameraManager = function ( canvas ){
    
    var _videoSetup = false;
	var _canvas = canvas;
    var _streamCanvas = null;
    var _loop, _stopLoop = false;
	
	var _orientImage = function( orientation, img ){
		switch( orientation ){
            //case 2: img.position.set(img.width, 0); img.scale.set(-1, 1); break;
            case 3: img.rotation = Math.PI; img.position.set( img.width, img.height ); break;
            //case 4: img.position.set(0, img.height); img.scale.set(1, -1); break;
            //case 5: img.rotation = (0.5 * Math.PI); img.scale.set(1, -1); break;
            case 6: img.rotation = (0.5 * Math.PI); img.position.set( img.height, 0 ); break;
            //case 7: img.rotation = (0.5 * Math.PI); img.position.set(img.width, -img.height); img.scale.set(-1, 1); break;
            case 8: img.rotation = (-0.5 * Math.PI); img.position.set( 0, img.width ); break;
        }
	}
	
	var _mobilePhoto = function( callback ){
		var inputElement = document.getElementById("photo");
    
		inputElement.click();
		inputElement.onchange = function (event) {
			var files = event.target.files, file;
			
			if (files && files.length > 0) {
				file = files[0];
				
				var base64ToArrayBuffer = function(base64) {
					base64 = base64.replace(/^data\:([^\;]+)\;base64,/gmi, '');
					var binaryString = atob(base64);
					var len = binaryString.length;
					var bytes = new Uint8Array(len);
					for (var i = 0; i < len; i++) {
						bytes[i] = binaryString.charCodeAt(i);
					}
					return bytes.buffer;
				}
				var fileReader = new FileReader();
				
				fileReader.onload = function (event) {
					var img = new Image();
					var exif = EXIF.readFromBinaryFile( base64ToArrayBuffer( this.result ) );
					var orientation = exif.Orientation;
					
					img.src = event.target.result;
					img.onload = function(e){
						var basetx = new PIXI.BaseTexture( img );
                        basetx.imageUrl = img.src;
                        
						var texture = new PIXI.Texture( basetx );
						
						callback.apply( null, [ texture, orientation ] );
					}
				};
				fileReader.readAsDataURL( file );
			}
            inputElement.value = "";
		}
	}

	var _takeDesktopPhoto = function( callback ){
		var tempCanvas = document.createElement('canvas');
		var video = document.body.querySelector('video');
        var sCanvas = document.getElementById("stream");
		
		tempCanvas.width = video.videoWidth;
		tempCanvas.height = video.videoHeight;
		
		tempCanvas.getContext('2d').drawImage( video, 0, 0, video.videoWidth, video.videoHeight );
		
		video.pause();
		video.src = "";
		window.stream.getTracks()[0].stop();
		document.getElementById( "vidiv" ).removeChild( video );
		
        _stopUpdate();
        document.getElementById( "vidiv" ).removeChild( sCanvas );
        
		var img = new Image();
		img.src = tempCanvas.toDataURL();
		
		img.onload = function(){
			var basetx = new PIXI.BaseTexture( img );
			var texture = new PIXI.Texture( basetx );
			
			callback.apply( null, [ texture ] );
		};
	}
	
    var _update = function( x, y, width, height ){
        var sCanvas = document.getElementById("stream");
        var sCtx = sCanvas.getContext('2d');
        var video = document.body.querySelector('video');
        
        var ratio = 1;
        if( width !== -1 ) ratio = width / video.videoWidth;
        if( height !== -1 ) ratio = height / video.videoHeight;
        var newWidth = video.videoWidth * ratio;
		var newHeight = video.videoHeight * ratio;
        
        var posX = x - ( newWidth * 0.5 );
        var posY = y - ( newHeight * 0.5 );
        
        _stopLoop = false;
        var loop = function() {
            if( _stopLoop === false ){
                sCtx.drawImage( video, posX, posY, newWidth, newHeight );
                requestAnimationFrame( loop );
            }
        }
        _loop = requestAnimationFrame( loop );
    }
    
    var _stopUpdate = function(){
        if ( _loop ) {
            cancelAnimationFrame( _loop );
        }
        _stopLoop = true;
    }
    
    /*********
    * PUBLIC
    **********/
    return {
        /**
         * @param (STRING) callback - where the resulting contianer will be returned to
		 * @param (BOOL) isMobile
		 * @param (NUMBER) maxWidth
		 * @param (NUMBER) maxHeight
         * @desc creates image from upload or camera use
         */
        getVideoSetup: function(){
            return _videoSetup;
        },
        
        setupVideo: function( onsuccess, onfail, posX, posY, width, height ){
            if( _videoSetup === true ) return;
            
            var constraints = { audio: false, video: true };
            
            if (navigator.mediaDevices === undefined) {
                navigator.mediaDevices = {};
            }

            // Some browsers partially implement mediaDevices. We can't just assign an object
            // with getUserMedia as it would overwrite existing properties.
            // Here, we will just add the getUserMedia property if it's missing.
            if (navigator.mediaDevices.getUserMedia === undefined) {
                navigator.mediaDevices.getUserMedia = function( constraints ) {
                   // First get ahold of the legacy getUserMedia, if present
                    var getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia;

                    // Some browsers just don't implement it - return a rejected promise with an error
                    // to keep a consistent interface
                    if (!getUserMedia) {
                      return Promise.reject(new Error('getUserMedia is not implemented in this browser'));
                    }

                    // Otherwise, wrap the call to the old navigator.getUserMedia with a Promise
                    return new Promise(function(resolve, reject) {
                        getUserMedia.call(navigator, constraints, resolve, reject);
                    });
                }
            }

            navigator.mediaDevices.getUserMedia( constraints )
            .then(function(stream) {
                var vidTest = document.createElement( 'video' );
                vidTest.autoplay = true;

                _canvas.style.position = 'absolute';
                
                vidTest.style.position = 'absolute';
                vidTest.style.display = 'none';
                document.getElementById( "vidiv" ).appendChild( vidTest );
                
                _streamCanvas = null;
                _streamCanvas = document.createElement( 'canvas' );
                _streamCanvas.id = 'stream';
                _streamCanvas.style.position = 'absolute';
                _streamCanvas.width = _canvas.width;
                _streamCanvas.height = _canvas.height;
                _streamCanvas.style.width = _canvas.style.width;
                _streamCanvas.style.height = _canvas.style.height;
                _streamCanvas.style.display = "block";
                _streamCanvas.style.marginTop = _canvas.style.marginTop;
                _streamCanvas.style.marginBottom = _canvas.style.marginBottom;
                _streamCanvas.style.marginLeft = _canvas.style.marginLeft;
                _streamCanvas.style.marginRight = _canvas.style.marginRight;
                _streamCanvas.style.paddingLeft = _canvas.style.paddingLeft;
                _streamCanvas.style.paddingRight = _canvas.style.paddingRight;
                _streamCanvas.style.paddingTop = _canvas.style.paddingTop;
                _streamCanvas.style.paddingBottom = _canvas.style.paddingBottom;
                
                document.getElementById( "vidiv" ).appendChild( _streamCanvas );

                var video = document.querySelector('video');
                window.stream = stream;
                video.src = URL.createObjectURL(stream);
                video.play();

                video.onloadeddata = function(){
                    _videoSetup = true;
                    onsuccess();
                    _update( posX, posY, width, height );
                }
            })
            .catch( function(err) {
                alert( err.name + ": " + err.message );
                onfail();
            });
        },
        
        takePhoto: function( callback, isMobile ){
            if( isMobile ){
				var callTex = function( texture, orientation ){
					var imgContainer = new EHDI.aka.Container();
					var imgSprite = new EHDI.aka.Sprite( texture );
					
					_orientImage( orientation, imgSprite );
					imgContainer.addChild( imgSprite );

					callback.apply( null, [imgContainer] );
				}
				_mobilePhoto( callTex );
			}
			else{
				var video = document.body.querySelector( 'video' );
				
				if( typeof video !== 'undefined' && video !== null  ){
					var callTex = function( texture ){
                        _videoSetup = false;
                        
						var imgContainer = new EHDI.aka.Container();
						var imgSprite = new EHDI.aka.Sprite( texture );

						imgContainer.addChild( imgSprite );
						
						callback.apply( null, [imgContainer] );
					};
					_takeDesktopPhoto( callTex );
				}
			}
        }
    }
};

//GET OR INITIALIZE EHDI
var EHDI = EHDI || Object.create(null);

/**
 * @param (STRING) name
 * @desc Custom Event for Ehdi
 */
EHDI.Event = function(name){
  this.name = name;
  this.callbacks = [];
}

/**
 * @param (FUNCTION) callback
 */
EHDI.Event.prototype.registerCallback = function(callback){
  this.callbacks.push(callback);
}

EHDI.Event.prototype.unregisterCallback = function(callback){
  var index = this.callbacks.indexOf(callback);
  if(index > -1) this.callbacks.splice(index, 1);
}

EHDI.Event.prototype.clearCallbacks = function(){
  this.callbacks.length = 0;
}

/**
 * @desc EventManager for custom events in javascript
 */

EHDI.EventManager = function(){
  "use strict"; "use restrict";
  var _eventController = Object.create(null);
  var _events = Object.create(null);
  var _maxListeners = 10;
  
  //PUBLIC
  /**
   * @desc sets the maximum number of listeners
   * @default 10
   */
  Object.defineProperty(_eventController, "maxListeners",{
	  set: function(val){
		if(typeof val !== "number") return;
		_maxListeners = val;
	  },
	  get: function(){
		return _maxListeners;  
	  }
  })
  
  /**
   * @param (STRING) name
   */
  _eventController.register = function(name){
    var e = new EHDI.Event(name);
    _events[name] = e;
  }
  
  /**
   * @param (STRING) name
   * @desc unregisters the event and removes all of its listeners
   */
  _eventController.unregister = function(name){
	if(!(name in _events)) throw new Error("event not found");
	_events[name].clearCallbacks();
	delete _events[name];
  }

  /**
   * @param (STRING) name
   * @param (OBJECT) data
   */
  _eventController.dispatch = function(name, data){
    if(!(name in _events)) throw new Error("event is unregistered");
    var callbacks = _events[name].callbacks;
    for(var i = 0, len = callbacks.length; i < len; i++){
      if(typeof data !== "undefined"){
        callbacks[i](data);
      }else callbacks[i]();
    };
  }

  /**
   * @param (STRING) name
   * @param (FUNCTION) callback - note avoid using anonymous function for callback
   */
  _eventController.addListener = function(name, callback){
    if(!(name in _events)) throw new Error("event is unregistered");
	if(_events[name].callbacks.length >= _maxListeners)  throw new Error("max amount of listeners limit reached, maxListener: " + _maxListeners);
    _events[name].registerCallback(callback);
  }

  /**
   * @param (STRING) name
   * @param (FUNCTION) callback
   */
   _eventController.removeListener = function(name, callback){
     if(!(name in _events)) throw new Error("event is unregistered");
	 if(_events[name].callbacks.indexOf(callback) <= -1) console.log("callback listener not found");
     _events[name].unregisterCallback(callback);
   }
   
  return _eventController;
};

//GET OR INITIALIZE EHDI
var EHDI = EHDI || Object.create(null);

/**
 * @param (JSON) configData
 * @param (JSON) localeData
 * @desc sets a JSONManager to handle localization and/or configuration
 */
EHDI.JSONManager = function(configData, localeData){
  "use strict"; "use restrict";
  /*********
  * PRIVATES
  **********/
  var _configData = configData;
  var _localeData = localeData;

  /*********
  * PUBLIC
  **********/
  return{
    /**
     * @param (JSON) data
     * @desc sets config data. will not overwrite when config data exist.
     */
     setConfigData: function(data){
       if(typeof _configData === "undefined") _configData = data;
     },

    /**
     * @param (JSON) data
     * @desc sets locale data. will not overwrite when locale data exist.
     */
    setLocaleData: function(data){
      if(typeof _localeData === "undefined") _localeData = data;
    },

    /**
     * @param (STRING)  id;
     * @return (OBJECT) returns _localeData.data[id] or _localeData.data;
     */
    getLocale: function(id){
      if(arguments.length < 1) {
        return _localeData.data;
      }else{
        return _localeData.data[id];
      }
    },

    /**
     * @return (OBJECT) returns config data.
     */
    getConfig: function(){
      return _configData;
    }
  };
};

(function(){
  "use strict"; "use restrict";
  //GET OR INITIALIZE EHDI
  EHDI = EHDI || Object.create(null);

  /**
   * @desc Asset Storage
   * @member images - Pixi Textures
   * @member cjAssets - String and Sound Files
   */
  EHDI.Assets = {
    images: EHDI.aka.TextureCache,
	fonts: []
  };

  /**
   * @class
   * @desc LoadManager for managing fonts, strings, images and audio
   *       images and fonts are handled by PixiJS while
   *       strings and audio are handled by CreateJS
   *     Loading Priority - createJS loads first then pixiJS.
   *     Load starts by using EHDI.LoadManager.start();
   */
  EHDI.LoadManager = (function(){
    /***************
     *  PRIVATES
     ***************/
    //const
	var _STRINGEXTENSION = ["json", "js", "xml", "txt"];
    var _AUDIOEXTENSION = ["ogg", "mp3", "wav"];
    var _FONTEXTENSION = ["ttf", "woff", "woff2", "otf"];

    //module
    var _public = Object.create(null);
    var _cjAssets, _pixiLoader;

    //manifest for createJS, sounds and strings;
    var _createJSManifest = [];
    var _pixiAssetToBeLoaded = [];
    var _fontToBeParsed = [];
    var _functionOnComplete = null;
    var _onCompleteParam = [];
    var _isLoading = false;
    var _loadProgress = 0;
    var _soundProgress = 0;
    var _totalObjectsToLoad = 0;

    var _createJSManifestToUnload = [];
    var _pixiAssetToBeUnload = [];
    var _totalObjectsToUnload = 0;
    /**
     * loader initalization
     */
    var init = function(){
      _pixiLoader = EHDI.aka.Loader;
      _cjAssets = new createjs.LoadQueue();
      createjs.Sound.alternateExtensions = _AUDIOEXTENSION;

      Object.defineProperty(EHDI.Assets, "cjAssets",{value: _cjAssets,
                                                     enumerable: false });
													 
      _cjAssets.installPlugin(createjs.Sound);
      _cjAssets.addEventListener("progress", cjProgressHandler);
      _cjAssets.addEventListener("complete", cjCompleteHandler);
      _cjAssets.addEventListener("error", cjErrorHandler);

      _pixiLoader.on("progress", pixiProgressHandler);
      _pixiLoader.on("error", pixiErrorHandler);
    }

    /**
     * @param (STRING) id
     * @return the asset from createJS.Loader or pixi.loader
     *         returns null if no object is found
     */
    EHDI.Assets.fetch = function(id){
      var result = _cjAssets.getResult(id);
      if(!result){
        result = EHDI.aka.Loader.resources[id] || null;
      }
      return result;
    }

    /**
     * @desc clears the manifest file
     */
    var clearManifest = function(){
      _pixiAssetToBeLoaded.length = 0;
      _createJSManifest.length = 0;
      _createJSManifestToUnload.length = 0;
      _pixiAssetToBeUnload.length = 0;
    }

    /**
     * @param (Array) urls
     * @param (Array) exts
     */
    var getUrlsBaseOnExtension = function(urls, exts){
      var fileSourcePaths = urls.filter(function (source) {
          if(typeof source !== "string")
              source = source.url;
          var extension = source.split('.').pop();
          return (exts.indexOf(extension) !== -1);
      });
      return fileSourcePaths;
    }

    var fontParser = function(source){
	  var fontData = source.split("/").pop().split(".");
      var fontFamily = fontData[0];
      var fontExt = fontData[1];
      
	  if(fontExt === "ttf") fontExt = "truetype";
	  if(fontExt === "otf") fontExt = "opentype";
	  if(fontExt === "eot") fontExt = "embedded-opentype";
	  
      var newStyle = document.createElement("style");
      var fontFace = "@font-face {font-family: '" + fontFamily + "'; src: url('" + source + "') format('" + fontExt + "');";
	  newStyle.appendChild(document.createTextNode(fontFace));
      document.body.appendChild(newStyle);
      EHDI.Assets.fonts.push(fontFamily);
    }

    var pixiProgressHandler =  function (loader,resource) {
      _loadProgress = _soundProgress + (loader.progress * (_pixiAssetToBeLoaded.length) /  _totalObjectsToLoad);
    };

    var pixiErrorHandler = function(error, loader,resource){
      console.log("PixiJS Loading Error!");
      console.log(error);
    }

    var pixiCompleteHandler = function(loader,resources){
      clearManifest();
	  _isLoading = false;
      if(_fontToBeParsed.length > 0) {
          _fontToBeParsed.length = 0;
      }
	  if(typeof _functionOnComplete === "function") _functionOnComplete.apply(null, _onCompleteParam);
    }

    var cjProgressHandler = function(e){
      var progress = (e.progress > 1) ? 1 : e.progress;
      _loadProgress = (progress * (_createJSManifest.length) / _totalObjectsToLoad) * 100;
      _soundProgress = _loadProgress;
    }

    var cjCompleteHandler = function(e){
      if(_pixiAssetToBeLoaded.length <= 0){
        pixiCompleteHandler();
        return;
      }
      _pixiLoader.add(_pixiAssetToBeLoaded).load(pixiCompleteHandler);
    }

    var cjErrorHandler = function(e){
      console.log("CreateJS Loading Error");
      console.log(e);
    }

    /**
     * @param (jsonmanager) -jsonmanager component
     * @param (id) - config file id
     */
    var configHandler = function(jsonmanager, id, callback){
      var configJSON, localeConfig, locid, localeUrl, lang, onDone;
      var ext = ".json";
      var _loader;
      var _fontsToLoad, _stringToLoad;
      configJSON = _cjAssets.getResult(id);
      localeConfig = configJSON.locale;
      localeUrl = localeConfig.url;
      lang = (typeof localeConfig.lang !== "undefined") ? localeConfig.lang : "en";
      locid = localeConfig.id + lang;

      if(typeof localeConfig.font[lang] === "undefined"){
        _fontsToLoad = localeConfig.font["default"];
      }else{
        _fontsToLoad = localeConfig.font[lang];
      }

      _stringToLoad = [localeUrl+locid+ext];

      onDone = function(){
        jsonmanager.setConfigData(configJSON);
        jsonmanager.setLocaleData(_cjAssets.getResult(locid));
        if(typeof callback === "function") callback();
      }
      _public.queueStrings(_stringToLoad);
      _public.queueFonts(_fontsToLoad);
      _public.start(onDone);
    }

    var startUnload = function(){
      var asset, item;
      while(_createJSManifestToUnload.length > 0){
        item = _createJSManifestToUnload.pop();
        asset =  _cjAssets.getItem(item);
        _cjAssets.remove(asset.id);
        if(asset.type === "sound"){
          createjs.Sound.removeSound(asset.id);
        }
      }

      while(_pixiAssetToBeUnload.length > 0){
        item = _pixiAssetToBeUnload.pop();
        asset = EHDI.Assets.images[item];
        asset.destroy(true);
      }

      if(_createJSManifest.length > 0){
        _cjAssets.loadManifest(_createJSManifest);
      }else{
        cjCompleteHandler();
      }
    }

    init();

    /**************
     *  PUBLIC
     *************/
    /**
     * @param (ARRAY<STRING>) url paths of the strings to be loaded
     * @desc add string url to queue
     */
    _public.queueStrings = function(urls){
      var manifest = [];
      var url, id;
      while(urls.length > 0){
        url = urls.pop();
        //id = url.split("/").pop(); //has .fileType
        id = url.split("/").pop().split(".")[0];

        manifest.push({
          id: id, src: url
        })
      };

      _createJSManifest = _createJSManifest.concat(manifest);
    }

    /**
     * @param (ARRAY<STRING>) url paths of the fonts to be loaded
     * @desc add font url to queue
     */
    _public.queueFonts = function(urls){
      //var fontsToLoad = []
      var url, id;
      while(urls.length > 0){
        url = urls.pop();
        id = url.split("/").pop().split(".")[0];
        _fontToBeParsed.push(fontParser(url));
        /*fontsToLoad.push({
          name: id, url: url
        })*/
      };

      //_pixiAssetToBeLoaded = _pixiAssetToBeLoaded.concat(fontsToLoad);
    }

    /**
     * @param (ARRAY<STRING>) url paths of the fonts to be loaded
     * @desc add audio url to queue
     */
    _public.queueAudios = function(urls){
      var manifest = []
      var url, id;
      while(urls.length > 0){
        url = urls.pop();
        if(typeof url !== "string") {
            id = url.id;
            url = url.url;
        } else {
            
            id = url.split("/").pop().split(".")[0];
        }
        manifest.push({
          id: id, src: url
        })
      };
      _createJSManifest = _createJSManifest.concat(manifest);
    }

    /**
     * @param (ARRAY<STRING>) url paths of the images to be loaded
     * @desc add image url to queue, can also use to parse atlas
     */
    _public.queueImages = function(urls){
      var imagesToBeLoaded = [];
      var url, id;
      while(urls.length > 0){
        url = urls.pop();
        if(typeof url !== "string") {
            id = url.id;
            url = url.url;
        } else {
            id = url.split("/").pop().split(".")[0];
        }
        imagesToBeLoaded.push({
          name: id, url: url
        })
      };

      _pixiAssetToBeLoaded = _pixiAssetToBeLoaded.concat(imagesToBeLoaded);
    }

    /**
     * @param (ARRAY<STRING>) url paths of the assets to be loaded
     * @desc loads all assets.
     */
    _public.queueAssets = function(urls){
      var filterUrls = function(main, filt){
        main = main.filter(function (source) {
            return filt.indexOf(source) < 0;
        });
        return main;
      }

      var fontsToLoad = getUrlsBaseOnExtension(urls, _FONTEXTENSION);
      var audiosToLoad = getUrlsBaseOnExtension(urls, _AUDIOEXTENSION);
	  var stringsToLoad = getUrlsBaseOnExtension(urls, _STRINGEXTENSION);
      var imgFileToLoad = filterUrls(urls, fontsToLoad);
	  imgFileToLoad = filterUrls(imgFileToLoad, stringsToLoad);
      imgFileToLoad = filterUrls(imgFileToLoad, audiosToLoad);
	  

      _public.queueFonts(fontsToLoad);
      _public.queueAudios(audiosToLoad);
	  _public.queueStrings(stringsToLoad);
      _public.queueImages(imgFileToLoad);
    }

    /**
     * @param (STRING) url path of the config file
     * @param (OBJECT) JSONManager component
     * @param (FUNCTION) callback
     * @desc loads config file and its dependencies
     */
    _public.loadConfig = function(url, jsonmanager, callback){
      if(typeof url !== "string") throw new Error("Invalid URL");
      if(typeof jsonmanager === "undefined") throw new Error("needs JSONManager component");
      if(_isLoading) throw new Error("Load manager is currently running");
      var id = url.split("/").pop().split(".")[0];
      clearManifest();
      _public.queueStrings([url]);
      _public.start(configHandler, [jsonmanager, id, callback]);
    }

	/**
	 * @return gets the progress of the load manager.
	 */
    _public.getProgress = function(){
      return _loadProgress;
    }

    /**
     * @param (function) callback - the callback function when loading ends
     * @param (ARRAY) params - the callback parameters
     * @desc starts loading and storing files
     */
    _public.start = function(callback, params){
      if(_isLoading) throw new Error("EHDI Load manager is currently running");
      _functionOnComplete = callback;
      _onCompleteParam = params;
      _isLoading = true;
      _loadProgress = 0;
	  _soundProgress = 0;
      _totalObjectsToLoad = _createJSManifest.length + _pixiAssetToBeLoaded.length;
      _totalObjectsToUnload = _createJSManifestToUnload.length + _pixiAssetToBeUnload.length;
	  _pixiLoader.reset();
	  startUnload();
    }

    /**
     * @param (ARRAY<STRING>) url paths of the images to be loaded
     * @desc add urls to unload queue
     */
    _public.unloadAssets = function(urls){
      var filterUrls = function(main, filt){
        main = main.filter(function (source) {
            return filt.indexOf(source) < 0;
        });
        return main;
      }

      var fontsToUnload = getUrlsBaseOnExtension(urls, _FONTEXTENSION);
      var audiosToUnload = getUrlsBaseOnExtension(urls, _AUDIOEXTENSION);
	  var stringsToUnload = getUrlsBaseOnExtension(urls, _STRINGEXTENSION);
      var imgFileToUnload = filterUrls(urls, audiosToUnload);
	  imgFileToUnload = filterUrls(imgFileToUnload, stringsToUnload);
      imgFileToUnload = filterUrls(imgFileToUnload, fontsToUnload);

      _createJSManifestToUnload = _createJSManifestToUnload.concat(audiosToUnload);
	  _createJSManifestToUnload = _createJSManifestToUnload.concat(stringsToUnload);
      _pixiAssetToBeUnload = _pixiAssetToBeUnload.concat(imgFileToUnload);
    }

    return _public;

  }());

}());

var EHDI = EHDI || Object.create(null);

EHDI.ScaleManager = function(renderer, stage, type, defaultWidth, defaultHeight) {
    var resizeCallback =  arguments.length <= 5 || typeof arguments[5] === "undefined" ? null : arguments[5];
    var scaleX, scaleY, orientation, isAutoScale, center, margin, resizeClock;
    
    
    var newStyle = document.createElement("style");
    var style = "html, body {padding : 0; margin : 0; overflow : hidden; width: 100%; height: 100%, position : fixed}";
    newStyle.appendChild(document.createTextNode(style));
    document.head.appendChild(newStyle);
    
    var ratio = 1;
    var width = defaultWidth;
    var height = defaultHeight;
    
    EHDI.screen = EHDI.screen || Object.create(null);
    
    updateDeviceOrientation();
    scaleToWindow();
    
    function scaleToWindow() {
        scaleX = window.innerWidth / defaultWidth;
        scaleY = window.innerHeight / defaultHeight;
        if(type === EHDI.ScaleManager.DOCKING.WIDTH) {
            ratio = scaleX;
        } else if(type === EHDI.ScaleManager.DOCKING.HEIGHT) {
            ratio = scaleY;
        } else if(type === EHDI.ScaleManager.DOCKING.AUTO) {
            ratio = Math.min(scaleX, scaleY);
        } else if(type === EHDI.ScaleManager.DOCKING.FULLSCREEN) {
            ratio = Math.max(scaleX, scaleY);
        }
        var canvas = renderer.view;
        
        canvas.style.paddingLeft = 0;
        canvas.style.paddingRight = 0;
        canvas.style.paddingTop = 0;
        canvas.style.paddingBottom = 0;
        canvas.style.display = "block";
        
        width = Math.floor(defaultWidth * ratio);
        height = Math.floor(defaultHeight * ratio);
        stage.scale.x = stage.scale.y = ratio;
        if(width > window.innerWidth) {
			EHDI.screen.xOffset = (window.innerWidth - width) * 0.5;
			width = window.innerWidth;
            EHDI.screen.viewWidth = width / ratio;
        } else {
			EHDI.screen.viewWidth = window.innerWidth / ratio;
            if(EHDI.screen.viewWidth > defaultWidth) {
                EHDI.screen.viewWidth = defaultWidth;
            }
			EHDI.screen.xOffset = 0;
        }
        if(height > window.innerHeight) {
			EHDI.screen.yOffset = (window.innerHeight - height) * 0.5;
            height = window.innerHeight;
            EHDI.screen.viewHeight = height / ratio;
        } else {
            EHDI.screen.viewHeight = window.innerHeight / ratio;        
            if(EHDI.screen.viewHeight > defaultHeight) {
                EHDI.screen.viewHeight = defaultHeight;
            }
			EHDI.screen.yOffset = 0;
        }
        
        if(EHDI.screen.centerOrigin) {
            stage.children.forEach(function(element) {
                element.position.set(EHDI.screen.viewWidth * 0.5, EHDI.screen.viewHeight * 0.5);
            });
        }
        
		// EHDI.screen.xOffset = EHDI.screen.stageWidth - EHDI.screen.viewWidth;
        // EHDI.screen.yOffset = EHDI.screen.stageHeight - EHDI.screen.viewHeight;
		
        renderer.resize(width, height);
        
        centerCanvas();
        window.scrollTo(0, 0);
        
		updateDeviceOrientation();
        
        if(resizeCallback) {
            resizeCallback();
        }
    };
    
    function updateDeviceOrientation() {
        if(window.innerHeight > window.innerWidth){
            orientation = EHDI.ScaleManager.SCREEN_ORIENTATION.PORTRAIT;
        } else {
            orientation = EHDI.ScaleManager.SCREEN_ORIENTATION.LANDSCAPE;
        }
        
        return orientation;
    };
    
    function centerCanvas() {
        var canvas = renderer.view;
        canvas.style.marginTop = 0;
        canvas.style.marginBottom = 0;
        canvas.style.marginLeft = 0;
        canvas.style.marginRight = 0;
        
        
        if (type == EHDI.ScaleManager.DOCKING.HEIGHT || type == EHDI.ScaleManager.DOCKING.FULLSCREEN || (type == EHDI.ScaleManager.DOCKING.AUTO  && width < window.innerWidth)) {
            margin = (window.innerWidth - width) / 2;
            canvas.style.marginLeft = margin + "px";
            canvas.style.marginRight = margin + "px";
        }

        //Center vertically (for wide canvases) 
        if (type == EHDI.ScaleManager.DOCKING.WIDTH || type == EHDI.ScaleManager.DOCKING.FULLSCREEN || (type == EHDI.ScaleManager.DOCKING.AUTO  && height < window.innerHeight)) {
            margin = (window.innerHeight - height) / 2;
            canvas.style.marginTop = margin + "px";
            canvas.style.marginBottom = margin + "px";
        }
    };
    /**
	 * @param (NUMBER) timeout - the scale timeout
	 */
    function addAutomaticScaling(timeout) {
       if(!isAutoScale)
            window.addEventListener("resize", function() {
                clearTimeout(resizeClock);
				timeout = timeout || 500;
                resizeClock = setTimeout(scaleToWindow, timeout);
                isAutoScale = true;
            });
    }
    
    function getScale() {
        return ratio;
    }
    
    function getOrientation() {
        return orientation;
    }
    
    return {
        getScale : getScale,
        getOrientation : getOrientation,
        scaleToWindow : scaleToWindow,
		setResizeCallback : function(callback){
			if(typeof callback !== "function") throw new Error("insert function as parameter")
			resizeCallback  = callback;
		},
        addAutomaticScaling : addAutomaticScaling
    }
};

EHDI.ScaleManager.SCREEN_ORIENTATION = {
    LANDSCAPE : 0,
    PORTRAIT : 1
}

EHDI.ScaleManager.DOCKING = {
    WIDTH: 0,
    HEIGHT: 1,
    AUTO: 2,
    FULLSCREEN : 3
}
var EHDI = EHDI || Object.create(null);

EHDI.scene = EHDI.scene || Object.create(null);

EHDI.SceneManager = function(width, height, nogl, centerOrigin) {
    var rendererView = arguments.length <= 4 || typeof arguments[4] === "undefined" ? document.getElementById("game-canvas") : arguments[4];
    var _stage = new EHDI.aka.Container();
    var rendererOptions = {
        view: rendererView,
        antialiasing: false,
        transparent: true,
        resolution: window.devicePixelRatio,
        autoResize: true,
    }
	var _renderer;
	
	if(!!nogl){
		_renderer = new EHDI.aka.CanvasRenderer(width, height, rendererOptions);
	}else{
		_renderer = new EHDI.aka.AutoDetectRenderer(width, height, rendererOptions);
	}

    var _stageWidth = width;
    var _stageHeight = height;

    var _sceneList = [];
	var _popUpList = [];
    var _currentScene = null;

    var _sceneLayer = new EHDI.aka.Container();
    var _popupLayer = new EHDI.aka.Container();
    var _notificationLayer = new EHDI.aka.Container();
    
    EHDI.screen = EHDI.screen || Object.create(null);
    EHDI.screen.stageWidth = width;
    EHDI.screen.stageHeight = height;
    EHDI.screen.centerOrigin = centerOrigin;
    if(centerOrigin) {
        _sceneLayer.position.set(width * 0.5, height * 0.5);
        _popupLayer.position.set(width * 0.5, height * 0.5);
        _notificationLayer.position.set(width * 0.5, height * 0.5);
    }
    
    _stage.addChild(_sceneLayer);
    _stage.addChild(_popupLayer);
    _stage.addChild(_notificationLayer);

    return {
        //GETTERS
        getStage : function () {
            return _stage;
        },
        getRenderer : function () {
            return _renderer;
        },
        getStageWidth : function () {
            return _stageWidth;
        },
        getStageHeight : function () {
            return _stageHeight;
        },
        defaultWidth : width,
        defaultHeight : height,

        renderScreen : function(){
          _renderer.render(_stage);
        },
		
        changeScene : function(scene, transition, destroyPrevious) {

            if(typeof scene.screenWillAppear === 'function') scene.screenWillAppear();
            if(_currentScene)
                if(typeof _currentScene.screenWillDisappear === 'function') _currentScene.screenWillDisappear();
            if(transition) {
				var values = Object.create(null);
                EHDI.config.isTransition = true;
				
				var keys = Object.keys(transition)
                for(var i = 0; i< keys.length; i++){
                  if(transition[keys[i]].hasOwnProperty('from') &&
                     transition[keys[i]].hasOwnProperty('to')){
						
						scene[keys[i]] = transition[keys[i]].from;
						values[keys[i]] = transition[keys[i]].to;					   
					
                  }else if(!transition[keys[i]].hasOwnProperty('duration')){
                    
					values[keys[i]] = transition[keys[i]];
					
                  }
                }

                _sceneLayer.addChild(scene);

                values.onComplete = function() {
                    EHDI.config.isTransition = false;
                    if(_currentScene) {
                        if(typeof _currentScene.screenDidDisappear === 'function') _currentScene.screenDidDisappear();
                        _sceneLayer.removeChild(_currentScene);
                    }
                    if(typeof scene.screenDidAppear === 'function') scene.screenDidAppear();
                    if(destroyPrevious)
                        _currentScene.destroy({children : true});
                    _currentScene = scene;
                }

                TweenLite.to(scene, transition.duration, values);
            } else {
                _sceneLayer.addChild(scene);
                if(_currentScene) {
                    _sceneLayer.removeChild(_currentScene);
                    if(typeof _currentScene.screenDidDisappear === 'function') _currentScene.screenDidDisappear();
                }
                if(typeof scene.screenDidAppear === 'function') scene.screenDidAppear();
                if(destroyPrevious)
                    _currentScene.destroy({children : true});
                _currentScene = scene;
            }
        },

		/**
		 * @desc CurrentScene popup functions will work when first popup is added, succeeding popup won't call the function.
		 */
        pushPopUp : function(popup, transition) {
            if(typeof popup.popUpWillAppear === 'function') popup.popUpWillAppear();
            if(typeof _currentScene.popUpWillAppear === 'function' && _popUpList.length === 0) _currentScene.popUpWillAppear();
            if(transition) {
                var values = Object.create(null);
                EHDI.config.isTransition = true;
				
				var keys = Object.keys(transition)
                for(var i = 0; i< keys.length; i++){
                  if(transition[keys[i]].hasOwnProperty('from') &&
                     transition[keys[i]].hasOwnProperty('to')){
						
						popup[keys[i]] = transition[keys[i]].from;
						values[keys[i]] = transition[keys[i]].to;
                   
                  }else if(!transition[keys[i]].hasOwnProperty('duration')){
                    
					values[keys[i]] = transition[keys[i]];
					
                  }
                }

                _popupLayer.addChild(popup);

                values.onComplete = function() {
                    EHDI.config.isTransition = false;
                    if(typeof popup.popUpDidAppear === 'function') popup.popUpDidAppear();
                    if(typeof _currentScene.popUpDidAppear === 'function' && _popUpList.length === 0) _currentScene.popUpDidAppear();
                    _popUpList.push(popup);
                }

                TweenLite.to(popup, transition.duration, values);
            } else {
                _popUpList.push(popup);
                _popupLayer.addChild(popup);
                if(typeof popup.popUpDidAppear === 'function') popup.popUpDidAppear();
            }

        },

		/**
		 * @desc CurrentScene popPopUp function will be called when last popup is removed.
		 */
        popPopUp : function(transition, destroyPrevious) {
            if(_popUpList.length <= 0)
                throw "Pop Up list is empty!";

            var popUpToRemove = _popUpList.pop();
            if(typeof popUpToRemove.popUpWillDisappear === 'function') popUpToRemove.popUpWillDisappear();
            if(typeof _currentScene.popUpWillDisappear === 'function' && _popUpList.length === 0) _currentScene.popUpWillDisappear();

            if(transition) {
                var values = Object.create(null);
                EHDI.config.isTransition = true;
				
				var keys = Object.keys(transition)
                for(var i = 0; i< keys.length; i++){
                  if(transition[keys[i]].hasOwnProperty('from') &&
                     transition[keys[i]].hasOwnProperty('to')){
						 
						popUpToRemove[keys[i]] = transition[keys[i]].from;
						values[keys[i]] = transition[keys[i]].to;
					
                  }else if(!transition[keys[i]].hasOwnProperty('duration')){
                    
					values[keys[i]] = transition[keys[i]];
					
                  }
                }

                values.onComplete = function() {
                    EHDI.config.isTransition = false;
                    if(typeof popUpToRemove.popUpDidDisappear === 'function') popUpToRemove.popUpDidDisappear();
                    if(typeof _currentScene.popUpDidDisappear === 'function' && _popUpList.length === 0) _currentScene.popUpDidDisappear();
                    _popupLayer.removeChild(popUpToRemove);
                    if(destroyPrevious)
                        popUpToRemove.destroy({children : true});
                }

                TweenLite.to(popUpToRemove, transition.duration, values);
            }else {
                _popupLayer.removeChild(popUpToRemove);
                 if(typeof popUpToRemove.popUpDidDisappear === 'function') popUpToRemove.popUpDidDisappear();
                 if(typeof _currentScene.popUpDidDisappear === 'function' && _popUpList.length === 0) _currentScene.popUpDidDisappear();
                if(destroyPrevious)
                    popUpToRemove.destroy({children : true});
            }
        },

		popAllPopUps: function(destroyPrevious){
			while(_popUpList.length > 0){
				var popup = _popUpList.pop();
				if(typeof popup.popUpWillDisappear === 'function') popup.popUpWillDisappear();
				if(typeof _currentScene.popUpWillDisappear === 'function' && _popUpList.length === 0) _currentScene.popUpWillDisappear();

				_popupLayer.removeChild(popup);
				 if(typeof popup.popUpDidDisappear === 'function') popup.popUpDidDisappear();
                 if(typeof _currentScene.popUpDidDisappear === 'function' && _popUpList.length === 0) _currentScene.popUpDidDisappear();
                if(destroyPrevious)
                    popup.destroy({children : true});
			}
		},

        addNotification: function(notif){
          _notificationLayer.addChild(notif);
        },

		/**
		 * @param (OBJECT) notif - notification object
		 * @param (BOOLEAN) destroy - set to true to destroy object 
		 */
        removeNotification: function(notif, destroy){
            var obj, index = _notificationLayer.children.indexOf(notif);
            if(index > -1){
				obj = _notificationLayer.removeChild(notif);
			}
			if(destroy) obj.destroy({children : true});
			obj = null;
        },
		
		/**
		 * @desc returns the topmost object from the notification layer
		 * @return (DisplayObject)
		 */
		popNofication: function(){
			return _notificationLayer.children.pop()
		},
		
        screenResize: function() {
            if(_currentScene && typeof _currentScene.onScreenResize === 'function') _currentScene.onScreenResize();
            _popUpList.forEach(function(element) {
                if(typeof element.onScreenResize === 'function') element.onScreenResize();
            });
            _notificationLayer.children.forEach(function(element) {
                if(typeof element.onScreenResize === 'function') element.onScreenResize();
            });
        }
    }
};

EHDI.scene.TransitionParameter  = function (from, to) {
    this.from = from;
    this.to = to;
}

EHDI.scene.TransitionParameter.constructor = EHDI.scene.TransitionParameter;

var EHDI = EHDI || Object.create(null);

EHDI.SoundManager = function (isAddInterrupt) {
    var _bgm = null;
    var _sfx = [];
    var _vo = null;
    var _muted  = false;
    var _isActive = true;
    var _isAutoResume = true;
	var _volume = { bgm: 1, sfx: 1, vo: 1 };
	var _hasInterrupt = isAddInterrupt || true;
	
    var pauseAll = function() {
        if(_bgm) {
            _bgm.paused = true;
        } 
        _sfx.forEach(function (sfxElement) {
            sfxElement.paused = true;
        });
        if(_vo) {
            _vo.paused = true;
        }
    }
    
    var resumeAll = function() {
        if(!_isAutoResume)
            return;
        if(_bgm) {
            _bgm.paused = false;
        } 
        _sfx.forEach(function (sfxElement) {
            sfxElement.paused = false;
        });
        if(_vo) {
            _vo.paused = false;
        }
    }
    
    var checkInterrupt = function() {
        if (window.document.webkitHidden || window.document.hidden) {
            pauseAll();   
        } else {
            resumeAll();
        }
    }
    
    var addInterruptListener = function(){
		window.addEventListener("blur", pauseAll);
        window.addEventListener("focus", resumeAll);
        window.addEventListener("pagehide", pauseAll);
        window.addEventListener("pageshow", resumeAll);
        window.addEventListener("webkitvisibilitychange", checkInterrupt);
        window.addEventListener("webkitvisibilitychange", checkInterrupt);
	}

	var removeInterruptListener = function(){
		window.removeEventListener("blur", pauseAll);
        window.removeEventListener("focus", resumeAll);
        window.removeEventListener("pagehide", pauseAll);
        window.removeEventListener("pageshow", resumeAll);
        window.removeEventListener("webkitvisibilitychange", checkInterrupt);
        window.removeEventListener("webkitvisibilitychange", checkInterrupt);
	}
	
	if(_hasInterrupt) {
		addInterruptListener();
    }
	
    return {
		
		set enableInterrupt(v){
			if(typeof v !== "boolean" || _hasInterrupt === v) return;
			_hasInterrupt = v;
			if(_hasInterrupt){
				addInterruptListener();
			}else{
				removeInterruptListener();
			}
		},
		
		get enableInterrupt(){
			return _hasInterrupt;
		},
		
		set sfxVolume(v){
			if(typeof v !== "number") return;
			_volume.sfx = v;
			if(_sfx){
				_sfx.forEach( 
					function(sfxElement) {
						sfxElement.volume = sfxElement.volume * _volume.sfx;
					} );
			}
		},
		
		get sfxVolume(){
			return _volume.sfx;
		},
		
		set bgmVolume(v){
			if(typeof v !== "number") return;
			_volume.bgm = v;
			
			if(_bgm) _bgm.volume = _bgm.volume * _volume.bgm;
		},
		
		get bgmVolume(){
			return _volume.bgm;
		},
		
		set voVolume(v){
			if(typeof v !== "number") return;
			_volume.vo = v;
			
			if(_vo) _vo.volume = _vo.volume * _volume.vo;
		},
		
		get voVolume(){
			return _volume.vo;
		},		
		
        playBGM : function(bgmToPlay, volume) {
			volume = ( volume * _volume.bgm ) || _volume.bgm;
            if(typeof bgmToPlay === 'string') {
                if(_bgm instanceof createjs.AbstractSoundInstance) {
                    _bgm.stop();
                    _bgm.destroy();
                }
                _bgm = createjs.Sound.play(bgmToPlay, {loop : -1});
                _bgm.volume = volume;
                _bgm.muted = _muted;
                return _bgm;
            } else {
                throw("pass string id of BGM to be played");
            }
        },
		
        stopBGM : function () {
            if(_bgm) {
                _bgm.stop();
                _bgm.destroy();
				_bgm = null;
            }
        },
		
        pauseBGM : function () {
            if(_bgm) {
                _bgm.paused = true;
            } 
        },
		
        resumeBGM : function () {
            if(_bgm) {
              _bgm.paused = false;              
            }
        },
		
        playSFX : function(sfxToPlay, volume) {
			volume = ( volume * _volume.sfx ) || _volume.sfx;
            if(typeof sfxToPlay === 'string') {
                var playingSFX = createjs.Sound.play(sfxToPlay);
                playingSFX.volume = volume;
                playingSFX.muted = _muted;
                _sfx.push(playingSFX);
                var sfxListener = playingSFX.on("complete", function(sfxToStop) {
                    var index = _sfx.indexOf(sfxToStop.currentTarget);
                    if(index > -1) {
                        var forDisposal = _sfx.splice(index, 1)[0];
						playingSFX.off("complete", sfxListener);
                        forDisposal.destroy();
                    }
                });
                return playingSFX;
            } else {
                throw("pass string id of SFX to be played");
            }
        },
		
        stopSFX : function (sfxToStop) {
            var index = _sfx.indexOf(sfxToStop);
			if(index > -1) {
                var forDisposal = _sfx.splice(index, 1)[0];
                forDisposal.stop();
                forDisposal.destroy();
            }
        },
		
        stopAllSFX : function () {
            _sfx.forEach(function (sfxElement) {
                sfxElement.stop();
                sfxElement.destroy();
            });
            _sfx = [];
        },
		
        pauseAllSFX : function() {
            _sfx.forEach(function (sfxElement) {
                sfxElement.paused = true;
            });
        },
		
        resumeAllSFX : function() {
            _sfx.forEach(function (sfxElement) {
                sfxElement.paused = false;
            });
        },
		
        playVO : function(VOToPlay, volume) {
            volume = ( volume * _volume.vo ) || _volume.vo;
			if(typeof VOToPlay === 'string') {
                _vo = createjs.Sound.play(VOToPlay);
                _vo.volume = volume;
                _vo.muted = _muted;
                return _vo;
            } else {
                throw("pass string ID of VO to be played");
            }
        },
		
        stopVO : function() {
            if(_vo) {
                _vo.stop();
                _vo.destroy();
            }
        },
		
        pauseVO : function() {
            if(_vo) {
                _vo.paused = true;
            }
        },
		
        resumeVO : function() {
            if(_vo) {
                _vo.paused = false;
            }
        },
		
        setMute : function() {
            var isMute = arguments.length <= 0 || typeof arguments[0] === "undefined" ? !_muted : arguments[0];;
            _muted = isMute;
            if(_bgm)
                _bgm.muted = _muted;
            _sfx.forEach(function(sfxElement) {
               sfxElement.muted = _muted; 
            });
            if(_vo)
                _vo.muted = _muted;
        },
		
		getMuted : function() {
            return _muted;
        },
		
        setDeactivate : function() {
            var isDeactivate = arguments.length <= 0 || typeof arguments[0] === "undefined" ? !_isActive : arguments[0];;
            _isActive = isDeactivate;
            if(_bgm)
                _bgm.paused = !_isActive;
            _sfx.forEach(function(sfxElement) {
               sfxElement.paused = !_isActive; 
            });
            if(_vo)
                _vo.muted = !_isActive;
        },
		
        autoResumeToggle : function(isAutoResume) {
            _isAutoResume = isAutoResume;
        }
    };
};


var EHDI = EHDI || Object.create(null);

/**
 * @desc creates and manages local storage.
 *       handles one shared object at a time per ID. uses "game_data" for default storage
 *
 *       ```js
 *       var storageManager = EHDI.StorageManager();
 *       storageManager.setLocalInfo("HighScoreData", hsObj)
 *       storageManager.setDataID("another_data") will use "another_data" for default storage
 *       storageManager.setDataID() reverts back to "game_data" as default storage
 *       storageManager.clearLocalData() clears data on the dataID specified.
 *       ```
 */
EHDI.StorageManager = function (){
  'use strict'; 'use restrict';
    /*********
    * PRIVATE
    **********/
    var _dataID = "game_data";
	var _isSupported = true;
    var _sharedObject = JSON.parse(localStorage.getItem(_dataID));
	
	var _isLocalStorageNameSupported = function(){
		try{
			localStorage.setItem('t3st', '1');
			localStorage.removeItem('t3st');
			return true;
		}catch(error){
			return false;
		}
	}
	
    var _checkLocalData = function(){
		if(!_isSupported) return false;
		var obj;
        if(_sharedObject === null && _dataID !== null){
            _sharedObject = Object.create(null);
            obj = JSON.stringify(_sharedObject);
            localStorage.setItem(_dataID, obj);
            return true;
        }else if(_sharedObject !== null){
            return true;
        }
        return false;
    }
	
	_isSupported = _isLocalStorageNameSupported();
	if(!_isSupported){
		_sharedObject = Object.create(null);
		console.log("Local storage is not supported. Current session will not be saved offline");
	}else{
		_checkLocalData();
	}
    /*********
    * PUBLIC
    **********/
    return {
        /**
         * @desc it checks the local data.
         * @return (BOOL) true if data already exists
         */
        checkLocalData : _checkLocalData,

        /**
         * @param (STRING) id
         * @desc creates new dataID to be manage and used
         */
        setDataID: function(id){
            if(arguments.length < 0 || typeof id !== "string") id = "game_data";
            _dataID = id;
            _checkLocalData();
        },

        /**
         * @return (STRING) dataID
         */
        getDataID: function(){
            return _dataID;
        },

        /**
         * @param (STRING) key - get the info of the key
         * @return (OBJECT) the value of the sharedObject
         *         (null) if the key is not found
         */
        getLocalInfo: function(key){
            if(typeof key !== "string") throw "invalid key";
            if(typeof _sharedObject[key] === "undefined"){
              return null;
            }else{
              return _sharedObject[key];
            }
        },

        /**
         * @param (STRING) key
         * @param (OBJECT || ARRAY) val
         * @desc sets or updates the data on the sharedObject
         */
        setLocalInfo: function(key, val){
            if(arguments.length < 2) throw "invalid parameters";
            if(typeof key !== "string") throw "invalid key";
			
			_sharedObject[key] = val;
			if(!!_checkLocalData()){
                localStorage.setItem(_dataID, JSON.stringify(_sharedObject));
            }
        },

        /**
         * @param (STRING) key
         * @desc deletes the data on the sharedObject
         */
        deleteLocalInfo: function(key){
            if(typeof key !== "string") throw "invalid key";
            
			delete _sharedObject[key];
            localStorage.setItem(_dataID, JSON.stringify(_sharedObject));
        },

        /**
         * @desc clears the overall local data in stored on dataID
         */
        clearLocalData: function(){
            var obj;
			_sharedObject = Object.create(null);
			if(_isSupported){
				obj = JSON.stringify(_sharedObject);
				localStorage.setItem(_dataID, obj);
			}
        }
    }
};

//GET OR INITIALIZE EHDI
var EHDI = EHDI || Object.create(null);

/**
 * @param (PIXI.Renderer) renderer - pass PIXI renderer as param here.
 * @param (PIXI.Container) stage - pass PIXI container that will be rendered.
 * @desc use and initialize the UpdateManager, this will handle the update utility and auto rendering
 *       if renderer and stage are added in the parameters
 */
EHDI.UpdateManager = function(renderer, stage){
	"use strict";
	// PRIVATES
	// Properties
	var _autoRender = false;
	var _updateList = [];
	var _prevTime;
    var _frameNumber = 0;
    var _fpsStartTime;
    var _fps;
	var _renderer, _stage;
	
	/**
	 * @desc frameLoop - updates every frame and returns dt in milliseconds
	 */
	var _frameLoop = function(){
		window.requestAnimationFrame(_frameLoop);

		var curTime = new Date();
        if(!_fpsStartTime)
            _fpsStartTime = new Date().getTime();
		var dt = (curTime - _prevTime);
        var fpsCountTime = (curTime.getTime() - _fpsStartTime) / 1000;
        _frameNumber++;
        _fps = Math.floor(_frameNumber / fpsCountTime);
        if(fpsCountTime > 1) {
            _fpsStartTime = new Date().getTime();
            _frameNumber = 0;
        }
		if(_updateList.length > 0){
			for(var i = 0;i < _updateList.length;i++){
				_updateList[i](dt);
			}
		}

		_prevTime = curTime;

		//Render the graphics
		if(!!_autoRender) _renderer.render(_stage);
	}
	
	//check if renderer and stage is passed as parameters
	if(arguments.length > 0){
		if(!(renderer instanceof PIXI.CanvasRenderer) && !(renderer instanceof PIXI.WebGLRenderer)) throw new Error("Please pass renderer as parameter")
		if(!(stage instanceof PIXI.DisplayObject)) throw new Error("Stage is not a display object")
		_autoRender = true;
		_renderer = renderer;
		_stage = stage;
	}
	//start the update
	_frameLoop();

	// PUBLICS
	return{
		/**
		 * @param (BOOL) val
		 */
        getFPS : function() {
            return _fps;
        },

		/**
		 * @param (BOOL) val
		 */
		setAutoRender: function(val){
			_autoRender = val;
		},

		/**
		 * @return (BOOL) returns true if manager auto renders gfx
		 */
		isAutoRendering: function(){
			return _autoRender;
		},

		/**
		 * @param (Function) callback - the callback function to be added
		 */
		addFrameListener: function(callback){
			if(typeof callback !== 'function') throw new Error("Callback must be a function");
			_updateList.push(callback);
		},

		/**
		 * @param (Function) callback - check if the callback exist
		 * @return (BOOL)
		 */
		hasFrameListener: function(callback){
			if(typeof callback !== 'function') throw new Error("Callback must be a function");
			var index = _updateList.indexOf(callback);
			if(index > -1) return true;
			return false;
		},

		/**
		 * @param (Function) callback - the callback function that needs to be removed
		 */
		removeFrameListener: function(callback){
			if(typeof callback !== 'function') throw "Callback must be a function";
			var index = _updateList.indexOf(callback);
			if(index > -1) _updateList.splice(index, 1);
		},

		/**
		 * @desc removes all callback listeners
		 */
		removeAllFrameListeners: function(){
			_updateList.length = 0;
		}
	};
};
/**
 *@TODO add detection for MS EDGE
 *		add detection for cocoon wrapper
 */
(function(ehdi){
	'use strict';
	ehdi.BrowserInfo = ehdi.BrowserInfo || Object.create(null);
	
	var navigator = window.navigator;
	var info = ehdi.BrowserInfo;
	var userAgent = navigator.userAgent;
	var regex, ver;

	var getiPhoneVersion = function(){
		var iHeight = window.screen.height;
		var iWidth = window.screen.width;
		if (iWidth === 320 && iHeight === 480) {
			return "4";
		}
		else if (iWidth === 375 && iHeight === 667) {
			return "6";
		}
		else if (iWidth === 414 && iHeight === 736) {
			return "6+";
		}
		else if (iWidth === 320 && iHeight === 568) {
			return "5";
		}
		else if (iHeight <= 480) {
			return "1-3";
		}
		return ' ';
	}
	
	info.platformType = navigator.platform;
	info.platformVersion = "";
	info.browserName = navigator.appName;
	info.browserVersion = navigator.appVersion;
	info.isMobileDevice = false;
	info.isIOS = false;
	info.deviceType = "desktop";
	
	//Platform
	if(navigator.platform.indexOf('iPhone') !== -1){
		info.isMobileDevice = true;
		info.platformType = "iPhone " + getiPhoneVersion();
		info.deviceType = "phone";
		info.isIOS = true;
		regex = /OS (\d+_\d+)/g;
		if(userAgent.search(regex) !== -1){
			ver = String(userAgent.match(regex));
			info.platformVersion = ver.replace("_",".");
		}
	}else if(navigator.platform.indexOf('iPod') != -1){
		info.isMobileDevice = true;
		info.platformType = "iPod";
		info.deviceType = "tablet";
		info.isIOS = true;
		regex = /OS (\d+_\d+)/g;
		if(userAgent.search(regex) !== -1){
			ver = String(userAgent.match(regex));
			info.platformVersion = ver.replace("_",".");
		}
	}else if(navigator.platform.indexOf('iPad') != -1){
		info.isMobileDevice = true;
		info.platformType = "iPad";
		info.deviceType = "tablet";
		info.isIOS = true;
		regex = /OS (\d+_\d+)/g;
		if(userAgent.search(regex) !== -1){
			ver = String(userAgent.match(regex));
			info.platformVersion = ver.replace("_",".");
		}
	}else if(userAgent.indexOf('Android') != -1){
		info.isMobileDevice = true;
		info.platformType = "Android";
		info.deviceType = "tablet";
		regex = /OS (\d+_\d+)/g;
		if(userAgent.search(regex) !== -1){
			ver = String(userAgent.match(regex));
			info.platformVersion = ver.replace("_",".");
		}
	}else if(userAgent.indexOf('Kindle') != -1 || userAgent.indexOf('Silk') != -1){
		info.isMobileDevice = true;
		info.platformType = "Android";
		info.deviceType = "tablet";
	}else if(userAgent.indexOf('IEMobile') != -1){
		info.isMobileDevice = true;
		info.platformType = "IEMobile";
		info.deviceType = "phone";
		regex  = /IEMobile\/(\d+\.\d+)/g;
		if(userAgent.search(regex) !== -1) info.platformVersion = String(userAgent.match(regex));
	}else if(navigator.platform.indexOf('Win') != -1){
		info.platformType = 'Windows';
		info.deviceType = "desktop";
	}else if(navigator.platform.indexOf('Mac') != -1){
		info.platformType = 'MAC';
		info.deviceType = "desktop";
		regex = /OS (\d+_\d+)/g;
		if(userAgent.search(regex) !== -1){
			ver = String(userAgent.match(regex));
			info.platformVersion = ver.replace("_",".");
		}
	}else if(navigator.platform.indexOf('Linux') != -1){
		info.platformType = 'Linux';
		info.deviceType = "desktop";
	}
	
	var _browser = (function(){
		var ua= navigator.userAgent, tem,
		M= ua.match(/(crios|samsungbrowser|opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
		if(/trident/i.test(M[1])){
			tem=  /\brv[ :]+(\d+)/g.exec(ua) || [];
			return 'IE '+(tem[1] || '');
		}
		if(M[1]=== 'Chrome'){
			tem= ua.match(/\b(OPR|Edge)\/(\d+)/);
			if(tem != null){
				if(tem.indexOf('OPR') != -1) return tem.slice(1).join(' ').replace('OPR', 'Opera');
				if(tem.indexOf('Edge') != -1) return tem.slice(1).join(' ').replace('Edge', 'Edge');				
			}
		}
		M= M[2]? [M[1], M[2]]: [navigator.appName, navigator.appVersion, '-?'];
		if((tem= ua.match(/version\/(\d+)/i))!= null) M.splice(1, 1, tem[1]);
		return M.join(' ');
	})();
	
	info.browserName = _browser.split(" ")[0];
	if(info.browserName.toUpperCase() === "CRIOS") info.browserName = "Chrome";
	info.browserVersion = _browser.split(" ")[1]; 
	
	ehdi.checkGLQuality = function(renderer){
		if(!renderer) throw new Error("pass renderer as parameters");
		var max = 0;
		var gl = renderer.view.getContext("webgl") || renderer.view.getContext("experimental-webgl");
		
		if(!gl) return "canvas";
		
		var ext = (
			gl.getExtension('EXT_texture_filter_anisotropic') ||
			gl.getExtension('MOZ_EXT_texture_filter_anisotropic') ||
			gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic')
		)
		if(ext) max = gl.getParameter(ext.MAX_TEXTURE_MAX_ANISOTROPY_EXT);
		
		if(max > 4) return "gl-high"
		
		return "gl-normal";
	}
	
	return ehdi;
}(EHDI || Object.create(null)))

//GET OR INITIALIZE EHDI
var EHDI = EHDI || Object.create(null);

EHDI.CollisionUtil = function(){};

//METHODS
/**
 * @param (Object) rect1 - 1st rectangle that contains: {x, y, width, height}
 * @param (Object) rect2 - 2nd rectangle that contains: {x, y, width, height}
 * @return (Bool) true or false if there was collision
 */
EHDI.CollisionUtil.rectToRect = function( rect1, rect2 ){

	if(
		rect1.x < rect2.x + rect2.width		&&
		rect1.x + rect1.width > rect2.x		&&
		rect1.y < rect2.y + rect2.height	&&
		rect1.height + rect1.y > rect2.y
	){
        return true;
    }
	
	return false;
}

/**
 * @param (Object) cir - circle that contains: {x, y, r}
 * @param (Object) rect - rectangle that contains: {x, y, width, height}
 * @return (Bool) true or false if there was collision
 */
EHDI.CollisionUtil.circleToRect = function( cir, rect ){

	var distX = Math.abs( cir.x - rect.x - ( rect.width * 0.5 ) );
    var distY = Math.abs( cir.y - rect.y - ( rect.height * 0.5 ) );

    if( distX > ( ( rect.width * 0.5 ) + cir.r ) ) return false;
    if( distY > ( ( rect.height * 0.5 ) + cir.r ) ) return false;

    if( distX <= ( rect.width * 0.5 ) ) return true;
    if( distY <= ( rect.height * 0.5 ) ) return true;

    var dx = distX - ( rect.width * 0.5 );
    var dy = distY - ( rect.height * 0.5 );
	
    return ( dx * dx + dy * dy <= ( cir.r * cir.r ) );
}

/**
 * @param (Object) cir1 - 1st circle that contains: {x, y, r}
 * @param (Object) cir2 - 2nd circle that contains: {x, y, r}
 * @return (Bool) true or false if there was collision
 */
EHDI.CollisionUtil.circleToCircle = function( cir1, cir2 ){

	var dx = cir1.x - cir2.x;
	var dy = cir1.y - cir2.y;
	var distance = Math.sqrt(dx * dx + dy * dy);

	if (distance < cir1.r + cir2.r) {
		return true;
	}
	
	return false;
}
//GET OR INITIALIZE EHDI
var EHDI = EHDI || Object.create(null);

EHDI.NumberUtil = EHDI.NumberUtil || Object.create(null);

//PROPERTIES
EHDI.NumberUtil.GOLDEN_RATIO = 1.61803398875;

//METHODS
/**
 * @param (Number) val - the value in degrees
 * @return (Number) val - the value in radians
 */
EHDI.NumberUtil.degreeToRadian = function(val){
	return (val * (Math.PI / 180));
}

/**
 * @param (Number) val - the value in radians
 * @return (Number) val - the value in degrees
 */
EHDI.NumberUtil.radianToDegree = function(val){
	return (val * (180/ Math.PI));
}

/**
 * @param (Number) val - interpolation value
 * @param (Number) min
 * @param (Number) max
 * @return interpolate the val
 */
EHDI.NumberUtil.lerp = function(val, min, max){
	return (1 - val) * min + val * max;
}

/**
 * @param (Number) val - the value that needs to be normalize
 * @param (Number) min
 * @param (Number) max
 * @return normalize the val
 */
EHDI.NumberUtil.normalize = function(val, min, max){
	return (val - min) / (max - min);
}

/**
 * @param (Number) val - the value that needs to be map
 * @param (Number) minX - val min
 * @param (Number) maxX - val max
 * @param (Number) minY - result min 
 * @param (Number) maxY - result max
 * @param (Boolean) strict - set to true to lock val to minY and maxY
 * @return returns map val
 */
 EHDI.NumberUtil.map = function(val, minX, maxX, minY, maxY, strict){
	var strict = (typeof strict !== 'undefined') ? strict : false;
	if(!!strict){
		if(val > minX) return minY;
		if(val < maxX) return maxY;
	}
	return NumberUtil.lerp( NumberUtil.normalize(val, minX, maxX), minY, maxY );
 }

/**
 * @param (Number) val - the value that needs to be clamp
 * @param (Number) min
 * @param (Number) max
 * @return lock the val on min/max
 */
EHDI.NumberUtil.clamp = function(val, min, max) {
	return Math.max(min, Math.min(max, val));
}	

/**
 * @param (Number) min
 * @param (Number) max
 * @return generate a random number from min to max
 */
EHDI.NumberUtil.randomRange = function(min, max){
	if(min > max){
		return (Math.random() * (min - max) + max);
	}else{
		return (Math.random() * (max - min) + min);
	}
}

/**
 * @param (Number) num
 * @return get number of digit of a non-floating number
 */
EHDI.NumberUtil.getDigit = function(num){
	return num.toString().length;
}

/**
 * @param (ARRAY) myArray
 * @return a shuffled array
 */
EHDI.NumberUtil.shuffleArray = function(myArray) {
    var swap = function(arr, i, j) {
        var temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    };
    
    var randInt = function(max) {
        return Math.floor(Math.random() * max);
    };
    
    for(var slot = myArray.length - 1; slot > 0; slot--) {
        var element = randInt(slot + 1);
        swap(myArray, element, slot);
    } 
}
/* Based on Stress Test function by Mat Groves*/

EHDI = EHDI || Object.create(null);

EHDI.StressTest = function(callback) {
    var _callback = callback;
    
    var _stage = new PIXI.Container();
    
    var _stressCanvas = document.createElement('canvas');
    _stressCanvas.width =  _stressCanvas.height = "500px";
    document.body.appendChild(_stressCanvas);
    
     var rendererOptions = {
        view: _stressCanvas,
        antialiasing: false,
        transparent: true,
        resolution: window.devicePixelRatio,
        autoResize: true
    };
	
    var _renderer = new EHDI.aka.AutoDetectRenderer(500, 500, rendererOptions);
    _renderer.view.style.position = "absolute";
    
    var _cover = document.createElement("div");
    _cover.style.width = _cover.style.height = "500px";
    _cover.style.background = "#FFFFFF";
    document.body.appendChild(_cover);
    _cover.style.position = "absolute";
    _cover.style.zIndex = 2;
    
    var _this = this;
    
    var _frameRate = [];
    var _testSprites = [];
    
    var _startTime, _lastTime, _texture;
    
    this.update = function() {
        var curTime = Date.now();
        for(var i=0; i < _testSprites.length; i++) {
            _testSprites[i].rotation += 0.3;
        }
        _renderer.render(_stage);
        
        var diff = curTime - _lastTime;
        diff *= 0.6;
        _frameRate.push(diff);
        _lastTime = curTime;
        var elapsedTime = curTime - _startTime;
        if(elapsedTime < 1500) {
            window.requestAnimationFrame(function() {
                _this.update();
            })
        } else {
            document.body.removeChild(_renderer.view);
            document.body.removeChild(_cover);
            var result = _frameRate.length / 1.5;
            EHDI.BrowserInfo = EHDI.BrowserInfo || Object.create(null);
            EHDI.BrowserInfo.isLowEndDevice = result < 30;
            if(_callback)
                _callback();
        }
    }
    
    this.begin = function() {
        _texture = EHDI.displays.TextureRectangle(0xFFFFFF, 52, 74);
        for(var i = 0; i < 300; i++) {
            var sprite = new PIXI.Sprite(_texture);
            sprite.anchor.set(0.5, 0.5);
            _stage.addChild(sprite);
            sprite.position.set(50, + Math.random() * 400, 50 + Math.random() * 400);
            _testSprites.push(sprite);
        };
        _startTime = Date.now();
        _lastTime = Date.now();
        _renderer.render(_stage);
        _this.update();
    }
    _this.begin();
    return _this;
}

"use strict";
var APP = (function () {

    // Properties
    var _result = Object.create( null );
    var  _config, _display, _game, _managers, _popups, _save, _scenes, _ui;

    Object.defineProperties( _result, {
        "config": {
            get: function () { return _config; },
            set: function ( p_val ) { if ( !_config ) _config = p_val; },
            enumerable: true
        },
        "display": {
            get: function () { return _display; },
            set: function ( p_val ) { if ( !_display ) _display = p_val; },
            enumerable: true
        },
        "game": {
            get: function () { return _game; },
            set: function ( p_val ) { if ( !_game ) _game = p_val; },
            enumerable: true
        },
        "managers": {
            get: function () { return _managers; },
            set: function ( p_val ) { if ( !_managers ) _managers = p_val; },
            enumerable: true
        },
        "popups": {
            get: function () { return _popups; },
            set: function ( p_val ) { if ( !_popups ) _popups = p_val; },
            enumerable: true
        },
        "save": {
            get: function () { return _save; },
            set: function ( p_val ) { _save = p_val; },
            enumerable: true
        },
        "scenes": {
            get: function () { return _scenes; },
            set: function ( p_val ) { if ( !_scenes ) _scenes = p_val; },
            enumerable: true
        },
        "ui": {
            get: function () { return _ui; },
            set: function ( p_val ) { if ( !_ui ) _ui = p_val; },
            enumerable: true
        },
    });

    return _result;

})();

APP.config = (function (){

    // Properties
    var _result = Object.create( null );

    Object.defineProperties( _result, {
        "debugEnabled": {
            enumerable: true,
            writable: true,
            value: false
        },
        "id": {
            enumerable: true,
            writable: false,
            value: gameId//"13062761"
        },
        "language": {
            enumerable: true,
            writable: false,
            value: "en"
        },
        "maxListeners": {
            enumerable: true,
            writable: false,
            value: 100
        },
        "stageWidth": {
            enumerable: true,
            writable: false,
            value: 1024
        },
        "stageHeight": {
            enumerable: true,
            writable: false,
            value: 600
        },
        "version": {
            enumerable: true,
            writable: true
        }
    });
    
    return _result;
})();

APP.display = (function (){

    // Properties
    var _result = Object.create( null );
    var _canvas, _stage, _renderer;

    Object.defineProperties( _result, {
        "canvas": {
            get: function () { return _canvas; },
            set: function ( p_val ) { if ( _canvas != p_val ) _canvas = p_val; },
            enumerable: true
        },
        "renderer": {
            get: function () { return _renderer; },
            set: function ( p_val ) { if ( _renderer != p_val ) _renderer = p_val; },
            enumerable: true
        },
        "stage": {
            get: function () { return _stage; },
            set: function ( p_val ) { if ( _stage != p_val ) _stage = p_val; },
            enumerable: true
        },
    });
    
    return _result;

})();

APP.game = (function (){

    // Properties
    var _result = Object.create( null );
    var _animal, _cage, _level, _btnPause;

    Object.defineProperties( _result, {
        "debugEnabled": {
            enumerable: true,
            writable: false,
            value: false
        },
        "btnPause": {
            get: function () { return _btnPause; },
            set: function ( p_val ) { if ( _btnPause !== p_val ) _btnPause = p_val; },
            enumerable: true
        },
        "AnimalConfig": {
            enumerable: true,
            writable: false,
            value: {
                MIN_DELTA_AI: 3,
                MAX_DELTA_AI: 10,
                MIN_MOVE_SPEED: 2,
                MAX_MOVE_SPEED: 5
            }
        },
        "AnimalObject": {
            get: function () { return _animal; },
            set: function ( p_val ) { if ( !_animal ) _animal = p_val; },
            enumerable: true
        },
        "AnimalEvent": {
            enumerable: true,
            writable: false,
            value: {
                DRAG_START: "animalEvt_dragStart",
                DRAG_END: "animalEvt_dragEnd",
                MOVING: "animalEvt_moving",
                UPDATED_STATE: "animalEvt_updatedState"
            }
        },
        "AnimalState": {
            enumerable: true,
            writable: false,
            value: {
                IDLE: 1,
                MOVE: 2
            }
        },
        "AnimalType": {
            enumerable: true,
            writable: false,
            value: {
                GOAT: 1,
                SHEEP: 2,
                LION: 3
            }
        },
        "CageObject": {
            get: function () { return _cage; },
            set: function ( p_val ) { if ( !_cage ) _cage = p_val; },
            enumerable: true
        },
        "LevelConfig": {
            enumerable: true,
            writable: false,
            value: {
                GAME_TIME: 90,
                RATINGS: [ 500, 1000, 1500 ]
            }
        },
        "LevelObject": {
            get: function () { return _level; },
            set: function ( p_val ) { if ( !_level ) _level = p_val; },
            enumerable: true
        },
        "LevelEvent": {
            enumerable: true,
            writable: false,
            value: {
                START: "levelEvt_start",
                END: "levelEvt_end",
                UPDATED_SCORE: "levelEvt_updatedScore"
            }
        },
    });

    // Return result
    return _result;

})();

APP.managers = (function (){

    // Properties
    var _result = Object.create( null );
    var _event, _json, _load, _scale, _scene, _sound, _storage, _update;

    Object.defineProperties( _result, {
        "event": {
            get: function () { return _event; },
            set: function ( p_val ) { if ( !_event ) _event = p_val; },
            enumerable: true
        },
        "json": {
            get: function () { return _json; },
            set: function ( p_val ) { if ( !_json ) _json = p_val; },
            enumerable: true
        },
        "load": {
            get: function () { return _load; },
            set: function ( p_val ) { if ( !_load ) _load = p_val; },
            enumerable: true
        },
        "scale": {
            get: function () { return _scale; },
            set: function ( p_val ) { if ( !_scale ) _scale = p_val; },
            enumerable: true
        },
        "scene": {
            get: function () { return _scene; },
            set: function ( p_val ) { if ( !_scene ) _scene = p_val; },
            enumerable: true
        },
        "sound": {
            get: function () { return _sound; },
            set: function ( p_val ) { if ( !_sound ) _sound = p_val; },
            enumerable: true
        },
        "storage": {
            get: function () { return _storage; },
            set: function ( p_val ) { if ( !_storage ) _storage = p_val; },
            enumerable: true
        },
        "update": {
            get: function () { return _update; },
            set: function ( p_val ) { if ( !_update ) _update = p_val; },
            enumerable: true
        },
    });

    return _result;
})();

APP.popups = (function (){

    // Properties
    var _result = Object.create( null );
    var _confirmation, _pause, _end;

    Object.defineProperties( _result, {
        "ConfirmationPopup": {
            get: function () { return _confirmation; },
            set: function ( p_val ) { if ( !_confirmation ) _confirmation = p_val; },
            enumerable: true
        },
        "PausePopup": {
            get: function () { return _pause; },
            set: function ( p_val ) { if ( !_pause ) _pause = p_val; },
            enumerable: true
        },
        "EndPopup": {
            get: function () { return _end; },
            set: function ( p_val ) { if ( !_end ) _end = p_val; },
            enumerable: true
        },
    });

    // Return
    return _result;

})();

APP.scenes = (function (){

    // Properties
    var _result = Object.create( null );
    var _preloader, _title, _game;

    Object.defineProperties( _result, {
        "PreloaderScene": {
            get: function () { return _preloader; },
            set: function ( p_val ) { if ( !_preloader ) _preloader = p_val; },
            enumerable: true
        },
        "TitleScene": {
            get: function () { return _title; },
            set: function ( p_val ) { if ( !_title ) _title = p_val; },
            enumerable: true
        },
        "GameScene": {
            get: function () { return _game; },
            set: function ( p_val ) { if ( !_game ) _game = p_val; },
            enumerable: true
        }
    });

    // Return
    return _result;

})();

APP.ui = (function (){

    // Properties
    var _result = Object.create( null );
    var _score, _timer;

     Object.defineProperties( _result, {
        "ScoreUI": {
            get: function () { return _score; },
            set: function ( p_val ) { if ( !_score ) _score = p_val; },
            enumerable: true
        },
        "ScoreType": {
            enumerable: true,
            writable: false,
            value: {
                HIGHSCORE: 1,
                SCORE: 2
            }
        },
        "TimerUI": {
            get: function () { return _timer; },
            set: function ( p_val ) { if ( !_timer ) _timer = p_val; },
            enumerable: true
        },
        "TimerType": {
            enumerable: true,
            writable: false,
            value: {
                COUNTDOWN: 1,
                COUNTUP: 2
            }
        },
    });

    // Return
    return _result;

})();
"use strict";


// Create Main Module and scenes if not yet initialized
var Main = Main || Object.create( null );

// Main onResize function
Main.onResize = function () {
    // Get vendor game element
    var _vendorGameElement = Main.SB.getVendorGameElement();

    // Initialize needed values
    var _width = APP.managers.scene.defaultWidth,
    _height = APP.managers.scene.defaultHeight,
    _scaleX = _vendorGameElement.offsetWidth / APP.managers.scene.defaultWidth,
    _scaleY = _vendorGameElement.offsetHeight / APP.managers.scene.defaultHeight,
    _ratio = Math.min( _scaleX, _scaleY );

    // Compute width and height
    _width = Math.ceil( _width * _ratio );
    _height = Math.ceil( _height * _ratio );

    // Set stage scale
    APP.display.stage.scale.x = APP.display.stage.scale.y = _ratio;

    // Resize renderer
    APP.display.renderer.resize( _width, _height );

    // Set canvas properties
    APP.display.canvas.style.paddingLeft = 0;
    APP.display.canvas.style.paddingRight = 0;
    APP.display.canvas.style.paddingTop = 0;
    APP.display.canvas.style.paddingBottom = 0;
    APP.display.canvas.style.display = "block";
    APP.display.canvas.style.position = "absolute";
    APP.display.canvas.style.top = 0;
    APP.display.canvas.style.left = 0;
    APP.display.canvas.style.right = 0;
    APP.display.canvas.style.bottom = 0;

    // Adjust margins according to the following
    var _margin;
    if( _width < _vendorGameElement.offsetWidth ) {

        // Compute margin
        _margin = ( _vendorGameElement.offsetWidth - _width ) / 2;

        // Set left and right margins
        APP.display.canvas.style.left = _margin + "px";
        APP.display.canvas.style.right = _margin + "px";
    }

    if ( _height < _vendorGameElement.offsetHeight ) {

        // Compute margin
        _margin = ( _vendorGameElement.offsetHeight - _height ) / 2;

        // Set top and bottom margins
        APP.display.canvas.style.top = _margin + "px";
        APP.display.canvas.style.bottom = _margin + "px";
    }

    // Scroll to 0, 0
    window.scrollTo( 0, 0 );
};

// Main onInit function
Main.onInit = function () {

    // Initialize scene manager instance
    APP.managers.scene = EHDI.SceneManager( APP.config.stageWidth, APP.config.stageHeight );

    // Initialize display values for renderer and stage
    APP.display.renderer = APP.managers.scene.getRenderer();
    APP.display.stage = APP.managers.scene.getStage();
    APP.display.canvas = APP.display.renderer.view;

    // Initialize event manager
    APP.managers.event = EHDI.EventManager();
    APP.managers.event.maxListeners = APP.config.maxListeners;

    // Initialize load manager
    APP.managers.load = EHDI.LoadManager;

    // Initialize sound manager
    APP.managers.sound = EHDI.SoundManager( true );

    // Initialize storage manager
    APP.managers.storage = EHDI.StorageManager();

    // Initialize update manager
    APP.managers.update = EHDI.UpdateManager( APP.display.renderer, APP.display.stage );

    // Get save data and store to SB reference
    APP.save = APP.managers.storage.getLocalInfo( APP.config.id ) || { isMuted : false, isFirstTimePlay : true, highscore: 0 };
    if ( typeof APP.save.highscore === "undefined" ) APP.save.highscore = 0;
    APP.managers.storage.setLocalInfo( APP.config.id, APP.save );

    // Set sound manager default mute state
    APP.managers.sound.setMute( APP.save.isMuted );

    // Set resize callback to Superbook instance
    Main.SB.resizeCallback = Main.onResize;

    // Call resize callback
    Main.onResize();

    // Set debug version
    APP.config.debugEnabled = true;

    // Set game version
    APP.config.version = "v.0.2.3";

    // Initialize scale manager -- Disabled for Superbook
    /* APP.managers.scale = EHDI.ScaleManager( APP.display.renderer, APP.display.stage,
                                            EHDI.ScaleManager.DOCKING.AUTO, APP.config.stageWidth, APP.config.stageWidth );
    Main.scaleManager.addAutomaticScaling(); */

    // Initialize preloaded assets
    // APP.managers.load.queueStrings( AssetDirectory.strings );
    // APP.managers.load.queueStrings( AssetDirectory.preloader_strings );
    // APP.managers.load.queueFonts( AssetDirectory.fonts );
    // APP.managers.load.queueImages( AssetDirectory.preloader_ui );
    APP.managers.load.queueAssets(AssetDirectory.preload);

    // APP.managers.load.start( function () {

    //     var promises = [];

    //             this.fontObserve = [];
    //             for(var i = 0; i < EHDI.Assets.fonts.length;i++){
    //                 this.fontObserve[i] = new FontFaceObserver(EHDI.Assets.fonts[i]);
    //                 promises.push(this.fontObserve[i].load());
    //             }
    //             Promise.all( promises )
    //                 .then( function() {

    //                     // Change to preloader
    //                     APP.managers.scene.changeScene(new APP.scenes.PreloaderScene() );

    //                     // Call resize callback
    //                     Main.onResize();
    //             })


    // } );



                var promises = [];

                        this.fontObserve = [];
                        for(var i = 0; i < EHDI.Assets.fonts.length;i++){
                            this.fontObserve[i] = new FontFaceObserver(EHDI.Assets.fonts[i]);
                            promises.push(this.fontObserve[i].load(null,8000));
                        }
                        Promise.all( promises )
                            .then( function() {

                                //Load SB DATA
                                Main.SB.loadGameData(undefined,
                                    //LOAD DATA SUCCESS
                                    function(data){
                                        APP.SBData = data || {highScore: 0, isFirstTimePlay: true};
                                        APP.managers.load.start(function(){
                                            APP.managers.scene.changeScene(new APP.scenes.PreloaderScene() )
                                        });
                                    },
                                    //LOAD DATA FAILED
                                    function(){
                                        APP.SBData = {highScore: 0, isFirstTimePlay: true};
                                        APP.managers.load.start(function(){
                                            APP.managers.scene.changeScene(new APP.scenes.PreloaderScene() )
                                        });
                                    }
                                )
                                // Change to preloader
                                // Call resize callback
                                Main.onResize();
                        })

};

// Main onLoad function
Main.onLoad = function () {

    // Initialize Superbook Game instance
    Main.SB = new SuperbookGame( APP.config.id, "state", Main.onInit );
    Main.SB.renderGameArea();
    // Get vendor game element from Superbook game instance
    var _vendorGameElement = Main.SB.getVendorGameElement();

    // Set canvas to Main
    Main.canvas = document.createElement( "canvas" );
    Main.canvas.id = "game-canvas";
    Main.canvas.width = _vendorGameElement.style.width;
    Main.canvas.height = _vendorGameElement.style.height;
    _vendorGameElement.appendChild( Main.canvas );

    // Start Superbook instance
    Main.SB.start();
};

// Prevent default on window touch move
/*
document.ontouchmove = function (e) {
    e.preventDefault();
    window.scrollTo(0, 0);
};
*/

// Set on load function
window.onload = Main.onLoad;

var AssetDirectory = {
	"load": [
		"assets/bgm/bgm.ogg",
		"assets/game/fx_firsttimeplay_glow.png",
		"assets/game/fx_sparkle_ske.json",
		"assets/game/fx_sparkle_tex.json",
		"assets/game/fx_sparkle_tex.png",
		"assets/game/goat_anim_ske.json",
		"assets/game/goat_anim_tex.json",
		"assets/game/goat_anim_tex.png",
		"assets/game/gs_prop1.png",
		"assets/game/gs_prop2.png",
		"assets/game/gs_prop3.png",
		"assets/game/gs_prop4.png",
		"assets/game/gs_prop5.png",
		"assets/game/gs_prop6.png",
		"assets/game/gs_prop7.png",
		"assets/game/gs_prop8.png",
		"assets/game/img_fence_back.png",
		"assets/game/img_fence_front.png",
		"assets/game/img_game_bg.png",
		"assets/game/img_ground_overlay.png",
		"assets/game/img_sign_1.png",
		"assets/game/img_sign_2.png",
		"assets/game/lion_anim_ske.json",
		"assets/game/lion_anim_tex.json",
		"assets/game/lion_anim_tex.png",
		"assets/game/sheep_anim_ske.json",
		"assets/game/sheep_anim_tex.json",
		"assets/game/sheep_anim_tex.png",
		"assets/sfx/animal_pickup.ogg",
		"assets/sfx/button_sfx.ogg",
		"assets/sfx/goat.ogg",
		"assets/sfx/lamb.ogg",
		"assets/sfx/score_points.ogg",
		"assets/sfx/star_gain.ogg",
		"assets/title/img_title_bg.png",
		"assets/title/img_title_gizmo.png",
		"assets/title/img_title_logo.png",
		"assets/ui/btn_audio1.png",
		"assets/ui/btn_audio2.png",
		"assets/ui/btn_audio3.png",
		"assets/ui/btn_audio4.png",
		"assets/ui/btn_exit.png",
		"assets/ui/btn_exit2.png",
		"assets/ui/btn_pause.png",
		"assets/ui/btn_pause2.png",
		"assets/ui/btn_play.png",
		"assets/ui/btn_play2.png",
		"assets/ui/btn_prevnext.png",
		"assets/ui/btn_prevnext2.png",
		"assets/ui/btn_return.png",
		"assets/ui/btn_return2.png",
		"assets/ui/check-button1.png",
		"assets/ui/check-button2.png",
		"assets/ui/gfx_container.png",
		"assets/ui/gfx_container_white.png",
		"assets/ui/gfx_explode.png",
		"assets/ui/gfx_flare_long.png",
		"assets/ui/gfx_flare_star.png",
		"assets/ui/gfx_pop.png",
		"assets/ui/gfx_pop2.png",
		"assets/ui/gfx_star0.png",
		"assets/ui/gfx_star1.png",
		"assets/ui/gfx_starBG.png",
		"assets/ui/htp_separate1.png",
		"assets/ui/htp_separate2.png",
		"assets/ui/htp_separate3.png",
		"assets/ui/htp_separate4.png",
		"assets/ui/htp_separate5.png",
		"assets/ui/htp_separate6.png",
		"assets/ui/htp_separate7.png",
		"assets/ui/x-button1.png",
		"assets/ui/x-button2.png"
	],
	"preload": [
		"assets/preloader_strings/GizmoLoading_ske.json",
		"assets/preloader_strings/GizmoLoading_tex.json",
		"assets/preloader_strings/strings.json",
		"assets/preloader_ui/gfx_bg.png",
		"assets/preloader_ui/gfx_loading.png",
		"assets/preloader_ui/gfx_loading_bar_con.png",
		"assets/preloader_ui/GizmoLoading_tex.png",
		"assets/preload_fonts/exo-bold.ttf",
		"assets/preload_fonts/exo-medium.ttf",
		"assets/preload_fonts/proximanova-black.ttf"
	],
	"preloadstring": [
		"assets/strings/config.json"
	]
};
var EHDI = EHDI || Object.create(null);

EHDI.displays = EHDI.displays || Object.create(null);

EHDI.displays.FillRectangle = function(color, x, y, width, height) {
    var alpha = arguments.length <= 4 || typeof arguments[5] == "undefined" ? 1 : arguments[5]; 
    
    var graphics = new PIXI.Graphics();
    graphics._sprite = null;
    graphics._width = width;
    graphics._height = height;
    graphics._color = color;
    
    var draw = function(width, height, fillStyle) {
        graphics.clear();
        graphics.beginFill(fillStyle);
        graphics.drawRect(0,0,width, height);
        graphics.endFill();
    };
    
    draw(graphics._width, graphics._height, graphics._color);
    
    var texture = graphics.generateCanvasTexture(1);
    
    var sprite = new EHDI.aka.Sprite(texture);
    
    sprite.position.set(x,y);
    sprite.alpha = alpha;
    
    graphics.sprite = sprite;
    return sprite;
};

EHDI.displays.changeRectangleColor = function(color, width, height) {
    var alpha = arguments.length <= 4 || typeof arguments[5] == "undefined" ? 1 : arguments[5]; 
    
    var graphics = new PIXI.Graphics();
    graphics._sprite = null;
    graphics._width = width;
    graphics._height = height;
    graphics._color = color;
    
    var draw = function(width, height, fillStyle) {
        graphics.clear();
        graphics.beginFill(fillStyle);
        graphics.drawRect(0,0,width, height);
        graphics.endFill();
    };
    
    draw(graphics._width, graphics._height, graphics._color);
    
    var texture = graphics.generateCanvasTexture(1);
    return texture;
}




var EHDI = EHDI || Object.create(null);

EHDI.components = EHDI.components || Object.create(null);

EHDI.components.PauseButton = function() {
    EHDI.displays.Button.call(this, EHDI.Assets.images["btn_pause"], EHDI.Assets.images["btn_pause2"], null, null);

    this.isPaused = false;
    this.isEndGame = false;
    
    // APP.managers.sound.autoResumeToggle(false);
    
    this.setOnClickFunction(this.sfxThenPause.bind(this));
    
    this.position.set(APP.config.stageWidth * 0.95, APP.config.stageHeight * 0.075);
    
    APP.game.btnPause = this;

    this.pauseTheGame = APP.game.btnPause.pauseGame.bind(APP.game.btnPause).bind(APP.game.btnPause);
    this.checkIfInterrupt = APP.game.btnPause.checkInterrupt.bind(APP.game.btnPause);
    
    window.addEventListener("blur", this.pauseTheGame);
    window.addEventListener("pagehide", this.pauseTheGame);
    window.addEventListener("webkitvisibilitychange", this.checkIfInterrupt);
    window.addEventListener("visibilitychange", this.checkIfInterrupt);
    
};

EHDI.components.PauseButton.prototype = Object.create(EHDI.displays.Button.prototype);

EHDI.components.PauseButton.prototype.sfxThenPause = function() {
    APP.managers.sound.playSFX("button_sfx");
    this.pauseGame();
}

EHDI.components.PauseButton.prototype.checkInterrupt = function() {
    if (window.document.webkitHidden || window.document.hidden) {
			this.pauseGame();
    }
};

EHDI.components.PauseButton.prototype.pauseGame = function() {
    if(this.isPaused || this.isEndGame)
        return;
    this.isPaused = true;
    APP.managers.scene.pushPopUp(new APP.popups.PausePopup( true ), { y : new EHDI.scene.TransitionParameter(-APP.config.stageHeight, APP.config.stageHeight * 0.5), duration : 0.25});
}; 

EHDI.components.PauseButton.prototype.resumeGame = function() {
    this.isPaused = false;
};

EHDI.components.PauseButton.prototype.endGame = function() {
    this.isEndGame = true;
//    this.hidePauseButton();
    window.removeEventListener("blur", this.pauseTheGame);
    window.removeEventListener("pagehide", this.pauseTheGame);
    window.removeEventListener("webkitvisibilitychange", this.checkIfInterrupt);
    window.removeEventListener("visibilitychange", this.checkIfInterrupt);
};

EHDI.components.PauseButton.prototype.destroy = function() {
    // APP.managers.sound.autoResumeToggle(true);
	EHDI.aka.Sprite.prototype.destroy.apply(this, arguments);
}

EHDI.components.PauseButton.prototype.hidePauseButton = function() {
    TweenLite.to(this, 0.25, {y : -this.y});
};
"use strict";
APP.game.AnimalObject = function ( p_type, p_objLevel ) {

    // Invoke (needed)
    EHDI.aka.Container.call( this );

    // Properties

    var HOLD_LIMIT = 2;


    // ** Parent (This reference)
    var _parent = this;

    // ** Level Reference
    var _objLevel;

    // ** General Values
    var _deltaAI, _direction, _initialPos, _isCaged, _isCageCorrect, _isDraggable, _isDragging, _isPaused, _state, _prevTouch, _type;

    // ** Graphics
    var _sprAnimal, _timelineMove, _isHidden, _isProwling, _hideTimer, _prowlPhase, _isScared, _finalXDest, _isExitingCage;
    var _animalSpeed = APP.config.stageWidth / 20;
    var LION_VISION = 250;
    var DOUBLE_CLICK_TIMEOUT = 250;
    var _clickCounter;

    // Private Methods

    // ** General Methods

    /**
     * Get position limits.
     */
    var _getPositionLimits = function () {

        var result;

        if ( _parent ) {

            result = {
                minX: ( _parent.width * 0.5 ),
                maxX: APP.config.stageWidth - ( _parent.width * 0.5 ),
                minY: _parent.height + 175,
                maxY: APP.config.stageHeight,
            };
        }

        return result;
    };

    /**
     * Set direction.
     * @param {*Number} p_value The new direction
     */
    var _setDirection = function ( p_value ) {

        if ( p_value !== -1 &&
            p_value !== 1 ) throw "Invalid value for direction." + p_value;
        
        _direction = p_value;
        
        // Set scale x accoring to direction
        if ( _sprAnimal ) _sprAnimal.scale.x = _direction;
    };

    // Randomize delta ai
    var _randomizeDeltaAI = function () {

        _deltaAI = Math.round( EHDI.NumberUtil.randomRange( APP.game.AnimalConfig.MIN_DELTA_AI, APP.game.AnimalConfig.MAX_DELTA_AI ) ) * 1000;
    };

    var _randomizeDuration = function () {

        var result = Math.round( EHDI.NumberUtil.randomRange( APP.game.AnimalConfig.MIN_MOVE_SPEED, APP.game.AnimalConfig.MAX_MOVE_SPEED ) );

        return result;
    }

    var _addMove = function (  p_posX, p_posY, p_callback, p_startMove, p_duration ) {

        if ( !_timelineMove ) _timelineMove = new TimelineMax();

        // Get limits
        var limits = _getPositionLimits();
        
        // Constrain to limits
        var posX = EHDI.NumberUtil.clamp( p_posX, limits.minX, limits.maxX );
        var posY = EHDI.NumberUtil.clamp( p_posY, limits.minY, limits.maxY );

        var duration = p_duration|| _randomizeDuration();
       
        // Add to timeline
        _timelineMove.to( _parent,  duration, 
            { 
                x: posX, 
                y: posY, 
                onStart: function () {

                     // Check if to change directions
                    if ( posX > _parent.x && _direction === -1 ) _setDirection( 1 );
                    else if ( posX < _parent.x && _direction === 1 ) _setDirection( -1 );
                    else if ( posX == _parent.x ) _setDirection( _direction );
                
                },
                onComplete: function () {

                    if ( p_callback ) p_callback();

                }, ease:Power0.easeNone
            } );

        if ( p_startMove === true ) _timelineMove.play();
    };

    var _setState = function ( p_state ) {

        // Check if values are the same, then return
        if ( _state === p_state ) return;

        // Set state
        _state = p_state;

        // Do according to state
        switch ( _state ) {

            case APP.game.AnimalState.IDLE:
            if(Math.random() < 0.8)
                {
                _parent.armature.animation.gotoAndPlay(_parent.animList[0], -1, -1, 0);
                var randomizedTime = Math.floor(Math.random()* 1000);
                _parent.armature.advanceTime(randomizedTime);
                }
            else
                _parent.armature.animation.gotoAndPlay(_parent.animList[3], -1, -1, 0);

                // Remove move tweens here
                if ( _timelineMove ) {
                    _timelineMove.stop();
                    _timelineMove.kill();
                }
                _timelineMove = null;
                _isScared = false;
                

                // Randomize delta AI
                _randomizeDeltaAI();

            break;

            case APP.game.AnimalState.MOVE: 
            if(_type !== APP.game.AnimalType.LION) 
                {
                    if(_isScared)    
                        _parent.armature.animation.gotoAndPlay(_parent.animList[4], -1, -1, 0);
                    else
                        _parent.armature.animation.gotoAndPlay(_parent.animList[1], -1, -1, 0);
                }
            else
                {
                    _parent.armature.animation.gotoAndPlay(_parent.animList[0], -1, -1, 0);
                }

                // Check if tweens are active, then throw error
                if ( _timelineMove ) throw "Tween is active when state is set to MOVE.";

                if (_type !== APP.game.AnimalType.LION ) 
                {


                    // Initialize values
                    var spawnArea = null;
                    var randSpawn = null;
                    


                        // Do according to isCaged
                        if ( _isCaged === true ) {
                            _isExitingCage = true;
                            // Add move to exit
                            _addMove( APP.config.stageWidth * 0.5, 
                                    _parent.y );

                            // Add move to spawn
                            // ** Set position to random spawn
                            // ** Get random spawn area
                            // randSpawn = Math.round( EHDI.NumberUtil.randomRange( 1, 2 ) );
                            // if ( randSpawn === 1 ) spawnArea = _objLevel.spawnBottom;
                            // else if ( randSpawn === 2 ) spawnArea = _objLevel.spawnTop;

                            spawnArea = _objLevel.spawnBottom;

                            // **Randomize position ( y-only )
                            _addMove( APP.config.stageWidth * 0.5, 
                                        EHDI.NumberUtil.randomRange( spawnArea.y, spawnArea.y + spawnArea.height ),
                                        function()
                                        {
                                            _isExitingCage = false;
                                        }
                                     );
                            
                            // Add move within spawn area
                            _addMove( EHDI.NumberUtil.randomRange( spawnArea.x, spawnArea.x + spawnArea.width ),
                                        EHDI.NumberUtil.randomRange( spawnArea.y, spawnArea.y + spawnArea.height ), 
                                        function () {
                                            // Set state to idle
                                            _setState( APP.game.AnimalState.IDLE );
                                        }, true );
                            
                        }
                        else if ( _isCaged === false ) {

                            // Move in spawn area or go to spawn area
                            if ( _objLevel ) {

                                // // Initialize needed vaulues
                                // var boundsAnimal = _parent.getBounds();
                                // var boundsSpawnBottom = _objLevel.spawnBottom.getBounds();
                                // var boundsSpawnTop = _objLevel.spawnTop.getBounds();

                                // // If collides with top spawn, set spawn area to top
                                // // If collides with bottom spawn, set spawn area to bottom
                                // if ( EHDI.CollisionUtil.rectToRect( boundsSpawnTop, boundsAnimal ) ) spawnArea = _objLevel.spawnTop;
                                // else if ( EHDI.CollisionUtil.rectToRect( boundsSpawnBottom, boundsAnimal ) ) spawnArea = _objLevel.spawnBottom;
                                // else {
                                //     // ** Get random spawn area
                                //     randSpawn = Math.round( EHDI.NumberUtil.randomRange( 1, 2 ) );
                                //     if ( randSpawn === 1 ) spawnArea = _objLevel.spawnBottom;
                                //     else if ( randSpawn === 2 ) spawnArea = _objLevel.spawnTop;
                                // }


                                spawnArea = _objLevel.spawnBottom;

                                //c = square root of [(xA-xB)^2+(yA-yB)^2]

                                var xDest = EHDI.NumberUtil.randomRange( spawnArea.x, spawnArea.x + spawnArea.width );
                                var yDest = EHDI.NumberUtil.randomRange( spawnArea.y, spawnArea.y + spawnArea.height );

                                var xDistSquared = Math.pow((_parent.x - xDest), 2);
                                var yDistSquared = Math.pow((_parent.y - yDest), 2);
                                var travelDist = Math.sqrt(xDistSquared + yDistSquared);

                                var speed= _animalSpeed;
                                if(_isScared)
                                    speed *= 9;
                                var duration = Math.abs(travelDist) / speed;
                                // Move
                                _addMove( xDest,
                                            yDest,
                                            function () { 
                                                _setState( APP.game.AnimalState.IDLE );
                                            }, true , duration);
                            
                            }
                        }
                }
            break;

            default:

                // Do nothing
        }
        
        // Dispatch event
        APP.managers.event.dispatch( APP.game.AnimalEvent.UPDATED_STATE, { obj: _parent } );
    };

    var _updateAI = function ( p_delta ) {

        if ( _state !== APP.game.AnimalState.IDLE ) return;

        if ( _isDragging ) return;

        if ( typeof _deltaAI !== "number" ) return;
        
        if (_type === APP.game.AnimalType.LION ) return;

        _deltaAI -= p_delta;


        if (( _deltaAI > 0 )) return;

        _setState( APP.game.AnimalState.MOVE );

        _randomizeDeltaAI();
    };

    var detectLion = function()
    {
        
        // if ( _state !== APP.game.AnimalState.IDLE ) return;

        if ( _isDragging ) return;

        if ( typeof _deltaAI !== "number" ) return;
        
        if (_type === APP.game.AnimalType.LION ) return;
        if ((!APP.game.lion) || (_isScared)) return;

        if(_isExitingCage) return;       

        var lionNear = false;
        if(APP.game.lion.isProwling)
        {
            var xDistSquared = Math.pow((_parent.x - APP.game.lion.x), 2);
            var yDistSquared = Math.pow((_parent.y - APP.game.lion.y), 2);
            var lionDistance = Math.sqrt(xDistSquared + yDistSquared);

            if(lionDistance <= LION_VISION)
                {
                    lionNear = true;
                    _isScared = true;
                }
        }
        

        if (lionNear)
            {
                _setState(APP.game.AnimalState.IDLE );
                _setState( APP.game.AnimalState.MOVE );
                _randomizeDeltaAI();
            }

    }

    // ** Handlers

    /**
     * Handler for frame update
     * @param {Number} p_delta 
     */
    var _handler_frameUpdate = function ( p_delta ) {
        
        if ( APP.game.btnPause ) {

            if ( APP.game.btnPause.isPaused === true || 
                APP.game.btnPause.isEndGame === true ) return;
        }
        
        if(_type === APP.game.AnimalType.LION)
            {
                if((_isHidden) && (!_isProwling))
                    {
                        _hideTimer -= p_delta

                        if(_hideTimer <= 0)
                            prowl();
                    }

            }


        
        // Do according to state
        if ( _state === APP.game.AnimalState.IDLE ) {

            detectLion();
            // Update ai
            _updateAI( p_delta );
        }
        else if ( _state === APP.game.AnimalState.MOVE ) {

            // Dispatch event on MOVE
            APP.managers.event.dispatch( APP.game.AnimalEvent.MOVING, { obj: _parent } );
        }

        if(_clickCounter > 0)
            {
                _clickTimer -= p_delta;

                if(_clickTimer <= 0)
                    {
                        _clickCounter = 0;
                    }
            }
    };

    /**
     * Handler for touch begin interaction.
     * @param {Pixi.interaction.InteractionEvent} e  The event dispatched
     */
    var _handler_touchBegin = function (e) {
        // var _handler_touchBegin = function ( e ) {
        
        // // Check if event values are valid
        // if ( !e ) return;
        // if ( !e.data ) return;

        // If not draggable, return
        if ( _isDraggable === false ) return;

        // If already dragging, return
        if ( _isDragging === true ) return;

        // If parent is empty return
        if ( !_parent ) return;

        if(APP.game.TouchObjects.count >= HOLD_LIMIT)  return;
        
        var propName = "interactId_"+e.data.identifier;

        if(APP.game.TouchObjects[propName]) return;

        APP.game.TouchObjects[propName] = _parent; 
        APP.game.TouchObjects.count++

        // Set isDragging to true
        _isDragging = true;


        if(_type !== APP.game.AnimalType.LION)
            {
                // Set state to idle
                _setState( APP.game.AnimalState.IDLE );

                _parent.armature.animation.gotoAndPlay(_parent.animList[2], -1, -1, 0);
                APP.managers.sound.playSFX("animal_pickup");
                APP.game.cages[_type-1].glow();

            }

        // Set initial position
        _initialPos = { x: _parent.x, y: _parent.y };
 
        // Set mouse/touch event data
        _prevTouch = {
            identifier: e.data.identifier,
            x: e.data.global.x,
            y: e.data.global.y,
        };
        
        // Dispatch event
        APP.managers.event.dispatch( APP.game.AnimalEvent.DRAG_START, { obj: _parent } );

        if (_type !== APP.game.AnimalType.LION )
            {
        // Snap to center of object
        _parent.x = ( e.data.global.x / APP.display.stage.scale.x );
        _parent.y = ( e.data.global.y / APP.display.stage.scale.y ) + ( ( _parent.height * _parent.scale.y ) * 0.5 );
            }
    };

    /**
     * Handler for touch move interaction.
     * @param {Pixi.interaction.InteractionEvent} e  The event dispatched
     */
    var _handler_touchMove = function (e ) {
        // var _handler_touchMove = function ( e ) {
        
        // // Check if event values are valid
        // if ( !e ) return;
        // if ( !e.data ) return;

        // If not draggable, return
        if ( _isDraggable === false ) return;

        // If not dragging, return
        if ( _isDragging === false ) return;

        // If touch data is empty, return
        if ( !_prevTouch ) return;
        
        // If current touch id is not equal to prev touch id, return
        // if ( e.data.identifier !== _prevTouch.identifier ) return;

        // If parent is empty return
        if ( !_parent ) return;
        
        if(_type === APP.game.AnimalType.LION)  return;

        // Initialize some values
        var currentTouch = e.data;
        
        var diffX = ( currentTouch.global.x - _prevTouch.x ) / APP.display.stage.scale.x;
        var diffY = ( currentTouch.global.y - _prevTouch.y ) / APP.display.stage.scale.y;
        
        if ( diffX === 0 && diffY === 0 ) return;

        // Set prev position
        _prevTouch.x = currentTouch.global.x;
        _prevTouch.y = currentTouch.global.y;
        
        // Snap to center
        _parent.x = ( currentTouch.global.x / APP.display.stage.scale.x );
        _parent.y = ( currentTouch.global.y / APP.display.stage.scale.y ) + ( ( _parent.height * _parent.scale.y ) * 0.5 );
        
        // Get limits
        var limits = _getPositionLimits();

        _parent.x = EHDI.NumberUtil.clamp( _parent.x, limits.minX, limits.maxX );
        _parent.y = EHDI.NumberUtil.clamp( _parent.y, limits.minY, limits.maxY );
    };

     /**
     * Handler for touch end interaction.
     * @param {Pixi.interaction.InteractionEvent} e  The event dispatched
     */
    var _handler_touchEnd = function ( e ) {
        // var _handler_touchEnd = function ( e ) {
        
        // // Check if event values are valid
        // if ( !e ) return;
        // if ( !e.data ) return;

        // If not draggable, return
        if ( _isDraggable === false ) return;

        // If not dragging, return
        if ( _isDragging === false ) return;

        // If touch data is empty, return
        if ( !_prevTouch ) return;

        
        var propName = "interactId_"+e.data.identifier;

        if(APP.game.TouchObjects[propName] != _parent)
                return;
        
        APP.game.TouchObjects[propName] = null;  
        APP.game.TouchObjects.count--;

        // // If current touch id is not equal to prev touch id, return
        // if ( e.data.identifier !== _prevTouch.identifier ) return;

        // If parent is empty return
        if ( !_parent ) return;

        // Set isDragging to false
        _isDragging = false;

        // Nullify prev touch data
        _prevTouch = null;

        // Dispatch event
        APP.managers.event.dispatch( APP.game.AnimalEvent.DRAG_END, { obj: _parent } );

        // Nullify initial position
        _initialPos = null;

  

        if(_type !== APP.game.AnimalType.LION)
            {      
                // Set state to idle
                _setState(null);
                _setState( APP.game.AnimalState.IDLE );       
                
                APP.game.cages[_type-1].glowFade();
            }

        _clickCounter++;
        _clickTimer = DOUBLE_CLICK_TIMEOUT;

        if(_clickCounter >= 2)
            {                
                if(_type  === APP.game.AnimalType.LION)
                {
                    APP.gameInstance.lionSparkle(_parent.x, _parent.y);
                    hide();
                }
            }
    };

    /**
     * Handler for animal drag start.
     * @param {Event} e The corresponding event. 
     */
    var _handlerAnimal_dragStart = function ( e ) {
       
        // Check if event values are valid
        if ( !e ) return;
        if ( !e.obj ) return;

        // If event object is equal to this instance, return
        if ( e.obj === _parent ) return;

        // If already not draggable, return
        if ( _isDraggable === false ) return;

        // If already dragging, return
        if ( _isDragging === true ) return;

        // Set isDraggable to false
        // _isDraggable = false;  
        
        // Set isDragging to false
        _isDragging = false;

        // Set prevTouch to false
        _prevTouch = null;

        // Nullify initial position
        _initialPos = null;
    };
 

    /**
     * Handler for animal drag end.
     * @param {Event} e The corresponding event. 
     */
    var _handlerAnimal_dragEnd = function ( e ) {

         // Check if event values are valid
        if ( !e ) return;
        if ( !e.obj ) return;

        // If event object is equal to this instance, return
        if ( e.obj === _parent ) return;

        // If already draggable, return
        if ( _isDraggable === true ) return;


        // Set isDraggable to true
        _isDraggable = true;
    };

    // ** Initialization Methods

    var _initProps = function ( p_type, p_objLevel ) {

        // Check if param value if not valid, then throw errpr
        if ( p_type !== APP.game.AnimalType.SHEEP && 
            p_type !== APP.game.AnimalType.GOAT &&
            p_type !== APP.game.AnimalType.LION) throw "Type value for animal is invalid.";

        if ( !p_objLevel ) throw "Level object reference for animal is invalid.";

        // Initialize properties
        _objLevel = p_objLevel;

        _type = p_type;
        _deltaAI = 0;
        _direction = null;
        _state = APP.game.AnimalState.IDLE;
        _initialPos = null;
        _isCaged = false;
        _isCageCorrect = false;
        _isDraggable = true;
        _isDragging = false;
        _isPaused = false;
        _prevTouch = null;
        _isScared = false;
        _isExitingCage = false;

        _isHidden = false;
        _isProwling = false;
        _hideTimer =0;

        _clickCounter = 0;
        _clickTimer = DOUBLE_CLICK_TIMEOUT;



        // Randomize delta ai
        _randomizeDeltaAI();
    };

    var _initGraphics = function () {

        // Set interactive to true
        _parent.interactive = true;

        // Initialize graphics
        if ( !_sprAnimal ) {

            // Get image according to 
            _sprAnimal = new EHDI.aka.Sprite();
            // _sprAnimal.anchor.set( 0.5, 1 );

            if(_type == 1)
                _parent.armature = EHDI.DBoneFactory.createArmature("goat_armature");
            else if(_type == 2)
                _parent.armature = EHDI.DBoneFactory.createArmature("sheep_armature");
            else
                _parent.armature = EHDI.DBoneFactory.createArmature("lion_armature");

            _parent.animationSprite = _parent.armature.getDisplay();
            _parent.animList = _parent.armature.animation.animationList;
            _parent.armature.animation.gotoAndPlay(_parent.animList[0], -1, -1, 0);
            var randomizedTime = Math.floor(Math.random()* 1000);
            _parent.armature.advanceTime(randomizedTime);
            _parent.animationSprite.scaleX = -1;
            _sprAnimal.addChild(  _parent.animationSprite );

           // Randomize direction
            var rand = Math.round( EHDI.NumberUtil.randomRange( 1, 2 ) );
            if ( rand === 1 ) _setDirection( -1 );
            else if ( rand === 2 ) _setDirection( 1 );
                      
            if ( _parent )_parent.addChild( _sprAnimal );
        }

        // Initialize tween properties
        _timelineMove = null;
    };

    var _initListeners = function () {

        // Add frame listeners
        APP.managers.update.addFrameListener( _handler_frameUpdate );

        // Add interaction listeners
        if ( _parent ) {

            if ( EHDI.BrowserInfo.isMobileDevice ) {
                _parent.on( "touchstart", _handler_touchBegin );
                // _parent.on( "touchmove", _handler_touchMove );
                _parent.on( "touchend", _handler_touchEnd );
                _parent.on( "touchcancel", _handler_touchEnd );
                _parent.on( "touchendoutside", _handler_touchEnd );
            }
            else {
                _parent.on( "mousedown", _handler_touchBegin );
                // _parent.on( "mousemove", _handler_touchMove );
                _parent.on( "mouseup", _handler_touchEnd );
                _parent.on( "mouseupoutside", _handler_touchEnd );
            }
        }

        // Add satelite listeners
        APP.managers.event.addListener( APP.game.AnimalEvent.DRAG_START, _handlerAnimal_dragStart );
        APP.managers.event.addListener( APP.game.AnimalEvent.DRAG_END, _handlerAnimal_dragEnd );
    };

    // ** Kill Methods

    var _killProps = function () {

        _parent = null;

        _objLevel = null;

        _deltaAI = null;
        _direction = null;
        _initialPos = null;
        _isCaged = null;
        _isCageCorrect = null;
        _isDraggable = null;
        _isDragging = null;
        _isPaused = null;
        _state = null;
        _type = null;
        _prevTouch = null;
    };

    var _killGraphics = function () {

        // Set interactive to false
        _parent.interactive = false;

        // ** Kill tweens
        if ( _timelineMove ) _timelineMove.kill();
        _timelineMove = null;

        if ( _sprAnimal ) {

            if ( _sprAnimal.parent ) _sprAnimal.parent.removeChild( _sprAnimal );

            _sprAnimal.destroy( { children: true } );
        }
        _sprAnimal = null;

        EHDI.DBoneFactory.destroyArmature(_parent.armature);
    };

    var _killListeners = function () {

        // Remove frame listeners
        APP.managers.update.removeFrameListener( _handler_frameUpdate );

        // Remove interaction listeners
        if ( _parent ) {

            if ( EHDI.BrowserInfo.isMobileDevice ) {

                _parent.off( "touchstart", _handler_touchBegin );
                // _parent.off( "touchmove", _handler_touchMove );
                _parent.off( "touchend", _handler_touchEnd );
                _parent.off( "touchcancel", _handler_touchEnd );
                _parent.off( "touchendoutside", _handler_touchEnd );
            }
            else {

                _parent.off( "mousedown", _handler_touchBegin );
                // _parent.off( "mousemove", _handler_touchMove );
                _parent.off( "mouseup", _handler_touchEnd );
                _parent.off( "mouseupoutside", _handler_touchEnd );
            }
        }

        // Remove satelite listeners
        APP.managers.event.removeListener( APP.game.AnimalEvent.DRAG_START, _handlerAnimal_dragStart );
        APP.managers.event.removeListener( APP.game.AnimalEvent.DRAG_END, _handlerAnimal_dragEnd );
    };

    // Public Methods

    this.destroy = function () {
        
        // Kill listeners
        _killListeners();

        // Kill graphics
        _killGraphics();

        // Kill props
        _killProps();

        // Call superclass method
        APP.game.AnimalObject.prototype.destroy.apply( this, arguments );
    };


    var hide = function()
    {
        if(_type !== APP.game.AnimalType.LION)
            return;
        
        _setState( null );
        _setState( APP.game.AnimalState.IDLE );

        if(Math.random() < 0.5)
            _parent.x = -50 - _parent.width;
        else
            _parent.x = APP.config.stageWidth +50 + _parent.width;

        _parent.y = APP.config.stageHeight - (Math.random() * 25);
        _isHidden = true;
        _isProwling = false;
        _prowlPhase = 0;
        _hideTimer = EHDI.NumberUtil.randomRange( 15000, 20000 );

        
        _finalXDest = 200;
        if(Math.random() < 0.5)
            _finalXDest = APP.config.stageWidth -200;
    }
    // this._hide = function(){ hide()};

    var prowl = function()
    {
        if(_type !== APP.game.AnimalType.LION)
            return;

        _setState( null );
        _setState( APP.game.AnimalState.IDLE );
        _setState( APP.game.AnimalState.MOVE );
        _isHidden = false;
        _isProwling = true;
        
        if(_prowlPhase == 0)
        {
            var xDestInit = 300;
            if(_parent.x > 512) //1024
                xDestInit = 700;

            _addMove( xDestInit, _parent.y,
                function()
                {
                    _prowlPhase++;
                    prowl();
                }
            , true,7.5);//, null, null, 10);

       
        }
        else if(_prowlPhase == 1)
        {
            var yDest = EHDI.NumberUtil.randomRange( 200, 250 );
            _addMove( APP.config.stageWidth * 0.5, yDest,
                function()
                {
                    _prowlPhase++;
                    prowl();
                }
            , true,5);
        }
        else if(_prowlPhase == 2)
        {
            // var xDest = 200;
            // if(Math.random() < 0.5)
            //     xDest = APP.config.stageWidth -200;
                
            _addMove( _finalXDest, _parent.y, 
                function () {
                    // Set state to idle
                    _setState( APP.game.AnimalState.IDLE );

                    // call game over
                    if(APP.gameOverCall)
                        APP.gameOverCall();
                }, true, 5 );
        }
    }
    this._prowl = function() {prowl()};

    // Call init methods
    _initProps( p_type, p_objLevel );
    _initGraphics();
    _initListeners();

    if(_type === APP.game.AnimalType.LION)
        {
            hide();
            _hideTimer = 30000;
        }

     Object.defineProperties( _parent, {
        "initialPosition": {
            get: function () { return _initialPos; },
            enumerable: true
        },
        "isCaged": {
            get: function () { return _isCaged; },
            set: function ( p_value ) { if ( _isCaged !== p_value  ) _isCaged = p_value; },
            enumerable: true
        },
        "isCageCorrect": {
            get: function () { return _isCageCorrect; },
            set: function ( p_value ) { if ( _isCageCorrect !== p_value  ) _isCageCorrect = p_value; },
            enumerable: true
        },
        "paused": {
            get: function () { return _isPaused; },
            set: function ( p_value ) {

                if ( p_value !== true &&
                    p_value !== false ) throw "Pause value should be boolean.";

                if ( _isPaused === p_value ) return;

                // Set isPaused
                _isPaused = p_value;
                
                if ( _isPaused === true ) {

                    if ( _timelineMove ) {

                        if ( _timelineMove.isActive() ) _timelineMove.pause();
                    }

                }
                else if ( _isPaused === false ) {

                    if ( _timelineMove ) {

                        if ( !_timelineMove.isActive() ) _timelineMove.play();
                    }
                }
                
            },
            enumerable: true
        },
        "state": {
            get: function () { return _state; },
            set: function ( p_val ) { _setState( p_val ); },
            enumerable: true
        },
        "type": {
            get: function () { return _type; },
            enumerable: true
        },
        "isProwling": {
            get: function () { return _isProwling; },
            enumerable: true
        },
        "hideTimer": {
            get: function () { return _hideTimer; },
            set: function ( p_value ) { _hideTimer = p_value; },
            enumerable: true
        },
    });

    _parent.interactMove = _handler_touchMove;

    // Return
    return _parent;

};
APP.game.AnimalObject.prototype = Object.create( EHDI.aka.Container.prototype );
APP.game.AnimalObject.prototype.constructor = APP.game.AnimalObject;
"use strict";
APP.game.CageObject = function ( p_type ) {

    // Invoke (needed)
    EHDI.aka.Container.call( this );

    // Properties

    // ** Parent (This reference)
    var _parent = this;

    // ** General Values
    var _type;

    // ** Graphics
    var _grpHit, _sprCage;
    var _glow;

    // Private Methods

    // ** Handlers

    /**
     * Handler for frame update
     * @param {Number} p_delta 
     */
    var _handler_frameUpdate = function ( p_delta ) {
        
        if ( APP.game.btnPause ) {

            if ( APP.game.btnPause.isPaused  === true ) return;
        }
        // Do something here

        if(_glow)
            _glow.update(p_delta);
    };

    this.glow = function()
    {
        if(!_glow)
            return;

        _glow.appear();
        _glow.visible = true;
    }

    this.glowFade = function()
    {
        if(!_glow) 
            return;

        _glow.disappear();
        _glow.visible = false;
    }

    this.disableGlow = function()
    {
        if(!_glow)
            return;
        this.glowFade();
        _glow = null;
        _parent.removeChild(_glow);
    }

    
    /**
     * Handler for animal drag start.
     * @param {Event} e The corresponding event. 
     */
    var _handlerAnimal_dragStart = function ( e ) {
       
        // Check if event values are valid
        if ( !e ) return;
        if ( !e.obj ) return;

    };

    /**
     * Handler for animal drag end.
     * @param {Event} e The corresponding event. 
     */
    var _handlerAnimal_dragEnd = function ( e ) {

         // Check if event values are valid
        if ( !e ) return;
        if ( !e.obj ) return;

    };

    /**
     * Handler for animal drag end.
     * @param {Event} e The corresponding event. 
     */
    var _handlerAnimal_updatedState = function ( e ) {

         // Check if event values are valid
        if ( !e ) return;
        if ( !e.obj ) return;

    };


    // ** Initialization Methods

    var _initProps = function ( p_type) {

        // Check if param value if not valid, then throw errpr
        if ( p_type !== APP.game.AnimalType.SHEEP && 
            p_type !== APP.game.AnimalType.GOAT  ) throw "Type value for cage is invalid.";
        
        // Initialize properties
        _type = p_type;

    };

    var _initGraphics = function () {

        // Initialize graphics
        if ( !_sprCage ) {

            _sprCage = new EHDI.aka.Sprite( EHDI.Assets.images[ "assets/game/img_ground_overlay.png" ] );
            _sprCage.anchor.set( 0.5, 1 );

            if ( _parent ) _parent.addChild( _sprCage );
        }

        if(!_glow)
            {
                _glow = new EHDI.components.GlowEffect(216);
                _glow.y =_sprCage.height * -0.5;                
                _glow.visible = false;

                
            if ( _parent ) _parent.addChild( _glow );

            }

        if ( !_grpHit ) {

            // Draw graphics
            _grpHit = new EHDI.aka.Graphics();
            _grpHit.clear();

            _grpHit.beginFill( 0x00FF00 );
            // Rectangle within the ellipse
            // Rectangle width = Ellipse width / Math.sqrt( 2 ) 
            // Rectangle height = Ellipse height / Math.sqrt( 2 )
            // _grpHit.drawRect( 0, 0, _sprCage.width / Math.sqrt( 2 ), _sprCage.height / Math.sqrt( 2 ) );
            _grpHit.drawRect( 0, 0, _sprCage.width, _sprCage.height );
            _grpHit.endFill();

            _grpHit.x = -( _grpHit.width * 0.5 );
            _grpHit.y = -( _grpHit.height * 0.5 ) - ( _sprCage.height * 0.5 );

            _grpHit.alpha = 0.5;

            if ( APP.game.debugEnabled === true ) _grpHit.visible = true;
            else _grpHit.visible = false;
            
            if ( _parent ) _parent.addChild( _grpHit );
        }
    };

    var _initListeners = function () {

        // Add frame listeners
        APP.managers.update.addFrameListener( _handler_frameUpdate );

        // Add satelite listeners
        APP.managers.event.addListener( APP.game.AnimalEvent.DRAG_START, _handlerAnimal_dragStart );
        APP.managers.event.addListener( APP.game.AnimalEvent.DRAG_END, _handlerAnimal_dragEnd );
        APP.managers.event.addListener( APP.game.AnimalEvent.UPDATED_STATE, _handlerAnimal_updatedState );
    };

    // ** Kill Methods

    var _killProps = function () {

        _parent = null;
        _type = null;
    };

    var _killGraphics = function () {

        if ( _sprCage ) {
            
            if ( _sprCage.parent ) _sprCage.parent.removeChild( _sprCage );

            _sprCage.destroy( { children: true } );
        }
        _sprCage = null;

        if ( _grpHit ) {
            
            _grpHit.clear();
            if ( _grpHit.parent ) _grpHit.parent.removeChild( _grpHit );

            _grpHit.destroy( { children: true } );
        }
        _grpHit = null;
    };

    var _killListeners = function () {

        // Remove frame listeners
        APP.managers.update.removeFrameListener( _handler_frameUpdate );

        // Add satelite listeners
        APP.managers.event.removeListener( APP.game.AnimalEvent.DRAG_START, _handlerAnimal_dragStart );
        APP.managers.event.removeListener( APP.game.AnimalEvent.DRAG_END, _handlerAnimal_dragEnd );
        APP.managers.event.removeListener( APP.game.AnimalEvent.UPDATED_STATE, _handlerAnimal_updatedState );
    };

    // Public Methods

    this.destroy = function () {
        
        // Kill listeners
        _killListeners();

        // Kill graphics
        _killGraphics();

        // Kill props
        _killProps();

        // Call superclass method
        APP.game.CageObject.prototype.destroy.apply( this, arguments );
    };

    // Call init methods
    _initProps( p_type );
    _initGraphics();
    _initListeners();

     Object.defineProperties( _parent, {
        "hit": {
            get: function () { return _grpHit; },
            enumerable: true
        },
        "type": {
            get: function () { return _type; },
            enumerable: true
        },
    });

    // Return
    return _parent;
};
APP.game.CageObject.prototype = Object.create( EHDI.aka.Container.prototype );
APP.game.CageObject.prototype.constructor = APP.game.CageObject;

var EHDI = EHDI || Object.create(null);
var UTILS = UTILS || Object.create(null);
var POOLS = POOLS || Object.create(null);

EHDI.components = EHDI.components || Object.create(null);

EHDI.components.GlowEffect = function(size) {     
    EHDI.aka.Container.call(this);

    this.active = false;

    this.visual = new EHDI.aka.Sprite(EHDI.Assets.images["fx_firsttimeplay_glow"]);
    this.visual.anchor.set(0.5, 0.5);
    this.scale.x = size / this.visual.width;
    this.scale.y = size / this.visual.height;
    this.addChild(this.visual);

    this.speed = (360 *(Math.PI / 180 )) / 10000;

    

    this.appear = function(score)
    {
        if(this.active)
            return;

        this.active = true;

    }

    this.disappear = function()
    {
        if(!this.active)
            return;

        this.active = false;
    }


    this.update = function (delta)
    {
        if(!this.active)
            return false;

        this.rotation += delta * this.speed;


        return false;
    }

}
EHDI.components.GlowEffect.prototype = Object.create(EHDI.aka.Container.prototype);
"use strict";

APP.game.LevelObject = function () {

    // Invoke (needed)
    EHDI.aka.Container.call( this );

    // Constants
    var ADD_SCORE_ON_PLACE  =   5;
    var ADD_SCORE_ON_TICK   =   10;

    // Properties

    // ** Parent (This reference)
    var _parent = this;

    // ** General Values
    var _isPaused, _score;

    // ** Object References
    var _objAnimals, _objCages;

    // ** Graphics
    var _grpSpawn_bottom, _grpSpawn_top,
    _layerBG, _layerDrag, _layerObjects,
    _sprBG, _sprFenceLeft_back,  _sprFenceLeft_front, _sprFenceRight_back, _sprFenceRight_front,
    _sprSign_left, _sprSign_right, _sparkleArmature, _sparkleAnimationSprite;   

    var _interactionMan;

    var scoreEffectXs, scoreEffectY, scoreEffects, _lion, _sfxTimer;
    

    // Private Methods

    // ** General Methods

    /**
     * Rearrange objects.
     */
    var _rearrangeObjects = function () {
        
        // If layer is empty return
        if ( !_layerObjects ) return;
        
        // Go through layer children
        for ( var i = 0; i < _layerObjects.children.length; i++ ) {

            var indexCurrent = ( _layerObjects.children.length - 1 ) - i;
            var childCurrent = _layerObjects.getChildAt( indexCurrent );

            var indexPrev = indexCurrent - 1;
            var childPrev = null;
           
            try { childPrev = _layerObjects.getChildAt( indexPrev ); } 
            catch ( e ) { childPrev = null; }

            if ( childPrev ) {
                
                // If current child y is less than prev child y
                // And current index is greater than prev index
                // Swap children
                if ( childCurrent.y < childPrev.y && indexCurrent > indexPrev ) {
                    
                    _layerObjects.swapChildren( childCurrent, childPrev );
                }
            }
        }
    };

    var _addScore = function ( p_addScore, type ) {
        
        if ( typeof _score !== "number" ) return;

        if(_score == 0)
            _lion.hideTimer = 500;

        _score += p_addScore;

        scoreEffects.popScore(scoreEffectXs[type-1], scoreEffectY, p_addScore);

        APP.managers.event.dispatch( APP.game.LevelEvent.UPDATED_SCORE, { score: _score } );
    };

    var _updateScore = function () {
        
        if(APP.pauseButton)
            {
                if ( APP.pauseButton.isPaused === true || APP.pauseButton.isEndGame === true )
                return;
            }

            if (window.document.webkitHidden || window.document.hidden)
                return;

        if ( !_objAnimals ) return;
        
        var correctGoatCount = 0;
        var correctSheepCount = 0;

        for ( var i = 0; i < _objAnimals.length; i++ ) {

            var objAnimal = _objAnimals[ i ];

            if ( !objAnimal ) continue;

            if ( objAnimal.isCaged === true &&
                 objAnimal.isCageCorrect === true )
                 {
                    if(objAnimal.type ==1)
                        correctGoatCount++;
                    else
                        correctSheepCount++;
                 }
        }

        if ( correctGoatCount > 0 ) _addScore( ADD_SCORE_ON_TICK * correctGoatCount , 1);
        if ( correctSheepCount > 0 ) _addScore( ADD_SCORE_ON_TICK * correctSheepCount, 2 );
    };

    // ** Handlers

    /**
     * Handler for frame update
     * @param {Number} p_delta 
     */
    var _handler_frameUpdate = function ( p_delta ) {

        // Rearrange objects
        _rearrangeObjects();


        
        scoreEffects.update(p_delta);

        if ( APP.game.btnPause ) {
            
                        if ( APP.game.btnPause.isPaused === true || 
                            APP.game.btnPause.isEndGame === true ) return;
                    }

        _sfxTimer -= p_delta;

        if(_sfxTimer <= 0)
        {
            _sfxTimer = EHDI.NumberUtil.randomRange( 3500, 12000 );

            if(Math.random() < 0.5)
                APP.managers.sound.playSFX("goat");
            else
                APP.managers.sound.playSFX("lamb");
        }
        
    };

    /**
     * Handler for animal drag start.
     * @param {Event} e The corresponding event. 
     */
    var _handlerAnimal_dragStart = function ( e ) {
        
        // Check if values are invalid then return
        if ( !e ) return;
        if ( !e.obj ) return;

        if ( !_layerDrag ) return;

        // Set animal object
        var objAnimal = e.obj;

        // Remove object from parent
        if ( objAnimal.parent ) objAnimal.parent.removeChild( objAnimal );

        // Scale up
        if(objAnimal.type !== APP.game.AnimalType.LION)
            objAnimal.scale.set( 1.25 );

        // Add to drag layer
        _layerDrag.addChild( objAnimal );

        // Rearrange objects
        _rearrangeObjects();
    };

    /**
     * Handler for animal drag end.
     * @param {Event} e The corresponding event. 
     */
    var _handlerAnimal_dragEnd = function ( e ) {
        
        // Check if values are invalid then return
        if ( !e ) return;
        if ( !e.obj ) return;

        if ( !_layerObjects ) return;
        if ( !_objCages ) return;

        // Set animal object
        var objAnimal = e.obj;

        if((objAnimal.type === APP.game.AnimalType.SHEEP) ||
            (objAnimal.type === APP.game.AnimalType.GOAT))
        {

            // Check if cage object is hit
            var objCageHit = null;
            
            for ( var i = 0; i < _objCages.length; i++ ) {

                var objCage = _objCages[ i ];

                if ( !objCage.hit ) continue;

                if ( EHDI.CollisionUtil.rectToRect( objCage.hit.getBounds(), objAnimal.getBounds() ) && 
                    !EHDI.CollisionUtil.rectToRect( _grpSpawn_bottom.getBounds(), objAnimal.getBounds() ) && 
                    !EHDI.CollisionUtil.rectToRect( _grpSpawn_top.getBounds(), objAnimal.getBounds() ) ) {

                    objCageHit = objCage;

                    break;
                }
            }

            // Remove object from parent
            if ( objAnimal.parent ) objAnimal.parent.removeChild( objAnimal );

            // Scale to normal
            objAnimal.scale.set( 1 );

            // Add to objects layer
            _layerObjects.addChild( objAnimal );

            // Do according to objCageHit value
            if ( !objCageHit ) {
                
                // If not hit, reset position to initial
                if ( objAnimal.initialPosition ) {

                    objAnimal.x = objAnimal.initialPosition.x;
                    objAnimal.y = objAnimal.initialPosition.y;
                }
            }
            else {

                // If hit,
                objCageHit.disableGlow();

                // Set isCaged to true
                objAnimal.isCaged = true;
                
                // Set isCageCorrect if cage type and animal type is sane
                if ( objCageHit.type === objAnimal.type ) {
                    
                    if ( objAnimal.isCageCorrect === false ) {
                        
                        objAnimal.isCageCorrect = true;

                        _addScore( ADD_SCORE_ON_PLACE, objAnimal.type );
                    }

                }
                else objAnimal.isCageCorrect = false;
                
                // Limit within cage bounds
                // Localize cage bounds
                var boundsCage = objCageHit.hit.getBounds();
                
                var localPosCage = _parent.toLocal( new PIXI.Point( boundsCage.x, boundsCage.y ) );
                var localBoundsCage = objCageHit.hit.getLocalBounds();

                boundsCage = new PIXI.Rectangle( localPosCage.x, localPosCage.y, localBoundsCage.width, localBoundsCage.height );
            
                // Set limits
                var minX = boundsCage.left + ( objAnimal.width * 0.5 );
                var maxX = boundsCage.right - ( objAnimal.width * 0.5 );

                var minY = boundsCage.top;
                var maxY = boundsCage.bottom;

                objAnimal.x = EHDI.NumberUtil.clamp( objAnimal.x, minX, maxX );
                objAnimal.y = EHDI.NumberUtil.clamp( objAnimal.y, minY, maxY );
            }
        }
        // else if(objAnimal.type === APP.game.AnimalType.LION)
        // {

        //     var sideBounds = (50 + objAnimal.width);
        //     if(objAnimal.x < sideBounds|| objAnimal.x> APP.config.stageWidth-sideBounds)
        //         {
        //             objAnimal._hide();
        //         }
        //     else
        //         {
        //             if ( objAnimal.initialPosition ) {
                        
        //                                     objAnimal.x = objAnimal.initialPosition.x;
        //                                     objAnimal.y = objAnimal.initialPosition.y;
        //                                 }
        //         }
        // }


        // Rearrange objects
        _rearrangeObjects();
    };

    /**
     * Handler for animal moving.
     * @param {Event} e The corresponding event. 
     */
    var _handlerAnimal_moving = function ( e ) {

        // Check if values are invalid then return
        if ( !e ) return;
        if ( !e.obj ) return;

        if ( !_objCages ) return;

        // Set animal object
        var objAnimal = e.obj;

        // Check if cage object is hit
        var objCageHit = null;
        
        for ( var i = 0; i < _objCages.length; i++ ) {

            var objCage = _objCages[ i ];

            if ( !objCage.hit ) continue;

            if ( EHDI.CollisionUtil.rectToRect( objCage.hit.getBounds(), objAnimal.getBounds() ) && 
                !EHDI.CollisionUtil.rectToRect( _grpSpawn_bottom.getBounds(), objAnimal.getBounds() ) && 
                !EHDI.CollisionUtil.rectToRect( _grpSpawn_top.getBounds(), objAnimal.getBounds() ) ) {

                objCageHit = objCage;

                break;
            }
        }

        // Do according to objCageHit value
        if ( !objCageHit ) {

            // Set isCaged to false
            objAnimal.isCaged = false;

            // Set isCageCorrect to false
            objAnimal.isCageCorrect = false;
        }
    }

    var _interactionLayer_move= function ( e ) 
    {
        var propName = "interactId_"+e.data.identifier;

        // console.log(APP.game.TouchObjects[propName]);
        if(APP.game.TouchObjects[propName] == null)
            return;
        
        APP.game.TouchObjects[propName].interactMove(e);
    }

  

    // ** Initialization Methods

    /**
     * Initialize properties.
     */
    var _initProps = function () {

        // Initialize properties
        _isPaused = false;
        _score = 0;        
        _sfxTimer = EHDI.NumberUtil.randomRange( 500, 3500 );
        
        _interactionMan = new PIXI.interaction.InteractionManager(APP.managers.scene.getRenderer());
    };

    
    /**
     * Initialize graphics
     */
    var _initGraphics = function () {
        
        // Initialize graphics

        // ** Initialize layers
        if ( !_layerBG ) {

            _layerBG = new EHDI.aka.Container();

            if ( _parent ) _parent.addChild( _layerBG );
        }

        if ( !_layerObjects ) {

            _layerObjects = new EHDI.aka.Container();

            if ( _parent ) _parent.addChild( _layerObjects );
        }

        if ( !_layerDrag ) {

            _layerDrag = new EHDI.aka.Container();

            if ( _parent ) _parent.addChild( _layerDrag );
        }
      




                        // _touchTest =new EHDI.displays.FillRectangle( 0x00FF00, 0,0,1024,600);
                        // _touchTest.interactive = true;

                        // var _handler_touchBegin = function(e)
                        // {
                        //     console.log("touch begin");
                        //     console.log(e.identifier, e.data.identifier);

                        //     //e.identifier is null
                        //     //e.data.identifier works, map this to the animals
                        //     // save target animal to   map
                        // }

                        // _parent.addChild(_touchTest)

                        
                        // _touchTest.on( "touchstart", _handler_touchBegin );






        // ** Initialize bg
        if ( !_sprBG ) {

            // Get image according to 
            _sprBG = new EHDI.aka.Sprite( EHDI.Assets.images[ "assets/game/img_game_bg.png" ] );
            
            if ( _layerBG ) _layerBG.addChild( _sprBG );
        }

        // ** Add cages
        if ( !_objCages ) {

            _objCages = [];
            scoreEffectXs = [];

            for ( var cageCount = 1; cageCount <= 2; cageCount++ ) {

                var cageType;

                if ( cageCount === 1 ) cageType = APP.game.AnimalType.GOAT;
                else if ( cageCount === 2 ) cageType = APP.game.AnimalType.SHEEP;
                var objCage = new APP.game.CageObject( cageType );

                if ( cageCount === 1 ) objCage.x = ( objCage.width * 0.5 ) + 10;
                else if ( cageCount === 2 ) objCage.x = APP.config.stageWidth - ( objCage.width  * 0.5 ) - 10;
                objCage.y = 200+objCage.height;//( APP.config.stageHeight * 0.55 )  + ( objCage.height * 0.5 );

                _objCages.push( objCage );

                if ( _layerBG ) _layerBG.addChild( objCage );
            }
        }

        // Get cage references
        var objCage_left = _objCages[ 0 ];
        var objCage_right = _objCages[ 1 ];

        // ** Initialize fence left
        if ( !_sprFenceLeft_back ) {

            _sprFenceLeft_back = new EHDI.aka.Sprite( EHDI.Assets.images[ "assets/game/img_fence_back.png" ] );
            _sprFenceLeft_back.anchor.set( 0.5, 1 );
            _sprFenceLeft_back.position.set( objCage_left.x, objCage_left.y - objCage_left.height + 10 );

            if ( _layerObjects ) _layerObjects.addChild( _sprFenceLeft_back );
        }

        if ( !_sprFenceLeft_front ) {

            _sprFenceLeft_front = new EHDI.aka.Sprite( EHDI.Assets.images[ "assets/game/img_fence_front.png" ] );
            _sprFenceLeft_front.anchor.set( 0.5, 1 );
            _sprFenceLeft_front.position.set( objCage_left.x, objCage_left.y + 10 );

            if ( _layerObjects ) _layerObjects.addChild( _sprFenceLeft_front );
        }

        // ** Initialize fence right
        if ( !_sprFenceRight_back ) {

            _sprFenceRight_back = new EHDI.aka.Sprite( EHDI.Assets.images[ "assets/game/img_fence_back.png" ] );
            _sprFenceRight_back.anchor.set( 0.5, 1 );
            _sprFenceRight_back.position.set( objCage_right.x, objCage_right.y - objCage_right.height + 10 );

            if ( _layerObjects ) _layerObjects.addChild( _sprFenceRight_back );
        }

        if ( !_sprFenceRight_front ) {

            _sprFenceRight_front = new EHDI.aka.Sprite( EHDI.Assets.images[ "assets/game/img_fence_front.png" ] );
            _sprFenceRight_front.anchor.set( 0.5, 1 );
            _sprFenceRight_front.position.set( objCage_right.x, objCage_right.y + 10 );
            _sprFenceRight_front.scale.x = -1;

            if ( _layerObjects ) _layerObjects.addChild( _sprFenceRight_front );
        }

        // ** Initialize signs
        if ( !_sprSign_left ) {

            _sprSign_left = new EHDI.aka.Sprite( EHDI.Assets.images[ "assets/game/img_sign_1.png" ] );
            _sprSign_left.anchor.set( 0.5, 1 );
            _sprSign_left.position.set( _sprFenceLeft_back.x + ( _sprFenceLeft_back.width * 0.5 ) + ( _sprSign_left.width * 0.25 ), 
                                    _sprFenceLeft_back.y + ( _sprFenceLeft_back.height * 0.325 ) );
                                    //_sprFenceLeft_back.y - ( _sprFenceLeft_back.height * 0.325 ) );
            
            scoreEffectXs.push(_sprSign_left.position.x);
            scoreEffectY = _sprSign_left.position.y;

            if ( _layerObjects ) _layerObjects.addChild( _sprSign_left );
        }

        if ( !_sprSign_right ) {

            _sprSign_right = new EHDI.aka.Sprite( EHDI.Assets.images[ "assets/game/img_sign_2.png" ] );
            _sprSign_right.anchor.set( 0.5, 1 );
            _sprSign_right.position.set( _sprFenceRight_back.x - ( _sprFenceRight_back.width * 0.5 ) - ( _sprSign_right.width * 0.25 ), 
                                     _sprFenceRight_back.y + ( _sprFenceRight_back.height * 0.325 ) );
                                    // _sprFenceRight_back.y - ( _sprFenceRight_back.height * 0.325 ) );

            scoreEffectXs.push(_sprSign_right.position.x);

            if ( _layerObjects ) _layerObjects.addChild( _sprSign_right );
        }

        
        scoreEffects = new EHDI.components.ScoreEffectManager();
        if ( _layerObjects )
            scoreEffects.init(_layerObjects);

        // ** Create spawn areas
        if ( !_grpSpawn_bottom ) {

            // Draw graphics
            _grpSpawn_bottom = new EHDI.aka.Graphics();
            _grpSpawn_bottom.clear();

            _grpSpawn_bottom.beginFill( 0x00FF00 );

            _grpSpawn_bottom.drawRect( 0, 0, APP.config.stageWidth, 
                            APP.config.stageHeight - Math.max( _sprFenceLeft_front.y, _sprFenceRight_front.y ) - 10 );
            _grpSpawn_bottom.endFill();

            _grpSpawn_bottom.position.set( 0, APP.config.stageHeight - _grpSpawn_bottom.height );
            _grpSpawn_bottom.alpha = 0.5;

            if ( APP.game.debugEnabled === true ) _grpSpawn_bottom.visible = true;
            else _grpSpawn_bottom.visible = false;
            
            if ( _layerBG ) _layerBG.addChild( _grpSpawn_bottom );
        }

        if ( !_grpSpawn_top ) {

            // Draw graphics
            _grpSpawn_top = new EHDI.aka.Graphics();
            _grpSpawn_top.clear();

            _grpSpawn_top.beginFill( 0x00FF00 );

            _grpSpawn_top.drawRect( 0, 0, APP.config.stageWidth, 
                            Math.min( _sprFenceLeft_back.y - ( _sprFenceLeft_back.height * 0.25 ), _sprFenceRight_back.y - ( _sprFenceRight_back.height * 0.25 ) ) - 10 );
            _grpSpawn_top.endFill();

            _grpSpawn_top.position.set( 0, 0 );
            _grpSpawn_top.alpha = 0.5;

            if ( APP.game.debugEnabled === true ) _grpSpawn_top.visible = true;
            else _grpSpawn_top.visible = false;
            
            if ( _layerBG ) _layerBG.addChild( _grpSpawn_top );
        }

        if ( !_objAnimals ) {

            _objAnimals = [];
            
            var spawnCount = 20;
            var spawnPerType = spawnCount / _objCages.length;

            var lastSpawnArea;

            for ( var countAnimal = 0; countAnimal < spawnCount; countAnimal++ ) {

                var typeAnimal = Math.floor( ( spawnPerType + countAnimal ) / spawnPerType );

                var objAnimal = new APP.game.AnimalObject( typeAnimal, _parent );

                // // Get random spawn area
                // var randSpawnArea = Math.round( EHDI.NumberUtil.randomRange( 1, 2 ) );

                // do { randSpawnArea = Math.round( EHDI.NumberUtil.randomRange( 1, 2 ) ); }
                // while ( randSpawnArea == lastSpawnArea );

                // // Set last spawn area
                // lastSpawnArea = randSpawnArea;

                // // Set random position within bounds
                // if ( randSpawnArea === 1 ) {

                //     // Set random position via top spawn
                //     objAnimal.x = EHDI.NumberUtil.randomRange( _grpSpawn_top.x + ( objAnimal.width * 0.5 ), ( _grpSpawn_top.x + _grpSpawn_top.width ) - ( objAnimal.width * 0.5 ) );
                //     objAnimal.y = EHDI.NumberUtil.randomRange( _grpSpawn_top.y + objAnimal.height, _grpSpawn_top.y + _grpSpawn_top.height );
                // }
                // else if ( randSpawnArea === 2 ) {

                //     // Set random position via bottom spawn
                //     objAnimal.x = EHDI.NumberUtil.randomRange( _grpSpawn_bottom.x + ( objAnimal.width * 0.5 ), ( _grpSpawn_bottom.x + _grpSpawn_bottom.width ) - ( objAnimal.width * 0.5 ) );
                //     objAnimal.y = EHDI.NumberUtil.randomRange( _grpSpawn_bottom.y + 10, _grpSpawn_bottom.y + _grpSpawn_bottom.height );
                // } 

                
                // Set random position via bottom spawn
                objAnimal.x = EHDI.NumberUtil.randomRange( _grpSpawn_bottom.x + ( objAnimal.width * 0.5 ), ( _grpSpawn_bottom.x + _grpSpawn_bottom.width ) - ( objAnimal.width * 0.5 ) );
                objAnimal.y = EHDI.NumberUtil.randomRange( _grpSpawn_bottom.y + 10, _grpSpawn_bottom.y + _grpSpawn_bottom.height );
                
                // Push to list
                _objAnimals.push( objAnimal );

                // Add to layer
                if ( _layerObjects ) _layerObjects.addChild( objAnimal );
            }
            
        }

        var objAnimal = new APP.game.AnimalObject( APP.game.AnimalType.LION, _parent );
        // Add to layer
        if ( _layerObjects ) _layerObjects.addChild( objAnimal );
        _lion = objAnimal;
        APP.game.lion = _lion;


        
        _sparkleArmature = EHDI.DBoneFactory.createArmature("sparkle_armature");
        _sparkleAnimationSprite = _sparkleArmature.getDisplay();
        _sparkleAnimationSprite.visible = false;

        
        if ( _layerObjects ) _layerObjects.addChild( _sparkleAnimationSprite );


        
        
        // Rearrange objects
        _rearrangeObjects();
    };

    var _lionSparkle = function(xPos, yPos)
    {
        _sparkleAnimationSprite.x = xPos;
        _sparkleAnimationSprite.y = yPos;
        _sparkleAnimationSprite.visible = true;
        
        _sparkleArmature.animation.gotoAndPlay("fx_sparkle", -1, -1, 1);
    }
    this.lionSparkle = _lionSparkle;

    var _initListeners_primary = function () {

        // Register game events
        APP.managers.event.register( APP.game.LevelEvent.START );
        APP.managers.event.register( APP.game.LevelEvent.END );
        APP.managers.event.register( APP.game.LevelEvent.UPDATED_SCORE );

        APP.managers.event.register( APP.game.AnimalEvent.DRAG_START );
        APP.managers.event.register( APP.game.AnimalEvent.DRAG_END );
        APP.managers.event.register( APP.game.AnimalEvent.MOVING );
        APP.managers.event.register( APP.game.AnimalEvent.UPDATED_STATE );
    }

    var _initListeners = function () {

        // Add frame listeners
        APP.managers.update.addFrameListener( _handler_frameUpdate );

        // Add satelite listeners
        APP.managers.event.addListener( APP.game.AnimalEvent.DRAG_START, _handlerAnimal_dragStart );
        APP.managers.event.addListener( APP.game.AnimalEvent.DRAG_END, _handlerAnimal_dragEnd );
        APP.managers.event.addListener( APP.game.AnimalEvent.MOVING, _handlerAnimal_moving );


        
        if ( EHDI.BrowserInfo.isMobileDevice ) {            
            _interactionMan.on( "touchmove", _interactionLayer_move );
        }
        else {

            _interactionMan.on( "mousemove", _interactionLayer_move );
        }
    };

    // ** Kill Methods

    var _killProps = function () {

        _isPaused = null;
        _score = null;
        APP.game.lion = null;
        _interactionMan = null;
    };

    var _killGraphics = function () {

        // ** Kill BG
        if ( _sprBG ) {

            if ( _sprBG.parent ) _sprBG.parent.removeChild( _sprBG );

            _sprBG.destroy( { children: true } );
        }
        _sprBG = null;

        // ** Kill fence left
        if ( _sprFenceLeft_back ) {

            if ( _sprFenceLeft_back.parent ) _sprFenceLeft_back.parent.removeChild( _sprFenceLeft_back );

            _sprFenceLeft_back.destroy( { children: true } );
        }
        _sprFenceLeft_back = null;

        if ( _sprFenceLeft_front ) {

            if ( _sprFenceLeft_front.parent ) _sprFenceLeft_front.parent.removeChild( _sprFenceLeft_front );

            _sprFenceLeft_front.destroy( { children: true } );
        }
        _sprFenceLeft_front = null;
        
        // ** Kill fence right
        if ( _sprFenceRight_back ) {

            if ( _sprFenceRight_back.parent ) _sprFenceRight_back.parent.removeChild( _sprFenceRight_back );

            _sprFenceRight_back.destroy( { children: true } );
        }
        _sprFenceRight_back = null;

        if ( _sprFenceRight_front ) {

            if ( _sprFenceRight_front.parent ) _sprFenceRight_front.parent.removeChild( _sprFenceRight_front );

            _sprFenceRight_front.destroy( { children: true } );
        }
        _sprFenceRight_front = null;

        // ** Kill signs
        if ( _sprSign_left ) {

            if ( _sprSign_left.parent ) _sprSign_left.parent.removeChild( _sprSign_left );

            _sprSign_left.destroy( { children: true } );
        }
        _sprSign_left = null;

        if ( _sprSign_right ) {

            if ( _sprSign_right.parent ) _sprSign_right.parent.removeChild( _sprSign_right );

            _sprSign_right.destroy( { children: true } );
        }
        _sprSign_right = null;

        // ** Kill cages
        var i;
        if ( _objCages ) {

            for ( i = 0; i < _objCages.length; i++ ) {

                var objCage = _objCages[ i ];

                if ( objCage.parent ) objCage.parent.removeChild( objCage );

                objCage.destroy( { children: true } );

                _objCages[ i ] = null;
            }

            _objCages.splice( 0, _objCages.length );
        }
        _objCages = null;

        // ** Kill animals
        if ( _objAnimals ) {

            for ( i = 0; i < _objAnimals.length; i++ ) {

                var objAnimal = _objAnimals[ i ];

                if ( objAnimal.parent ) objAnimal.parent.removeChild( objAnimal );

                objAnimal.destroy( { children: true } );

                _objAnimals[ i ] = null;
            }

            _objAnimals.splice( 0, _objAnimals.length );
        }
        _objAnimals = null;

        if ( _layerBG ) {

            if ( _layerBG.parent ) _layerBG.parent.removeChild( _layerBG );

            _layerBG.destroy( { children: true } );
        }
        _layerBG = null;

        if ( _layerObjects ) {

            if ( _layerObjects.parent ) _layerObjects.parent.removeChild( _layerObjects );

            _layerObjects.destroy( { children: true } );
        }
        _layerObjects = null;

        if ( _layerDrag ) {

            if ( _layerDrag.parent ) _layerDrag.parent.removeChild( _layerDrag );

            _layerDrag.destroy( { children: true } );
        }
        _layerDrag = null;

    };

    var _killListeners_primary = function () {

        // Unregister game events
        APP.managers.event.unregister( APP.game.LevelEvent.START );
        APP.managers.event.unregister( APP.game.LevelEvent.END );
        APP.managers.event.unregister( APP.game.LevelEvent.UPDATED_SCORE );

        APP.managers.event.unregister( APP.game.AnimalEvent.DRAG_START );
        APP.managers.event.unregister( APP.game.AnimalEvent.DRAG_END );
        APP.managers.event.unregister( APP.game.AnimalEvent.MOVING );
        APP.managers.event.unregister( APP.game.AnimalEvent.UPDATED_STATE );
    }

    var _killListeners = function () {

        // Remove frame listeners
        APP.managers.update.removeFrameListener( _handler_frameUpdate );

        // Remove satelite listeners
        APP.managers.event.removeListener( APP.game.AnimalEvent.DRAG_START, _handlerAnimal_dragStart );
        APP.managers.event.removeListener( APP.game.AnimalEvent.DRAG_END, _handlerAnimal_dragEnd );
        APP.managers.event.removeListener( APP.game.AnimalEvent.MOVING, _handlerAnimal_moving );
        
         
        if ( EHDI.BrowserInfo.isMobileDevice ) {            
            _interactionMan.off( "touchmove", _interactionLayer_move );
        }
        else {

            _interactionMan.off( "mousemove", _interactionLayer_move );
        }
    };

    // Public Methods

    this.destroy = function () {
        
        // Kill listeners
        _killListeners();

        // Kill graphics
        _killGraphics();

        // Kill primary listeners
        _killListeners_primary();

        // Kill props
        _killProps();

        // Call superclass method
        APP.game.LevelObject.prototype.destroy.apply( this, arguments );
    };

    // Call init methods
    _initProps();
    _initListeners_primary();
    _initGraphics();
    _initListeners();

    Object.defineProperties( _parent, {
        "score": {
            get: function () { return _score; },
            enumerable: true
        },
        "check": {
            get: function () { return _updateScore; },
            enumerable: true
        },
        "paused": {
            get: function () { return _isPaused; },
            set: function ( p_value ) {

                if ( p_value !== true &&
                    p_value !== false ) throw "Pause value should be boolean.";

                if ( _isPaused === p_value ) return;

                // Set isPaused
                _isPaused = p_value;
                var i = 0;
                if ( _isPaused === true ) {
                    
                    if ( _objAnimals ) {

                        for ( i = 0; i < _objAnimals.length; i++ ) {
                            if ( _objAnimals[ i ] ) _objAnimals[ i ].paused = true;
                        }
                    }

                    if(_lion)
                        _lion.paused = true;

                }
                else if ( _isPaused === false ) {

                    if ( _objAnimals ) {

                        for ( i = 0; i < _objAnimals.length; i++ ) {
                            if ( _objAnimals[ i ] ) _objAnimals[ i ].paused = false;
                        }
                    }

                    if(_lion)
                        _lion.paused = false;
                }
                
            },
            enumerable: true
        },
        "spawnBottom": {
            get: function () { return _grpSpawn_bottom; },
            enumerable: true
        },
        "spawnTop": {
            get: function () { return _grpSpawn_top; },
            enumerable: true
        },
    });
  
    APP.game.cages = _objCages;
    // Return
    return _parent;
};
APP.game.TouchObjects = Object.create(null);
APP.game.TouchObjects.count = 0;
APP.game.LevelObject.prototype = Object.create( EHDI.aka.Container.prototype );
APP.game.LevelObject.prototype.constructor = APP.game.LevelObject;
APP.popups.ConfirmationPopup = function(onClickYes, onClickNo) {
    EHDI.aka.Container.call(this);
    this.confirmationContainer,this.overlay = null, this.btnYes, this.btnNo;
    this.headerTxt = null;
    this.confirmTxt = null;
    this.interactive = true;
    this.onYesClick = onClickYes || null;
    this.onNoClick = onClickNo || null;
};

APP.popups.ConfirmationPopup.prototype = Object.create(EHDI.aka.Container.prototype);

APP.popups.ConfirmationPopup.prototype.popUpWillAppear = function() {
    this.overlay = new EHDI.aka.Graphics();
    this.overlay.beginFill(0x000000);
    this.overlay.drawRect(0, 0, APP.config.stageWidth, APP.config.stageHeight);
    this.overlay.alpha = 0.5;
    this.overlay.visible = false;

    this.confirmationContainer = new EHDI.aka.Sprite(EHDI.Assets.images["gfx_pop2"]);
    this.confirmationContainer.position.set(APP.config.stageWidth * 0.5, APP.config.stageHeight * 0.5);
    this.confirmationContainer.anchor.set(0.5,0.5);
    
    this.btnYes = new EHDI.displays.Button(EHDI.Assets.images["check-button1"], EHDI.Assets.images["check-button2"]);
    this.btnYes.setOnClickFunction(this.btnYesClick.bind(this));
    this.btnYes.x = (this.confirmationContainer.x + (this.confirmationContainer.width * 0.25));
    this.btnYes.y = (this.confirmationContainer.y);

    this.btnNo = new EHDI.displays.Button(EHDI.Assets.images["x-button1"], EHDI.Assets.images["x-button2"]);
    this.btnNo.setOnClickFunction(this.btnNoClick.bind(this));
    this.btnNo.x = (this.confirmationContainer.x - (this.confirmationContainer.width * 0.25));
    this.btnNo.y = (this.confirmationContainer.y);

    this.addChild(this.overlay);
    this.addChild(this.confirmationContainer);
};

APP.popups.ConfirmationPopup.prototype.popUpDidAppear = function() {
    //this.overlay.alpha = 0.5;
    
    
    this.headerTxt = new EHDI.displays.TextSprite(APP.managers.json.getLocale("STR_CONFIRM"));
    this.headerTxt.anchor.set(0.5, 0.5);
    this.headerTxt.position.set(-this.confirmationContainer.width * 0.2, -this.confirmationContainer.width * 0.18);
    
    this.confirmationContainer.addChild(this.headerTxt);
    
    this.overlay.visible = true;
    this.addChild(this.btnYes);
    this.addChild(this.btnNo);

};

APP.popups.ConfirmationPopup.prototype.btnYesClick = function(){
    APP.managers.sound.playSFX("button_sfx");
    if(this.onYesClick){
        this.onYesClick();
        APP.managers.scene.popPopUp();
    }else{
        APP.managers.scene.popPopUp();
    }
};

APP.popups.ConfirmationPopup.prototype.btnNoClick = function(){
    APP.managers.sound.playSFX("button_sfx");
    if(this.onNoClick){
        this.onNoClick();
    }else{
        APP.managers.scene.popPopUp();
    } 
};

APP.popups.ConfirmationPopup.prototype.setHeader = function(format){
    this.headerTxt = new EHDI.displays.TextSprite(format);
    this.headerTxt.anchor.set(0.5,0.5);
};

APP.popups.ConfirmationPopup.prototype.setMessage = function(format){
    this.confirmTxt = new EHDI.displays.TextSprite(format);
    this.confirmTxt.anchor.set(0.5,1);
    this.confirmTxt.y = -10;
};

APP.popups.ConfirmationPopup.prototype.popUpDidDisappear = function(){
  this.btnYes.dispose();
  delete this.btnYes;
  this.btnNo.dispose();
  delete this.btnNo;
  this.overlay.destroy();
  delete this.overlay;
  this.confirmationContainer.destroy({children: true});
  delete this.confirmationContainer;
  delete this.onClickYes;
  delete this.onClickNo;
  this.destroy({children: true});
};

"use strict";

APP.popups.EndPopup = function ( p_score, p_rating ) {

    // Invoke (needed)
    EHDI.aka.Container.call( this );

    // Properties

    // ** Parent (This reference)
    var _parent = this;

    // ** General Values
    var _score, _rating;

    // ** Graphics
    var _btnReturn, _sprBG, _sprExplode, _sprOverlay, _sprStarsBG, _sprStars, _txtHeader, _txtScore, _txtHighscore, _timelineStars;

    // Private Methods

    // ** General Methods
    var _showStar = function ( p_target ) {

        p_target.visible = true;

        APP.managers.sound.playSFX( "star_gain" );
    };

    // ** Handlers
    var _handler_btnReturn = function () {

        // Stop bgm
        APP.managers.sound.stopBGM();

        // Play button sfx
        APP.managers.sound.playSFX( "button_sfx", 0.7 );

        // Call SB
        Main.SB.end( this.score );
    };

    // ** Initialization Methods
    var _initProps = function ( p_score, p_rating ) {

        // Check if param values are invalid, then throw error
        if ( typeof p_score !== "number" ) throw "Score value for is not valid. Must be number.";
        if ( p_score < 0 ) throw "Score value for is not valid. Must be greater than or equal to zero.";

        if ( typeof p_rating !== "number" ) throw "Rating value for is not valid. Must be number.";
        if ( p_rating < 0 ) throw "Rating value for is not valid. Must be greater than or equal to zero.";

        // Intialize properties
        _score = p_score;
        _rating = p_rating;
    };

    var _initGraphics = function () {

        // Set parent position
        if ( _parent ) {

            _parent.x = APP.config.stageWidth * 0.5;
            _parent.y = APP.config.stageHeight * 0.5;
        }

        if ( !_sprOverlay ) {

            _sprOverlay =  EHDI.displays.FillRectangle( 0x000000, 0, 0, APP.config.stageWidth, APP.config.stageHeight, 0 );
            _sprOverlay.alpha = 0.5;
            _sprOverlay.anchor.set( 0.5, 0.5 );
            _sprOverlay.interactive = true;

            if ( _parent ) _parent.addChild( _sprOverlay );
        }

        if ( !_sprBG ) {

            _sprBG = new EHDI.aka.Sprite( EHDI.Assets.images[ "assets/ui/gfx_pop.png" ] );
            _sprBG.anchor.set( 0.5, 0.5 );

            if ( _parent ) _parent.addChild( _sprBG );
        }

        if ( !_txtHeader ) {

            _txtHeader = new EHDI.displays.TextSprite(APP.managers.json.getLocale("STR_GAMEOVER"));
            _txtHeader.anchor.set( 0.5, 0.5 );

            _txtHeader.position.set( -_sprBG.width * 0.2, -_sprBG.width * 0.24 );
            _sprBG.addChild( _txtHeader );
        }

        if ( !_btnReturn ) {

            _btnReturn = new EHDI.displays.Button( EHDI.Assets.images[ "assets/ui/btn_return.png" ],
                                                EHDI.Assets.images[ "assets/ui/btn_return2.png" ], null, null);

            _btnReturn.position.set( 0, _sprBG.height * 0.35 );
            _btnReturn.setOnClickFunction( _handler_btnReturn );

            _sprBG.addChild( _btnReturn );
        }

        if ( !_sprStarsBG ) {

            _sprStarsBG = new EHDI.aka.Sprite( EHDI.Assets.images[ "assets/ui/gfx_starBG.png" ] );
            _sprStarsBG.anchor.set( 0.5, 0.5 );
            _sprStarsBG.position.set( 0, -_sprBG.height * 0.175 );
            _sprBG.addChild( _sprStarsBG );
        }

        if ( !_sprStars ) {

            _sprStars = [];

            for( var i = 0; i < 3; i++ ) {

                var sprStarBack = new EHDI.aka.Sprite(EHDI.Assets.images[ "assets/ui/gfx_star0.png" ]);
                sprStarBack.anchor.set( 0.5,0.5 );
                sprStarBack.position.set( _sprStarsBG.width * ( -0.15 + ( 0.15 * i ) ), 0 );
                _sprStarsBG.addChild( sprStarBack );

                var sprStarFront = new EHDI.aka.Sprite( EHDI.Assets.images[ "assets/ui/gfx_star1.png" ] );
                sprStarFront.anchor.set( 0.5, 0.5 );
                sprStarFront.scale.set( 1.2, 1.2 );

                _sprStars.push( sprStarFront );
                sprStarFront.visible = false;
                sprStarBack.addChild( sprStarFront );
            }
        }

        if ( !_txtScore ) {

            _txtScore = new EHDI.displays.TextSprite(APP.managers.json.getLocale("STR_SCORE"));
            _txtScore.text += _score.toString();
            _txtScore.anchor.set( 0.5, 0.5 );
            _txtScore.position.set( 0, _sprBG.height * 0.035 );
            _sprBG.addChild( _txtScore );
        }

        if ( !_txtHighscore ) {

            _txtHighscore = new EHDI.displays.TextSprite(APP.managers.json.getLocale("STR_BESTSCORE"));
            // _txtHighscore.text += APP.save.highscore.toString();
            _txtHighscore.text += APP.SBData.highScore.toString();
            _txtHighscore.anchor.set( 0.5, 0.5 );
            _txtHighscore.position.set( 0, _sprBG.height * 0.15 );
            _sprBG.addChild( _txtHighscore );
        }

        if ( !_sprExplode ) {

            _sprExplode = new EHDI.aka.Sprite(EHDI.Assets.images[ "assets/ui/gfx_explode.png" ] );
            _sprExplode.alpha = 0;
            _sprExplode.anchor.set( 0.5, 0.5 );
            _sprExplode.scale.set( 0.5, 0.5 );
            _sprStarsBG.addChild( _sprExplode );
        }

        if ( !_timelineStars ) {

            _timelineStars = new TimelineMax( { delay: 0.25 } );
            for ( var j = 0; j < _rating; j++ ) {

                _timelineStars.addCallback( _showStar, "+=0", [ _sprStars[ j ] ] );
                _timelineStars.to( _sprExplode, 0, { x : _sprStarsBG.width * ( -0.15 + ( 0.15 * j ) ), alpha : 1 }, "+=0.00001" );
                _timelineStars.to( _sprStars[ j ].scale, 0.5, { x : 1, y : 1 });
                _timelineStars.to( _sprExplode.scale, 0.6, { x : 1, y : 1 }, "-=0.5" );
                _timelineStars.to( _sprExplode, 0.6, { alpha : 0 }, "-=0.5" );
                _timelineStars.to( _sprExplode.scale, 0, { x : 0.5, y : 0.5 } );

            }

            _timelineStars.pause();
        }

    };

    var _initListeners = function () { };

    // ** Initialization Methods
    var _killProps = function () {

        _parent = null;

        _score = null;
        _rating = null;
    };

    var _killGraphics = function () {

        if ( _sprExplode ) {

            if ( _sprExplode.parent ) _sprExplode.parent.removeChild( _sprExplode );

            _sprExplode.destroy( { children: true } );
        }
        _sprExplode = null;

        if ( _sprStars ) {

            for ( var i = 0; i < _sprStars.length; i++ ) {

                var sprStar = _sprStars[ i ];

                if ( sprStar ) {

                    if ( sprStar.parent ) sprStar.parent.removeChild( sprStar );

                    sprStar.destroy( { children: true } );
                }

                _sprStars[ i ] = null;
            }
        }
        _sprStars = null;

        if ( _sprStarsBG ) {

            if ( _sprStarsBG.parent ) _sprStarsBG.parent.removeChild( _sprStarsBG );

            _sprStarsBG.destroy( { children: true } );
        }
        _sprStarsBG = null;

        if ( _btnReturn ) {

            _btnReturn.setOnClickFunction( null );
            if ( _btnReturn.parent ) _btnReturn.parent.removeChild( _btnReturn );

            _btnReturn.destroy( { children: true } );
        }
        _btnReturn = null;

        if ( _txtScore ) {

            if ( _txtScore.parent ) _txtScore.parent.removeChild( _txtScore );

            _txtScore.destroy( { children: true } );
        }
        _txtScore = null;

        if ( _txtHighscore ) {

            if ( _txtHighscore.parent ) _txtHighscore.parent.removeChild( _txtHighscore );

            _txtHighscore.destroy( { children: true } );
        }
        _txtHighscore = null;

        if ( _sprBG ) {

            if ( _sprBG.parent ) _sprBG.parent.removeChild( _sprBG );

            _sprBG.destroy( { children: true } );
        }
        _sprBG = null;

        if ( _sprOverlay ) {

            if ( _sprOverlay.parent ) _sprOverlay.parent.removeChild( _sprOverlay );

            _sprOverlay.destroy( { children: true } );
        }
        _sprOverlay = null;

        if ( _timelineStars ) {

            _timelineStars.stop();
            _timelineStars.kill();
        }
        _timelineStars = null;

    };

    var _killListeners = function () { };

    // Public Methods

    // ** Popup Methods
    this.popUpWillAppear = function () { };

    this.popUpDidAppear = function () { if ( _timelineStars ) _timelineStars.play(); };

    this.popUpWillDisappear = function () { if ( _sprOverlay ) _sprOverlay.alpha = 0; };

    this.popUpDidDisappear = function () { this.destroy( { children: true } ); };

    // ** Destroy
    this.destroy = function () {

        // Kill listeners
        _killListeners();

        // Kill graphics
        _killGraphics();

        // Kill props
        _killProps();

        // Call superclass method
        APP.popups.GameScene.prototype.destroy.apply( this, arguments );
    };

    // Call init methods
    _initProps( p_score, p_rating );
    _initGraphics();
    _initListeners();

    Object.defineProperties( _parent, {
        "overlay": {
            get: function () { return _sprOverlay; },
            enumerable: true
        },
    });

    // Return parent
    return _parent;
}
APP.popups.EndPopup.prototype = Object.create( EHDI.aka.Container.prototype );
APP.popups.EndPopup.prototype.constructor = APP.popups.EndPopup;

"use strict";

APP.popups.PausePopup = function ( p_fromPauseButton ) {

    // Invoke (needed)
    EHDI.aka.Container.call( this );

    // ** Parent (This reference)
    var _parent = this;
    
    // ** General Values
    var _action, _filePaths, _fromPauseButton, 
    _maxPages, _messages, _pageNumber;

    // ** Graphics
    var _btnAudio, _btnExit, _btnReturn, _btnNext, _btnPrev, 
    _sprBG, _sprOverlay, _sprPageCurrent, _sprPageNext, _txtHeader, _timelinePage;

    // Private Methods
    
    /**
     * Exit game (return to title screen)
     */
    var _exitGame = function () {

        // Send pause button isEndGame to true
        APP.game.btnPause.isEndGame = true;

        // Remove this popup
        APP.managers.scene.popPopUp();

        // Change scene
        APP.managers.scene.changeScene( new APP.scenes.TitleScene(), { alpha : new EHDI.scene.TransitionParameter( 0,1 ), duration : 0.25});
    };

    /**
     * End transition
     */
    var _endTransition = function () {

        if ( _sprPageCurrent ) _sprPageCurrent.destroy( { children: true } );
        _sprPageCurrent = _sprPageNext;
        _sprPageNext = null;
        _sprPageCurrent.alpha = 1;    
    }

    /**
     * Move page.
     * @param {*Number} p_direction Direction of which page to go next. 1 or -1 only.
     */
    var _movePage = function( p_direction ) {

        // Check param value is valid then throw error
        if ( p_direction !== 1 &&
            p_direction !== -1 ) throw "Invalid direction for move page. 1 or -1 only.";
        
        // Check if values are invalid, then return
        if ( !_sprBG ) return;
        if ( typeof _pageNumber !== "number" ) return;

        // Play button sfx
        APP.managers.sound.playSFX( "button_sfx" );
        
        // Kill transition
        if ( _timelinePage ) _timelinePage.kill();

        // If next page value is not empty, end transition
        if( _sprPageNext ) _endTransition();
        
        _sprPageNext = new EHDI.aka.Container();
        _sprPageNext.alpha = 0;
        _pageNumber += p_direction;
        
        // Clamp page index   
        if(_pageNumber < 1)
            _pageNumber = _maxPages;
        else if(_pageNumber > _maxPages)
            _pageNumber = 1;

        // Create page image
        var sprImage = new EHDI.aka.Sprite( EHDI.Assets.images[ _filePaths[ _pageNumber - 1 ] ] );
        sprImage.anchor.set( 0.5, 0.5 );
        sprImage.position.set( 0, -_sprBG.height * 0.15 );
        _sprPageNext.addChild( sprImage );
        
        // Create text content
        var sprContent = _messages[ _pageNumber -1 ];
        var txtContent = new EHDI.displays.TextSprite(sprContent);
        txtContent.style.wordWrap = true;
        txtContent.style.wordWrapWidth = sprImage.width * 0.95;

        txtContent.anchor.set( 0.5, 0 );
        txtContent.position.set( 0, _sprBG.height * 0.05 );
        _sprPageNext.addChild( txtContent );
        
        _timelinePage = new TimelineMax();
        _timelinePage.to( _sprPageNext, 0.5, { alpha : 1 } );
        _timelinePage.to( _sprPageCurrent, 0.5, { alpha : 0 }, 0 );
        _timelinePage.add( _endTransition );

        _sprBG.addChild( _sprPageNext );
    };

    // ** Handler

    /**
     * Handler for audio button.
     * @param {*Boolean} p_enable Value if enabled.
     */
    var _handler_btnAudio = function ( p_enable ) {

        // Set mute to sound manager
        APP.managers.sound.setMute( p_enable );

        // Save to storage
        APP.save.isMuted = p_enable;
        APP.managers.storage.setLocalInfo( APP.config.id, APP.save );

        // Play sfx when enabled
        if ( APP.save.isMuted === false ) APP.managers.sound.playSFX( "button_sfx" );
    };

    /**
     * Handler for exit button.
     */
    var _handler_btnExit = function () {

        // Play button sfx
        APP.managers.sound.playSFX( "button_sfx" );

        // Add confirmation popup
        APP.managers.scene.pushPopUp( new APP.popups.ConfirmationPopup( _exitGame, null ), {y : new EHDI.scene.TransitionParameter( APP.config.stageHeight, 0 ), duration : 0.25 } );
    };

    /**
     * Handler for return button.
     */
    var _handler_btnReturn = function () {

        // Play button sfx
        APP.managers.sound.playSFX( "button_sfx" );

        // Remove popup
        APP.managers.scene.popPopUp( { y : new EHDI.scene.TransitionParameter( APP.config.stageHeight * 0.5, -APP.config.stageHeight ), duration : 0.25 } );

    };

    /**
     * Handler for next button.
     */
    var _handler_btnNext = function () { _movePage( 1 ); };

    /**
     * Handler for prev button.
     */
    var _handler_btnPrev = function () { _movePage( -1 ); };

    // ** Initialization Methods

    /**
     * Initialize properties
     * @param {*Boolean} p_fromPauseButton If popup was invoked by pause button.
     */
    var _initProps = function ( p_fromPauseButton ) {

        // Chek param values is invalid, then throw error
        if ( p_fromPauseButton !== true &&
            p_fromPauseButton !== false ) throw "fromPauseButton value should be boolean.";

        // Initialize values
        _fromPauseButton = p_fromPauseButton;
        _pageNumber = 1;


      

        if ( EHDI.BrowserInfo.isMobileDevice )
        {
            _messages = [
                APP.managers.json.getLocale("STR_HTP_0"),
                APP.managers.json.getLocale("STR_HTP_1"),
                APP.managers.json.getLocale("STR_HTP_2"),
                APP.managers.json.getLocale("STR_HTP_3"),
                APP.managers.json.getLocale("STR_HTP_4_MOBILE"),
                APP.managers.json.getLocale("STR_HTP_5"),
                APP.managers.json.getLocale("STR_HTP_6")
            ];
        }
        else
            {
                _messages = [
                    APP.managers.json.getLocale("STR_HTP_0"),
                    APP.managers.json.getLocale("STR_HTP_1"),
                    APP.managers.json.getLocale("STR_HTP_2"),
                    APP.managers.json.getLocale("STR_HTP_3"),
                    APP.managers.json.getLocale("STR_HTP_4_DESKTOP"),
                    APP.managers.json.getLocale("STR_HTP_5"),
                    APP.managers.json.getLocale("STR_HTP_6")
                ];
            }

        _filePaths = [
            "assets/ui/htp_separate1.png",
            "assets/ui/htp_separate2.png",
            "assets/ui/htp_separate3.png",
            "assets/ui/htp_separate4.png",
            "assets/ui/htp_separate5.png",
            "assets/ui/htp_separate6.png",
            "assets/ui/htp_separate7.png"
        ];

        _maxPages = _filePaths.length;
    };

    /**
     * Initialize graphics.
     */
    var _initGraphics = function () {

        // Set parent position
        if ( _parent ) {
            
            _parent.x = APP.config.stageWidth * 0.5;
            _parent.y = APP.config.stageHeight * 0.5;
        }

        if ( !_sprOverlay ) {

            _sprOverlay =  EHDI.displays.FillRectangle( 0x000000, 0, 0, APP.config.stageWidth, APP.config.stageHeight, 0 );
            _sprOverlay.alpha = 0.5;
            _sprOverlay.anchor.set( 0.5, 0.5 );
            _sprOverlay.interactive = true;

            if ( _parent ) _parent.addChild( _sprOverlay );
        }

        if ( !_sprBG ) {

            _sprBG = new EHDI.aka.Sprite( EHDI.Assets.images[ "assets/ui/gfx_pop.png" ] );
            _sprBG.anchor.set( 0.5, 0.5 );

            if ( _parent ) _parent.addChild( _sprBG );
        }

        if ( !_txtHeader ) {

            var strHeader;

            if(this.fromPauseBtn){
                strHeader = APP.managers.json.getLocale("STR_PAUSED");
            }
            else{
                strHeader = APP.managers.json.getLocale("STR_HTP");
            }
            _txtHeader = new EHDI.displays.TextSprite(strHeader);
            _txtHeader.anchor.set( 0.5, 0.5 );

            _txtHeader.position.set( -_sprBG.width * 0.2, -_sprBG.width * 0.24 );
            _sprBG.addChild( _txtHeader );
        }
        
        if ( !_sprPageCurrent ) {

            _sprPageCurrent = new EHDI.aka.Container();

            _sprBG.addChild( _sprPageCurrent );
        
            var sprImage = new EHDI.aka.Sprite( EHDI.Assets.images[ _filePaths[ 0 ] ] );
            sprImage.anchor.set( 0.5, 0.5 );
            sprImage.position.set( 0, -_sprBG.height * 0.15 );

            _sprPageCurrent.addChild( sprImage );

            var txtContent = new EHDI.displays.TextSprite(_messages[0]);
            txtContent.style.wordWrap = true;
            txtContent.style.wordWrapWidth = sprImage.width * 0.95;
            txtContent.anchor.set( 0.5, 0 );
            txtContent.position.set( 0, _sprBG.height * 0.05 );

            _sprPageCurrent.addChild( txtContent );
        }

        if ( !_btnNext ) {

            _btnNext = new EHDI.displays.Button( EHDI.Assets.images[ "assets/ui/btn_prevnext.png" ], 
                                                EHDI.Assets.images[ "assets/ui/btn_prevnext2.png" ], null, null);
    
            _btnNext.position.set( _sprBG.width * 0.45, 0 );
            _btnNext.setOnClickFunction( _handler_btnNext );
            
            _sprBG.addChild( _btnNext );
        }

        if ( !_btnPrev ) {

            _btnPrev = new EHDI.displays.Button( EHDI.Assets.images[ "assets/ui/btn_prevnext.png" ], 
                                                EHDI.Assets.images[ "assets/ui/btn_prevnext2.png" ], null, null);
    
            _btnPrev.position.set( -_sprBG.width * 0.45, 0 );
            _btnPrev.scale.x = -1;
            _btnPrev.setOnClickFunction( _handler_btnPrev );
            
            _sprBG.addChild( _btnPrev );
        }

        if ( !_btnReturn ) {

            _btnReturn = new EHDI.displays.Button( EHDI.Assets.images[ "assets/ui/btn_return.png" ], 
                                                EHDI.Assets.images[ "assets/ui/btn_return2.png" ], null, null);
    
            _btnReturn.position.set( 0, _sprBG.height * 0.35 );
            _btnReturn.setOnClickFunction( _handler_btnReturn );
            
            _sprBG.addChild( _btnReturn );
        }

        

        if ( _fromPauseButton == true ) {

            if ( !_btnExit ) {

                _btnExit = new EHDI.displays.Button( EHDI.Assets.images[ "assets/ui/btn_exit.png" ], 
                                                    EHDI.Assets.images[ "assets/ui/btn_exit2.png" ], null, null);
        
                _btnExit.position.set( -_sprBG.width * 0.3, _sprBG.height * 0.35 );
                _btnExit.setOnClickFunction( _handler_btnExit );
                
                _sprBG.addChild( _btnExit );
            }

            if ( !_btnAudio ) {

               _btnAudio = new EHDI.displays.ToggleButton( EHDI.Assets.images[ "assets/ui/btn_audio1.png" ], 
                                                        EHDI.Assets.images[ "assets/ui/btn_audio3.png" ], 
                                                        EHDI.Assets.images[ "assets/ui/btn_audio2.png" ], 
                                                        EHDI.Assets.images[ "assets/ui/btn_audio4.png" ], 
                                                        APP.managers.sound.getMuted() );
                _btnAudio.position.set( _sprBG.width * 0.3, _sprBG.height * 0.35 );
                _btnAudio.setOnClickFunction( _handler_btnAudio );
                
                _sprBG.addChild( _btnAudio );
            }
        }
    };

    /**
     * Initialize listeners.
     */
    var _initListeners = function () { };

    // ** Kill Methods

    /**
     * Kill properties.
     */
    var _killProps = function () {

        // Kill properties
        _parent = null;
        _action = null;
        if ( _filePaths ) {

            for ( var i = 0; i < _filePaths.length; i++ ) {

                _filePaths[ i ] = null;
            }
        }
        _filePaths = null;
        _fromPauseButton = null;
        _maxPages = null;

        if ( _messages ) {

            for ( var i = 0; i < _messages.length; i++ ) {

                _messages[ i ] = null;
            }
        }
        _messages = null;
        _pageNumber = null;

    };

    /**
     * Kill graphics.
     *  
     */
    var _killGraphics = function () {

        var i = 0;

        // ** Kill timelines
        if ( _timelinePage ) {

            _timelinePage.stop();
            _timelinePage.kill();
        }
        _timelinePage = null;

        // ** Kill texts
        if ( _txtHeader ) {
            
            if ( _txtHeader.parent ) _txtHeader.parent.removeChild( _txtHeader );

            _txtHeader.destroy( { children: true } );
        }
        _txtHeader = null;

        // ** Kill buttons

        if ( _btnAudio ) {
            
            _btnAudio.setOnClickFunction( null );
            if ( _btnAudio.parent ) _btnAudio.parent.removeChild( _btnAudio );

            _btnAudio.destroy( { children: true } );
        }
        _btnAudio = null;

        if ( _btnExit ) {
            
            _btnExit.setOnClickFunction( null );
            if ( _btnExit.parent ) _btnExit.parent.removeChild( _btnExit );

            _btnExit.destroy( { children: true } );
        }
        _btnExit = null;

        if ( _btnReturn ) {
            
            _btnReturn.setOnClickFunction( null );
            if ( _btnReturn.parent ) _btnReturn.parent.removeChild( _btnReturn );

            _btnReturn.destroy( { children: true } );
        }
        _btnReturn = null;

        if ( _btnNext ) {
            
            _btnNext.setOnClickFunction( null );
            if ( _btnNext.parent ) _btnNext.parent.removeChild( _btnNext );

            _btnNext.destroy( { children: true } );
        }
        _btnNext = null;

        if ( _btnPrev ) {
            
            _btnPrev.setOnClickFunction( null );
            if ( _btnPrev.parent ) _btnPrev.parent.removeChild( _btnPrev );

            _btnPrev.destroy( { children: true } );
        }
        _btnPrev = null;

        // ** Kill sprite

        if ( _sprPageCurrent ) {
            
            if ( _sprPageCurrent.parent ) _sprPageCurrent.parent.removeChild( _sprPageCurrent );

            _sprPageCurrent.destroy( { children: true } );
        }
        _sprPageCurrent = null;

        if ( _sprPageNext ) {
            
            if ( _sprPageNext.parent ) _sprPageNext.parent.removeChild( _sprPageNext );

            _sprPageNext.destroy( { children: true } );
        }
        _sprPageNext = null;

        if ( _sprBG ) {
            
            if ( _sprBG.parent ) _sprBG.parent.removeChild( _sprBG );

            _sprBG.destroy( { children: true } );
        }
        _sprBG = null;

        if ( _sprOverlay ) {
            
            if ( _sprOverlay.parent ) _sprOverlay.parent.removeChild( _sprOverlay );

            _sprOverlay.destroy( { children: true } );
        }
        _sprOverlay = null;
    };

    /**
     * Kill listeners.
     */
    var _killListeners = function () { };

    // Public Methods

    // ** Popup Methods
    this.popUpWillAppear = function () { };

    this.popUpDidAppear = function () { };

    this.popUpWillDisappear = function() { if ( _sprOverlay ) _sprOverlay.alpha = 0; };

    this.popUpDidDisappear = function () { 
        
        if ( APP.game.btnPause ) APP.game.btnPause.resumeGame();

        this.destroy( { children: true } );
    };

    // ** Destroy 
    this.destroy = function () {
        
        // Kill listeners
        _killListeners();

        // Kill graphics
        _killGraphics();

        // Kill props
        _killProps();

        // Call superclass method
        APP.popups.PausePopup.prototype.destroy.apply( this, arguments );
    };

    // Call init methods
    _initProps( p_fromPauseButton );
    _initGraphics();
    _initListeners();

    Object.defineProperties( _parent, {
        "overlay": {
            get: function () { return _sprOverlay; },
            enumerable: true
        },
    });
    
    // Return parent
    return _parent;
}
APP.popups.PausePopup.prototype = Object.create( EHDI.aka.Container.prototype );
APP.popups.PausePopup.prototype.constructor = APP.popups.PausePopup;
"use strict";

APP.scenes.GameScene = function () {

    // Invoke (needed)
    EHDI.aka.Container.call( this );

    // ** Properties

    // ** Parent (This reference)
    var _parent = this;

    // ** Object References
    var _objLevel;

    // ** Graphics
    var _uiScore, _uiTimer, _btnPause;

    // Private Methods

    // ** General Methods

    // ** Handler
    var _handlerLevel_end = function ( e ) {

    };

    var _handlerLevel_start = function ( e ) {

    };

    var _handlerLevel_updatedScore = function ( e ) {

        if ( !e ) return;
        if ( !e.score ) return;

        if ( !_uiScore ) return;

        var diffScore = e.score - _uiScore.value;

        _uiScore.setScore( diffScore, true );
    };

    var _handlerTimer_tick = function () {
        if ( _btnPause.isPaused === true || _btnPause.isEndGame === true )
            return;


        if (window.document.webkitHidden || window.document.hidden)
                return;

        if ( _objLevel ) _objLevel.check();
    };

    var _handler_timerComplete = function () {

        console.log('timer complete');
        // Pause elements
        if ( _btnPause ) _btnPause.endGame();

        // Save score to shared object
        if ( _objLevel ) {

            // Pause game
            if ( typeof _objLevel.score === "number" ) {

                if ( typeof APP.SBData.highscore === "undefined" ) APP.SBData.highscore = 0;

                if ( _objLevel.score > APP.SBData.highscore ) {

                    // APP.save.highscore = _objLevel.score;
                    APP.SBData.highScore = _objLevel.score;
                    // Main.SB.saveGameData( APP.save );
                    Main.SB.saveGameData(APP.SBData, "DEFAULT", function(){
                        console.log("data saved.");
                    });
                }

                APP.managers.storage.setLocalInfo( APP.config.id, APP.save );

                // Compute rating
                var rating = 0;

                for ( var i = 0; i < APP.game.LevelConfig.RATINGS.length; i++ ) {

                    var ratingScore = APP.game.LevelConfig.RATINGS[ i ];

                    if ( _objLevel.score >= ratingScore ) rating += 1;
                }

                // Push popup
                //APP.managers.scene.pushPopUp( new APP.popups.EndPopup( _objLevel.score, rating ), { y : new EHDI.scene.TransitionParameter( -APP.config.stageHeight, APP.config.stageHeight * 0.5 ), duration : 0.25 } );
                Main.SB.end( _objLevel.score);
            }
        }

        // Show end popup here
    };

    /**
     * Handler for frame update
     * @param {Number} p_delta
     */
    var _handler_frameUpdate = function ( p_delta ) {

        if ( _btnPause ) {

            if ( _btnPause.isPaused === true || _btnPause.isEndGame === true ) {

                if ( _objLevel ) {
                    if ( _objLevel.paused === false ) _objLevel.paused = true;
                }

                if ( _uiScore ) {
                    if ( _uiScore.paused === false ) _uiScore.paused = true;
                }

                if ( _uiTimer ) {
                    if ( _uiTimer.paused === false ) _uiTimer.paused = true;
                }
            }
            else if ( _btnPause.isPaused === false ) {
                dragonBones.WorldClock.clock.advanceTime(p_delta * 0.001);

                if ( _objLevel ) {
                    if ( _objLevel.paused === true ) _objLevel.paused = false;
                }

                if ( _uiScore ) {
                    if ( _uiScore.paused === true ) _uiScore.paused = false;
                }

                if ( _uiTimer ) {
                    if ( _uiTimer.paused === true ) _uiTimer.paused = false;
                }
            }
        }
    };

    // ** Initialization Methods
    var _initProps = function () {

    };

    var _initGraphics = function () {

        if ( !_objLevel ) {

            _objLevel = new APP.game.LevelObject();

            if ( _parent ) _parent.addChild( _objLevel );
        }

        if ( !_btnPause ) {

            _btnPause = new EHDI.components.PauseButton();

            if ( _parent ) _parent.addChild( _btnPause );
        }

        if ( !_uiTimer ) {

            _uiTimer = new APP.ui.TimerUI( APP.ui.TimerType.COUNTDOWN, APP.game.LevelConfig.GAME_TIME, _handler_timerComplete, _handlerTimer_tick );

            _uiTimer.position.set( 15, 15 );

            if ( _parent ) _parent.addChild( _uiTimer );
        }

        if ( !_uiScore ) {

            _uiScore = new APP.ui.ScoreUI( APP.ui.ScoreType.SCORE, 0 );

            _uiScore.position.set( _uiTimer.x + _uiTimer.width + 10, 15 );

            if ( _parent ) _parent.addChild( _uiScore );
        }


    };

    var _initListeners = function () {

        // Add frame listeners
        APP.managers.update.addFrameListener( _handler_frameUpdate );

        // Initialize satellite listeners
        APP.managers.event.addListener( APP.game.LevelEvent.START, _handlerLevel_start );
        APP.managers.event.addListener( APP.game.LevelEvent.END, _handlerLevel_end );
        APP.managers.event.addListener( APP.game.LevelEvent.UPDATED_SCORE, _handlerLevel_updatedScore );
    };

    // ** Initialization Methods
    var _killProps = function () {

    };

    var _killGraphics = function () {

        if ( _btnPause ) {

            if ( _btnPause.parent )  _btnPause.parent.removeChild( _btnPause );
            _btnPause.destroy( { children: true } );
        }
        _btnPause = null;

        if ( _objLevel ) {

            if ( _objLevel.parent ) _objLevel.parent.removeChild( _objLevel );

            _objLevel.destroy( { children: true } );
        }
        _objLevel = null;

        if ( _uiTimer ) {

            if ( _uiTimer.parent ) _uiTimer.parent.removeChild( _uiTimer );

            _uiTimer.destroy( { children: true } );
        }
        _uiTimer = null;

        if ( _uiScore ) {

            if ( _uiScore.parent ) _uiScore.parent.removeChild( _uiScore );

            _uiScore.destroy( { children: true } );
        }
        _uiScore = null;
    };

    var _killListeners = function () {

        // Add frame listeners
        APP.managers.update.removeFrameListener( _handler_frameUpdate );

        // Remove satellite listeners
        APP.managers.event.removeListener( APP.game.LevelEvent.START, _handlerLevel_start );
        APP.managers.event.removeListener( APP.game.LevelEvent.END, _handlerLevel_end );
        APP.managers.event.removeListener( APP.game.LevelEvent.UPDATED_SCORE, _handlerLevel_updatedScore );
    };

    // Public Methods

    // ** Scene Methods
    this.screenWillAppear = function () {
        EHDI.DBoneFactory.enableClock = false;
    };

    this.screenDidAppear = function(){

       // if(APP.save.isFirstTimePlay)
       if(APP.SBData.isFirstTimePlay)
           {
               // APP.save.isFirstTimePlay = false;
               APP.SBData.isFirstTimePlay = false;
               // APP.managers.storage.setLocalInfo( APP.config.id, APP.save );
               Main.SB.saveGameData(APP.SBData, "DEFAULT", function(){
                   console.log("data saved.");
               });
               _btnPause.pauseGame();
           }

    };

    this.screenWillDisappear = function(){


    };

    this.screenDidDisappear = function () {

        this.destroy( { children: true } );
    };

    this.destroy = function () {

        // Kill listeners
        _killListeners();

        // Kill graphics
        _killGraphics();

        // Kill props
        _killProps();

        // Call superclass method
        APP.scenes.GameScene.prototype.destroy.apply( this, arguments );
    };

    // Call init methods
    _initProps();
    _initGraphics();
    _initListeners();

    APP.pauseButton = _btnPause;
    APP.gameOverCall = _handler_timerComplete;
    APP.gameInstance = _objLevel;
    // Return parent
    return _parent;

};
APP.scenes.GameScene.prototype = Object.create( EHDI.aka.Container.prototype );
APP.scenes.GameScene.prototype.constructor = APP.scenes.GameScene;

"use strict";

APP.scenes.PreloaderScene = function () {

    // Invoke (needed)
    EHDI.aka.Container.call( this );

    APP.managers.json = EHDI.JSONManager(null, EHDI.Assets.fetch("assets/preloader_strings/strings.json"));

    // Properties

    // ** Parent (This reference)
    var _parent = this;

    // ** General Values
    var _isLoaded = false;

    // ** Graphics
    var _animRobot, _dbFactory, _textureImage, _textureAtlas, _skeleton, _armature,
    _sprBar_bg, _sprBar_border, _sprBar_fill, _sprBg, _sprBorder,
    _twnTap, _txtExoBold, _txtExoMedium, _txtLoading, _txtProxima, _txtTap;

    // Private Methods

    // ** General Methods
    var _changeScene = function () {

        // Change to next scene
        APP.managers.scene.changeScene( new APP.scenes.TitleScene(), { alpha : new EHDI.scene.TransitionParameter( 0, 1 ), duration : 1 } );
    };

    // **  Handlers
    var _handler_frameUpdate = function ( p_delta ) {

        if ( _sprBar_fill ) _sprBar_fill.scale.x = APP.managers.load.getProgress() / 100;

        // dragonBones.WorldClock.clock.advanceTime( p_delta * 0.001 );
    };

    var _handler_loadComplete = function () {

        if ( _isLoaded ) return;

        
        EHDI.DBoneFactory.addToFactory("sheep_anim_tex","sheep_anim_tex","sheep_anim_ske");
        EHDI.DBoneFactory.addToFactory("goat_anim_tex","goat_anim_tex","goat_anim_ske");
        EHDI.DBoneFactory.addToFactory("lion_anim_tex","lion_anim_tex","lion_anim_ske");
        EHDI.DBoneFactory.addToFactory("fx_sparkle_tex","fx_sparkle_tex","fx_sparkle_ske");

        // Set isLoaded to true
        _isLoaded = true;

        // Set bar fill
        if ( _sprBar_fill ) _sprBar_fill.scale.x = APP.managers.load.getProgress() / 100;
        
        // Do according to device
        if ( EHDI.BrowserInfo.isIOS ) {

            // Hide bar fill and bg
            if ( _sprBar_fill ) _sprBar_fill.visible = false;
            if ( _sprBar_bg ) _sprBar_bg.visible = false;
            
            // Add tap text
            if ( !_txtTap ) {

                _txtTap = new EHDI.displays.TextSprite(APP.managers.json.getLocale("STR_TAP_CONT"));
                _txtTap.anchor.set( 0.5, 0.5 );
                _txtTap.position.set( APP.config.stageWidth * 0.5, APP.config.stageHeight * 0.65 );
                _txtTap.alpha = 0;
                _parent.addChild( _txtTap );
                
                if ( !_twnTap ) {

                    _twnTap = new TimelineMax();
                    _twnTap.to( _txtLoading, 0.25, { alpha : 0 }, 0 );
                    _twnTap.to( this, 0.25, { alpha : 0 }, 0 );
                    _twnTap.to( _txtTap, 0.25, { alpha : 1 }, 0 );
                    _twnTap.add( function() {
                        if ( _sprBg ) _sprBg.interactive = true;
                        _twnTap.kill();
                        _twnTap = new TimelineMax({repeat : -1, repeatDelay : 1, delay : 1});
                        _twnTap.to( _txtTap, 1, { alpha : 0 } );
                        _twnTap.to( _txtTap, 0.5, { alpha : 1 }, "+=0.2" );
                    });
                }
            }
            
            if ( _sprBg ) {

                _sprBg.touchstart = function () {
                    
                    // Set interactive to false
                    _sprBg.interactive = false;

                    // Play button sound
                    APP.managers.sound.playSFX( "button_sfx" );

                    // Change scene
                    _changeScene();
                };
            }
        }
        else {

            // Timeout before next scene
            setTimeout( function () {
                // Change scene
                _changeScene();
            }, 500 );
        }
    };
    

    // ** Initialization Methods

    var _initGraphics = function () {

        // Initialize fonts needed for texts
        if ( !_txtExoBold ) {
            _txtExoBold = new EHDI.aka.PixiText( "ExoBold", { fontFamily: "exo-bold", fill: 0xFFFFFF, fontSize : 16 } );
            _parent.addChild( _txtExoBold );
        }

        if ( !_txtExoMedium ) {
            _txtExoMedium = new EHDI.aka.PixiText( "ExoMedium", { fontFamily: "exo-medium", fill: 0xFFFFFF, fontSize : 16 } );
            _parent.addChild( _txtExoMedium );
        }

        if ( !_txtProxima ) {
            _txtProxima = new EHDI.aka.PixiText( "Proxima", { fontFamily: "proximanova-black", fill: 0xFFFFFF, fontSize : 16 } );
            _parent.addChild( _txtProxima );
        }

        // Initialize bg and border
        if ( !_sprBg ) {
            _sprBg = new EHDI.aka.TilingSprite( EHDI.Assets.images[ "gfx_bg" ], 
                                                   APP.config.stageWidth, 
                                                   APP.config.stageHeight );

            _parent.addChild( _sprBg );
        }

        if ( !_sprBorder ) {
            _sprBorder = new EHDI.aka.Sprite( EHDI.Assets.images[ "gfx_loading" ] );
            _sprBorder.anchor.set( 0.5, 0.5 );
            _sprBorder.position.set( APP.config.stageWidth * 0.5,
                                     APP.config.stageHeight * 0.5 );
            _parent.addChild( _sprBorder );
        }

        // Initialize loading bar components
        if ( !_sprBar_border ) {
            _sprBar_border = new EHDI.aka.Sprite( EHDI.Assets.images[ "gfx_loading_bar_con" ] );
            _sprBar_border.anchor.set( 0.5, 0.5 );
            _sprBar_border.position.set( APP.config.stageWidth * 0.5,
                                     APP.config.stageHeight * 0.64 );
            _parent.addChild( _sprBar_border );
        }

        if ( !_txtLoading ) {
            var loadingStyle = APP.managers.json.getLocale("STR_LOADING");
            _txtLoading= new EHDI.displays.TextSprite(loadingStyle);
            _txtLoading.style = loadingStyle.STYLE;
            _txtLoading.position.set( APP.config.stageWidth * 0.316,
                                      APP.config.stageHeight * 0.595 );
            _parent.addChild( _txtLoading );
        }

        if ( !_sprBar_bg ) {
            _sprBar_bg = new EHDI.displays.FillRectangle( 0x000000, 0, 0, 380, 27 );
            _sprBar_bg.anchor.set( 0.5, 0.5 );
            _sprBar_bg.position.set( APP.config.stageWidth * 0.5,
                                     APP.config.stageHeight * 0.65 );
            _parent.addChild( _sprBar_bg );
        }

        if ( !_sprBar_fill ) {
            _sprBar_fill = new EHDI.displays.FillRectangle( 0x1999F1, 0, 0, 380, 27 );
            _sprBar_fill.position.set( -( _sprBar_bg.width * 0.5 ),
                                       -( _sprBar_bg.height * 0.5 ) );
            _sprBar_bg.addChild( _sprBar_fill );
        }

        if ( !_animRobot ) {

            // _dbFactory = new dragonBones.PixiFactory();
            // _textureImage = EHDI.Assets.images[ "assets/preloader_ui/GizmoLoading_tex.png" ].baseTexture.source;

            // _textureAtlas = EHDI.Assets.fetch( "GizmoLoading_tex" );
            // _dbFactory.addTextureAtlas( new dragonBones.TextureAtlas( _textureImage, _textureAtlas ) );

            // _skeleton = EHDI.Assets.fetch( "GizmoLoading_ske" );

            // _dbFactory.addDragonBonesData( dragonBones.DataParser.parseDragonBonesData( _skeleton ) );

            // _armature = _dbFactory.buildArmature( _skeleton.armature[ 0 ].name );
            // dragonBones.WorldClock.clock.add( _armature );
            // _armature.animation.gotoAndPlay( _armature.animation.animationList[0], -1, -1, 0 );
            // _armature.animation.play();

            // _animRobot = _armature.getDisplay();
            // _animRobot.position.set( APP.config.stageWidth * 0.5, APP.config.stageHeight * 0.55 );
            // _parent.addChild( _animRobot );

                _dbFactory = new dragonBones.PixiFactory();

                EHDI.DBoneFactory.start("GizmoLoading_tex","GizmoLoading_tex","GizmoLoading_ske");
                _armature = EHDI.DBoneFactory.createArmature("Gizmo");
                dragonBones.WorldClock.clock.add(_armature);
                _armature.animation.gotoAndPlay(_armature.animation.animationList[0], -1, -1, 0);
                _armature.animation.play();
                var animationSprite = _armature.getDisplay();;
                animationSprite.position.set(APP.managers.scene.getStageWidth() * 0.5, APP.managers.scene.getStageHeight() * 0.55);
            
                _parent.addChild(animationSprite);



        }

    };

    var _initListeners = function () {

        // Add frame listeners
        APP.managers.update.addFrameListener( _handler_frameUpdate );
    };
    
    // ** Kill Methods

    var _killGraphics = function () {

        if ( _dbFactory ) _dbFactory.dispose();
        _dbFactory = null;

        _textureImage = null;
        _textureAtlas = null;
        _skeleton = null;

        if ( _armature ) {
            dragonBones.WorldClock.clock.remove( _armature );
            _armature.dispose();
        }
        _armature = null;

        // Destroy children
        _parent.destroy( { children : true } );
    };

    var _killListeners = function () {

        // Remove frame listeners
        APP.managers.update.removeFrameListener( _handler_frameUpdate );
    };

    // ** General Methods
    
    var _startLoad = function () {

        // Initialize load manager            
        APP.managers.load.queueAssets(AssetDirectory.load);
        APP.managers.load.start(_handler_loadComplete);


    };

    this.screenWillAppear = function () { 

        // Initialize graphics
        _initGraphics();

        // Initialize listeners
        _initListeners();
    };

    this.screenDidAppear = function(){
        // Start load
       _startLoad();
    };

    this.screenWillDisappear = function(){
        
        
    };

    this.screenDidDisappear = function(){

        // Kill listeners
        _killListeners();

        // Kill graphics
        _killGraphics();
    };
    
    this.destroy = function () {
        
        APP.scenes.PreloaderScene.prototype.destroy.apply( this, arguments );
    };

    // ** Handlers



};
APP.scenes.PreloaderScene.prototype = Object.create( EHDI.aka.Container.prototype );
APP.scenes.PreloaderScene.prototype.constructor = APP.scenes.PreloaderScene;
"use strict";

APP.scenes.TitleScene = function () {

    // Invoke (needed)
    EHDI.aka.Container.call( this );

    // ** Properties

    // ** Parent (This reference)
    var _parent = this;

    // ** Graphics
    var _btnAudio, _btnPlay, _sprBG, _sprGizmo, _sprLogo, _txtPlay, _uiScore;


    // Private Methods

    // ** General Methods

    // ** Handler

    var _handler_btnAudio = function ( p_enable ) {

        // Set mute to sound manager
        APP.managers.sound.setMute( p_enable );

        // Save to storage
        APP.save.isMuted = p_enable;
        APP.managers.storage.setLocalInfo( APP.config.id, APP.save );

        // Play sfx when enabled
        if ( APP.save.isMuted === false ) APP.managers.sound.playSFX( "button_sfx" );
    };

    var _handler_btnPlay = function () {

        // Play button sfx
        APP.managers.sound.playSFX( "button_sfx" );

        // Change to next scene
        APP.managers.scene.changeScene( new APP.scenes.GameScene(), { alpha : new EHDI.scene.TransitionParameter( 0, 1 ), duration : 0.25 } );
    };

    // ** Initialization Methods
    var _initProps = function () {


    };

    var _initGraphics = function () {

        // Initialize sprites
        if ( !_sprBG ) {

            // Get image according to
            _sprBG = new EHDI.aka.Sprite( EHDI.Assets.images[ "assets/title/img_title_bg.png" ] );

            if ( _parent ) _parent.addChild( _sprBG );
        }

        if ( !_sprGizmo ) {

            // Get image according to
            _sprGizmo = new EHDI.aka.Sprite( EHDI.Assets.images[ "assets/title/img_title_gizmo.png" ] );
            _sprGizmo.anchor.set( 0.5, 0.5 );
            _sprGizmo.position.set( 1024, 1200);
            if ( _parent ) _parent.addChild( _sprGizmo );
        }

        if ( !_sprLogo ) {

            // Get image according to
            _sprLogo = new EHDI.aka.Sprite( EHDI.Assets.images[ "assets/title/img_title_logo.png" ] );
            _sprLogo.anchor.set( 0.5, 0.5 );
            _sprLogo.position.set( APP.config.stageWidth * 0.5,  -500);

            if ( _parent ) _parent.addChild( _sprLogo );

        }

        if ( !_btnAudio ) {

            _btnAudio = new EHDI.displays.ToggleButton( EHDI.Assets.images[ "assets/ui/btn_audio1.png" ],
                                                        EHDI.Assets.images[ "assets/ui/btn_audio3.png" ],
                                                        EHDI.Assets.images[ "assets/ui/btn_audio2.png" ],
                                                        EHDI.Assets.images[ "assets/ui/btn_audio4.png" ],
                                                        APP.managers.sound.getMuted() );
            _btnAudio.setOnClickFunction( _handler_btnAudio );
            _btnAudio.position.set( APP.config.stageWidth * 0.1, APP.config.stageHeight * 0.09 );

            if ( _parent ) _parent.addChild( _btnAudio );
        }

        if ( !_btnPlay ) {

            _btnPlay = new EHDI.displays.Button( EHDI.Assets.images[ "assets/ui/btn_play.png" ],
                                                  EHDI.Assets.images[ "assets/ui/btn_play2.png" ], null, null );
            _btnPlay.setOnClickFunction( _handler_btnPlay );
            _btnPlay.position.set( APP.config.stageWidth * 0.5, APP.config.stageHeight * 0.85 );

            if ( _parent ) _parent.addChild( _btnPlay );

            _btnPlay.scaleX =0;
            _btnPlay.scaleY =0;
        }

        if ( !_txtPlay ) {

            _txtPlay = new EHDI.displays.TextSprite(APP.managers.json.getLocale("BTN_PLAY"));
            _txtPlay.anchor.set( 0.75, 0.5 );

            if ( _btnPlay ) _btnPlay.addChild( _txtPlay );
        }

        if ( !_uiScore ) {

            _uiScore = new APP.ui.ScoreUI( APP.ui.ScoreType.HIGHSCORE, APP.SBData.highScore );
            _uiScore.position.set( APP.config.stageWidth * 0.723, APP.config.stageHeight * 0.0417)
            if ( _parent ) _parent.addChild( _uiScore );
        }

        if ( APP.config.debugEnabled === true ) {

            if(!APP.debugUtils)
            {
                APP.debugUtils = new EHDI.debugUtils.debugUtilsContainer( APP.config.version );
                // APP.managers.scene.addNotification( APP.debugUtils );
            }
        }
    };



    var _initListeners = function () {

    };

    // ** Initialization Methods
    var _killProps = function () {

    };

    var _killGraphics = function () {

        if ( _sprBG ) {

            if ( _sprBG.parent ) _sprBG.parent.removeChild( _sprBG );

            _sprBG.destroy( { children: true } );
        }
        _sprBG = null;

        if ( _sprGizmo ) {

            if ( _sprGizmo.parent ) _sprGizmo.parent.removeChild( _sprGizmo );

            _sprGizmo.destroy( { children: true } );
        }
        _sprGizmo = null;

        if ( _sprLogo ) {

            if ( _sprLogo.parent ) _sprLogo.parent.removeChild( _sprLogo );

            _sprLogo.destroy( { children: true } );
        }
        _sprLogo = null;

        if ( _btnAudio ) {

            _btnAudio.setOnClickFunction( null );
            if ( _btnAudio.parent ) _btnAudio.parent.removeChild( _btnAudio );

            _btnAudio.destroy( { children: true } );
        }
        _btnAudio = null;

        if ( _txtPlay ) {

            if ( _txtPlay.parent ) _txtPlay.parent.removeChild( _txtPlay );

            _txtPlay.destroy( { children: true } );
        }
        _txtPlay = null;

        if ( _btnPlay ) {

            _btnPlay.setOnClickFunction( null );
            if ( _btnPlay.parent ) _btnPlay.parent.removeChild( _btnPlay );

            _btnPlay.destroy( { children: true } );
        }
        _btnPlay = null;

        if ( _uiScore ) {

            if ( _uiScore.parent ) _uiScore.parent.removeChild( _uiScore );

            _uiScore.destroy( { children: true } );
        }
        _uiScore = null;

    };

    var _killListeners = function () {

    };

    // ** Scene Methods
    this.screenWillAppear = function () {


    };

    this.screenDidAppear = function(){
    if(!APP.managers.sound.bgm)
        {
            APP.managers.sound.autoResumeToggle(true);
            APP.managers.sound.bgm = APP.managers.sound.playBGM("bgm");
        }


    var tlPhase2 = function()
    {

        this.tl.kill();
        this.tl = new TimelineMax({repeat: -1, yoyo: true});
        this.tl.to(_sprGizmo, 0.5, {y: _sprGizmo.y - 10, ease: Power0.easeNone});
        this.tl.play();

    }


    this.tl = new TimelineMax({repeat: 0});
    this.tl.to(_sprLogo, 1, {y:APP.config.stageHeight * 0.45 , ease: Bounce.easeOut});
    this.tl.to(_sprGizmo, 1, {x:APP.config.stageWidth * 0.3, y: APP.config.stageHeight * 0.45, ease: Back.easeOut});
    this.tl.to(_btnPlay, 0.25, {scaleX:1, scaleY:1, ease: Back.easeOut});
    this.tl.add(tlPhase2.bind(this));

    };

    this.screenWillDisappear = function(){

        this.tl.stop();
        this.tl.kill();

    };

    this.screenDidDisappear = function () {

        this.destroy( { children: true } );
    };

    // ** Handlers

    // Public Methods

    this.destroy = function () {

        // Kill listeners
        _killListeners();

        // Kill graphics
        _killGraphics();

        // Kill props
        _killProps();

        // Call superclass method
        APP.scenes.TitleScene.prototype.destroy.apply( this, arguments );
    };

    // Call init methods
    _initProps();
    _initGraphics();
    _initListeners();

};
APP.scenes.TitleScene.prototype = Object.create( EHDI.aka.Container.prototype );
APP.scenes.TitleScene.prototype.constructor = APP.scenes.TitleScene;

/* Font Face Observer v2.0.13 - © Bram Stein. License: BSD-3-Clause */(function(){'use strict';var f,g=[];function l(a){g.push(a);1==g.length&&f()}function m(){for(;g.length;)g[0](),g.shift()}f=function(){setTimeout(m)};function n(a){this.a=p;this.b=void 0;this.f=[];var b=this;try{a(function(a){q(b,a)},function(a){r(b,a)})}catch(c){r(b,c)}}var p=2;function t(a){return new n(function(b,c){c(a)})}function u(a){return new n(function(b){b(a)})}function q(a,b){if(a.a==p){if(b==a)throw new TypeError;var c=!1;try{var d=b&&b.then;if(null!=b&&"object"==typeof b&&"function"==typeof d){d.call(b,function(b){c||q(a,b);c=!0},function(b){c||r(a,b);c=!0});return}}catch(e){c||r(a,e);return}a.a=0;a.b=b;v(a)}}
function r(a,b){if(a.a==p){if(b==a)throw new TypeError;a.a=1;a.b=b;v(a)}}function v(a){l(function(){if(a.a!=p)for(;a.f.length;){var b=a.f.shift(),c=b[0],d=b[1],e=b[2],b=b[3];try{0==a.a?"function"==typeof c?e(c.call(void 0,a.b)):e(a.b):1==a.a&&("function"==typeof d?e(d.call(void 0,a.b)):b(a.b))}catch(h){b(h)}}})}n.prototype.g=function(a){return this.c(void 0,a)};n.prototype.c=function(a,b){var c=this;return new n(function(d,e){c.f.push([a,b,d,e]);v(c)})};
function w(a){return new n(function(b,c){function d(c){return function(d){h[c]=d;e+=1;e==a.length&&b(h)}}var e=0,h=[];0==a.length&&b(h);for(var k=0;k<a.length;k+=1)u(a[k]).c(d(k),c)})}function x(a){return new n(function(b,c){for(var d=0;d<a.length;d+=1)u(a[d]).c(b,c)})};window.Promise||(window.Promise=n,window.Promise.resolve=u,window.Promise.reject=t,window.Promise.race=x,window.Promise.all=w,window.Promise.prototype.then=n.prototype.c,window.Promise.prototype["catch"]=n.prototype.g);}());

(function(){function l(a,b){document.addEventListener?a.addEventListener("scroll",b,!1):a.attachEvent("scroll",b)}function m(a){document.body?a():document.addEventListener?document.addEventListener("DOMContentLoaded",function c(){document.removeEventListener("DOMContentLoaded",c);a()}):document.attachEvent("onreadystatechange",function k(){if("interactive"==document.readyState||"complete"==document.readyState)document.detachEvent("onreadystatechange",k),a()})};function r(a){this.a=document.createElement("div");this.a.setAttribute("aria-hidden","true");this.a.appendChild(document.createTextNode(a));this.b=document.createElement("span");this.c=document.createElement("span");this.h=document.createElement("span");this.f=document.createElement("span");this.g=-1;this.b.style.cssText="max-width:none;display:inline-block;position:absolute;height:100%;width:100%;overflow:scroll;font-size:16px;";this.c.style.cssText="max-width:none;display:inline-block;position:absolute;height:100%;width:100%;overflow:scroll;font-size:16px;";
this.f.style.cssText="max-width:none;display:inline-block;position:absolute;height:100%;width:100%;overflow:scroll;font-size:16px;";this.h.style.cssText="display:inline-block;width:200%;height:200%;font-size:16px;max-width:none;";this.b.appendChild(this.h);this.c.appendChild(this.f);this.a.appendChild(this.b);this.a.appendChild(this.c)}
function t(a,b){a.a.style.cssText="max-width:none;min-width:20px;min-height:20px;display:inline-block;overflow:hidden;position:absolute;width:auto;margin:0;padding:0;top:-999px;white-space:nowrap;font-synthesis:none;font:"+b+";"}function y(a){var b=a.a.offsetWidth,c=b+100;a.f.style.width=c+"px";a.c.scrollLeft=c;a.b.scrollLeft=a.b.scrollWidth+100;return a.g!==b?(a.g=b,!0):!1}function z(a,b){function c(){var a=k;y(a)&&a.a.parentNode&&b(a.g)}var k=a;l(a.b,c);l(a.c,c);y(a)};function A(a,b){var c=b||{};this.family=a;this.style=c.style||"normal";this.weight=c.weight||"normal";this.stretch=c.stretch||"normal"}var B=null,C=null,E=null,F=null;function G(){if(null===C)if(J()&&/Apple/.test(window.navigator.vendor)){var a=/AppleWebKit\/([0-9]+)(?:\.([0-9]+))(?:\.([0-9]+))/.exec(window.navigator.userAgent);C=!!a&&603>parseInt(a[1],10)}else C=!1;return C}function J(){null===F&&(F=!!document.fonts);return F}
function K(){if(null===E){var a=document.createElement("div");try{a.style.font="condensed 100px sans-serif"}catch(b){}E=""!==a.style.font}return E}function L(a,b){return[a.style,a.weight,K()?a.stretch:"","100px",b].join(" ")}
A.prototype.load=function(a,b){var c=this,k=a||"BESbswy",q=0,D=b||3E3,H=(new Date).getTime();return new Promise(function(a,b){if(J()&&!G()){var M=new Promise(function(a,b){function e(){(new Date).getTime()-H>=D?b():document.fonts.load(L(c,'"'+c.family+'"'),k).then(function(c){1<=c.length?a():setTimeout(e,25)},function(){b()})}e()}),N=new Promise(function(a,c){q=setTimeout(c,D)});Promise.race([N,M]).then(function(){clearTimeout(q);a(c)},function(){b(c)})}else m(function(){function u(){var b;if(b=-1!=
f&&-1!=g||-1!=f&&-1!=h||-1!=g&&-1!=h)(b=f!=g&&f!=h&&g!=h)||(null===B&&(b=/AppleWebKit\/([0-9]+)(?:\.([0-9]+))/.exec(window.navigator.userAgent),B=!!b&&(536>parseInt(b[1],10)||536===parseInt(b[1],10)&&11>=parseInt(b[2],10))),b=B&&(f==v&&g==v&&h==v||f==w&&g==w&&h==w||f==x&&g==x&&h==x)),b=!b;b&&(d.parentNode&&d.parentNode.removeChild(d),clearTimeout(q),a(c))}function I(){if((new Date).getTime()-H>=D)d.parentNode&&d.parentNode.removeChild(d),b(c);else{var a=document.hidden;if(!0===a||void 0===a)f=e.a.offsetWidth,
g=n.a.offsetWidth,h=p.a.offsetWidth,u();q=setTimeout(I,50)}}var e=new r(k),n=new r(k),p=new r(k),f=-1,g=-1,h=-1,v=-1,w=-1,x=-1,d=document.createElement("div");d.dir="ltr";t(e,L(c,"sans-serif"));t(n,L(c,"serif"));t(p,L(c,"monospace"));d.appendChild(e.a);d.appendChild(n.a);d.appendChild(p.a);document.body.appendChild(d);v=e.a.offsetWidth;w=n.a.offsetWidth;x=p.a.offsetWidth;I();z(e,function(a){f=a;u()});t(e,L(c,'"'+c.family+'",sans-serif'));z(n,function(a){g=a;u()});t(n,L(c,'"'+c.family+'",serif'));
z(p,function(a){h=a;u()});t(p,L(c,'"'+c.family+'",monospace'))})})};"object"===typeof module?module.exports=A:(window.FontFaceObserver=A,window.FontFaceObserver.prototype.load=A.prototype.load);}());

var EHDI = EHDI || Object.create(null);
var UTILS = UTILS || Object.create(null);
var POOLS = POOLS || Object.create(null);

EHDI.components = EHDI.components || Object.create(null);

EHDI.components.ScoreEffect = function(stage, highscore) {    
    EHDI.aka.Container.call(this);

    var DECAY_TIME = 500;
    var FLOAT_SPEED = 0.25;


    this.scoreDisplay = new EHDI.displays.TextSprite(APP.managers.json.getLocale("STR_CONT_SCOREEFFECT"));
        this.scoreDisplay.anchor.x = 0.5;
        this.scoreDisplay.anchor.y = 1;
        this.addChild(this.scoreDisplay);
    
    this.timer=0;
    this.active = false;

    this.appear = function(score)
    {
        if(this.active)
            return;

        this.scoreDisplay.y =0;
        this.scoreDisplay.text = score;
        this.scoreDisplay.anchor.x = 0.5;
        this.scoreDisplay.anchor.y = 1;
        this.timer = DECAY_TIME;
        this.active = true;
    }

    this.disappear = function()
    {
        if(!this.active)
            return;

        this.active = false;
        this.alpha =0;

    }

    this.update = function (delta)
    {
        if(!this.active)
            return false;

        this.timer -= delta;
        this.alpha = this.timer /  DECAY_TIME;
        this.scoreDisplay.y -= delta * FLOAT_SPEED;

        if (this.timer <= 0)
            {
                this.disappear();
                return true;
            }

        return false;
    }
}
EHDI.components.ScoreEffect.prototype = Object.create(EHDI.aka.Container.prototype);


EHDI.components.ScoreEffectManager = function()
{
    this.init = function(cont)
    {
        this.container = cont;
        this.scoreEffects = [];
        this.effectPool = new Pool(EHDI.components.ScoreEffect, 2);
    }

    this.popScore = function(x,y,score)
    {                                           
        var effect = this.effectPool.takeFromPool();
        effect.appear(score);
        effect.x = x;
        effect.y = y;
        this.scoreEffects.push(effect); 
        this.container.addChild(effect);
    }

    this.update = function(delta)
    {  
        if(this.scoreEffects.length > 0)
        {
            var toReturn = [];
            for(var i = 0, l = this.scoreEffects.length; i<l; i++)
                {
                    var effect =this.scoreEffects[i];
                    if(effect.update(delta))
                        toReturn.push(effect);
                }
            this.effectPool.returnBatch(this.scoreEffects, toReturn);
        }
    }
}


"use strict";
APP.ui.ScoreUI = function ( p_type, p_value ) {

    // Invoke (needed)
    EHDI.aka.Container.call( this );

    // Properties

    // ** Parent (This reference)
    var _parent = this;

    // ** General Values
    var _type, _isPaused, _isUpdateActive, _value;

    // ** Graphics
    var _sprBG, _sprFlash, _sprLine, _sprSparkle, _txtHeader, _txtValue, _timelineUpdate;

    // ** General Methods

    var _setValue = function ( p_value, p_addValue ) {
        
        // Check if param values are invalid, then throw error
        if ( typeof p_value !== "number" ) throw "Score value for score ui is not valid. Must be number.";
        if ( p_value < 0 ) throw "Score value for score ui is not valid. Must be greater than or equal to zero.";

        // Check if some propeties are invalid, then return
        if ( !_txtValue ) return;
        if ( !_timelineUpdate ) return;

        // Set value
        if ( p_addValue === true ) _value += p_value;
        else _value = p_value;

        // Set text
        var str = _value.toString();
        if ( _txtValue.text !== str ) _txtValue.text = str; 
        
        // Start animation
        _isUpdateActive = true;
        _timelineUpdate.restart();
        _timelineUpdate.play();

        // Play sfx
        APP.managers.sound.playSFX( "score_points" );
    };

    var _toggleEffects = function( p_value ) {
        
        // Check if param values are invalid, then throw error
        if ( p_value !== true &&
            p_value !== false ) throw "Value must be boolean.";
        
        // Toggle
        if ( _sprLine ) _sprLine.visible = p_value;
        if ( _sprSparkle ) _sprSparkle.visible = p_value;
    }
    
    var _toggleFlash  = function( p_value ) {

        // Check if param values are invalid, then throw error
        if ( p_value !== true &&
            p_value !== false ) throw "Value must be boolean.";
        
        // Toggle
        if ( _sprFlash ) _sprFlash.visible = p_value;
    }

    // ** Initialization Methods

    var _initProps = function ( p_type, p_value ) {

        // Check if param values are invalid, then throw error
        if ( p_type !== APP.ui.ScoreType.HIGHSCORE &&
            p_type !== APP.ui.ScoreType.SCORE ) throw "Type value for score ui is invalid.";

        if ( typeof p_value !== "number" ) throw "Score value for score ui is not valid. Must be number.";
        if ( p_value < 0 ) throw "Score value for score ui is not valid. Must be greater than or equal to zero.";

        // Initialize properties
        _type = p_type;
        _isPaused = false;
        _isUpdateActive = false;
        _value = p_value;
    };

    var _initGraphics = function () {

        // Initialize graphics
        if ( !_sprBG ) {

            _sprBG = new EHDI.aka.Sprite( EHDI.Assets.images[ "assets/ui/gfx_container.png" ] );

            if ( _parent ) _parent.addChild( _sprBG );
        }
        
        if ( !_txtHeader ) {

            var strHeader;

            if ( _type === APP.ui.ScoreType.HIGHSCORE ) strHeader = APP.managers.json.getLocale("STR_CONT_BEST");
            else if ( _type === APP.ui.ScoreType.SCORE ) strHeader = APP.managers.json.getLocale("STR_CONT_SCORETITLE");

            _txtHeader = new EHDI.displays.TextSprite(strHeader);
            _txtHeader.anchor.set( 0.5, 0.5 );
            _txtHeader.position.set( _sprBG.width * 0.169, _sprBG.height * 0.4 );

            if ( _parent ) _parent.addChild( _txtHeader );
        }

        if ( !_txtValue ) {
            
            _txtValue = new EHDI.displays.TextSprite(APP.managers.json.getLocale("STR_CONT_BESTSCORE"));
            _txtValue.text =  _value.toString();            
            _txtValue.anchor.set( 0.5, 0.5 );
            _txtValue.position.set( _sprBG.width * 0.675, _sprBG.height * 0.45 );
            
            if ( _parent ) _parent.addChild( _txtValue );
        }

        if ( !_sprFlash ) {

            _sprFlash = new EHDI.aka.Sprite( EHDI.Assets.images[ "assets/ui/gfx_container_white.png" ] );
            _sprFlash.alpha = 0;
            _sprFlash.visible = false;

            if ( _parent ) _parent.addChild( _sprFlash );
        }

        if ( !_sprSparkle ) {

            _sprSparkle = new EHDI.aka.Sprite( EHDI.Assets.images[ "assets/ui/gfx_flare_star.png" ] );
            _sprSparkle.anchor.set( 0.5, 0.5 );
            _sprSparkle.position.set( _txtHeader.x, _txtHeader.y );
            _sprSparkle.scale.set( 0, 0 );
            _sprSparkle.visible = false;
            if ( _parent ) _parent.addChild( _sprSparkle );
        }

        if ( !_sprLine ) {

            _sprLine = new EHDI.aka.Sprite( EHDI.Assets.images[ "assets/ui/gfx_flare_long.png" ] );
            _sprLine.anchor.set( 0.5, 0.5 );
            _sprLine.position.set( _sprBG.width * 0.5, _sprBG.height * 0.4 );
            _sprLine.scale.set( 0, 1 );
            _sprLine.visible = false;
            if ( _parent ) _parent.addChild( _sprLine );
        }

        if ( !_timelineUpdate ) {

            _timelineUpdate = new TimelineMax( { onComplete: function () { if ( _isUpdateActive === true ) _isUpdateActive = false; } } );
            _timelineUpdate.to( _txtValue.scale, 0.1, { x: 1.5, y : 1.5 } );
            _timelineUpdate.to( _txtValue.scale, 0.1, { x: 1, y : 1 } );
            _timelineUpdate.addCallback( _toggleEffects, "+=0", [ true ] );
            _timelineUpdate.addCallback( _toggleFlash, "+=0", [ true ] );
            _timelineUpdate.to( _sprSparkle.scale, 0.1, { x: 1, y : 1, ease: Power0.easeNone } );
            _timelineUpdate.to( _sprLine.scale, 0.2, { x: 1, y : 1, ease: Power0.easeNone }, "-=0.1" );
            _timelineUpdate.to( _sprFlash, 0.05, { alpha : 0.75 } );
            _timelineUpdate.to( _sprSparkle, 0.15, { x: _parent.width * 0.9, rotation: 5, ease: Power0.easeNone }, "-=0.15" );
            _timelineUpdate.to( _sprFlash, 0.1, { alpha : 0 }, "-=0.025" );
            _timelineUpdate.addCallback( _toggleFlash, "-=0.05", [ false ] );
            _timelineUpdate.addCallback( _toggleEffects, "+=0.025", [ false ] );
            _timelineUpdate.pause();
        }
    };

    var _initListeners = function () {};

    // ** Kill Methods
    var _killProps = function () {

        _parent = null;
        _type = null;
        _isPaused = null;
        _isUpdateActive = null;
        _value = null;
    };

    var _killGraphics = function () {

        if ( _sprBG ) {
            
            if ( _sprBG.parent ) _sprBG.parent.removeChild( _sprBG );

            _sprBG.destroy( { children: true } );
        }
        _sprBG = null;

        if ( _sprFlash ) {
            
            if ( _sprFlash.parent ) _sprFlash.parent.removeChild( _sprFlash );

            _sprFlash.destroy( { children: true } );
        }
        _sprFlash = null;

        if ( _sprLine ) {
            
            if ( _sprLine.parent ) _sprLine.parent.removeChild( _sprLine );

            _sprLine.destroy( { children: true } );
        }
        _sprLine = null;

        if ( _sprSparkle ) {
            
            if ( _sprSparkle.parent ) _sprSparkle.parent.removeChild( _sprSparkle );

            _sprSparkle.destroy( { children: true } );
        }
        _sprSparkle = null;

        if ( _txtHeader ) {
            
            if ( _txtHeader.parent ) _txtHeader.parent.removeChild( _txtHeader );

            _txtHeader.destroy( { children: true } );
        }
        _txtHeader = null;

        if ( _txtValue ) {
            
            if ( _txtValue.parent ) _txtValue.parent.removeChild( _txtValue );

            _txtValue.destroy( { children: true } );
        }
        _txtValue = null;

        if ( _timelineUpdate ) {

            _timelineUpdate.stop();
            _timelineUpdate.kill();
        }
        _timelineUpdate = null;
    };

    var _killListeners = function () { };

    // Public Methods

    this.destroy = function () {
        
        // Kill listeners
        _killListeners();

        // Kill graphics
        _killGraphics();

        // Kill props
        _killProps();

        // Call superclass method
        APP.ui.ScoreUI.prototype.destroy.apply( this, arguments );
    };

    // Call init methods
    _initProps( p_type, p_value );
    _initGraphics();
    _initListeners();

    Object.defineProperties( _parent, {
        "value": {
            get: function () { return _value; },
            enumerable: true
        },
        "paused": {
            get: function () { return _isPaused; },
            set: function ( p_value ) {

                if ( p_value !== true &&
                    p_value !== false ) throw "Pause value should be boolean.";

                if ( _isPaused === p_value ) return;

                // Set isPaused
                _isPaused = p_value;
                
                if ( _isPaused === true ) {

                    if ( _timelineUpdate ) {

                        if ( _timelineUpdate.isActive() && _isUpdateActive === true ) _timelineUpdate.pause();
                    }

                }
                else if ( _isPaused === false ) {

                    if ( _timelineUpdate ) {

                        if ( !_timelineUpdate.isActive() && _isUpdateActive === true ) _timelineUpdate.play();
                    }
                }
                
            },
            enumerable: true
        },
        "setScore": {
            enumerable: true,
            writable: true,
            value: function ( p_value, p_addValue ) { _setValue( p_value, p_addValue ); } 
        }
    });

    // Return
    return _parent;
};
APP.ui.ScoreUI.prototype = Object.create( EHDI.aka.Container.prototype );
APP.ui.ScoreUI.prototype.constructor = APP.ui.ScoreUI;
"use strict";
APP.ui.TimerUI = function ( p_type, p_seconds, p_callbackComplete, p_callbackTick ) {

    // Invoke (needed)
    EHDI.aka.Container.call( this );

    // Properties

    // ** Parent (This reference)
    var _parent = this;

    // ** General Values
    var _callbackComplete, _callbackTick, _currentTime, _endTime, _tickTime, _isComplete, _isPaused, _isUpdateActive, _isWarningActive, _type;

    // ** Graphics
    var _sprBG, _sprFlash, _sprLine, _sprSparkle, _txtHeader, _txtValue, _timelineShake, _timelineUpdate;

    // Private Methods

    // ** General Methods
    
    var _getConvertedTime = function () {

        var result = "";

        if ( _currentTime && _txtValue ) {

            var timeInSecs = Math.round( _currentTime / 1000 );
            var minutes = Math.floor( timeInSecs / 60 );
            var seconds = Math.round( timeInSecs % 60 );

            var strMins, strSecs;
            
            if ( minutes < 10 ) strMins = "0" + minutes.toString();
            else strMins = minutes.toString();

            if ( seconds < 10 ) strSecs = "0" + seconds.toString();
            else strSecs = seconds.toString();

            var str = strMins + ":" + strSecs;
            if ( _txtValue.text !== str ) _txtValue.text = str; 
        }

        return result;
    };

    var _setValue = function ( p_value, p_addValue ) {
        
        // Check if param values are invalid, then throw error
        if ( typeof p_value !== "number" ) throw "Time value for time ui is not valid. Must be number.";
        if ( p_value <= 0 ) throw "Time value for time ui is not valid. Must be greater than zero.";

        // Check if some propeties are invalid, then return
        if ( !_txtValue ) return;
        if ( !_timelineUpdate ) return;

        // Set value
        if ( p_addValue === true ) _currentTime += p_value;
        else _currentTime = p_value;

        // Convert time
        _getConvertedTime();

        // Start animation
        _isUpdateActive = true;
        _timelineUpdate.restart();
        _timelineUpdate.play();
    };

    var _toggleEffects = function( p_value ) {
        
        // Check if param values are invalid, then throw error
        if ( p_value !== true &&
            p_value !== false ) throw "Value must be boolean.";
        
        // Toggle
        if ( _sprLine ) _sprLine.visible = p_value;
        if ( _sprSparkle ) _sprSparkle.visible = p_value;
    };
    
    var _toggleFlash  = function( p_value ) {

        // Check if param values are invalid, then throw error
        if ( p_value !== true &&
            p_value !== false ) throw "Value must be boolean.";
        
        // Toggle
        if ( _sprFlash ) _sprFlash.visible = p_value;
    };

    var _updateTime = function ( p_delta ) {

        // Check values if invalid, then retun
        if ( !_type ) return;

        if ( typeof _currentTime !== "number" ) return;
        if ( typeof _endTime !== "number" ) return;

        if ( _isComplete === true ) return;
        if ( _isPaused === true ) return;

        // Do according to value 
        if ( _type === APP.ui.TimerType.COUNTDOWN ) {

            _currentTime -= p_delta;
            _currentTime = Math.max( 0, _currentTime );

            if ( _currentTime <= _endTime ) _isComplete = true;
        }
        else if ( _type === APP.ui.TimerType.COUNTUP ) {

            _currentTime += p_delta;
            _currentTime = Math.min( 0, _endTime );

            if ( _currentTime <= _endTime ) _isComplete = true;
        }

        // Update tick time
        _tickTime -= p_delta;

        if ( _tickTime <= 0 ) {

            // Reset tick time, add one seconds in case tick goes over a second
            _tickTime += 1000;

            // Call tick callback
            if ( _callbackTick ) _callbackTick();
        }

        // Convert time
        _getConvertedTime();

        // If isCallbackCalled, invoke callback
        // Else check for warning
        if ( _isComplete ) {

            if ( _callbackComplete ) _callbackComplete();
        }
        else {
            
            // If text value is empty, return
            if ( !_txtValue ) return;

            // Get difference of current time to end time
            var timeLeft = Math.round( Math.abs( ( _endTime / 1000 ) - ( _currentTime / 1000 ) ) );
            
            // Do time left
            if ( timeLeft > 10 && _isWarningActive ) {

                // Set isWarningActive to false
                _isWarningActive = false;

                // Change style of text field
                _txtValue.style = { fontFamily:'proximanova-black', fill: 0xFFFFFF, fontSize: 36 };
                
                if ( _timelineShake ) {
                    if ( _timelineShake.isActive() ) {
                        _timelineShake.stop();
                        _timelineShake.reset();
                    }
                }
            } 
            else if ( timeLeft < 10 && !_isWarningActive ) {

                // Set warning to true
                _isWarningActive = true;
                
                // Change style of text field
                _txtValue.style = { fontFamily:'proximanova-black', fill: 0xED1C24, fontSize: 36 };
                
                if ( _timelineShake ) {
                    if ( !_timelineShake.isActive() ) {
                        _timelineShake.play();
                    }
                }
            }
        }
    };

    // ** Handlers

    /**
     * Handler for frame update
     * @param {Number} p_delta 
     */
    var _handler_frameUpdate = function ( p_delta ) {

        if(APP.pauseButton)
            {
                if ( APP.pauseButton.isPaused === true || APP.pauseButton.isEndGame === true )
                return;
            }
       // Update time
       _updateTime( p_delta );
    };

    // ** Initialization Methods

    var _initProps = function ( p_type, p_time, p_callbackComplete, p_callbackTick ) {

        // Check if param values are invalid, then throw error
        if ( p_type !== APP.ui.TimerType.COUNTDOWN &&
            p_type !== APP.ui.TimerType.COUNTUP ) throw "Type value for timer ui is invalid.";

        if ( !p_time ) throw "Time value for timer ui is not defined.";
        if ( typeof p_time !== "number" ) throw "Time value for timer ui is not valid. Must be number.";
        if ( p_time <= 0 ) throw "Time value for timer ui is not valid. Must be greater than zero";

        if ( !p_callbackComplete ) throw "Callback complete for timer ui is not defined.";
        if ( !p_callbackTick ) throw "Callback tick for timer ui is not defined.";

        // Initialize properties
        _callbackComplete = p_callbackComplete;
        _callbackTick = p_callbackTick;
        _isComplete = false;
        _isPaused = false;
        _isUpdateActive = false;
        _isWarningActive = false;
        _tickTime = 1000;
        _type = p_type;
        
        // Do according to type
        if ( p_type === APP.ui.TimerType.COUNTDOWN ) {

            _currentTime = p_time * 1000;
            _endTime = 0;
        }
        else if ( p_type === APP.ui.TimerType.COUNTUP ) {

            _currentTime = 0;
            _endTime = p_time * 1000;
        }
            
    };

    var _initGraphics = function () {

        // Initialize graphics
        if ( !_sprBG ) {

             _sprBG = new EHDI.aka.Sprite( EHDI.Assets.images[ "assets/ui/gfx_container.png" ] );

             if ( _parent ) _parent.addChild( _sprBG );
        }
        
        if ( !_txtHeader ) {

            _txtHeader = new EHDI.displays.TextSprite(APP.managers.json.getLocale("STR_CONT_TIMERTITLE"));
            _txtHeader.anchor.set( 0.5, 0.5 );
            _txtHeader.position.set( _sprBG.width * 0.169, _sprBG.height * 0.4 );

            if ( _parent ) _parent.addChild( _txtHeader );
        }

        if ( !_txtValue ) {
            
            _txtValue =  new EHDI.displays.TextSprite(APP.managers.json.getLocale("STR_CONT_TIMERVALUE"));
            _txtValue.anchor.set( 0.5, 0.5 );
            _txtValue.position.set( _sprBG.width * 0.675, _sprBG.height * 0.45 );
            
            if ( _parent ) _parent.addChild( _txtValue );

            // Get converted time
            _getConvertedTime();
        }

        if ( !_sprFlash ) {

            _sprFlash = new EHDI.aka.Sprite( EHDI.Assets.images[ "assets/ui/gfx_container_white.png" ] );
            _sprFlash.alpha = 0;
            _sprFlash.visible = false;

            if ( _parent ) _parent.addChild( _sprFlash );
        }
        
        if ( !_sprSparkle ) {

            _sprSparkle = new EHDI.aka.Sprite( EHDI.Assets.images[ "assets/ui/gfx_flare_star.png" ] );
            _sprSparkle.anchor.set( 0.5, 0.5 );
            _sprSparkle.position.set( _txtHeader.x, _txtHeader.y );
            _sprSparkle.scale.set( 0, 0 );
            _sprSparkle.visible = false;
            if ( _parent ) _parent.addChild( _sprSparkle );
        }

        if ( !_sprLine ) {

            _sprLine = new EHDI.aka.Sprite( EHDI.Assets.images[ "assets/ui/gfx_flare_long.png" ] );
            _sprLine.anchor.set( 0.5, 0.5 );
            _sprLine.position.set( _sprBG.width * 0.5, _sprBG.height * 0.4 );
            _sprLine.scale.set( 0, 1 );
            _sprLine.visible = false;
            if ( _parent ) _parent.addChild( _sprLine );
        }

        if ( !_timelineUpdate ) {

            _timelineUpdate = new TimelineMax( { onComplete: function () { if ( _isUpdateActive === true ) _isUpdateActive = false; } } );
            _timelineUpdate.to( _txtValue.scale, 0.1, { x: 1.5, y : 1.5 } );
            _timelineUpdate.to( _txtValue.scale, 0.1, { x: 1, y : 1 } );
            _timelineUpdate.addCallback( _toggleEffects, "+=0", [ true ] );
            _timelineUpdate.addCallback( _toggleFlash, "+=0", [ true ] );
            _timelineUpdate.to( _sprSparkle.scale, 0.1, { x: 1, y : 1, ease: Power0.easeNone } );
            _timelineUpdate.to( _sprLine.scale, 0.2, { x: 1, y : 1, ease: Power0.easeNone }, "-=0.1" );
            _timelineUpdate.to( _sprFlash, 0.05, { alpha : 0.75 } );
            _timelineUpdate.to( _sprSparkle, 0.15, { x: _parent.width * 0.9, rotation: 5, ease: Power0.easeNone }, "-=0.15" );
            _timelineUpdate.to( _sprFlash, 0.1, { alpha : 0 }, "-=0.025" );
            _timelineUpdate.addCallback( _toggleFlash, "-=0.05", [ false ] );
            _timelineUpdate.addCallback( _toggleEffects, "+=0.025", [ false ] );
            _timelineUpdate.pause();
        }

        if ( !_timelineShake ) {

            _timelineShake = new TimelineMax( { repeat : -1 } );
            _timelineShake.to( _txtValue, 0.05, { x : _sprBG.width * 0.69, ease : Power0.easeNone } );
            _timelineShake.to( _txtValue, 0.1, { x : _sprBG.width * 0.66, ease : Power0.easeNone } );
            _timelineShake.to( _txtValue, 0.05, { x : _sprBG.width * 0.675, ease : Power0.easeNone } );
            _timelineShake.pause();
        }
    };

    var _initListeners = function () {

        // Add frame listeners
        APP.managers.update.addFrameListener( _handler_frameUpdate );
    };

    // ** Kill Methods
    var _killProps = function () {

        _parent = null;
        _callbackComplete = null;
        _currentTime = null;
        _endTime = null;
        _isComplete = null;
        _isPaused = null;
        _isUpdateActive = null;
        _isWarningActive = null;
        _tickTime = null;
        _type = null;
    };

    var _killGraphics = function () {

        if ( _sprBG ) {
            
            if ( _sprBG.parent ) _sprBG.parent.removeChild( _sprBG );

            _sprBG.destroy( { children: true } );
        }
        _sprBG = null;

        if ( _sprFlash ) {
            
            if ( _sprFlash.parent ) _sprFlash.parent.removeChild( _sprFlash );

            _sprFlash.destroy( { children: true } );
        }
        _sprFlash = null;

        if ( _sprLine ) {
            
            if ( _sprLine.parent ) _sprLine.parent.removeChild( _sprLine );

            _sprLine.destroy( { children: true } );
        }
        _sprLine = null;

        if ( _sprSparkle ) {
            
            if ( _sprSparkle.parent ) _sprSparkle.parent.removeChild( _sprSparkle );

            _sprSparkle.destroy( { children: true } );
        }
        _sprSparkle = null;

        if ( _txtHeader ) {
            
            if ( _txtHeader.parent ) _txtHeader.parent.removeChild( _txtHeader );

            _txtHeader.destroy( { children: true } );
        }
        _txtHeader = null;

        if ( _txtValue ) {
            
            if ( _txtValue.parent ) _txtValue.parent.removeChild( _txtValue );

            _txtValue.destroy( { children: true } );
        }
        _txtValue = null;

        if ( _timelineShake ) {

            _timelineShake.stop();
            _timelineShake.kill();
        }
        _timelineShake = null;

        if ( _timelineUpdate ) {

            _timelineUpdate.stop();
            _timelineUpdate.kill();
        }
        _timelineUpdate = null;
    };

    var _killListeners = function () {

        // Remove frame listeners
        APP.managers.update.removeFrameListener( _handler_frameUpdate );
    };

    // Public Methods

    this.destroy = function () {
        
        // Kill listeners
        _killListeners();

        // Kill graphics
        _killGraphics();

        // Kill props
        _killProps();

        // Call superclass method
        APP.ui.TimerUI.prototype.destroy.apply( this, arguments );
    };

    // Call init methods
    _initProps( p_type, p_seconds, p_callbackComplete, p_callbackTick );
    _initGraphics();
    _initListeners();

    // ** Public Methods
    this.setTime = function ( p_value, p_addValue ) { _setValue( p_value, p_addValue ); };

    Object.defineProperties( _parent, {
        "value": {
            get: function () { return _value; },
            enumerable: true
        },
        "paused": {
            get: function () { return _isPaused; },
            set: function ( p_value ) {

                if ( p_value !== true &&
                    p_value !== false ) throw "Pause value should be boolean.";

                if ( _isPaused === p_value ) return;

                // Set isPaused
                _isPaused = p_value;
                
                if ( _isPaused === true ) {

                    if ( _timelineUpdate ) {

                        if ( _timelineUpdate.isActive() && _isUpdateActive === true ) _timelineUpdate.pause();
                    }

                    if ( _timelineShake ) {

                        if ( _timelineShake.isActive() && _isWarningActive === true ) _timelineShake.pause();
                    }

                }
                else if ( _isPaused === false ) {

                    if ( _timelineUpdate ) {

                        if ( !_timelineUpdate.isActive() && _isUpdateActive === true ) _timelineUpdate.play();
                    }
                    
                    if ( _timelineShake ) {

                        if ( !_timelineShake.isActive() && _isWarningActive === true ) _timelineShake.play();
                    }
                }
                
            },
            enumerable: true
        },
        
    });

    

    // Return
    return _parent;
};
APP.ui.TimerUI.prototype = Object.create( EHDI.aka.Container.prototype );
APP.ui.TimerUI.prototype.constructor = APP.ui.TimerUI;
var EHDI = (function(ehdi){
    ehdi.DBoneFactory =  (function(){
        var _public = Object.create(null);
        var enableClock = true;
        var armatures = [];
        var skelData = Object.create(null);

        var loop = function(dt){
            dragonBones.WorldClock.clock.advanceTime(dt * _public.dtMultiplier);
        }

        _public.dtMultiplier = 0.001;

        Object.defineProperty(_public, "enableClock", {
            set: function(val){
                enableClock = val;
                if(enableClock && !APP.managers.update.hasFrameListener(loop)){
                    APP.managers.update.addFrameListener(loop);
                }
                if(!enableClock && APP.managers.update.hasFrameListener(loop)){
                    APP.managers.update.removeFrameListener(loop);
                }
            },
            get: function(){
                return enableClock;
            }
        });

        _public.createArmature = function(name){
            var newArmature = _public.PixiFactory.buildArmature(name);
            dragonBones.WorldClock.clock.add(newArmature);
            armatures.push(newArmature);
            return newArmature;
        }

        _public.destroyArmature = function(armature){
            var index = armatures.indexOf(armature);
            if(index > -1){
                var arm = armatures.splice(index, 1)[0];
                dragonBones.WorldClock.clock.remove(arm);
                arm.dispose();
            }
        }

        _public.destroyAllArmature = function(){
            while(armatures.length > 0){
                var arm = armatures.pop();
                dragonBones.WorldClock.clock.remove(arm);
                arm.dispose();
            }
        }

        /**
        * @param (STRING) imgID texture file(png)
        * @param (STRING) dataID string file(json)
        * @param (STRING) SkelID string file(json)
        */
        _public.start = function(imgID, dataID, skelID){
            _public.PixiFactory = new dragonBones.PixiFactory();
            _public.addToFactory(imgID, dataID, skelID);
            _public.enableClock = true;
        }

        _public.addToFactory = function(imgID, dataID, skelID){
            var textureImg = EHDI.Assets.images[imgID].baseTexture.source;
            var textureData = EHDI.Assets.fetch(dataID);
            var skel = EHDI.Assets.fetch(skelID);
            
            _public.PixiFactory.addTextureAtlas(new dragonBones.TextureAtlas(textureImg, textureData));
            _public.PixiFactory.addDragonBonesData(dragonBones.DataParser.parseDragonBonesData(skel));
        }

        return _public;
        }());

    return ehdi;
}(EHDI || Object.create(null)));

var EHDI = EHDI || Object.create(null);

EHDI.debugUtils = EHDI.debugUtils || Object.create(null);

EHDI.debugUtils.debugUtilsContainer = function(version) {
    EHDI.aka.Container.call(this);
    
    var fpsDisplay  = new EHDI.debugUtils.FPSDisplay();
    fpsDisplay.anchor.y = 1;
    fpsDisplay.position.set( 10, APP.config.stageHeight );
    this.addChild( fpsDisplay );
    
    var versionDisplay = new EHDI.aka.PixiText(version, {fontFamily: 'proximanova-black', fill: 0xFFFFFF, dropShadow : true, fontSize: 32});
    versionDisplay.anchor.x = 1;
    versionDisplay.anchor.y = 1;
    versionDisplay.position.set( APP.config.stageWidth - 10, APP.config.stageHeight );
    
    this.addChild( versionDisplay );
    
    
};

EHDI.debugUtils.debugUtilsContainer.prototype = Object.create(EHDI.aka.Container.prototype);

EHDI.debugUtils.FPSDisplay = function() {
    this.fps = APP.managers.update.getFPS();
    EHDI.aka.PixiText.call(this, "FPS : " + this.fps, {fontFamily: 'proximanova-black', fill: 0xFFFFFF, dropShadow : true, fontSize: 32});
    
    APP.managers.update.addFrameListener(this.updateMe.bind(this));
};

EHDI.debugUtils.FPSDisplay.prototype = Object.create(EHDI.aka.PixiText.prototype);

EHDI.debugUtils.FPSDisplay.prototype.updateMe = function() {
    if(this.fps !== APP.managers.update.getFPS()) {

        var str =  "FPS :" + APP.managers.update.getFPS();
        
        if ( this.text !== str ) this.text = str;
    }
        
};

var UTILS = UTILS || Object.create(null);


UTILS.arrayUtils = UTILS.arrayUtils || Object.create(null);
UTILS.arrayUtils.removeFromArray =function(source, toRemove) 
{
    if((source == null) || (toRemove == null))
        return;

    while(toRemove.length > 0)
    {
        var item= toRemove.pop();
        var itemIndex =source.indexOf(item);

        if(itemIndex != -1)
            source = source.splice(itemIndex, 1);
    }

    toRemove = null;
}

UTILS.arrayUtils.clearArray = function(source)
{
    if(source == null)
        return;

    while(source.lenghth > 0)
    {
        source.pop();
    }
}

UTILS.arrayUtils.destroyArray = function(source)
{
    if(source == null)
        return;

    while(source.lenghth > 0)
    {
        var item = source.pop();
        
        if(item.dispose != null)
            item.dispose();
        if(item.destroy != null)
            item.destroy();
    }

    source = null;
}

UTILS.arrayUtils.shuffleArray = function(source, complexityFactor)
{
    if(source == null)
        return;

    if(Number.isNaN(complexityFactor))
        complexityFactor = 100;

    for(var i = 0; i< complexityFactor; i++)
        {
            var item= UTILS.arrayUtils.getRandom(source, true);
            source.push(item);
        }
}

UTILS.arrayUtils.getRandom = function(source, remove)
{
    if((source == null) || (source.lenghth <= 0))
        return null;

    var item = source[Math.floor(Math.random() * source.length)];

    if(remove)
        UTILS.arrayUtils.removeFromArray(source, [item]);

    return item;

}


UTILS.depthSwap = function(visualList) {
       visualList.sort(function(a,b) {
           a.y = a.y || 0;
           b.y = b.y || 0;
           return a.y - b.y;
       });
}



UTILS.objectPools = UTILS.objectPools || Object.create(null);
function Pool(obj, initialCount)
{
    var objPool = [];
    var type = obj;

    while(objPool.length < initialCount)
        {
            var item = new type();
            objPool.push(item);
        }

    this.takeFromPool = function()
    {
        if(objPool.length <= 0)
            {
                return new type();
            }
        else
            {
                return objPool.pop();
            }
    }

    this.returnBatch = function(source, toReturn) 
    {
        if(toReturn == null)
            return;

        while(toReturn.length > 0)
        {
            var item= toReturn.pop();
            if(source != null)
                {
                    var itemIndex =source.indexOf(item);
                    if(itemIndex != -1)
                        source.splice(itemIndex, 1);
                }
            objPool.push(item);
        }

        toReturn = null;
    }

    this.returnToPool = function(item) 
    {
        objPool.push(item);
    }

    this.clearPool = function()
    {
        UTILS.arrayUtils.clearArray(objPool);
    }

    this.destroyPool = function()
    {
         UTILS.arrayUtils.clearArray(destroyArray);
         objPool = null;
         type = null;
    }

}
//# sourceMappingURL=game.js.map