/** * Bounce.js 0.8.2 * MIT license */ !function(a){if("object"==typeof exports)module.exports=a();else if("function"==typeof define&&define.amd)define(a);else{var b;"undefined"!=typeof window?b=window:"undefined"!=typeof global?b=global:"undefined"!=typeof self&&(b=self),b.Bounce=a()}}(function(){return function a(b,c,d){function e(g,h){if(!c[g]){if(!b[g]){var i="function"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);throw new Error("Cannot find module '"+g+"'")}var j=c[g]={exports:{}};b[g][0].call(j.exports,function(a){var c=b[g][1][a];return e(c?c:a)},j,j.exports,a,b,c,d)}return c[g].exports}for(var f="function"==typeof require&&require,g=0;g=1?1:(b=a*this.limit,1-this.exponent(b)*this.oscillation(b))},b.prototype.calculateOmega=function(){return(this.bounces+.5)*Math.PI/this.limit},b.prototype.exponent=function(a){return Math.pow(Math.E,-this.alpha*a)},b.prototype.oscillation=function(a){return Math.cos(this.omega*a)},b.prototype.serialize=function(){return{stiffness:this.stiffness,bounces:this.bounces}},b}(d),b.exports=c},{"./index":9}],7:[function(a,b){var c,d,e={}.hasOwnProperty,f=function(a,b){function c(){this.constructor=a}for(var d in b)e.call(b,d)&&(a[d]=b[d]);return c.prototype=b.prototype,a.prototype=new c,a.__super__=b.prototype,a};c=a("./bounce"),d=function(a){function b(){return b.__super__.constructor.apply(this,arguments)}return f(b,a),b.prototype.oscillation=function(a){return Math.abs(Math.cos(this.omega*a))},b}(c),b.exports=d},{"./bounce":6}],8:[function(a,b){var c,d,e={}.hasOwnProperty,f=function(a,b){function c(){this.constructor=a}for(var d in b)e.call(b,d)&&(a[d]=b[d]);return c.prototype=b.prototype,a.prototype=new c,a.__super__=b.prototype,a};d=a("./sway"),c=function(a){function b(){return b.__super__.constructor.apply(this,arguments)}return f(b,a),b.prototype.oscillation=function(a){return Math.abs(Math.sin(this.omega*a))},b}(d),b.exports=c},{"./sway":10}],9:[function(a,b){var c,d;d=a("../math/helpers"),c=function(){function a(){}return a.prototype.calculate=function(a){return a},a.prototype.serialize=function(){return{}},a.prototype.findOptimalKeyPoints=function(a,b){var c,e,f,g,h,i,j,k;for(null==a&&(a=1),null==b&&(b=1e3),h=[0],k=function(){var a,c;for(c=[],f=a=0;b>=0?b>a:a>b;f=b>=0?++a:--a)c.push(this.calculate(f/b));return c}.call(this),h=h.concat(d.findTurningPoints(k)),h.push(b-1),f=0,i=1e3;i--&&f!==h.length-1;)c=d.areaBetweenLineAndCurve(k,h[f],h[f+1]),a>=c?f++:(e=Math.round(h[f]+(h[f+1]-h[f])/2),h.splice(f+1,0,e));return 0===i?[]:j=function(){var a,c,d;for(d=[],a=0,c=h.length;c>a;a++)g=h[a],d.push(g/(b-1));return d}()},a}(),b.exports=c},{"../math/helpers":12}],10:[function(a,b){var c,d,e={}.hasOwnProperty,f=function(a,b){function c(){this.constructor=a}for(var d in b)e.call(b,d)&&(a[d]=b[d]);return c.prototype=b.prototype,a.prototype=new c,a.__super__=b.prototype,a};c=a("./bounce"),d=function(a){function b(){return b.__super__.constructor.apply(this,arguments)}return f(b,a),b.prototype.calculate=function(a){var b;return a>=1?0:(b=a*this.limit,this.exponent(b)*this.oscillation(b))},b.prototype.calculateOmega=function(){return this.bounces*Math.PI/this.limit},b.prototype.oscillation=function(a){return Math.sin(this.omega*a)},b}(c),b.exports=d},{"./bounce":6}],11:[function(a,b){var c,d,e;e=a("./math/matrix4d"),d={scale:a("./components/scale"),rotate:a("./components/rotate"),translate:a("./components/translate"),skew:a("./components/skew")},c=function(){function a(){this.components=[]}return a.FPS=30,a.counter=1,a.prototype.components=null,a.prototype.duration=0,a.prototype.scale=function(a){return this.addComponent(new d.scale(a))},a.prototype.rotate=function(a){return this.addComponent(new d.rotate(a))},a.prototype.translate=function(a){return this.addComponent(new d.translate(a))},a.prototype.skew=function(a){return this.addComponent(new d.skew(a))},a.prototype.addComponent=function(a){return this.components.push(a),this.updateDuration(),this},a.prototype.serialize=function(){var a,b,c,d,e;for(b=[],e=this.components,c=0,d=e.length;d>c;c++)a=e[c],b.push(a.serialize());return b},a.prototype.deserialize=function(a){var b,c,e;for(c=0,e=a.length;e>c;c++)b=a[c],this.addComponent(new d[b.type](b));return this},a.prototype.updateDuration=function(){return this.duration=this.components.map(function(a){return a.duration+a.delay}).reduce(function(a,b){return Math.max(a,b)})},a.prototype.define=function(b){return this.name=b||a.generateName(),this.styleElement=document.createElement("style"),this.styleElement.innerHTML=this.getKeyframeCSS({name:this.name,prefix:!0}),document.body.appendChild(this.styleElement),this},a.prototype.applyTo=function(a,b){var c,d,e,f,g,h,i,j,k,l;for(null==b&&(b={}),this.define(),a.length||(a=[a]),g=this.getPrefixes(),d=null,window.jQuery&&window.jQuery.Deferred&&(d=new window.jQuery.Deferred),h=0,j=a.length;j>h;h++)for(e=a[h],l=g.animation,i=0,k=l.length;k>i;i++)f=l[i],c=[this.name,""+this.duration+"ms","linear","both"],b.loop&&c.push("infinite"),e.style[""+f+"animation"]=c.join(" ");return b.loop||setTimeout(function(a){return function(){return b.remove&&a.remove(),"function"==typeof b.onComplete&&b.onComplete(),d?d.resolve():void 0}}(this),this.duration),d},a.prototype.remove=function(){var a;if(this.styleElement)return this.styleElement.remove?this.styleElement.remove():null!=(a=this.styleElement.parentNode)?a.removeChild(this.styleElement):void 0},a.prototype.getPrefixes=function(a){var b,c;return b={transform:[""],animation:[""]},c=document.createElement("dummy").style,(a||!("transform"in c)&&"webkitTransform"in c)&&(b.transform=["-webkit-",""]),(a||!("animation"in c)&&"webkitAnimation"in c)&&(b.animation=["-webkit-",""]),b},a.prototype.getKeyframeCSS=function(b){var c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t;for(null==b&&(b={}),this.name=b.name||a.generateName(),i={transform:[""],animation:[""]},(b.prefix||b.forcePrefix)&&(i=this.getPrefixes(b.forcePrefix)),e=[],f=this.getKeyframes(b),r=this.keys,l=0,o=r.length;o>l;l++){for(d=r[l],g=f[d],j="matrix3d"+g,k=[],s=i.transform,m=0,p=s.length;p>m;m++)h=s[m],k.push(""+h+"transform: "+j+";");e.push(""+Math.round(100*d*100)/100+"% { "+k.join(" ")+" }")}for(c=[],t=i.animation,n=0,q=t.length;q>n;n++)h=t[n],c.push("@"+h+"keyframes "+this.name+" { \n "+e.join("\n ")+" \n}");return c.join("\n\n")},a.prototype.getKeyframes=function(b){var c,d,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v;if(null==b&&(b={}),k=[0,1],b.optimized)for(u=this.components,n=0,r=u.length;r>n;n++)c=u[n],d=c.easingObject.findOptimalKeyPoints().map(function(a){return function(b){return b*c.duration/a.duration+c.delay/a.duration}}(this)),c.delay&&d.push(c.delay/this.duration-.001),k=k.concat(d);else for(g=Math.round(this.duration/1e3*a.FPS),h=o=0;g>=0?g>=o:o>=g;h=g>=0?++o:--o)k.push(h/g);for(k=k.sort(function(a,b){return a-b}),this.keys=[],j={},p=0,s=k.length;s>p;p++)if(i=k[p],!j[i]){for(l=(new e).identity(),v=this.components,q=0,t=v.length;t>q;q++)c=v[q],f=i*this.duration,c.delay-f>1e-8||(m=(i-c.delay/this.duration)/(c.duration/this.duration),l.multiply(c.getEasedMatrix(m)));this.keys.push(i),j[i]=l.transpose().toFixed(3)}return j},a.generateName=function(){return"animation-"+a.counter++},a.isSupported=function(){var a,b,c,d,e,f,g,h,i;for(e=document.createElement("dummy").style,d=[["transform","webkitTransform"],["animation","webkitAnimation"]],f=0,h=d.length;h>f;f++){for(c=d[f],b=!1,g=0,i=c.length;i>g;g++)a=c[g],b||(b=a in e);if(!b)return!1}return!0},a}(),b.exports=c},{"./components/rotate":2,"./components/scale":3,"./components/skew":4,"./components/translate":5,"./math/matrix4d":13}],12:[function(a,b){var c;c=function(){function a(){}return a.prototype.sign=function(a){return 0>a?-1:1},a.prototype.findTurningPoints=function(a){var b,c,d,e,f,g;for(e=[],b=f=1,g=a.length-1;g>=1?g>f:f>g;b=g>=1?++f:--f)c=this.sign(a[b]-a[b-1]),d=this.sign(a[b+1]-a[b]),c!==d&&e.push(b);return e},a.prototype.areaBetweenLineAndCurve=function(a,b,c){var d,e,f,g,h,i,j,k;for(g=c-b,j=a[b],i=a[c],d=0,f=k=0;g>=0?g>=k:k>=g;f=g>=0?++k:--k)e=a[b+f],h=j+f/g*(i-j),d+=Math.abs(h-e);return d},a}(),b.exports=new c},{}],13:[function(a,b){var c;c=function(){function a(a){this._array=(null!=a?a.slice(0):void 0)||[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}return a.prototype._array=null,a.prototype.equals=function(a){return this.toString()===a.toString()},a.prototype.identity=function(){return this.setArray([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),this},a.prototype.multiply=function(b){var c,d,e,f,g,h,i,j;for(f=new a,c=h=0;4>h;c=++h)for(d=i=0;4>i;d=++i)for(e=j=0;4>j;e=++j)g=f.get(c,d)+this.get(c,e)*b.get(e,d),f.set(c,d,g);return this.copy(f)},a.prototype.transpose=function(){var a;return a=this.getArray(),this.setArray([a[0],a[4],a[8],a[12],a[1],a[5],a[9],a[13],a[2],a[6],a[10],a[14],a[3],a[7],a[11],a[15]]),this},a.prototype.get=function(a,b){return this.getArray()[4*a+b]},a.prototype.set=function(a,b,c){return this._array[4*a+b]=c},a.prototype.copy=function(a){return this._array=a.getArray(),this},a.prototype.clone=function(){return new a(this.getArray())},a.prototype.getArray=function(){return this._array.slice(0)},a.prototype.setArray=function(a){return this._array=a,this},a.prototype.toString=function(){return"("+this.getArray().join(", ")+")"},a.prototype.toFixed=function(a){var b;return this._array=function(){var c,d,e,f;for(e=this._array,f=[],c=0,d=e.length;d>c;c++)b=e[c],f.push(parseFloat(b.toFixed(a)));return f}.call(this),this},a}(),b.exports=c},{}],14:[function(a,b){var c;c=function(){function a(a,b){this.x=null!=a?a:0,this.y=null!=b?b:0}return a.prototype.x=0,a.prototype.y=0,a.prototype.add=function(b){return a.isVector2D(b)?(this.x+=b.x,this.y+=b.y,this):this._addScalar(b)},a.prototype._addScalar=function(a){return this.x+=a,this.y+=a,this},a.prototype.subtract=function(b){return a.isVector2D(b)?(this.x-=b.x,this.y-=b.y,this):this._subtractScalar(b)},a.prototype._subtractScalar=function(a){return this._addScalar(-a)},a.prototype.multiply=function(b){return a.isVector2D(b)?(this.x*=b.x,this.y*=b.y,this):this._multiplyScalar(b)},a.prototype._multiplyScalar=function(a){return this.x*=a,this.y*=a,this},a.prototype.divide=function(b){return a.isVector2D(b)?(this.x/=b.x,this.y/=b.y,this):this._divideScalar(b)},a.prototype._divideScalar=function(a){return this._multiplyScalar(1/a)},a.prototype.clone=function(){return new a(this.x,this.y)},a.prototype.copy=function(a){return this.x=a.x,this.y=a.y,this},a.prototype.equals=function(a){return a.x===this.x&&a.y===this.y},a.prototype.toString=function(){return"("+this.x+", "+this.y+")"},a.prototype.toFixed=function(a){return this.x=parseFloat(this.x.toFixed(a)),this.y=parseFloat(this.y.toFixed(a)),this},a.prototype.toArray=function(){return[this.x,this.y]},a.isVector2D=function(b){return b instanceof a},a}(),b.exports=c},{}]},{},[11])(11)}); /*! * jQuery JavaScript Library v1.12.4 * http://jquery.com/ * * Includes Sizzle.js * http://sizzlejs.com/ * * Copyright jQuery Foundation and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2016-05-20T17:17Z */ (function( global, factory ) { if ( typeof module === "object" && typeof module.exports === "object" ) { // For CommonJS and CommonJS-like environments where a proper `window` // is present, execute the factory and get jQuery. // For environments that do not have a `window` with a `document` // (such as Node.js), expose a factory as module.exports. // This accentuates the need for the creation of a real `window`. // e.g. var jQuery = require("jquery")(window); // See ticket #14549 for more info. module.exports = global.document ? factory( global, true ) : function( w ) { if ( !w.document ) { throw new Error( "jQuery requires a window with a document" ); } return factory( w ); }; } else { factory( global ); } // Pass this if window is not defined yet }(typeof window !== "undefined" ? window : this, function( window, noGlobal ) { // Support: Firefox 18+ // Can't be in strict mode, several libs including ASP.NET trace // the stack via arguments.caller.callee and Firefox dies if // you try to trace through "use strict" call chains. (#13335) //"use strict"; var deletedIds = []; var document = window.document; var slice = deletedIds.slice; var concat = deletedIds.concat; var push = deletedIds.push; var indexOf = deletedIds.indexOf; var class2type = {}; var toString = class2type.toString; var hasOwn = class2type.hasOwnProperty; var support = {}; var version = "1.12.4", // Define a local copy of jQuery jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' // Need init if jQuery is called (just allow error to be thrown if not included) return new jQuery.fn.init( selector, context ); }, // Support: Android<4.1, IE<9 // Make sure we trim BOM and NBSP rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, // Matches dashed string for camelizing rmsPrefix = /^-ms-/, rdashAlpha = /-([\da-z])/gi, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return letter.toUpperCase(); }; jQuery.fn = jQuery.prototype = { // The current version of jQuery being used jquery: version, constructor: jQuery, // Start with an empty selector selector: "", // The default length of a jQuery object is 0 length: 0, toArray: function() { return slice.call( this ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num != null ? // Return just the one element from the set ( num < 0 ? this[ num + this.length ] : this[ num ] ) : // Return all the elements in a clean array slice.call( this ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems ) { // Build a new jQuery matched element set var ret = jQuery.merge( this.constructor(), elems ); // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. each: function( callback ) { return jQuery.each( this, callback ); }, map: function( callback ) { return this.pushStack( jQuery.map( this, function( elem, i ) { return callback.call( elem, i, elem ); } ) ); }, slice: function() { return this.pushStack( slice.apply( this, arguments ) ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, eq: function( i ) { var len = this.length, j = +i + ( i < 0 ? len : 0 ); return this.pushStack( j >= 0 && j < len ? [ this[ j ] ] : [] ); }, end: function() { return this.prevObject || this.constructor(); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: push, sort: deletedIds.sort, splice: deletedIds.splice }; jQuery.extend = jQuery.fn.extend = function() { var src, copyIsArray, copy, name, options, clone, target = arguments[ 0 ] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; // skip the boolean and the target target = arguments[ i ] || {}; i++; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction( target ) ) { target = {}; } // extend jQuery itself if only one argument is passed if ( i === length ) { target = this; i--; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( ( options = arguments[ i ] ) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject( copy ) || ( copyIsArray = jQuery.isArray( copy ) ) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && jQuery.isArray( src ) ? src : []; } else { clone = src && jQuery.isPlainObject( src ) ? src : {}; } // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend( { // Unique for each copy of jQuery on the page expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ), // Assume jQuery is ready without the ready module isReady: true, error: function( msg ) { throw new Error( msg ); }, noop: function() {}, // See test/unit/core.js for details concerning isFunction. // Since version 1.3, DOM methods and functions like alert // aren't supported. They return false on IE (#2968). isFunction: function( obj ) { return jQuery.type( obj ) === "function"; }, isArray: Array.isArray || function( obj ) { return jQuery.type( obj ) === "array"; }, isWindow: function( obj ) { /* jshint eqeqeq: false */ return obj != null && obj == obj.window; }, isNumeric: function( obj ) { // parseFloat NaNs numeric-cast false positives (null|true|false|"") // ...but misinterprets leading-number strings, particularly hex literals ("0x...") // subtraction forces infinities to NaN // adding 1 corrects loss of precision from parseFloat (#15100) var realStringObj = obj && obj.toString(); return !jQuery.isArray( obj ) && ( realStringObj - parseFloat( realStringObj ) + 1 ) >= 0; }, isEmptyObject: function( obj ) { var name; for ( name in obj ) { return false; } return true; }, isPlainObject: function( obj ) { var key; // Must be an Object. // Because of IE, we also have to check the presence of the constructor property. // Make sure that DOM nodes and window objects don't pass through, as well if ( !obj || jQuery.type( obj ) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { return false; } try { // Not own constructor property must be Object if ( obj.constructor && !hasOwn.call( obj, "constructor" ) && !hasOwn.call( obj.constructor.prototype, "isPrototypeOf" ) ) { return false; } } catch ( e ) { // IE8,9 Will throw exceptions on certain host objects #9897 return false; } // Support: IE<9 // Handle iteration over inherited properties before own properties. if ( !support.ownFirst ) { for ( key in obj ) { return hasOwn.call( obj, key ); } } // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own. for ( key in obj ) {} return key === undefined || hasOwn.call( obj, key ); }, type: function( obj ) { if ( obj == null ) { return obj + ""; } return typeof obj === "object" || typeof obj === "function" ? class2type[ toString.call( obj ) ] || "object" : typeof obj; }, // Workarounds based on findings by Jim Driscoll // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context globalEval: function( data ) { if ( data && jQuery.trim( data ) ) { // We use execScript on Internet Explorer // We use an anonymous function so that context is window // rather than jQuery in Firefox ( window.execScript || function( data ) { window[ "eval" ].call( window, data ); // jscs:ignore requireDotNotation } )( data ); } }, // Convert dashed to camelCase; used by the css and data modules // Microsoft forgot to hump their vendor prefix (#9572) camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); }, each: function( obj, callback ) { var length, i = 0; if ( isArrayLike( obj ) ) { length = obj.length; for ( ; i < length; i++ ) { if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) { break; } } } else { for ( i in obj ) { if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) { break; } } } return obj; }, // Support: Android<4.1, IE<9 trim: function( text ) { return text == null ? "" : ( text + "" ).replace( rtrim, "" ); }, // results is for internal usage only makeArray: function( arr, results ) { var ret = results || []; if ( arr != null ) { if ( isArrayLike( Object( arr ) ) ) { jQuery.merge( ret, typeof arr === "string" ? [ arr ] : arr ); } else { push.call( ret, arr ); } } return ret; }, inArray: function( elem, arr, i ) { var len; if ( arr ) { if ( indexOf ) { return indexOf.call( arr, elem, i ); } len = arr.length; i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; for ( ; i < len; i++ ) { // Skip accessing in sparse arrays if ( i in arr && arr[ i ] === elem ) { return i; } } } return -1; }, merge: function( first, second ) { var len = +second.length, j = 0, i = first.length; while ( j < len ) { first[ i++ ] = second[ j++ ]; } // Support: IE<9 // Workaround casting of .length to NaN on otherwise arraylike objects (e.g., NodeLists) if ( len !== len ) { while ( second[ j ] !== undefined ) { first[ i++ ] = second[ j++ ]; } } first.length = i; return first; }, grep: function( elems, callback, invert ) { var callbackInverse, matches = [], i = 0, length = elems.length, callbackExpect = !invert; // Go through the array, only saving the items // that pass the validator function for ( ; i < length; i++ ) { callbackInverse = !callback( elems[ i ], i ); if ( callbackInverse !== callbackExpect ) { matches.push( elems[ i ] ); } } return matches; }, // arg is for internal usage only map: function( elems, callback, arg ) { var length, value, i = 0, ret = []; // Go through the array, translating each of the items to their new values if ( isArrayLike( elems ) ) { length = elems.length; for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret.push( value ); } } // Go through every key on the object, } else { for ( i in elems ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret.push( value ); } } } // Flatten any nested arrays return concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, // Bind a function to a context, optionally partially applying any // arguments. proxy: function( fn, context ) { var args, proxy, tmp; if ( typeof context === "string" ) { tmp = fn[ context ]; context = fn; fn = tmp; } // Quick check to determine if target is callable, in the spec // this throws a TypeError, but we will just return undefined. if ( !jQuery.isFunction( fn ) ) { return undefined; } // Simulated bind args = slice.call( arguments, 2 ); proxy = function() { return fn.apply( context || this, args.concat( slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || jQuery.guid++; return proxy; }, now: function() { return +( new Date() ); }, // jQuery.support is not used in Core but other projects attach their // properties to it so it needs to exist. support: support } ); // JSHint would error on this code due to the Symbol not being defined in ES5. // Defining this global in .jshintrc would create a danger of using the global // unguarded in another place, it seems safer to just disable JSHint for these // three lines. /* jshint ignore: start */ if ( typeof Symbol === "function" ) { jQuery.fn[ Symbol.iterator ] = deletedIds[ Symbol.iterator ]; } /* jshint ignore: end */ // Populate the class2type map jQuery.each( "Boolean Number String Function Array Date RegExp Object Error Symbol".split( " " ), function( i, name ) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); } ); function isArrayLike( obj ) { // Support: iOS 8.2 (not reproducible in simulator) // `in` check used to prevent JIT error (gh-2145) // hasOwn isn't used here due to false negatives // regarding Nodelist length in IE var length = !!obj && "length" in obj && obj.length, type = jQuery.type( obj ); if ( type === "function" || jQuery.isWindow( obj ) ) { return false; } return type === "array" || length === 0 || typeof length === "number" && length > 0 && ( length - 1 ) in obj; } var Sizzle = /*! * Sizzle CSS Selector Engine v2.2.1 * http://sizzlejs.com/ * * Copyright jQuery Foundation and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2015-10-17 */ (function( window ) { var i, support, Expr, getText, isXML, tokenize, compile, select, outermostContext, sortInput, hasDuplicate, // Local document vars setDocument, document, docElem, documentIsHTML, rbuggyQSA, rbuggyMatches, matches, contains, // Instance-specific data expando = "sizzle" + 1 * new Date(), preferredDoc = window.document, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; } return 0; }, // General-purpose constants MAX_NEGATIVE = 1 << 31, // Instance methods hasOwn = ({}).hasOwnProperty, arr = [], pop = arr.pop, push_native = arr.push, push = arr.push, slice = arr.slice, // Use a stripped-down indexOf as it's faster than native // http://jsperf.com/thor-indexof-vs-for/5 indexOf = function( list, elem ) { var i = 0, len = list.length; for ( ; i < len; i++ ) { if ( list[i] === elem ) { return i; } } return -1; }, booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", // Regular expressions // http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", // http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier identifier = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace + // Operator (capture 2) "*([*^$|!~]?=)" + whitespace + // "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]" "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace + "*\\]", pseudos = ":(" + identifier + ")(?:\\((" + // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments: // 1. quoted (capture 3; capture 4 or capture 5) "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" + // 2. simple (capture 6) "((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" + // 3. anything else (capture 2) ".*" + ")\\)|)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rwhitespace = new RegExp( whitespace + "+", "g" ), rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ), rpseudo = new RegExp( pseudos ), ridentifier = new RegExp( "^" + identifier + "$" ), matchExpr = { "ID": new RegExp( "^#(" + identifier + ")" ), "CLASS": new RegExp( "^\\.(" + identifier + ")" ), "TAG": new RegExp( "^(" + identifier + "|[*])" ), "ATTR": new RegExp( "^" + attributes ), "PSEUDO": new RegExp( "^" + pseudos ), "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), // For use in libraries implementing .is() // We use this for POS matching in `select` "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) }, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rnative = /^[^{]+\{\s*\[native \w/, // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rsibling = /[+~]/, rescape = /'|\\/g, // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ), funescape = function( _, escaped, escapedWhitespace ) { var high = "0x" + escaped - 0x10000; // NaN means non-codepoint // Support: Firefox<24 // Workaround erroneous numeric interpretation of +"0x" return high !== high || escapedWhitespace ? escaped : high < 0 ? // BMP codepoint String.fromCharCode( high + 0x10000 ) : // Supplemental Plane codepoint (surrogate pair) String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); }, // Used for iframes // See setDocument() // Removing the function wrapper causes a "Permission Denied" // error in IE unloadHandler = function() { setDocument(); }; // Optimize for push.apply( _, NodeList ) try { push.apply( (arr = slice.call( preferredDoc.childNodes )), preferredDoc.childNodes ); // Support: Android<4.0 // Detect silently failing push.apply arr[ preferredDoc.childNodes.length ].nodeType; } catch ( e ) { push = { apply: arr.length ? // Leverage slice if possible function( target, els ) { push_native.apply( target, slice.call(els) ); } : // Support: IE<9 // Otherwise append directly function( target, els ) { var j = target.length, i = 0; // Can't trust NodeList.length while ( (target[j++] = els[i++]) ) {} target.length = j - 1; } }; } function Sizzle( selector, context, results, seed ) { var m, i, elem, nid, nidselect, match, groups, newSelector, newContext = context && context.ownerDocument, // nodeType defaults to 9, since context defaults to document nodeType = context ? context.nodeType : 9; results = results || []; // Return early from calls with invalid selector or context if ( typeof selector !== "string" || !selector || nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) { return results; } // Try to shortcut find operations (as opposed to filters) in HTML documents if ( !seed ) { if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { setDocument( context ); } context = context || document; if ( documentIsHTML ) { // If the selector is sufficiently simple, try using a "get*By*" DOM method // (excepting DocumentFragment context, where the methods don't exist) if ( nodeType !== 11 && (match = rquickExpr.exec( selector )) ) { // ID selector if ( (m = match[1]) ) { // Document context if ( nodeType === 9 ) { if ( (elem = context.getElementById( m )) ) { // Support: IE, Opera, Webkit // TODO: identify versions // getElementById can match elements by name instead of ID if ( elem.id === m ) { results.push( elem ); return results; } } else { return results; } // Element context } else { // Support: IE, Opera, Webkit // TODO: identify versions // getElementById can match elements by name instead of ID if ( newContext && (elem = newContext.getElementById( m )) && contains( context, elem ) && elem.id === m ) { results.push( elem ); return results; } } // Type selector } else if ( match[2] ) { push.apply( results, context.getElementsByTagName( selector ) ); return results; // Class selector } else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) { push.apply( results, context.getElementsByClassName( m ) ); return results; } } // Take advantage of querySelectorAll if ( support.qsa && !compilerCache[ selector + " " ] && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { if ( nodeType !== 1 ) { newContext = context; newSelector = selector; // qSA looks outside Element context, which is not what we want // Thanks to Andrew Dupont for this workaround technique // Support: IE <=8 // Exclude object elements } else if ( context.nodeName.toLowerCase() !== "object" ) { // Capture the context ID, setting it first if necessary if ( (nid = context.getAttribute( "id" )) ) { nid = nid.replace( rescape, "\\$&" ); } else { context.setAttribute( "id", (nid = expando) ); } // Prefix every selector in the list groups = tokenize( selector ); i = groups.length; nidselect = ridentifier.test( nid ) ? "#" + nid : "[id='" + nid + "']"; while ( i-- ) { groups[i] = nidselect + " " + toSelector( groups[i] ); } newSelector = groups.join( "," ); // Expand context for sibling selectors newContext = rsibling.test( selector ) && testContext( context.parentNode ) || context; } if ( newSelector ) { try { push.apply( results, newContext.querySelectorAll( newSelector ) ); return results; } catch ( qsaError ) { } finally { if ( nid === expando ) { context.removeAttribute( "id" ); } } } } } } // All others return select( selector.replace( rtrim, "$1" ), context, results, seed ); } /** * Create key-value caches of limited size * @returns {function(string, object)} Returns the Object data after storing it on itself with * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) * deleting the oldest entry */ function createCache() { var keys = []; function cache( key, value ) { // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) if ( keys.push( key + " " ) > Expr.cacheLength ) { // Only keep the most recent entries delete cache[ keys.shift() ]; } return (cache[ key + " " ] = value); } return cache; } /** * Mark a function for special use by Sizzle * @param {Function} fn The function to mark */ function markFunction( fn ) { fn[ expando ] = true; return fn; } /** * Support testing using an element * @param {Function} fn Passed the created div and expects a boolean result */ function assert( fn ) { var div = document.createElement("div"); try { return !!fn( div ); } catch (e) { return false; } finally { // Remove from its parent by default if ( div.parentNode ) { div.parentNode.removeChild( div ); } // release memory in IE div = null; } } /** * Adds the same handler for all of the specified attrs * @param {String} attrs Pipe-separated list of attributes * @param {Function} handler The method that will be applied */ function addHandle( attrs, handler ) { var arr = attrs.split("|"), i = arr.length; while ( i-- ) { Expr.attrHandle[ arr[i] ] = handler; } } /** * Checks document order of two siblings * @param {Element} a * @param {Element} b * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b */ function siblingCheck( a, b ) { var cur = b && a, diff = cur && a.nodeType === 1 && b.nodeType === 1 && ( ~b.sourceIndex || MAX_NEGATIVE ) - ( ~a.sourceIndex || MAX_NEGATIVE ); // Use IE sourceIndex if available on both nodes if ( diff ) { return diff; } // Check if b follows a if ( cur ) { while ( (cur = cur.nextSibling) ) { if ( cur === b ) { return -1; } } } return a ? 1 : -1; } /** * Returns a function to use in pseudos for input types * @param {String} type */ function createInputPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === type; }; } /** * Returns a function to use in pseudos for buttons * @param {String} type */ function createButtonPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && elem.type === type; }; } /** * Returns a function to use in pseudos for positionals * @param {Function} fn */ function createPositionalPseudo( fn ) { return markFunction(function( argument ) { argument = +argument; return markFunction(function( seed, matches ) { var j, matchIndexes = fn( [], seed.length, argument ), i = matchIndexes.length; // Match elements found at the specified indexes while ( i-- ) { if ( seed[ (j = matchIndexes[i]) ] ) { seed[j] = !(matches[j] = seed[j]); } } }); }); } /** * Checks a node for validity as a Sizzle context * @param {Element|Object=} context * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value */ function testContext( context ) { return context && typeof context.getElementsByTagName !== "undefined" && context; } // Expose support vars for convenience support = Sizzle.support = {}; /** * Detects XML nodes * @param {Element|Object} elem An element or a document * @returns {Boolean} True iff elem is a non-HTML XML node */ isXML = Sizzle.isXML = function( elem ) { // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = elem && (elem.ownerDocument || elem).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; /** * Sets document-related variables once based on the current document * @param {Element|Object} [doc] An element or document object to use to set the document * @returns {Object} Returns the current document */ setDocument = Sizzle.setDocument = function( node ) { var hasCompare, parent, doc = node ? node.ownerDocument || node : preferredDoc; // Return early if doc is invalid or already selected if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { return document; } // Update global variables document = doc; docElem = document.documentElement; documentIsHTML = !isXML( document ); // Support: IE 9-11, Edge // Accessing iframe documents after unload throws "permission denied" errors (jQuery #13936) if ( (parent = document.defaultView) && parent.top !== parent ) { // Support: IE 11 if ( parent.addEventListener ) { parent.addEventListener( "unload", unloadHandler, false ); // Support: IE 9 - 10 only } else if ( parent.attachEvent ) { parent.attachEvent( "onunload", unloadHandler ); } } /* Attributes ---------------------------------------------------------------------- */ // Support: IE<8 // Verify that getAttribute really returns attributes and not properties // (excepting IE8 booleans) support.attributes = assert(function( div ) { div.className = "i"; return !div.getAttribute("className"); }); /* getElement(s)By* ---------------------------------------------------------------------- */ // Check if getElementsByTagName("*") returns only elements support.getElementsByTagName = assert(function( div ) { div.appendChild( document.createComment("") ); return !div.getElementsByTagName("*").length; }); // Support: IE<9 support.getElementsByClassName = rnative.test( document.getElementsByClassName ); // Support: IE<10 // Check if getElementById returns elements by name // The broken getElementById methods don't pick up programatically-set names, // so use a roundabout getElementsByName test support.getById = assert(function( div ) { docElem.appendChild( div ).id = expando; return !document.getElementsByName || !document.getElementsByName( expando ).length; }); // ID find and filter if ( support.getById ) { Expr.find["ID"] = function( id, context ) { if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { var m = context.getElementById( id ); return m ? [ m ] : []; } }; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { return elem.getAttribute("id") === attrId; }; }; } else { // Support: IE6/7 // getElementById is not reliable as a find shortcut delete Expr.find["ID"]; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id"); return node && node.value === attrId; }; }; } // Tag Expr.find["TAG"] = support.getElementsByTagName ? function( tag, context ) { if ( typeof context.getElementsByTagName !== "undefined" ) { return context.getElementsByTagName( tag ); // DocumentFragment nodes don't have gEBTN } else if ( support.qsa ) { return context.querySelectorAll( tag ); } } : function( tag, context ) { var elem, tmp = [], i = 0, // By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes too results = context.getElementsByTagName( tag ); // Filter out possible comments if ( tag === "*" ) { while ( (elem = results[i++]) ) { if ( elem.nodeType === 1 ) { tmp.push( elem ); } } return tmp; } return results; }; // Class Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) { if ( typeof context.getElementsByClassName !== "undefined" && documentIsHTML ) { return context.getElementsByClassName( className ); } }; /* QSA/matchesSelector ---------------------------------------------------------------------- */ // QSA and matchesSelector support // matchesSelector(:active) reports false when true (IE9/Opera 11.5) rbuggyMatches = []; // qSa(:focus) reports false when true (Chrome 21) // We allow this because of a bug in IE8/9 that throws an error // whenever `document.activeElement` is accessed on an iframe // So, we allow :focus to pass through QSA all the time to avoid the IE error // See http://bugs.jquery.com/ticket/13378 rbuggyQSA = []; if ( (support.qsa = rnative.test( document.querySelectorAll )) ) { // Build QSA regex // Regex strategy adopted from Diego Perini assert(function( div ) { // Select is set to empty string on purpose // This is to test IE's treatment of not explicitly // setting a boolean content attribute, // since its presence should be enough // http://bugs.jquery.com/ticket/12359 docElem.appendChild( div ).innerHTML = "" + ""; // Support: IE8, Opera 11-12.16 // Nothing should be selected when empty strings follow ^= or $= or *= // The test attribute must be unknown in Opera but "safe" for WinRT // http://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section if ( div.querySelectorAll("[msallowcapture^='']").length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); } // Support: IE8 // Boolean attributes and "value" are not treated correctly if ( !div.querySelectorAll("[selected]").length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); } // Support: Chrome<29, Android<4.4, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.8+ if ( !div.querySelectorAll( "[id~=" + expando + "-]" ).length ) { rbuggyQSA.push("~="); } // Webkit/Opera - :checked should return selected option elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":checked").length ) { rbuggyQSA.push(":checked"); } // Support: Safari 8+, iOS 8+ // https://bugs.webkit.org/show_bug.cgi?id=136851 // In-page `selector#id sibing-combinator selector` fails if ( !div.querySelectorAll( "a#" + expando + "+*" ).length ) { rbuggyQSA.push(".#.+[+~]"); } }); assert(function( div ) { // Support: Windows 8 Native Apps // The type and name attributes are restricted during .innerHTML assignment var input = document.createElement("input"); input.setAttribute( "type", "hidden" ); div.appendChild( input ).setAttribute( "name", "D" ); // Support: IE8 // Enforce case-sensitivity of name attribute if ( div.querySelectorAll("[name=d]").length ) { rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" ); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":enabled").length ) { rbuggyQSA.push( ":enabled", ":disabled" ); } // Opera 10-11 does not throw on post-comma invalid pseudos div.querySelectorAll("*,:x"); rbuggyQSA.push(",.*:"); }); } if ( (support.matchesSelector = rnative.test( (matches = docElem.matches || docElem.webkitMatchesSelector || docElem.mozMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector) )) ) { assert(function( div ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) support.disconnectedMatch = matches.call( div, "div" ); // This should fail with an exception // Gecko does not error, returns false instead matches.call( div, "[s!='']:x" ); rbuggyMatches.push( "!=", pseudos ); }); } rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") ); rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") ); /* Contains ---------------------------------------------------------------------- */ hasCompare = rnative.test( docElem.compareDocumentPosition ); // Element contains another // Purposefully self-exclusive // As in, an element does not contain itself contains = hasCompare || rnative.test( docElem.contains ) ? function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && ( adown.contains ? adown.contains( bup ) : a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 )); } : function( a, b ) { if ( b ) { while ( (b = b.parentNode) ) { if ( b === a ) { return true; } } } return false; }; /* Sorting ---------------------------------------------------------------------- */ // Document order sorting sortOrder = hasCompare ? function( a, b ) { // Flag for duplicate removal if ( a === b ) { hasDuplicate = true; return 0; } // Sort on method existence if only one input has compareDocumentPosition var compare = !a.compareDocumentPosition - !b.compareDocumentPosition; if ( compare ) { return compare; } // Calculate position if both inputs belong to the same document compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ? a.compareDocumentPosition( b ) : // Otherwise we know they are disconnected 1; // Disconnected nodes if ( compare & 1 || (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) { // Choose the first element that is related to our preferred document if ( a === document || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) { return -1; } if ( b === document || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) { return 1; } // Maintain original order return sortInput ? ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : 0; } return compare & 4 ? -1 : 1; } : function( a, b ) { // Exit early if the nodes are identical if ( a === b ) { hasDuplicate = true; return 0; } var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [ a ], bp = [ b ]; // Parentless nodes are either documents or disconnected if ( !aup || !bup ) { return a === document ? -1 : b === document ? 1 : aup ? -1 : bup ? 1 : sortInput ? ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : 0; // If the nodes are siblings, we can do a quick check } else if ( aup === bup ) { return siblingCheck( a, b ); } // Otherwise we need full lists of their ancestors for comparison cur = a; while ( (cur = cur.parentNode) ) { ap.unshift( cur ); } cur = b; while ( (cur = cur.parentNode) ) { bp.unshift( cur ); } // Walk down the tree looking for a discrepancy while ( ap[i] === bp[i] ) { i++; } return i ? // Do a sibling check if the nodes have a common ancestor siblingCheck( ap[i], bp[i] ) : // Otherwise nodes in our document sort first ap[i] === preferredDoc ? -1 : bp[i] === preferredDoc ? 1 : 0; }; return document; }; Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } // Make sure that attribute selectors are quoted expr = expr.replace( rattributeQuotes, "='$1']" ); if ( support.matchesSelector && documentIsHTML && !compilerCache[ expr + " " ] && ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { try { var ret = matches.call( elem, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || support.disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9 elem.document && elem.document.nodeType !== 11 ) { return ret; } } catch (e) {} } return Sizzle( expr, document, null, [ elem ] ).length > 0; }; Sizzle.contains = function( context, elem ) { // Set document vars if needed if ( ( context.ownerDocument || context ) !== document ) { setDocument( context ); } return contains( context, elem ); }; Sizzle.attr = function( elem, name ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } var fn = Expr.attrHandle[ name.toLowerCase() ], // Don't get fooled by Object.prototype properties (jQuery #13807) val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? fn( elem, name, !documentIsHTML ) : undefined; return val !== undefined ? val : support.attributes || !documentIsHTML ? elem.getAttribute( name ) : (val = elem.getAttributeNode(name)) && val.specified ? val.value : null; }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; /** * Document sorting and removing duplicates * @param {ArrayLike} results */ Sizzle.uniqueSort = function( results ) { var elem, duplicates = [], j = 0, i = 0; // Unless we *know* we can detect duplicates, assume their presence hasDuplicate = !support.detectDuplicates; sortInput = !support.sortStable && results.slice( 0 ); results.sort( sortOrder ); if ( hasDuplicate ) { while ( (elem = results[i++]) ) { if ( elem === results[ i ] ) { j = duplicates.push( i ); } } while ( j-- ) { results.splice( duplicates[ j ], 1 ); } } // Clear input after sorting to release objects // See https://github.com/jquery/sizzle/pull/225 sortInput = null; return results; }; /** * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ getText = Sizzle.getText = function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( !nodeType ) { // If no nodeType, this is expected to be an array while ( (node = elem[i++]) ) { // Do not traverse comment nodes ret += getText( node ); } } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements // innerText usage removed for consistency of new lines (jQuery #11153) if ( typeof elem.textContent === "string" ) { return elem.textContent; } else { // Traverse its children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes return ret; }; Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, createPseudo: markFunction, match: matchExpr, attrHandle: {}, find: {}, relative: { ">": { dir: "parentNode", first: true }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: true }, "~": { dir: "previousSibling" } }, preFilter: { "ATTR": function( match ) { match[1] = match[1].replace( runescape, funescape ); // Move the given value to match[3] whether quoted or unquoted match[3] = ( match[3] || match[4] || match[5] || "" ).replace( runescape, funescape ); if ( match[2] === "~=" ) { match[3] = " " + match[3] + " "; } return match.slice( 0, 4 ); }, "CHILD": function( match ) { /* matches from matchExpr["CHILD"] 1 type (only|nth|...) 2 what (child|of-type) 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 4 xn-component of xn+y argument ([+-]?\d*n|) 5 sign of xn-component 6 x of xn-component 7 sign of y-component 8 y of y-component */ match[1] = match[1].toLowerCase(); if ( match[1].slice( 0, 3 ) === "nth" ) { // nth-* requires argument if ( !match[3] ) { Sizzle.error( match[0] ); } // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); // other types prohibit arguments } else if ( match[3] ) { Sizzle.error( match[0] ); } return match; }, "PSEUDO": function( match ) { var excess, unquoted = !match[6] && match[2]; if ( matchExpr["CHILD"].test( match[0] ) ) { return null; } // Accept quoted arguments as-is if ( match[3] ) { match[2] = match[4] || match[5] || ""; // Strip excess characters from unquoted arguments } else if ( unquoted && rpseudo.test( unquoted ) && // Get excess from tokenize (recursively) (excess = tokenize( unquoted, true )) && // advance to the next closing parenthesis (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { // excess is a negative index match[0] = match[0].slice( 0, excess ); match[2] = unquoted.slice( 0, excess ); } // Return only captures needed by the pseudo filter method (type and argument) return match.slice( 0, 3 ); } }, filter: { "TAG": function( nodeNameSelector ) { var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); return nodeNameSelector === "*" ? function() { return true; } : function( elem ) { return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, "CLASS": function( className ) { var pattern = classCache[ className + " " ]; return pattern || (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && classCache( className, function( elem ) { return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== "undefined" && elem.getAttribute("class") || "" ); }); }, "ATTR": function( name, operator, check ) { return function( elem ) { var result = Sizzle.attr( elem, name ); if ( result == null ) { return operator === "!="; } if ( !operator ) { return true; } result += ""; return operator === "=" ? result === check : operator === "!=" ? result !== check : operator === "^=" ? check && result.indexOf( check ) === 0 : operator === "*=" ? check && result.indexOf( check ) > -1 : operator === "$=" ? check && result.slice( -check.length ) === check : operator === "~=" ? ( " " + result.replace( rwhitespace, " " ) + " " ).indexOf( check ) > -1 : operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : false; }; }, "CHILD": function( type, what, argument, first, last ) { var simple = type.slice( 0, 3 ) !== "nth", forward = type.slice( -4 ) !== "last", ofType = what === "of-type"; return first === 1 && last === 0 ? // Shortcut for :nth-*(n) function( elem ) { return !!elem.parentNode; } : function( elem, context, xml ) { var cache, uniqueCache, outerCache, node, nodeIndex, start, dir = simple !== forward ? "nextSibling" : "previousSibling", parent = elem.parentNode, name = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType, diff = false; if ( parent ) { // :(first|last|only)-(child|of-type) if ( simple ) { while ( dir ) { node = elem; while ( (node = node[ dir ]) ) { if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { return false; } } // Reverse direction for :only-* (if we haven't yet done so) start = dir = type === "only" && !start && "nextSibling"; } return true; } start = [ forward ? parent.firstChild : parent.lastChild ]; // non-xml :nth-child(...) stores cache data on `parent` if ( forward && useCache ) { // Seek `elem` from a previously-cached index // ...in a gzip-friendly way node = parent; outerCache = node[ expando ] || (node[ expando ] = {}); // Support: IE <9 only // Defend against cloned attroperties (jQuery gh-1709) uniqueCache = outerCache[ node.uniqueID ] || (outerCache[ node.uniqueID ] = {}); cache = uniqueCache[ type ] || []; nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; diff = nodeIndex && cache[ 2 ]; node = nodeIndex && parent.childNodes[ nodeIndex ]; while ( (node = ++nodeIndex && node && node[ dir ] || // Fallback to seeking `elem` from the start (diff = nodeIndex = 0) || start.pop()) ) { // When found, cache indexes on `parent` and break if ( node.nodeType === 1 && ++diff && node === elem ) { uniqueCache[ type ] = [ dirruns, nodeIndex, diff ]; break; } } } else { // Use previously-cached element index if available if ( useCache ) { // ...in a gzip-friendly way node = elem; outerCache = node[ expando ] || (node[ expando ] = {}); // Support: IE <9 only // Defend against cloned attroperties (jQuery gh-1709) uniqueCache = outerCache[ node.uniqueID ] || (outerCache[ node.uniqueID ] = {}); cache = uniqueCache[ type ] || []; nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; diff = nodeIndex; } // xml :nth-child(...) // or :nth-last-child(...) or :nth(-last)?-of-type(...) if ( diff === false ) { // Use the same loop as above to seek `elem` from the start while ( (node = ++nodeIndex && node && node[ dir ] || (diff = nodeIndex = 0) || start.pop()) ) { if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { // Cache the index of each encountered element if ( useCache ) { outerCache = node[ expando ] || (node[ expando ] = {}); // Support: IE <9 only // Defend against cloned attroperties (jQuery gh-1709) uniqueCache = outerCache[ node.uniqueID ] || (outerCache[ node.uniqueID ] = {}); uniqueCache[ type ] = [ dirruns, diff ]; } if ( node === elem ) { break; } } } } } // Incorporate the offset, then check against cycle size diff -= last; return diff === first || ( diff % first === 0 && diff / first >= 0 ); } }; }, "PSEUDO": function( pseudo, argument ) { // pseudo-class names are case-insensitive // http://www.w3.org/TR/selectors/#pseudo-classes // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters // Remember that setFilters inherits from pseudos var args, fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || Sizzle.error( "unsupported pseudo: " + pseudo ); // The user may use createPseudo to indicate that // arguments are needed to create the filter function // just as Sizzle does if ( fn[ expando ] ) { return fn( argument ); } // But maintain support for old signatures if ( fn.length > 1 ) { args = [ pseudo, pseudo, "", argument ]; return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? markFunction(function( seed, matches ) { var idx, matched = fn( seed, argument ), i = matched.length; while ( i-- ) { idx = indexOf( seed, matched[i] ); seed[ idx ] = !( matches[ idx ] = matched[i] ); } }) : function( elem ) { return fn( elem, 0, args ); }; } return fn; } }, pseudos: { // Potentially complex pseudos "not": markFunction(function( selector ) { // Trim the selector passed to compile // to avoid treating leading and trailing // spaces as combinators var input = [], results = [], matcher = compile( selector.replace( rtrim, "$1" ) ); return matcher[ expando ] ? markFunction(function( seed, matches, context, xml ) { var elem, unmatched = matcher( seed, null, xml, [] ), i = seed.length; // Match elements unmatched by `matcher` while ( i-- ) { if ( (elem = unmatched[i]) ) { seed[i] = !(matches[i] = elem); } } }) : function( elem, context, xml ) { input[0] = elem; matcher( input, null, xml, results ); // Don't keep the element (issue #299) input[0] = null; return !results.pop(); }; }), "has": markFunction(function( selector ) { return function( elem ) { return Sizzle( selector, elem ).length > 0; }; }), "contains": markFunction(function( text ) { text = text.replace( runescape, funescape ); return function( elem ) { return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; }; }), // "Whether an element is represented by a :lang() selector // is based solely on the element's language value // being equal to the identifier C, // or beginning with the identifier C immediately followed by "-". // The matching of C against the element's language value is performed case-insensitively. // The identifier C does not have to be a valid language name." // http://www.w3.org/TR/selectors/#lang-pseudo "lang": markFunction( function( lang ) { // lang value must be a valid identifier if ( !ridentifier.test(lang || "") ) { Sizzle.error( "unsupported lang: " + lang ); } lang = lang.replace( runescape, funescape ).toLowerCase(); return function( elem ) { var elemLang; do { if ( (elemLang = documentIsHTML ? elem.lang : elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) { elemLang = elemLang.toLowerCase(); return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; } } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); return false; }; }), // Miscellaneous "target": function( elem ) { var hash = window.location && window.location.hash; return hash && hash.slice( 1 ) === elem.id; }, "root": function( elem ) { return elem === docElem; }, "focus": function( elem ) { return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); }, // Boolean properties "enabled": function( elem ) { return elem.disabled === false; }, "disabled": function( elem ) { return elem.disabled === true; }, "checked": function( elem ) { // In CSS3, :checked should return both checked and selected elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked var nodeName = elem.nodeName.toLowerCase(); return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); }, "selected": function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { elem.parentNode.selectedIndex; } return elem.selected === true; }, // Contents "empty": function( elem ) { // http://www.w3.org/TR/selectors/#empty-pseudo // :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5), // but not by others (comment: 8; processing instruction: 7; etc.) // nodeType < 6 works because attributes (2) do not appear as children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { if ( elem.nodeType < 6 ) { return false; } } return true; }, "parent": function( elem ) { return !Expr.pseudos["empty"]( elem ); }, // Element/input types "header": function( elem ) { return rheader.test( elem.nodeName ); }, "input": function( elem ) { return rinputs.test( elem.nodeName ); }, "button": function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === "button" || name === "button"; }, "text": function( elem ) { var attr; return elem.nodeName.toLowerCase() === "input" && elem.type === "text" && // Support: IE<8 // New HTML5 attribute values (e.g., "search") appear with elem.type === "text" ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" ); }, // Position-in-collection "first": createPositionalPseudo(function() { return [ 0 ]; }), "last": createPositionalPseudo(function( matchIndexes, length ) { return [ length - 1 ]; }), "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { return [ argument < 0 ? argument + length : argument ]; }), "even": createPositionalPseudo(function( matchIndexes, length ) { var i = 0; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "odd": createPositionalPseudo(function( matchIndexes, length ) { var i = 1; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; --i >= 0; ) { matchIndexes.push( i ); } return matchIndexes; }), "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; ++i < length; ) { matchIndexes.push( i ); } return matchIndexes; }) } }; Expr.pseudos["nth"] = Expr.pseudos["eq"]; // Add button/input type pseudos for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { Expr.pseudos[ i ] = createInputPseudo( i ); } for ( i in { submit: true, reset: true } ) { Expr.pseudos[ i ] = createButtonPseudo( i ); } // Easy API for creating new setFilters function setFilters() {} setFilters.prototype = Expr.filters = Expr.pseudos; Expr.setFilters = new setFilters(); tokenize = Sizzle.tokenize = function( selector, parseOnly ) { var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[ selector + " " ]; if ( cached ) { return parseOnly ? 0 : cached.slice( 0 ); } soFar = selector; groups = []; preFilters = Expr.preFilter; while ( soFar ) { // Comma and first run if ( !matched || (match = rcomma.exec( soFar )) ) { if ( match ) { // Don't consume trailing commas as valid soFar = soFar.slice( match[0].length ) || soFar; } groups.push( (tokens = []) ); } matched = false; // Combinators if ( (match = rcombinators.exec( soFar )) ) { matched = match.shift(); tokens.push({ value: matched, // Cast descendant combinators to space type: match[0].replace( rtrim, " " ) }); soFar = soFar.slice( matched.length ); } // Filters for ( type in Expr.filter ) { if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || (match = preFilters[ type ]( match ))) ) { matched = match.shift(); tokens.push({ value: matched, type: type, matches: match }); soFar = soFar.slice( matched.length ); } } if ( !matched ) { break; } } // Return the length of the invalid excess // if we're just parsing // Otherwise, throw an error or return tokens return parseOnly ? soFar.length : soFar ? Sizzle.error( selector ) : // Cache the tokens tokenCache( selector, groups ).slice( 0 ); }; function toSelector( tokens ) { var i = 0, len = tokens.length, selector = ""; for ( ; i < len; i++ ) { selector += tokens[i].value; } return selector; } function addCombinator( matcher, combinator, base ) { var dir = combinator.dir, checkNonElements = base && dir === "parentNode", doneName = done++; return combinator.first ? // Check against closest ancestor/preceding element function( elem, context, xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { return matcher( elem, context, xml ); } } } : // Check against all ancestor/preceding elements function( elem, context, xml ) { var oldCache, uniqueCache, outerCache, newCache = [ dirruns, doneName ]; // We can't set arbitrary data on XML nodes, so they don't benefit from combinator caching if ( xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { if ( matcher( elem, context, xml ) ) { return true; } } } } else { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { outerCache = elem[ expando ] || (elem[ expando ] = {}); // Support: IE <9 only // Defend against cloned attroperties (jQuery gh-1709) uniqueCache = outerCache[ elem.uniqueID ] || (outerCache[ elem.uniqueID ] = {}); if ( (oldCache = uniqueCache[ dir ]) && oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) { // Assign to newCache so results back-propagate to previous elements return (newCache[ 2 ] = oldCache[ 2 ]); } else { // Reuse newcache so results back-propagate to previous elements uniqueCache[ dir ] = newCache; // A match means we're done; a fail means we have to keep checking if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) { return true; } } } } } }; } function elementMatcher( matchers ) { return matchers.length > 1 ? function( elem, context, xml ) { var i = matchers.length; while ( i-- ) { if ( !matchers[i]( elem, context, xml ) ) { return false; } } return true; } : matchers[0]; } function multipleContexts( selector, contexts, results ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[i], results ); } return results; } function condense( unmatched, map, filter, context, xml ) { var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null; for ( ; i < len; i++ ) { if ( (elem = unmatched[i]) ) { if ( !filter || filter( elem, context, xml ) ) { newUnmatched.push( elem ); if ( mapped ) { map.push( i ); } } } } return newUnmatched; } function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { if ( postFilter && !postFilter[ expando ] ) { postFilter = setMatcher( postFilter ); } if ( postFinder && !postFinder[ expando ] ) { postFinder = setMatcher( postFinder, postSelector ); } return markFunction(function( seed, results, context, xml ) { var temp, i, elem, preMap = [], postMap = [], preexisting = results.length, // Get initial elements from seed or context elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), // Prefilter to get matcher input, preserving a map for seed-results synchronization matcherIn = preFilter && ( seed || !selector ) ? condense( elems, preMap, preFilter, context, xml ) : elems, matcherOut = matcher ? // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, postFinder || ( seed ? preFilter : preexisting || postFilter ) ? // ...intermediate processing is necessary [] : // ...otherwise use results directly results : matcherIn; // Find primary matches if ( matcher ) { matcher( matcherIn, matcherOut, context, xml ); } // Apply postFilter if ( postFilter ) { temp = condense( matcherOut, postMap ); postFilter( temp, [], context, xml ); // Un-match failing elements by moving them back to matcherIn i = temp.length; while ( i-- ) { if ( (elem = temp[i]) ) { matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); } } } if ( seed ) { if ( postFinder || preFilter ) { if ( postFinder ) { // Get the final matcherOut by condensing this intermediate into postFinder contexts temp = []; i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) ) { // Restore matcherIn since elem is not yet a final match temp.push( (matcherIn[i] = elem) ); } } postFinder( null, (matcherOut = []), temp, xml ); } // Move matched elements from seed to results to keep them synchronized i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) && (temp = postFinder ? indexOf( seed, elem ) : preMap[i]) > -1 ) { seed[temp] = !(results[temp] = elem); } } } // Add elements to results, through postFinder if defined } else { matcherOut = condense( matcherOut === results ? matcherOut.splice( preexisting, matcherOut.length ) : matcherOut ); if ( postFinder ) { postFinder( null, results, matcherOut, xml ); } else { push.apply( results, matcherOut ); } } }); } function matcherFromTokens( tokens ) { var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[ tokens[0].type ], implicitRelative = leadingRelative || Expr.relative[" "], i = leadingRelative ? 1 : 0, // The foundational matcher ensures that elements are reachable from top-level context(s) matchContext = addCombinator( function( elem ) { return elem === checkContext; }, implicitRelative, true ), matchAnyContext = addCombinator( function( elem ) { return indexOf( checkContext, elem ) > -1; }, implicitRelative, true ), matchers = [ function( elem, context, xml ) { var ret = ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( (checkContext = context).nodeType ? matchContext( elem, context, xml ) : matchAnyContext( elem, context, xml ) ); // Avoid hanging onto element (issue #299) checkContext = null; return ret; } ]; for ( ; i < len; i++ ) { if ( (matcher = Expr.relative[ tokens[i].type ]) ) { matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; } else { matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); // Return special upon seeing a positional matcher if ( matcher[ expando ] ) { // Find the next relative operator (if any) for proper handling j = ++i; for ( ; j < len; j++ ) { if ( Expr.relative[ tokens[j].type ] ) { break; } } return setMatcher( i > 1 && elementMatcher( matchers ), i > 1 && toSelector( // If the preceding token was a descendant combinator, insert an implicit any-element `*` tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" }) ).replace( rtrim, "$1" ), matcher, i < j && matcherFromTokens( tokens.slice( i, j ) ), j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), j < len && toSelector( tokens ) ); } matchers.push( matcher ); } } return elementMatcher( matchers ); } function matcherFromGroupMatchers( elementMatchers, setMatchers ) { var bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function( seed, context, xml, results, outermost ) { var elem, j, matcher, matchedCount = 0, i = "0", unmatched = seed && [], setMatched = [], contextBackup = outermostContext, // We must always have either seed elements or outermost context elems = seed || byElement && Expr.find["TAG"]( "*", outermost ), // Use integer dirruns iff this is the outermost matcher dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1), len = elems.length; if ( outermost ) { outermostContext = context === document || context || outermost; } // Add elements passing elementMatchers directly to results // Support: IE<9, Safari // Tolerate NodeList properties (IE: "length"; Safari: ) matching elements by id for ( ; i !== len && (elem = elems[i]) != null; i++ ) { if ( byElement && elem ) { j = 0; if ( !context && elem.ownerDocument !== document ) { setDocument( elem ); xml = !documentIsHTML; } while ( (matcher = elementMatchers[j++]) ) { if ( matcher( elem, context || document, xml) ) { results.push( elem ); break; } } if ( outermost ) { dirruns = dirrunsUnique; } } // Track unmatched elements for set filters if ( bySet ) { // They will have gone through all possible matchers if ( (elem = !matcher && elem) ) { matchedCount--; } // Lengthen the array for every element, matched or not if ( seed ) { unmatched.push( elem ); } } } // `i` is now the count of elements visited above, and adding it to `matchedCount` // makes the latter nonnegative. matchedCount += i; // Apply set filters to unmatched elements // NOTE: This can be skipped if there are no unmatched elements (i.e., `matchedCount` // equals `i`), unless we didn't visit _any_ elements in the above loop because we have // no element matchers and no seed. // Incrementing an initially-string "0" `i` allows `i` to remain a string only in that // case, which will result in a "00" `matchedCount` that differs from `i` but is also // numerically zero. if ( bySet && i !== matchedCount ) { j = 0; while ( (matcher = setMatchers[j++]) ) { matcher( unmatched, setMatched, context, xml ); } if ( seed ) { // Reintegrate element matches to eliminate the need for sorting if ( matchedCount > 0 ) { while ( i-- ) { if ( !(unmatched[i] || setMatched[i]) ) { setMatched[i] = pop.call( results ); } } } // Discard index placeholder values to get only actual matches setMatched = condense( setMatched ); } // Add matches to results push.apply( results, setMatched ); // Seedless set matches succeeding multiple successful matchers stipulate sorting if ( outermost && !seed && setMatched.length > 0 && ( matchedCount + setMatchers.length ) > 1 ) { Sizzle.uniqueSort( results ); } } // Override manipulation of globals by nested matchers if ( outermost ) { dirruns = dirrunsUnique; outermostContext = contextBackup; } return unmatched; }; return bySet ? markFunction( superMatcher ) : superMatcher; } compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) { var i, setMatchers = [], elementMatchers = [], cached = compilerCache[ selector + " " ]; if ( !cached ) { // Generate a function of recursive functions that can be used to check each element if ( !match ) { match = tokenize( selector ); } i = match.length; while ( i-- ) { cached = matcherFromTokens( match[i] ); if ( cached[ expando ] ) { setMatchers.push( cached ); } else { elementMatchers.push( cached ); } } // Cache the compiled function cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); // Save selector and tokenization cached.selector = selector; } return cached; }; /** * A low-level selection function that works with Sizzle's compiled * selector functions * @param {String|Function} selector A selector or a pre-compiled * selector function built with Sizzle.compile * @param {Element} context * @param {Array} [results] * @param {Array} [seed] A set of elements to match against */ select = Sizzle.select = function( selector, context, results, seed ) { var i, tokens, token, type, find, compiled = typeof selector === "function" && selector, match = !seed && tokenize( (selector = compiled.selector || selector) ); results = results || []; // Try to minimize operations if there is only one selector in the list and no seed // (the latter of which guarantees us context) if ( match.length === 1 ) { // Reduce context if the leading compound selector is an ID tokens = match[0] = match[0].slice( 0 ); if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && support.getById && context.nodeType === 9 && documentIsHTML && Expr.relative[ tokens[1].type ] ) { context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0]; if ( !context ) { return results; // Precompiled matchers will still verify ancestry, so step up a level } else if ( compiled ) { context = context.parentNode; } selector = selector.slice( tokens.shift().value.length ); } // Fetch a seed set for right-to-left matching i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; while ( i-- ) { token = tokens[i]; // Abort if we hit a combinator if ( Expr.relative[ (type = token.type) ] ) { break; } if ( (find = Expr.find[ type ]) ) { // Search, expanding context for leading sibling combinators if ( (seed = find( token.matches[0].replace( runescape, funescape ), rsibling.test( tokens[0].type ) && testContext( context.parentNode ) || context )) ) { // If seed is empty or no tokens remain, we can return early tokens.splice( i, 1 ); selector = seed.length && toSelector( tokens ); if ( !selector ) { push.apply( results, seed ); return results; } break; } } } } // Compile and execute a filtering function if one is not provided // Provide `match` to avoid retokenization if we modified the selector above ( compiled || compile( selector, match ) )( seed, context, !documentIsHTML, results, !context || rsibling.test( selector ) && testContext( context.parentNode ) || context ); return results; }; // One-time assignments // Sort stability support.sortStable = expando.split("").sort( sortOrder ).join("") === expando; // Support: Chrome 14-35+ // Always assume duplicates if they aren't passed to the comparison function support.detectDuplicates = !!hasDuplicate; // Initialize against the default document setDocument(); // Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) // Detached nodes confoundingly follow *each other* support.sortDetached = assert(function( div1 ) { // Should return 1, but returns 4 (following) return div1.compareDocumentPosition( document.createElement("div") ) & 1; }); // Support: IE<8 // Prevent attribute/property "interpolation" // http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if ( !assert(function( div ) { div.innerHTML = ""; return div.firstChild.getAttribute("href") === "#" ; }) ) { addHandle( "type|href|height|width", function( elem, name, isXML ) { if ( !isXML ) { return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); } }); } // Support: IE<9 // Use defaultValue in place of getAttribute("value") if ( !support.attributes || !assert(function( div ) { div.innerHTML = ""; div.firstChild.setAttribute( "value", "" ); return div.firstChild.getAttribute( "value" ) === ""; }) ) { addHandle( "value", function( elem, name, isXML ) { if ( !isXML && elem.nodeName.toLowerCase() === "input" ) { return elem.defaultValue; } }); } // Support: IE<9 // Use getAttributeNode to fetch booleans when getAttribute lies if ( !assert(function( div ) { return div.getAttribute("disabled") == null; }) ) { addHandle( booleans, function( elem, name, isXML ) { var val; if ( !isXML ) { return elem[ name ] === true ? name.toLowerCase() : (val = elem.getAttributeNode( name )) && val.specified ? val.value : null; } }); } return Sizzle; })( window ); jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[ ":" ] = jQuery.expr.pseudos; jQuery.uniqueSort = jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; var dir = function( elem, dir, until ) { var matched = [], truncate = until !== undefined; while ( ( elem = elem[ dir ] ) && elem.nodeType !== 9 ) { if ( elem.nodeType === 1 ) { if ( truncate && jQuery( elem ).is( until ) ) { break; } matched.push( elem ); } } return matched; }; var siblings = function( n, elem ) { var matched = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { matched.push( n ); } } return matched; }; var rneedsContext = jQuery.expr.match.needsContext; var rsingleTag = ( /^<([\w-]+)\s*\/?>(?:<\/\1>|)$/ ); var risSimple = /^.[^:#\[\.,]*$/; // Implement the identical functionality for filter and not function winnow( elements, qualifier, not ) { if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep( elements, function( elem, i ) { /* jshint -W018 */ return !!qualifier.call( elem, i, elem ) !== not; } ); } if ( qualifier.nodeType ) { return jQuery.grep( elements, function( elem ) { return ( elem === qualifier ) !== not; } ); } if ( typeof qualifier === "string" ) { if ( risSimple.test( qualifier ) ) { return jQuery.filter( qualifier, elements, not ); } qualifier = jQuery.filter( qualifier, elements ); } return jQuery.grep( elements, function( elem ) { return ( jQuery.inArray( elem, qualifier ) > -1 ) !== not; } ); } jQuery.filter = function( expr, elems, not ) { var elem = elems[ 0 ]; if ( not ) { expr = ":not(" + expr + ")"; } return elems.length === 1 && elem.nodeType === 1 ? jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] : jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { return elem.nodeType === 1; } ) ); }; jQuery.fn.extend( { find: function( selector ) { var i, ret = [], self = this, len = self.length; if ( typeof selector !== "string" ) { return this.pushStack( jQuery( selector ).filter( function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } } ) ); } for ( i = 0; i < len; i++ ) { jQuery.find( selector, self[ i ], ret ); } // Needed because $( selector, context ) becomes $( context ).find( selector ) ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret ); ret.selector = this.selector ? this.selector + " " + selector : selector; return ret; }, filter: function( selector ) { return this.pushStack( winnow( this, selector || [], false ) ); }, not: function( selector ) { return this.pushStack( winnow( this, selector || [], true ) ); }, is: function( selector ) { return !!winnow( this, // If this is a positional/relative selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". typeof selector === "string" && rneedsContext.test( selector ) ? jQuery( selector ) : selector || [], false ).length; } } ); // Initialize a jQuery object // A central reference to the root jQuery(document) var rootjQuery, // A simple way to check for HTML strings // Prioritize #id over to avoid XSS via location.hash (#9521) // Strict HTML recognition (#11290: must start with <) rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/, init = jQuery.fn.init = function( selector, context, root ) { var match, elem; // HANDLE: $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // init accepts an alternate rootjQuery // so migrate can support jQuery.sub (gh-2101) root = root || rootjQuery; // Handle HTML strings if ( typeof selector === "string" ) { if ( selector.charAt( 0 ) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = rquickExpr.exec( selector ); } // Match html or make sure no context is specified for #id if ( match && ( match[ 1 ] || !context ) ) { // HANDLE: $(html) -> $(array) if ( match[ 1 ] ) { context = context instanceof jQuery ? context[ 0 ] : context; // scripts is true for back-compat // Intentionally let the error be thrown if parseHTML is not present jQuery.merge( this, jQuery.parseHTML( match[ 1 ], context && context.nodeType ? context.ownerDocument || context : document, true ) ); // HANDLE: $(html, props) if ( rsingleTag.test( match[ 1 ] ) && jQuery.isPlainObject( context ) ) { for ( match in context ) { // Properties of context are called as methods if possible if ( jQuery.isFunction( this[ match ] ) ) { this[ match ]( context[ match ] ); // ...and otherwise set as attributes } else { this.attr( match, context[ match ] ); } } } return this; // HANDLE: $(#id) } else { elem = document.getElementById( match[ 2 ] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE and Opera return items // by name instead of ID if ( elem.id !== match[ 2 ] ) { return rootjQuery.find( selector ); } // Otherwise, we inject the element directly into the jQuery object this.length = 1; this[ 0 ] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return ( context || root ).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(DOMElement) } else if ( selector.nodeType ) { this.context = this[ 0 ] = selector; this.length = 1; return this; // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return typeof root.ready !== "undefined" ? root.ready( selector ) : // Execute immediately if ready is not present selector( jQuery ); } if ( selector.selector !== undefined ) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }; // Give the init function the jQuery prototype for later instantiation init.prototype = jQuery.fn; // Initialize central reference rootjQuery = jQuery( document ); var rparentsprev = /^(?:parents|prev(?:Until|All))/, // methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.fn.extend( { has: function( target ) { var i, targets = jQuery( target, this ), len = targets.length; return this.filter( function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( this, targets[ i ] ) ) { return true; } } } ); }, closest: function( selectors, context ) { var cur, i = 0, l = this.length, matched = [], pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? jQuery( selectors, context || this.context ) : 0; for ( ; i < l; i++ ) { for ( cur = this[ i ]; cur && cur !== context; cur = cur.parentNode ) { // Always skip document fragments if ( cur.nodeType < 11 && ( pos ? pos.index( cur ) > -1 : // Don't pass non-elements to Sizzle cur.nodeType === 1 && jQuery.find.matchesSelector( cur, selectors ) ) ) { matched.push( cur ); break; } } } return this.pushStack( matched.length > 1 ? jQuery.uniqueSort( matched ) : matched ); }, // Determine the position of an element within // the matched set of elements index: function( elem ) { // No argument, return index in parent if ( !elem ) { return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1; } // index in selector if ( typeof elem === "string" ) { return jQuery.inArray( this[ 0 ], jQuery( elem ) ); } // Locate the position of the desired element return jQuery.inArray( // If it receives a jQuery object, the first element is used elem.jquery ? elem[ 0 ] : elem, this ); }, add: function( selector, context ) { return this.pushStack( jQuery.uniqueSort( jQuery.merge( this.get(), jQuery( selector, context ) ) ) ); }, addBack: function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter( selector ) ); } } ); function sibling( cur, dir ) { do { cur = cur[ dir ]; } while ( cur && cur.nodeType !== 1 ); return cur; } jQuery.each( { parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return dir( elem, "parentNode", until ); }, next: function( elem ) { return sibling( elem, "nextSibling" ); }, prev: function( elem ) { return sibling( elem, "previousSibling" ); }, nextAll: function( elem ) { return dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return siblings( ( elem.parentNode || {} ).firstChild, elem ); }, children: function( elem ) { return siblings( elem.firstChild ); }, contents: function( elem ) { return jQuery.nodeName( elem, "iframe" ) ? elem.contentDocument || elem.contentWindow.document : jQuery.merge( [], elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var ret = jQuery.map( this, fn, until ); if ( name.slice( -5 ) !== "Until" ) { selector = until; } if ( selector && typeof selector === "string" ) { ret = jQuery.filter( selector, ret ); } if ( this.length > 1 ) { // Remove duplicates if ( !guaranteedUnique[ name ] ) { ret = jQuery.uniqueSort( ret ); } // Reverse order for parents* and prev-derivatives if ( rparentsprev.test( name ) ) { ret = ret.reverse(); } } return this.pushStack( ret ); }; } ); var rnotwhite = ( /\S+/g ); // Convert String-formatted options into Object-formatted ones function createOptions( options ) { var object = {}; jQuery.each( options.match( rnotwhite ) || [], function( _, flag ) { object[ flag ] = true; } ); return object; } /* * Create a callback list using the following parameters: * * options: an optional list of space-separated options that will change how * the callback list behaves or a more traditional option object * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible options: * * once: will ensure the callback list can only be fired once (like a Deferred) * * memory: will keep track of previous values and will call any callback added * after the list has been fired right away with the latest "memorized" * values (like a Deferred) * * unique: will ensure a callback can only be added once (no duplicate in the list) * * stopOnFalse: interrupt callings when a callback returns false * */ jQuery.Callbacks = function( options ) { // Convert options from String-formatted to Object-formatted if needed // (we check in cache first) options = typeof options === "string" ? createOptions( options ) : jQuery.extend( {}, options ); var // Flag to know if list is currently firing firing, // Last fire value for non-forgettable lists memory, // Flag to know if list was already fired fired, // Flag to prevent firing locked, // Actual callback list list = [], // Queue of execution data for repeatable lists queue = [], // Index of currently firing callback (modified by add/remove as needed) firingIndex = -1, // Fire callbacks fire = function() { // Enforce single-firing locked = options.once; // Execute callbacks for all pending executions, // respecting firingIndex overrides and runtime changes fired = firing = true; for ( ; queue.length; firingIndex = -1 ) { memory = queue.shift(); while ( ++firingIndex < list.length ) { // Run callback and check for early termination if ( list[ firingIndex ].apply( memory[ 0 ], memory[ 1 ] ) === false && options.stopOnFalse ) { // Jump to end and forget the data so .add doesn't re-fire firingIndex = list.length; memory = false; } } } // Forget the data if we're done with it if ( !options.memory ) { memory = false; } firing = false; // Clean up if we're done firing for good if ( locked ) { // Keep an empty list if we have data for future add calls if ( memory ) { list = []; // Otherwise, this object is spent } else { list = ""; } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { // If we have memory from a past run, we should fire after adding if ( memory && !firing ) { firingIndex = list.length - 1; queue.push( memory ); } ( function add( args ) { jQuery.each( args, function( _, arg ) { if ( jQuery.isFunction( arg ) ) { if ( !options.unique || !self.has( arg ) ) { list.push( arg ); } } else if ( arg && arg.length && jQuery.type( arg ) !== "string" ) { // Inspect recursively add( arg ); } } ); } )( arguments ); if ( memory && !firing ) { fire(); } } return this; }, // Remove a callback from the list remove: function() { jQuery.each( arguments, function( _, arg ) { var index; while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { list.splice( index, 1 ); // Handle firing indexes if ( index <= firingIndex ) { firingIndex--; } } } ); return this; }, // Check if a given callback is in the list. // If no argument is given, return whether or not list has callbacks attached. has: function( fn ) { return fn ? jQuery.inArray( fn, list ) > -1 : list.length > 0; }, // Remove all callbacks from the list empty: function() { if ( list ) { list = []; } return this; }, // Disable .fire and .add // Abort any current/pending executions // Clear all callbacks and values disable: function() { locked = queue = []; list = memory = ""; return this; }, disabled: function() { return !list; }, // Disable .fire // Also disable .add unless we have memory (since it would have no effect) // Abort any pending executions lock: function() { locked = true; if ( !memory ) { self.disable(); } return this; }, locked: function() { return !!locked; }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { if ( !locked ) { args = args || []; args = [ context, args.slice ? args.slice() : args ]; queue.push( args ); if ( !firing ) { fire(); } } return this; }, // Call all the callbacks with the given arguments fire: function() { self.fireWith( this, arguments ); return this; }, // To know if the callbacks have already been called at least once fired: function() { return !!fired; } }; return self; }; jQuery.extend( { Deferred: function( func ) { var tuples = [ // action, add listener, listener list, final state [ "resolve", "done", jQuery.Callbacks( "once memory" ), "resolved" ], [ "reject", "fail", jQuery.Callbacks( "once memory" ), "rejected" ], [ "notify", "progress", jQuery.Callbacks( "memory" ) ] ], state = "pending", promise = { state: function() { return state; }, always: function() { deferred.done( arguments ).fail( arguments ); return this; }, then: function( /* fnDone, fnFail, fnProgress */ ) { var fns = arguments; return jQuery.Deferred( function( newDefer ) { jQuery.each( tuples, function( i, tuple ) { var fn = jQuery.isFunction( fns[ i ] ) && fns[ i ]; // deferred[ done | fail | progress ] for forwarding actions to newDefer deferred[ tuple[ 1 ] ]( function() { var returned = fn && fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise() .progress( newDefer.notify ) .done( newDefer.resolve ) .fail( newDefer.reject ); } else { newDefer[ tuple[ 0 ] + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments ); } } ); } ); fns = null; } ).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { return obj != null ? jQuery.extend( obj, promise ) : promise; } }, deferred = {}; // Keep pipe for back-compat promise.pipe = promise.then; // Add list-specific methods jQuery.each( tuples, function( i, tuple ) { var list = tuple[ 2 ], stateString = tuple[ 3 ]; // promise[ done | fail | progress ] = list.add promise[ tuple[ 1 ] ] = list.add; // Handle state if ( stateString ) { list.add( function() { // state = [ resolved | rejected ] state = stateString; // [ reject_list | resolve_list ].disable; progress_list.lock }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); } // deferred[ resolve | reject | notify ] deferred[ tuple[ 0 ] ] = function() { deferred[ tuple[ 0 ] + "With" ]( this === deferred ? promise : this, arguments ); return this; }; deferred[ tuple[ 0 ] + "With" ] = list.fireWith; } ); // Make the deferred a promise promise.promise( deferred ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; }, // Deferred helper when: function( subordinate /* , ..., subordinateN */ ) { var i = 0, resolveValues = slice.call( arguments ), length = resolveValues.length, // the count of uncompleted subordinates remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, // the master Deferred. // If resolveValues consist of only a single Deferred, just use that. deferred = remaining === 1 ? subordinate : jQuery.Deferred(), // Update function for both resolve and progress values updateFunc = function( i, contexts, values ) { return function( value ) { contexts[ i ] = this; values[ i ] = arguments.length > 1 ? slice.call( arguments ) : value; if ( values === progressValues ) { deferred.notifyWith( contexts, values ); } else if ( !( --remaining ) ) { deferred.resolveWith( contexts, values ); } }; }, progressValues, progressContexts, resolveContexts; // add listeners to Deferred subordinates; treat others as resolved if ( length > 1 ) { progressValues = new Array( length ); progressContexts = new Array( length ); resolveContexts = new Array( length ); for ( ; i < length; i++ ) { if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { resolveValues[ i ].promise() .progress( updateFunc( i, progressContexts, progressValues ) ) .done( updateFunc( i, resolveContexts, resolveValues ) ) .fail( deferred.reject ); } else { --remaining; } } } // if we're not waiting on anything, resolve the master if ( !remaining ) { deferred.resolveWith( resolveContexts, resolveValues ); } return deferred.promise(); } } ); // The deferred used on DOM ready var readyList; jQuery.fn.ready = function( fn ) { // Add the callback jQuery.ready.promise().done( fn ); return this; }; jQuery.extend( { // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Hold (or release) the ready event holdReady: function( hold ) { if ( hold ) { jQuery.readyWait++; } else { jQuery.ready( true ); } }, // Handle when the DOM is ready ready: function( wait ) { // Abort if there are pending holds or we're already ready if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { return; } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.resolveWith( document, [ jQuery ] ); // Trigger any bound ready events if ( jQuery.fn.triggerHandler ) { jQuery( document ).triggerHandler( "ready" ); jQuery( document ).off( "ready" ); } } } ); /** * Clean-up method for dom ready events */ function detach() { if ( document.addEventListener ) { document.removeEventListener( "DOMContentLoaded", completed ); window.removeEventListener( "load", completed ); } else { document.detachEvent( "onreadystatechange", completed ); window.detachEvent( "onload", completed ); } } /** * The ready event handler and self cleanup method */ function completed() { // readyState === "complete" is good enough for us to call the dom ready in oldIE if ( document.addEventListener || window.event.type === "load" || document.readyState === "complete" ) { detach(); jQuery.ready(); } } jQuery.ready.promise = function( obj ) { if ( !readyList ) { readyList = jQuery.Deferred(); // Catch cases where $(document).ready() is called // after the browser event has already occurred. // Support: IE6-10 // Older IE sometimes signals "interactive" too soon if ( document.readyState === "complete" || ( document.readyState !== "loading" && !document.documentElement.doScroll ) ) { // Handle it asynchronously to allow scripts the opportunity to delay ready window.setTimeout( jQuery.ready ); // Standards-based browsers support DOMContentLoaded } else if ( document.addEventListener ) { // Use the handy event callback document.addEventListener( "DOMContentLoaded", completed ); // A fallback to window.onload, that will always work window.addEventListener( "load", completed ); // If IE event model is used } else { // Ensure firing before onload, maybe late but safe also for iframes document.attachEvent( "onreadystatechange", completed ); // A fallback to window.onload, that will always work window.attachEvent( "onload", completed ); // If IE and not a frame // continually check to see if the document is ready var top = false; try { top = window.frameElement == null && document.documentElement; } catch ( e ) {} if ( top && top.doScroll ) { ( function doScrollCheck() { if ( !jQuery.isReady ) { try { // Use the trick by Diego Perini // http://javascript.nwbox.com/IEContentLoaded/ top.doScroll( "left" ); } catch ( e ) { return window.setTimeout( doScrollCheck, 50 ); } // detach all dom ready events detach(); // and execute any waiting functions jQuery.ready(); } } )(); } } } return readyList.promise( obj ); }; // Kick off the DOM ready check even if the user does not jQuery.ready.promise(); // Support: IE<9 // Iteration over object's inherited properties before its own var i; for ( i in jQuery( support ) ) { break; } support.ownFirst = i === "0"; // Note: most support tests are defined in their respective modules. // false until the test is run support.inlineBlockNeedsLayout = false; // Execute ASAP in case we need to set body.style.zoom jQuery( function() { // Minified: var a,b,c,d var val, div, body, container; body = document.getElementsByTagName( "body" )[ 0 ]; if ( !body || !body.style ) { // Return for frameset docs that don't have a body return; } // Setup div = document.createElement( "div" ); container = document.createElement( "div" ); container.style.cssText = "position:absolute;border:0;width:0;height:0;top:0;left:-9999px"; body.appendChild( container ).appendChild( div ); if ( typeof div.style.zoom !== "undefined" ) { // Support: IE<8 // Check if natively block-level elements act like inline-block // elements when setting their display to 'inline' and giving // them layout div.style.cssText = "display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1"; support.inlineBlockNeedsLayout = val = div.offsetWidth === 3; if ( val ) { // Prevent IE 6 from affecting layout for positioned elements #11048 // Prevent IE from shrinking the body in IE 7 mode #12869 // Support: IE<8 body.style.zoom = 1; } } body.removeChild( container ); } ); ( function() { var div = document.createElement( "div" ); // Support: IE<9 support.deleteExpando = true; try { delete div.test; } catch ( e ) { support.deleteExpando = false; } // Null elements to avoid leaks in IE. div = null; } )(); var acceptData = function( elem ) { var noData = jQuery.noData[ ( elem.nodeName + " " ).toLowerCase() ], nodeType = +elem.nodeType || 1; // Do not set data on non-element DOM nodes because it will not be cleared (#8335). return nodeType !== 1 && nodeType !== 9 ? false : // Nodes accept data unless otherwise specified; rejection can be conditional !noData || noData !== true && elem.getAttribute( "classid" ) === noData; }; var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/, rmultiDash = /([A-Z])/g; function dataAttr( elem, key, data ) { // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : // Only convert to a number if it doesn't change the string +data + "" === data ? +data : rbrace.test( data ) ? jQuery.parseJSON( data ) : data; } catch ( e ) {} // Make sure we set the data so it isn't changed later jQuery.data( elem, key, data ); } else { data = undefined; } } return data; } // checks a cache object for emptiness function isEmptyDataObject( obj ) { var name; for ( name in obj ) { // if the public data object is empty, the private is still empty if ( name === "data" && jQuery.isEmptyObject( obj[ name ] ) ) { continue; } if ( name !== "toJSON" ) { return false; } } return true; } function internalData( elem, name, data, pvt /* Internal Use Only */ ) { if ( !acceptData( elem ) ) { return; } var ret, thisCache, internalKey = jQuery.expando, // We have to handle DOM nodes and JS objects differently because IE6-7 // can't GC object references properly across the DOM-JS boundary isNode = elem.nodeType, // Only DOM nodes need the global jQuery cache; JS object data is // attached directly to the object so GC can occur automatically cache = isNode ? jQuery.cache : elem, // Only defining an ID for JS objects if its cache already exists allows // the code to shortcut on the same path as a DOM node with no cache id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey; // Avoid doing any more work than we need to when trying to get data on an // object that has no data at all if ( ( !id || !cache[ id ] || ( !pvt && !cache[ id ].data ) ) && data === undefined && typeof name === "string" ) { return; } if ( !id ) { // Only DOM nodes need a new unique ID for each element since their data // ends up in the global cache if ( isNode ) { id = elem[ internalKey ] = deletedIds.pop() || jQuery.guid++; } else { id = internalKey; } } if ( !cache[ id ] ) { // Avoid exposing jQuery metadata on plain JS objects when the object // is serialized using JSON.stringify cache[ id ] = isNode ? {} : { toJSON: jQuery.noop }; } // An object can be passed to jQuery.data instead of a key/value pair; this gets // shallow copied over onto the existing cache if ( typeof name === "object" || typeof name === "function" ) { if ( pvt ) { cache[ id ] = jQuery.extend( cache[ id ], name ); } else { cache[ id ].data = jQuery.extend( cache[ id ].data, name ); } } thisCache = cache[ id ]; // jQuery data() is stored in a separate object inside the object's internal data // cache in order to avoid key collisions between internal data and user-defined // data. if ( !pvt ) { if ( !thisCache.data ) { thisCache.data = {}; } thisCache = thisCache.data; } if ( data !== undefined ) { thisCache[ jQuery.camelCase( name ) ] = data; } // Check for both converted-to-camel and non-converted data property names // If a data property was specified if ( typeof name === "string" ) { // First Try to find as-is property data ret = thisCache[ name ]; // Test for null|undefined property data if ( ret == null ) { // Try to find the camelCased property ret = thisCache[ jQuery.camelCase( name ) ]; } } else { ret = thisCache; } return ret; } function internalRemoveData( elem, name, pvt ) { if ( !acceptData( elem ) ) { return; } var thisCache, i, isNode = elem.nodeType, // See jQuery.data for more information cache = isNode ? jQuery.cache : elem, id = isNode ? elem[ jQuery.expando ] : jQuery.expando; // If there is already no cache entry for this object, there is no // purpose in continuing if ( !cache[ id ] ) { return; } if ( name ) { thisCache = pvt ? cache[ id ] : cache[ id ].data; if ( thisCache ) { // Support array or space separated string names for data keys if ( !jQuery.isArray( name ) ) { // try the string as a key before any manipulation if ( name in thisCache ) { name = [ name ]; } else { // split the camel cased version by spaces unless a key with the spaces exists name = jQuery.camelCase( name ); if ( name in thisCache ) { name = [ name ]; } else { name = name.split( " " ); } } } else { // If "name" is an array of keys... // When data is initially created, via ("key", "val") signature, // keys will be converted to camelCase. // Since there is no way to tell _how_ a key was added, remove // both plain key and camelCase key. #12786 // This will only penalize the array argument path. name = name.concat( jQuery.map( name, jQuery.camelCase ) ); } i = name.length; while ( i-- ) { delete thisCache[ name[ i ] ]; } // If there is no data left in the cache, we want to continue // and let the cache object itself get destroyed if ( pvt ? !isEmptyDataObject( thisCache ) : !jQuery.isEmptyObject( thisCache ) ) { return; } } } // See jQuery.data for more information if ( !pvt ) { delete cache[ id ].data; // Don't destroy the parent cache unless the internal data object // had been the only thing left in it if ( !isEmptyDataObject( cache[ id ] ) ) { return; } } // Destroy the cache if ( isNode ) { jQuery.cleanData( [ elem ], true ); // Use delete when supported for expandos or `cache` is not a window per isWindow (#10080) /* jshint eqeqeq: false */ } else if ( support.deleteExpando || cache != cache.window ) { /* jshint eqeqeq: true */ delete cache[ id ]; // When all else fails, undefined } else { cache[ id ] = undefined; } } jQuery.extend( { cache: {}, // The following elements (space-suffixed to avoid Object.prototype collisions) // throw uncatchable exceptions if you attempt to set expando properties noData: { "applet ": true, "embed ": true, // ...but Flash objects (which have this classid) *can* handle expandos "object ": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" }, hasData: function( elem ) { elem = elem.nodeType ? jQuery.cache[ elem[ jQuery.expando ] ] : elem[ jQuery.expando ]; return !!elem && !isEmptyDataObject( elem ); }, data: function( elem, name, data ) { return internalData( elem, name, data ); }, removeData: function( elem, name ) { return internalRemoveData( elem, name ); }, // For internal use only. _data: function( elem, name, data ) { return internalData( elem, name, data, true ); }, _removeData: function( elem, name ) { return internalRemoveData( elem, name, true ); } } ); jQuery.fn.extend( { data: function( key, value ) { var i, name, data, elem = this[ 0 ], attrs = elem && elem.attributes; // Special expections of .data basically thwart jQuery.access, // so implement the relevant behavior ourselves // Gets all values if ( key === undefined ) { if ( this.length ) { data = jQuery.data( elem ); if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) { i = attrs.length; while ( i-- ) { // Support: IE11+ // The attrs elements can be null (#14894) if ( attrs[ i ] ) { name = attrs[ i ].name; if ( name.indexOf( "data-" ) === 0 ) { name = jQuery.camelCase( name.slice( 5 ) ); dataAttr( elem, name, data[ name ] ); } } } jQuery._data( elem, "parsedAttrs", true ); } } return data; } // Sets multiple values if ( typeof key === "object" ) { return this.each( function() { jQuery.data( this, key ); } ); } return arguments.length > 1 ? // Sets one value this.each( function() { jQuery.data( this, key, value ); } ) : // Gets one value // Try to fetch any internally stored data first elem ? dataAttr( elem, key, jQuery.data( elem, key ) ) : undefined; }, removeData: function( key ) { return this.each( function() { jQuery.removeData( this, key ); } ); } } ); jQuery.extend( { queue: function( elem, type, data ) { var queue; if ( elem ) { type = ( type || "fx" ) + "queue"; queue = jQuery._data( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !queue || jQuery.isArray( data ) ) { queue = jQuery._data( elem, type, jQuery.makeArray( data ) ); } else { queue.push( data ); } } return queue || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), startLength = queue.length, fn = queue.shift(), hooks = jQuery._queueHooks( elem, type ), next = function() { jQuery.dequeue( elem, type ); }; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); startLength--; } if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift( "inprogress" ); } // clear up the last queue stop function delete hooks.stop; fn.call( elem, next, hooks ); } if ( !startLength && hooks ) { hooks.empty.fire(); } }, // not intended for public consumption - generates a queueHooks object, // or returns the current one _queueHooks: function( elem, type ) { var key = type + "queueHooks"; return jQuery._data( elem, key ) || jQuery._data( elem, key, { empty: jQuery.Callbacks( "once memory" ).add( function() { jQuery._removeData( elem, type + "queue" ); jQuery._removeData( elem, key ); } ) } ); } } ); jQuery.fn.extend( { queue: function( type, data ) { var setter = 2; if ( typeof type !== "string" ) { data = type; type = "fx"; setter--; } if ( arguments.length < setter ) { return jQuery.queue( this[ 0 ], type ); } return data === undefined ? this : this.each( function() { var queue = jQuery.queue( this, type, data ); // ensure a hooks for this queue jQuery._queueHooks( this, type ); if ( type === "fx" && queue[ 0 ] !== "inprogress" ) { jQuery.dequeue( this, type ); } } ); }, dequeue: function( type ) { return this.each( function() { jQuery.dequeue( this, type ); } ); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); }, // Get a promise resolved when queues of a certain type // are emptied (fx is the type by default) promise: function( type, obj ) { var tmp, count = 1, defer = jQuery.Deferred(), elements = this, i = this.length, resolve = function() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } }; if ( typeof type !== "string" ) { obj = type; type = undefined; } type = type || "fx"; while ( i-- ) { tmp = jQuery._data( elements[ i ], type + "queueHooks" ); if ( tmp && tmp.empty ) { count++; tmp.empty.add( resolve ); } } resolve(); return defer.promise( obj ); } } ); ( function() { var shrinkWrapBlocksVal; support.shrinkWrapBlocks = function() { if ( shrinkWrapBlocksVal != null ) { return shrinkWrapBlocksVal; } // Will be changed later if needed. shrinkWrapBlocksVal = false; // Minified: var b,c,d var div, body, container; body = document.getElementsByTagName( "body" )[ 0 ]; if ( !body || !body.style ) { // Test fired too early or in an unsupported environment, exit. return; } // Setup div = document.createElement( "div" ); container = document.createElement( "div" ); container.style.cssText = "position:absolute;border:0;width:0;height:0;top:0;left:-9999px"; body.appendChild( container ).appendChild( div ); // Support: IE6 // Check if elements with layout shrink-wrap their children if ( typeof div.style.zoom !== "undefined" ) { // Reset CSS: box-sizing; display; margin; border div.style.cssText = // Support: Firefox<29, Android 2.3 // Vendor-prefix box-sizing "-webkit-box-sizing:content-box;-moz-box-sizing:content-box;" + "box-sizing:content-box;display:block;margin:0;border:0;" + "padding:1px;width:1px;zoom:1"; div.appendChild( document.createElement( "div" ) ).style.width = "5px"; shrinkWrapBlocksVal = div.offsetWidth !== 3; } body.removeChild( container ); return shrinkWrapBlocksVal; }; } )(); var pnum = ( /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/ ).source; var rcssNum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" ); var cssExpand = [ "Top", "Right", "Bottom", "Left" ]; var isHidden = function( elem, el ) { // isHidden might be called from jQuery#filter function; // in that case, element will be second argument elem = el || elem; return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); }; function adjustCSS( elem, prop, valueParts, tween ) { var adjusted, scale = 1, maxIterations = 20, currentValue = tween ? function() { return tween.cur(); } : function() { return jQuery.css( elem, prop, "" ); }, initial = currentValue(), unit = valueParts && valueParts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ), // Starting value computation is required for potential unit mismatches initialInUnit = ( jQuery.cssNumber[ prop ] || unit !== "px" && +initial ) && rcssNum.exec( jQuery.css( elem, prop ) ); if ( initialInUnit && initialInUnit[ 3 ] !== unit ) { // Trust units reported by jQuery.css unit = unit || initialInUnit[ 3 ]; // Make sure we update the tween properties later on valueParts = valueParts || []; // Iteratively approximate from a nonzero starting point initialInUnit = +initial || 1; do { // If previous iteration zeroed out, double until we get *something*. // Use string for doubling so we don't accidentally see scale as unchanged below scale = scale || ".5"; // Adjust and apply initialInUnit = initialInUnit / scale; jQuery.style( elem, prop, initialInUnit + unit ); // Update scale, tolerating zero or NaN from tween.cur() // Break the loop if scale is unchanged or perfect, or if we've just had enough. } while ( scale !== ( scale = currentValue() / initial ) && scale !== 1 && --maxIterations ); } if ( valueParts ) { initialInUnit = +initialInUnit || +initial || 0; // Apply relative offset (+=/-=) if specified adjusted = valueParts[ 1 ] ? initialInUnit + ( valueParts[ 1 ] + 1 ) * valueParts[ 2 ] : +valueParts[ 2 ]; if ( tween ) { tween.unit = unit; tween.start = initialInUnit; tween.end = adjusted; } } return adjusted; } // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function var access = function( elems, fn, key, value, chainable, emptyGet, raw ) { var i = 0, length = elems.length, bulk = key == null; // Sets many values if ( jQuery.type( key ) === "object" ) { chainable = true; for ( i in key ) { access( elems, fn, i, key[ i ], true, emptyGet, raw ); } // Sets one value } else if ( value !== undefined ) { chainable = true; if ( !jQuery.isFunction( value ) ) { raw = true; } if ( bulk ) { // Bulk operations run against the entire set if ( raw ) { fn.call( elems, value ); fn = null; // ...except when executing function values } else { bulk = fn; fn = function( elem, key, value ) { return bulk.call( jQuery( elem ), value ); }; } } if ( fn ) { for ( ; i < length; i++ ) { fn( elems[ i ], key, raw ? value : value.call( elems[ i ], i, fn( elems[ i ], key ) ) ); } } } return chainable ? elems : // Gets bulk ? fn.call( elems ) : length ? fn( elems[ 0 ], key ) : emptyGet; }; var rcheckableType = ( /^(?:checkbox|radio)$/i ); var rtagName = ( /<([\w:-]+)/ ); var rscriptType = ( /^$|\/(?:java|ecma)script/i ); var rleadingWhitespace = ( /^\s+/ ); var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|" + "details|dialog|figcaption|figure|footer|header|hgroup|main|" + "mark|meter|nav|output|picture|progress|section|summary|template|time|video"; function createSafeFragment( document ) { var list = nodeNames.split( "|" ), safeFrag = document.createDocumentFragment(); if ( safeFrag.createElement ) { while ( list.length ) { safeFrag.createElement( list.pop() ); } } return safeFrag; } ( function() { var div = document.createElement( "div" ), fragment = document.createDocumentFragment(), input = document.createElement( "input" ); // Setup div.innerHTML = "
a"; // IE strips leading whitespace when .innerHTML is used support.leadingWhitespace = div.firstChild.nodeType === 3; // Make sure that tbody elements aren't automatically inserted // IE will insert them into empty tables support.tbody = !div.getElementsByTagName( "tbody" ).length; // Make sure that link elements get serialized correctly by innerHTML // This requires a wrapper element in IE support.htmlSerialize = !!div.getElementsByTagName( "link" ).length; // Makes sure cloning an html5 element does not cause problems // Where outerHTML is undefined, this still works support.html5Clone = document.createElement( "nav" ).cloneNode( true ).outerHTML !== "<:nav>"; // Check if a disconnected checkbox will retain its checked // value of true after appended to the DOM (IE6/7) input.type = "checkbox"; input.checked = true; fragment.appendChild( input ); support.appendChecked = input.checked; // Make sure textarea (and checkbox) defaultValue is properly cloned // Support: IE6-IE11+ div.innerHTML = ""; support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue; // #11217 - WebKit loses check when the name is after the checked attribute fragment.appendChild( div ); // Support: Windows Web Apps (WWA) // `name` and `type` must use .setAttribute for WWA (#14901) input = document.createElement( "input" ); input.setAttribute( "type", "radio" ); input.setAttribute( "checked", "checked" ); input.setAttribute( "name", "t" ); div.appendChild( input ); // Support: Safari 5.1, iOS 5.1, Android 4.x, Android 2.3 // old WebKit doesn't clone checked state correctly in fragments support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked; // Support: IE<9 // Cloned elements keep attachEvent handlers, we use addEventListener on IE9+ support.noCloneEvent = !!div.addEventListener; // Support: IE<9 // Since attributes and properties are the same in IE, // cleanData must set properties to undefined rather than use removeAttribute div[ jQuery.expando ] = 1; support.attributes = !div.getAttribute( jQuery.expando ); } )(); // We have to close these tags to support XHTML (#13200) var wrapMap = { option: [ 1, "" ], legend: [ 1, "
", "
" ], area: [ 1, "", "" ], // Support: IE8 param: [ 1, "", "" ], thead: [ 1, "", "
" ], tr: [ 2, "", "
" ], col: [ 2, "", "
" ], td: [ 3, "", "
" ], // IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags, // unless wrapped in a div with non-breaking characters in front of it. _default: support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X
", "
" ] }; // Support: IE8-IE9 wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; function getAll( context, tag ) { var elems, elem, i = 0, found = typeof context.getElementsByTagName !== "undefined" ? context.getElementsByTagName( tag || "*" ) : typeof context.querySelectorAll !== "undefined" ? context.querySelectorAll( tag || "*" ) : undefined; if ( !found ) { for ( found = [], elems = context.childNodes || context; ( elem = elems[ i ] ) != null; i++ ) { if ( !tag || jQuery.nodeName( elem, tag ) ) { found.push( elem ); } else { jQuery.merge( found, getAll( elem, tag ) ); } } } return tag === undefined || tag && jQuery.nodeName( context, tag ) ? jQuery.merge( [ context ], found ) : found; } // Mark scripts as having already been evaluated function setGlobalEval( elems, refElements ) { var elem, i = 0; for ( ; ( elem = elems[ i ] ) != null; i++ ) { jQuery._data( elem, "globalEval", !refElements || jQuery._data( refElements[ i ], "globalEval" ) ); } } var rhtml = /<|&#?\w+;/, rtbody = / from table fragments if ( !support.tbody ) { // String was a , *may* have spurious elem = tag === "table" && !rtbody.test( elem ) ? tmp.firstChild : // String was a bare or wrap[ 1 ] === "
" && !rtbody.test( elem ) ? tmp : 0; j = elem && elem.childNodes.length; while ( j-- ) { if ( jQuery.nodeName( ( tbody = elem.childNodes[ j ] ), "tbody" ) && !tbody.childNodes.length ) { elem.removeChild( tbody ); } } } jQuery.merge( nodes, tmp.childNodes ); // Fix #12392 for WebKit and IE > 9 tmp.textContent = ""; // Fix #12392 for oldIE while ( tmp.firstChild ) { tmp.removeChild( tmp.firstChild ); } // Remember the top-level container for proper cleanup tmp = safe.lastChild; } } } // Fix #11356: Clear elements from fragment if ( tmp ) { safe.removeChild( tmp ); } // Reset defaultChecked for any radios and checkboxes // about to be appended to the DOM in IE 6/7 (#8060) if ( !support.appendChecked ) { jQuery.grep( getAll( nodes, "input" ), fixDefaultChecked ); } i = 0; while ( ( elem = nodes[ i++ ] ) ) { // Skip elements already in the context collection (trac-4087) if ( selection && jQuery.inArray( elem, selection ) > -1 ) { if ( ignored ) { ignored.push( elem ); } continue; } contains = jQuery.contains( elem.ownerDocument, elem ); // Append to fragment tmp = getAll( safe.appendChild( elem ), "script" ); // Preserve script evaluation history if ( contains ) { setGlobalEval( tmp ); } // Capture executables if ( scripts ) { j = 0; while ( ( elem = tmp[ j++ ] ) ) { if ( rscriptType.test( elem.type || "" ) ) { scripts.push( elem ); } } } } tmp = null; return safe; } ( function() { var i, eventName, div = document.createElement( "div" ); // Support: IE<9 (lack submit/change bubble), Firefox (lack focus(in | out) events) for ( i in { submit: true, change: true, focusin: true } ) { eventName = "on" + i; if ( !( support[ i ] = eventName in window ) ) { // Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP) div.setAttribute( eventName, "t" ); support[ i ] = div.attributes[ eventName ].expando === false; } } // Null elements to avoid leaks in IE. div = null; } )(); var rformElems = /^(?:input|select|textarea)$/i, rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|pointer|contextmenu|drag|drop)|click/, rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, rtypenamespace = /^([^.]*)(?:\.(.+)|)/; function returnTrue() { return true; } function returnFalse() { return false; } // Support: IE9 // See #13393 for more info function safeActiveElement() { try { return document.activeElement; } catch ( err ) { } } function on( elem, types, selector, data, fn, one ) { var origFn, type; // Types can be a map of types/handlers if ( typeof types === "object" ) { // ( types-Object, selector, data ) if ( typeof selector !== "string" ) { // ( types-Object, data ) data = data || selector; selector = undefined; } for ( type in types ) { on( elem, type, selector, data, types[ type ], one ); } return elem; } if ( data == null && fn == null ) { // ( types, fn ) fn = selector; data = selector = undefined; } else if ( fn == null ) { if ( typeof selector === "string" ) { // ( types, selector, fn ) fn = data; data = undefined; } else { // ( types, data, fn ) fn = data; data = selector; selector = undefined; } } if ( fn === false ) { fn = returnFalse; } else if ( !fn ) { return elem; } if ( one === 1 ) { origFn = fn; fn = function( event ) { // Can use an empty set, since event contains the info jQuery().off( event ); return origFn.apply( this, arguments ); }; // Use same guid so caller can remove using origFn fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); } return elem.each( function() { jQuery.event.add( this, types, fn, data, selector ); } ); } /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { global: {}, add: function( elem, types, handler, data, selector ) { var tmp, events, t, handleObjIn, special, eventHandle, handleObj, handlers, type, namespaces, origType, elemData = jQuery._data( elem ); // Don't attach events to noData or text/comment nodes (but allow plain objects) if ( !elemData ) { return; } // Caller can pass in an object of custom data in lieu of the handler if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; selector = handleObjIn.selector; } // Make sure that the handler has a unique ID, used to find/remove it later if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure and main handler, if this is the first if ( !( events = elemData.events ) ) { events = elemData.events = {}; } if ( !( eventHandle = elemData.handle ) ) { eventHandle = elemData.handle = function( e ) { // Discard the second event of a jQuery.event.trigger() and // when an event is called after a page has unloaded return typeof jQuery !== "undefined" && ( !e || jQuery.event.triggered !== e.type ) ? jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : undefined; }; // Add elem as a property of the handle fn to prevent a memory leak // with IE non-native events eventHandle.elem = elem; } // Handle multiple events separated by a space types = ( types || "" ).match( rnotwhite ) || [ "" ]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[ t ] ) || []; type = origType = tmp[ 1 ]; namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort(); // There *must* be a type, no attaching namespace-only handlers if ( !type ) { continue; } // If event changes its type, use the special event handlers for the changed type special = jQuery.event.special[ type ] || {}; // If selector defined, determine special event api type, otherwise given type type = ( selector ? special.delegateType : special.bindType ) || type; // Update special based on newly reset type special = jQuery.event.special[ type ] || {}; // handleObj is passed to all event handlers handleObj = jQuery.extend( { type: type, origType: origType, data: data, handler: handler, guid: handler.guid, selector: selector, needsContext: selector && jQuery.expr.match.needsContext.test( selector ), namespace: namespaces.join( "." ) }, handleObjIn ); // Init the event handler queue if we're the first if ( !( handlers = events[ type ] ) ) { handlers = events[ type ] = []; handlers.delegateCount = 0; // Only use addEventListener/attachEvent if the special events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { // Bind the global event handler to the element if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } else if ( elem.attachEvent ) { elem.attachEvent( "on" + type, eventHandle ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add to the element's handler list, delegates in front if ( selector ) { handlers.splice( handlers.delegateCount++, 0, handleObj ); } else { handlers.push( handleObj ); } // Keep track of which events have ever been used, for event optimization jQuery.event.global[ type ] = true; } // Nullify elem to prevent memory leaks in IE elem = null; }, // Detach an event or set of events from an element remove: function( elem, types, handler, selector, mappedTypes ) { var j, handleObj, tmp, origCount, t, events, special, handlers, type, namespaces, origType, elemData = jQuery.hasData( elem ) && jQuery._data( elem ); if ( !elemData || !( events = elemData.events ) ) { return; } // Once for each type.namespace in types; type may be omitted types = ( types || "" ).match( rnotwhite ) || [ "" ]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[ t ] ) || []; type = origType = tmp[ 1 ]; namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort(); // Unbind all events (on this namespace, if provided) for the element if ( !type ) { for ( type in events ) { jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); } continue; } special = jQuery.event.special[ type ] || {}; type = ( selector ? special.delegateType : special.bindType ) || type; handlers = events[ type ] || []; tmp = tmp[ 2 ] && new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ); // Remove matching events origCount = j = handlers.length; while ( j-- ) { handleObj = handlers[ j ]; if ( ( mappedTypes || origType === handleObj.origType ) && ( !handler || handler.guid === handleObj.guid ) && ( !tmp || tmp.test( handleObj.namespace ) ) && ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { handlers.splice( j, 1 ); if ( handleObj.selector ) { handlers.delegateCount--; } if ( special.remove ) { special.remove.call( elem, handleObj ); } } } // Remove generic event handler if we removed something and no more handlers exist // (avoids potential for endless recursion during removal of special event handlers) if ( origCount && !handlers.length ) { if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { delete elemData.handle; // removeData also checks for emptiness and clears the expando if empty // so use it instead of delete jQuery._removeData( elem, "events" ); } }, trigger: function( event, data, elem, onlyHandlers ) { var handle, ontype, cur, bubbleType, special, tmp, i, eventPath = [ elem || document ], type = hasOwn.call( event, "type" ) ? event.type : event, namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split( "." ) : []; cur = tmp = elem = elem || document; // Don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } // focus/blur morphs to focusin/out; ensure we're not firing them right now if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { return; } if ( type.indexOf( "." ) > -1 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split( "." ); type = namespaces.shift(); namespaces.sort(); } ontype = type.indexOf( ":" ) < 0 && "on" + type; // Caller can pass in a jQuery.Event object, Object, or just an event type string event = event[ jQuery.expando ] ? event : new jQuery.Event( type, typeof event === "object" && event ); // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) event.isTrigger = onlyHandlers ? 2 : 3; event.namespace = namespaces.join( "." ); event.rnamespace = event.namespace ? new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ) : null; // Clean up the event in case it is being reused event.result = undefined; if ( !event.target ) { event.target = elem; } // Clone any incoming data and prepend the event, creating the handler arg list data = data == null ? [ event ] : jQuery.makeArray( data, [ event ] ); // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { return; } // Determine event propagation path in advance, per W3C events spec (#9951) // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { bubbleType = special.delegateType || type; if ( !rfocusMorph.test( bubbleType + type ) ) { cur = cur.parentNode; } for ( ; cur; cur = cur.parentNode ) { eventPath.push( cur ); tmp = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if ( tmp === ( elem.ownerDocument || document ) ) { eventPath.push( tmp.defaultView || tmp.parentWindow || window ); } } // Fire handlers on the event path i = 0; while ( ( cur = eventPath[ i++ ] ) && !event.isPropagationStopped() ) { event.type = i > 1 ? bubbleType : special.bindType || type; // jQuery handler handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Native handler handle = ontype && cur[ ontype ]; if ( handle && handle.apply && acceptData( cur ) ) { event.result = handle.apply( cur, data ); if ( event.result === false ) { event.preventDefault(); } } } event.type = type; // If nobody prevented the default action, do it now if ( !onlyHandlers && !event.isDefaultPrevented() ) { if ( ( !special._default || special._default.apply( eventPath.pop(), data ) === false ) && acceptData( elem ) ) { // Call a native DOM method on the target with the same name name as the event. // Can't use an .isFunction() check here because IE6/7 fails that test. // Don't do default actions on window, that's where global variables be (#6170) if ( ontype && elem[ type ] && !jQuery.isWindow( elem ) ) { // Don't re-trigger an onFOO event when we call its FOO() method tmp = elem[ ontype ]; if ( tmp ) { elem[ ontype ] = null; } // Prevent re-triggering of the same event, since we already bubbled it above jQuery.event.triggered = type; try { elem[ type ](); } catch ( e ) { // IE<9 dies on focus/blur to hidden element (#1486,#12518) // only reproducible on winXP IE8 native, not IE9 in IE8 mode } jQuery.event.triggered = undefined; if ( tmp ) { elem[ ontype ] = tmp; } } } } return event.result; }, dispatch: function( event ) { // Make a writable jQuery.Event from the native event object event = jQuery.event.fix( event ); var i, j, ret, matched, handleObj, handlerQueue = [], args = slice.call( arguments ), handlers = ( jQuery._data( this, "events" ) || {} )[ event.type ] || [], special = jQuery.event.special[ event.type ] || {}; // Use the fix-ed jQuery.Event rather than the (read-only) native event args[ 0 ] = event; event.delegateTarget = this; // Call the preDispatch hook for the mapped type, and let it bail if desired if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { return; } // Determine handlers handlerQueue = jQuery.event.handlers.call( this, event, handlers ); // Run delegates first; they may want to stop propagation beneath us i = 0; while ( ( matched = handlerQueue[ i++ ] ) && !event.isPropagationStopped() ) { event.currentTarget = matched.elem; j = 0; while ( ( handleObj = matched.handlers[ j++ ] ) && !event.isImmediatePropagationStopped() ) { // Triggered event must either 1) have no namespace, or 2) have namespace(s) // a subset or equal to those in the bound event (both can have no namespace). if ( !event.rnamespace || event.rnamespace.test( handleObj.namespace ) ) { event.handleObj = handleObj; event.data = handleObj.data; ret = ( ( jQuery.event.special[ handleObj.origType ] || {} ).handle || handleObj.handler ).apply( matched.elem, args ); if ( ret !== undefined ) { if ( ( event.result = ret ) === false ) { event.preventDefault(); event.stopPropagation(); } } } } } // Call the postDispatch hook for the mapped type if ( special.postDispatch ) { special.postDispatch.call( this, event ); } return event.result; }, handlers: function( event, handlers ) { var i, matches, sel, handleObj, handlerQueue = [], delegateCount = handlers.delegateCount, cur = event.target; // Support (at least): Chrome, IE9 // Find delegate handlers // Black-hole SVG instance trees (#13180) // // Support: Firefox<=42+ // Avoid non-left-click in FF but don't block IE radio events (#3861, gh-2343) if ( delegateCount && cur.nodeType && ( event.type !== "click" || isNaN( event.button ) || event.button < 1 ) ) { /* jshint eqeqeq: false */ for ( ; cur != this; cur = cur.parentNode || this ) { /* jshint eqeqeq: true */ // Don't check non-elements (#13208) // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) if ( cur.nodeType === 1 && ( cur.disabled !== true || event.type !== "click" ) ) { matches = []; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; // Don't conflict with Object.prototype properties (#13203) sel = handleObj.selector + " "; if ( matches[ sel ] === undefined ) { matches[ sel ] = handleObj.needsContext ? jQuery( sel, this ).index( cur ) > -1 : jQuery.find( sel, this, null, [ cur ] ).length; } if ( matches[ sel ] ) { matches.push( handleObj ); } } if ( matches.length ) { handlerQueue.push( { elem: cur, handlers: matches } ); } } } } // Add the remaining (directly-bound) handlers if ( delegateCount < handlers.length ) { handlerQueue.push( { elem: this, handlers: handlers.slice( delegateCount ) } ); } return handlerQueue; }, fix: function( event ) { if ( event[ jQuery.expando ] ) { return event; } // Create a writable copy of the event object and normalize some properties var i, prop, copy, type = event.type, originalEvent = event, fixHook = this.fixHooks[ type ]; if ( !fixHook ) { this.fixHooks[ type ] = fixHook = rmouseEvent.test( type ) ? this.mouseHooks : rkeyEvent.test( type ) ? this.keyHooks : {}; } copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; event = new jQuery.Event( originalEvent ); i = copy.length; while ( i-- ) { prop = copy[ i ]; event[ prop ] = originalEvent[ prop ]; } // Support: IE<9 // Fix target property (#1925) if ( !event.target ) { event.target = originalEvent.srcElement || document; } // Support: Safari 6-8+ // Target should not be a text node (#504, #13143) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } // Support: IE<9 // For mouse/key events, metaKey==false if it's undefined (#3368, #11328) event.metaKey = !!event.metaKey; return fixHook.filter ? fixHook.filter( event, originalEvent ) : event; }, // Includes some event props shared by KeyEvent and MouseEvent props: ( "altKey bubbles cancelable ctrlKey currentTarget detail eventPhase " + "metaKey relatedTarget shiftKey target timeStamp view which" ).split( " " ), fixHooks: {}, keyHooks: { props: "char charCode key keyCode".split( " " ), filter: function( event, original ) { // Add which for key events if ( event.which == null ) { event.which = original.charCode != null ? original.charCode : original.keyCode; } return event; } }, mouseHooks: { props: ( "button buttons clientX clientY fromElement offsetX offsetY " + "pageX pageY screenX screenY toElement" ).split( " " ), filter: function( event, original ) { var body, eventDoc, doc, button = original.button, fromElement = original.fromElement; // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && original.clientX != null ) { eventDoc = event.target.ownerDocument || document; doc = eventDoc.documentElement; body = eventDoc.body; event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); } // Add relatedTarget, if necessary if ( !event.relatedTarget && fromElement ) { event.relatedTarget = fromElement === event.target ? original.toElement : fromElement; } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && button !== undefined ) { event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); } return event; } }, special: { load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, focus: { // Fire native event if possible so blur/focus sequence is correct trigger: function() { if ( this !== safeActiveElement() && this.focus ) { try { this.focus(); return false; } catch ( e ) { // Support: IE<9 // If we error on focus to hidden element (#1486, #12518), // let .trigger() run the handlers } } }, delegateType: "focusin" }, blur: { trigger: function() { if ( this === safeActiveElement() && this.blur ) { this.blur(); return false; } }, delegateType: "focusout" }, click: { // For checkbox, fire native event so checked state will be right trigger: function() { if ( jQuery.nodeName( this, "input" ) && this.type === "checkbox" && this.click ) { this.click(); return false; } }, // For cross-browser consistency, don't fire native .click() on links _default: function( event ) { return jQuery.nodeName( event.target, "a" ); } }, beforeunload: { postDispatch: function( event ) { // Support: Firefox 20+ // Firefox doesn't alert if the returnValue field is not set. if ( event.result !== undefined && event.originalEvent ) { event.originalEvent.returnValue = event.result; } } } }, // Piggyback on a donor event to simulate a different one simulate: function( type, elem, event ) { var e = jQuery.extend( new jQuery.Event(), event, { type: type, isSimulated: true // Previously, `originalEvent: {}` was set here, so stopPropagation call // would not be triggered on donor event, since in our own // jQuery.event.stopPropagation function we had a check for existence of // originalEvent.stopPropagation method, so, consequently it would be a noop. // // Guard for simulated events was moved to jQuery.event.stopPropagation function // since `originalEvent` should point to the original event for the // constancy with other events and for more focused logic } ); jQuery.event.trigger( e, null, elem ); if ( e.isDefaultPrevented() ) { event.preventDefault(); } } }; jQuery.removeEvent = document.removeEventListener ? function( elem, type, handle ) { // This "if" is needed for plain objects if ( elem.removeEventListener ) { elem.removeEventListener( type, handle ); } } : function( elem, type, handle ) { var name = "on" + type; if ( elem.detachEvent ) { // #8545, #7054, preventing memory leaks for custom events in IE6-8 // detachEvent needed property on element, by name of that event, // to properly expose it to GC if ( typeof elem[ name ] === "undefined" ) { elem[ name ] = null; } elem.detachEvent( name, handle ); } }; jQuery.Event = function( src, props ) { // Allow instantiation without the 'new' keyword if ( !( this instanceof jQuery.Event ) ) { return new jQuery.Event( src, props ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = src.defaultPrevented || src.defaultPrevented === undefined && // Support: IE < 9, Android < 4.0 src.returnValue === false ? returnTrue : returnFalse; // Event type } else { this.type = src; } // Put explicitly provided properties onto the event object if ( props ) { jQuery.extend( this, props ); } // Create a timestamp if incoming event doesn't have one this.timeStamp = src && src.timeStamp || jQuery.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { constructor: jQuery.Event, isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse, preventDefault: function() { var e = this.originalEvent; this.isDefaultPrevented = returnTrue; if ( !e ) { return; } // If preventDefault exists, run it on the original event if ( e.preventDefault ) { e.preventDefault(); // Support: IE // Otherwise set the returnValue property of the original event to false } else { e.returnValue = false; } }, stopPropagation: function() { var e = this.originalEvent; this.isPropagationStopped = returnTrue; if ( !e || this.isSimulated ) { return; } // If stopPropagation exists, run it on the original event if ( e.stopPropagation ) { e.stopPropagation(); } // Support: IE // Set the cancelBubble property of the original event to true e.cancelBubble = true; }, stopImmediatePropagation: function() { var e = this.originalEvent; this.isImmediatePropagationStopped = returnTrue; if ( e && e.stopImmediatePropagation ) { e.stopImmediatePropagation(); } this.stopPropagation(); } }; // Create mouseenter/leave events using mouseover/out and event-time checks // so that event delegation works in jQuery. // Do the same for pointerenter/pointerleave and pointerover/pointerout // // Support: Safari 7 only // Safari sends mouseenter too often; see: // https://code.google.com/p/chromium/issues/detail?id=470258 // for the description of the bug (it existed in older Chrome versions as well). jQuery.each( { mouseenter: "mouseover", mouseleave: "mouseout", pointerenter: "pointerover", pointerleave: "pointerout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { delegateType: fix, bindType: fix, handle: function( event ) { var ret, target = this, related = event.relatedTarget, handleObj = event.handleObj; // For mouseenter/leave call the handler if related is outside the target. // NB: No relatedTarget if the mouse left/entered the browser window if ( !related || ( related !== target && !jQuery.contains( target, related ) ) ) { event.type = handleObj.origType; ret = handleObj.handler.apply( this, arguments ); event.type = fix; } return ret; } }; } ); // IE submit delegation if ( !support.submit ) { jQuery.event.special.submit = { setup: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Lazy-add a submit handler when a descendant form may potentially be submitted jQuery.event.add( this, "click._submit keypress._submit", function( e ) { // Node name check avoids a VML-related crash in IE (#9807) var elem = e.target, form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? // Support: IE <=8 // We use jQuery.prop instead of elem.form // to allow fixing the IE8 delegated submit issue (gh-2332) // by 3rd party polyfills/workarounds. jQuery.prop( elem, "form" ) : undefined; if ( form && !jQuery._data( form, "submit" ) ) { jQuery.event.add( form, "submit._submit", function( event ) { event._submitBubble = true; } ); jQuery._data( form, "submit", true ); } } ); // return undefined since we don't need an event listener }, postDispatch: function( event ) { // If form was submitted by the user, bubble the event up the tree if ( event._submitBubble ) { delete event._submitBubble; if ( this.parentNode && !event.isTrigger ) { jQuery.event.simulate( "submit", this.parentNode, event ); } } }, teardown: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Remove delegated handlers; cleanData eventually reaps submit handlers attached above jQuery.event.remove( this, "._submit" ); } }; } // IE change delegation and checkbox/radio fix if ( !support.change ) { jQuery.event.special.change = { setup: function() { if ( rformElems.test( this.nodeName ) ) { // IE doesn't fire change on a check/radio until blur; trigger it on click // after a propertychange. Eat the blur-change in special.change.handle. // This still fires onchange a second time for check/radio after blur. if ( this.type === "checkbox" || this.type === "radio" ) { jQuery.event.add( this, "propertychange._change", function( event ) { if ( event.originalEvent.propertyName === "checked" ) { this._justChanged = true; } } ); jQuery.event.add( this, "click._change", function( event ) { if ( this._justChanged && !event.isTrigger ) { this._justChanged = false; } // Allow triggered, simulated change events (#11500) jQuery.event.simulate( "change", this, event ); } ); } return false; } // Delegated event; lazy-add a change handler on descendant inputs jQuery.event.add( this, "beforeactivate._change", function( e ) { var elem = e.target; if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "change" ) ) { jQuery.event.add( elem, "change._change", function( event ) { if ( this.parentNode && !event.isSimulated && !event.isTrigger ) { jQuery.event.simulate( "change", this.parentNode, event ); } } ); jQuery._data( elem, "change", true ); } } ); }, handle: function( event ) { var elem = event.target; // Swallow native change events from checkbox/radio, we already triggered them above if ( this !== elem || event.isSimulated || event.isTrigger || ( elem.type !== "radio" && elem.type !== "checkbox" ) ) { return event.handleObj.handler.apply( this, arguments ); } }, teardown: function() { jQuery.event.remove( this, "._change" ); return !rformElems.test( this.nodeName ); } }; } // Support: Firefox // Firefox doesn't have focus(in | out) events // Related ticket - https://bugzilla.mozilla.org/show_bug.cgi?id=687787 // // Support: Chrome, Safari // focus(in | out) events fire after focus & blur events, // which is spec violation - http://www.w3.org/TR/DOM-Level-3-Events/#events-focusevent-event-order // Related ticket - https://code.google.com/p/chromium/issues/detail?id=449857 if ( !support.focusin ) { jQuery.each( { focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler on the document while someone wants focusin/focusout var handler = function( event ) { jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ) ); }; jQuery.event.special[ fix ] = { setup: function() { var doc = this.ownerDocument || this, attaches = jQuery._data( doc, fix ); if ( !attaches ) { doc.addEventListener( orig, handler, true ); } jQuery._data( doc, fix, ( attaches || 0 ) + 1 ); }, teardown: function() { var doc = this.ownerDocument || this, attaches = jQuery._data( doc, fix ) - 1; if ( !attaches ) { doc.removeEventListener( orig, handler, true ); jQuery._removeData( doc, fix ); } else { jQuery._data( doc, fix, attaches ); } } }; } ); } jQuery.fn.extend( { on: function( types, selector, data, fn ) { return on( this, types, selector, data, fn ); }, one: function( types, selector, data, fn ) { return on( this, types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { var handleObj, type; if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event handleObj = types.handleObj; jQuery( types.delegateTarget ).off( handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler ); return this; } if ( typeof types === "object" ) { // ( types-object [, selector] ) for ( type in types ) { this.off( type, selector, types[ type ] ); } return this; } if ( selector === false || typeof selector === "function" ) { // ( types [, fn] ) fn = selector; selector = undefined; } if ( fn === false ) { fn = returnFalse; } return this.each( function() { jQuery.event.remove( this, types, fn, selector ); } ); }, trigger: function( type, data ) { return this.each( function() { jQuery.event.trigger( type, data, this ); } ); }, triggerHandler: function( type, data ) { var elem = this[ 0 ]; if ( elem ) { return jQuery.event.trigger( type, data, elem, true ); } } } ); var rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g, rnoshimcache = new RegExp( "<(?:" + nodeNames + ")[\\s/>]", "i" ), rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^>]*)\/>/gi, // Support: IE 10-11, Edge 10240+ // In IE/Edge using regex groups here causes severe slowdowns. // See https://connect.microsoft.com/IE/feedback/details/1736512/ rnoInnerhtml = /\s*$/g, safeFragment = createSafeFragment( document ), fragmentDiv = safeFragment.appendChild( document.createElement( "div" ) ); // Support: IE<8 // Manipulating tables requires a tbody function manipulationTarget( elem, content ) { return jQuery.nodeName( elem, "table" ) && jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ? elem.getElementsByTagName( "tbody" )[ 0 ] || elem.appendChild( elem.ownerDocument.createElement( "tbody" ) ) : elem; } // Replace/restore the type attribute of script elements for safe DOM manipulation function disableScript( elem ) { elem.type = ( jQuery.find.attr( elem, "type" ) !== null ) + "/" + elem.type; return elem; } function restoreScript( elem ) { var match = rscriptTypeMasked.exec( elem.type ); if ( match ) { elem.type = match[ 1 ]; } else { elem.removeAttribute( "type" ); } return elem; } function cloneCopyEvent( src, dest ) { if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { return; } var type, i, l, oldData = jQuery._data( src ), curData = jQuery._data( dest, oldData ), events = oldData.events; if ( events ) { delete curData.handle; curData.events = {}; for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } // make the cloned public data object a copy from the original if ( curData.data ) { curData.data = jQuery.extend( {}, curData.data ); } } function fixCloneNodeIssues( src, dest ) { var nodeName, e, data; // We do not need to do anything for non-Elements if ( dest.nodeType !== 1 ) { return; } nodeName = dest.nodeName.toLowerCase(); // IE6-8 copies events bound via attachEvent when using cloneNode. if ( !support.noCloneEvent && dest[ jQuery.expando ] ) { data = jQuery._data( dest ); for ( e in data.events ) { jQuery.removeEvent( dest, e, data.handle ); } // Event data gets referenced instead of copied if the expando gets copied too dest.removeAttribute( jQuery.expando ); } // IE blanks contents when cloning scripts, and tries to evaluate newly-set text if ( nodeName === "script" && dest.text !== src.text ) { disableScript( dest ).text = src.text; restoreScript( dest ); // IE6-10 improperly clones children of object elements using classid. // IE10 throws NoModificationAllowedError if parent is null, #12132. } else if ( nodeName === "object" ) { if ( dest.parentNode ) { dest.outerHTML = src.outerHTML; } // This path appears unavoidable for IE9. When cloning an object // element in IE9, the outerHTML strategy above is not sufficient. // If the src has innerHTML and the destination does not, // copy the src.innerHTML into the dest.innerHTML. #10324 if ( support.html5Clone && ( src.innerHTML && !jQuery.trim( dest.innerHTML ) ) ) { dest.innerHTML = src.innerHTML; } } else if ( nodeName === "input" && rcheckableType.test( src.type ) ) { // IE6-8 fails to persist the checked state of a cloned checkbox // or radio button. Worse, IE6-7 fail to give the cloned element // a checked appearance if the defaultChecked value isn't also set dest.defaultChecked = dest.checked = src.checked; // IE6-7 get confused and end up setting the value of a cloned // checkbox/radio button to an empty string instead of "on" if ( dest.value !== src.value ) { dest.value = src.value; } // IE6-8 fails to return the selected option to the default selected // state when cloning options } else if ( nodeName === "option" ) { dest.defaultSelected = dest.selected = src.defaultSelected; // IE6-8 fails to set the defaultValue to the correct value when // cloning other types of input fields } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; } } function domManip( collection, args, callback, ignored ) { // Flatten any nested arrays args = concat.apply( [], args ); var first, node, hasScripts, scripts, doc, fragment, i = 0, l = collection.length, iNoClone = l - 1, value = args[ 0 ], isFunction = jQuery.isFunction( value ); // We can't cloneNode fragments that contain checked, in WebKit if ( isFunction || ( l > 1 && typeof value === "string" && !support.checkClone && rchecked.test( value ) ) ) { return collection.each( function( index ) { var self = collection.eq( index ); if ( isFunction ) { args[ 0 ] = value.call( this, index, self.html() ); } domManip( self, args, callback, ignored ); } ); } if ( l ) { fragment = buildFragment( args, collection[ 0 ].ownerDocument, false, collection, ignored ); first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } // Require either new content or an interest in ignored elements to invoke the callback if ( first || ignored ) { scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); hasScripts = scripts.length; // Use the original fragment for the last item // instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). for ( ; i < l; i++ ) { node = fragment; if ( i !== iNoClone ) { node = jQuery.clone( node, true, true ); // Keep references to cloned scripts for later restoration if ( hasScripts ) { // Support: Android<4.1, PhantomJS<2 // push.apply(_, arraylike) throws on ancient WebKit jQuery.merge( scripts, getAll( node, "script" ) ); } } callback.call( collection[ i ], node, i ); } if ( hasScripts ) { doc = scripts[ scripts.length - 1 ].ownerDocument; // Reenable scripts jQuery.map( scripts, restoreScript ); // Evaluate executable scripts on first document insertion for ( i = 0; i < hasScripts; i++ ) { node = scripts[ i ]; if ( rscriptType.test( node.type || "" ) && !jQuery._data( node, "globalEval" ) && jQuery.contains( doc, node ) ) { if ( node.src ) { // Optional AJAX dependency, but won't run scripts if not present if ( jQuery._evalUrl ) { jQuery._evalUrl( node.src ); } } else { jQuery.globalEval( ( node.text || node.textContent || node.innerHTML || "" ) .replace( rcleanScript, "" ) ); } } } } // Fix #11809: Avoid leaking memory fragment = first = null; } } return collection; } function remove( elem, selector, keepData ) { var node, elems = selector ? jQuery.filter( selector, elem ) : elem, i = 0; for ( ; ( node = elems[ i ] ) != null; i++ ) { if ( !keepData && node.nodeType === 1 ) { jQuery.cleanData( getAll( node ) ); } if ( node.parentNode ) { if ( keepData && jQuery.contains( node.ownerDocument, node ) ) { setGlobalEval( getAll( node, "script" ) ); } node.parentNode.removeChild( node ); } } return elem; } jQuery.extend( { htmlPrefilter: function( html ) { return html.replace( rxhtmlTag, "<$1>" ); }, clone: function( elem, dataAndEvents, deepDataAndEvents ) { var destElements, node, clone, i, srcElements, inPage = jQuery.contains( elem.ownerDocument, elem ); if ( support.html5Clone || jQuery.isXMLDoc( elem ) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) { clone = elem.cloneNode( true ); // IE<=8 does not properly clone detached, unknown element nodes } else { fragmentDiv.innerHTML = elem.outerHTML; fragmentDiv.removeChild( clone = fragmentDiv.firstChild ); } if ( ( !support.noCloneEvent || !support.noCloneChecked ) && ( elem.nodeType === 1 || elem.nodeType === 11 ) && !jQuery.isXMLDoc( elem ) ) { // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 destElements = getAll( clone ); srcElements = getAll( elem ); // Fix all IE cloning issues for ( i = 0; ( node = srcElements[ i ] ) != null; ++i ) { // Ensure that the destination node is not null; Fixes #9587 if ( destElements[ i ] ) { fixCloneNodeIssues( node, destElements[ i ] ); } } } // Copy the events from the original to the clone if ( dataAndEvents ) { if ( deepDataAndEvents ) { srcElements = srcElements || getAll( elem ); destElements = destElements || getAll( clone ); for ( i = 0; ( node = srcElements[ i ] ) != null; i++ ) { cloneCopyEvent( node, destElements[ i ] ); } } else { cloneCopyEvent( elem, clone ); } } // Preserve script evaluation history destElements = getAll( clone, "script" ); if ( destElements.length > 0 ) { setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); } destElements = srcElements = node = null; // Return the cloned set return clone; }, cleanData: function( elems, /* internal */ forceAcceptData ) { var elem, type, id, data, i = 0, internalKey = jQuery.expando, cache = jQuery.cache, attributes = support.attributes, special = jQuery.event.special; for ( ; ( elem = elems[ i ] ) != null; i++ ) { if ( forceAcceptData || acceptData( elem ) ) { id = elem[ internalKey ]; data = id && cache[ id ]; if ( data ) { if ( data.events ) { for ( type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } } // Remove cache only if it was not already removed by jQuery.event.remove if ( cache[ id ] ) { delete cache[ id ]; // Support: IE<9 // IE does not allow us to delete expando properties from nodes // IE creates expando attributes along with the property // IE does not have a removeAttribute function on Document nodes if ( !attributes && typeof elem.removeAttribute !== "undefined" ) { elem.removeAttribute( internalKey ); // Webkit & Blink performance suffers when deleting properties // from DOM nodes, so set to undefined instead // https://code.google.com/p/chromium/issues/detail?id=378607 } else { elem[ internalKey ] = undefined; } deletedIds.push( id ); } } } } } } ); jQuery.fn.extend( { // Keep domManip exposed until 3.0 (gh-2225) domManip: domManip, detach: function( selector ) { return remove( this, selector, true ); }, remove: function( selector ) { return remove( this, selector ); }, text: function( value ) { return access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().append( ( this[ 0 ] && this[ 0 ].ownerDocument || document ).createTextNode( value ) ); }, null, value, arguments.length ); }, append: function() { return domManip( this, arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.appendChild( elem ); } } ); }, prepend: function() { return domManip( this, arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.insertBefore( elem, target.firstChild ); } } ); }, before: function() { return domManip( this, arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this ); } } ); }, after: function() { return domManip( this, arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this.nextSibling ); } } ); }, empty: function() { var elem, i = 0; for ( ; ( elem = this[ i ] ) != null; i++ ) { // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); } // Remove any remaining nodes while ( elem.firstChild ) { elem.removeChild( elem.firstChild ); } // If this is a select, ensure that it displays empty (#12336) // Support: IE<9 if ( elem.options && jQuery.nodeName( elem, "select" ) ) { elem.options.length = 0; } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map( function() { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); } ); }, html: function( value ) { return access( this, function( value ) { var elem = this[ 0 ] || {}, i = 0, l = this.length; if ( value === undefined ) { return elem.nodeType === 1 ? elem.innerHTML.replace( rinlinejQuery, "" ) : undefined; } // See if we can take a shortcut and just use innerHTML if ( typeof value === "string" && !rnoInnerhtml.test( value ) && ( support.htmlSerialize || !rnoshimcache.test( value ) ) && ( support.leadingWhitespace || !rleadingWhitespace.test( value ) ) && !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) { value = jQuery.htmlPrefilter( value ); try { for ( ; i < l; i++ ) { // Remove element nodes and prevent memory leaks elem = this[ i ] || {}; if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch ( e ) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function() { var ignored = []; // Make the changes, replacing each non-ignored context element with the new content return domManip( this, arguments, function( elem ) { var parent = this.parentNode; if ( jQuery.inArray( this, ignored ) < 0 ) { jQuery.cleanData( getAll( this ) ); if ( parent ) { parent.replaceChild( elem, this ); } } // Force callback invocation }, ignored ); } } ); jQuery.each( { appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var elems, i = 0, ret = [], insert = jQuery( selector ), last = insert.length - 1; for ( ; i <= last; i++ ) { elems = i === last ? this : this.clone( true ); jQuery( insert[ i ] )[ original ]( elems ); // Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get() push.apply( ret, elems.get() ); } return this.pushStack( ret ); }; } ); var iframe, elemdisplay = { // Support: Firefox // We have to pre-define these values for FF (#10227) HTML: "block", BODY: "block" }; /** * Retrieve the actual display of a element * @param {String} name nodeName of the element * @param {Object} doc Document object */ // Called only from within defaultDisplay function actualDisplay( name, doc ) { var elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ), display = jQuery.css( elem[ 0 ], "display" ); // We don't have any data stored on the element, // so use "detach" method as fast way to get rid of the element elem.detach(); return display; } /** * Try to determine the default display value of an element * @param {String} nodeName */ function defaultDisplay( nodeName ) { var doc = document, display = elemdisplay[ nodeName ]; if ( !display ) { display = actualDisplay( nodeName, doc ); // If the simple way fails, read from inside an iframe if ( display === "none" || !display ) { // Use the already-created iframe if possible iframe = ( iframe || jQuery( ""); // The first load event gets fired after the iframe has been injected // into the DOM, and is used to prepare the actual submission. iframe.bind("load", function() { // The second load event gets fired when the response to the form // submission is received. The implementation detects whether the // actual payload is embedded in a `\n'; tOffice = ''; tGdocs = ''; tVideo = '\n'; tAudio = '\n'; tFlash = '\n'; tPdf = '\n'; tObject = '\n' + '\n' + $h.OBJECT_PARAMS + ' ' + $h.DEFAULT_PREVIEW + '\n\n'; tOther = '
\n' + $h.DEFAULT_PREVIEW + '\n
\n'; tZoomCache = ''; vDefaultDim = {width: "100%", height: "100%", 'min-height': "480px"}; self.defaults = { layoutTemplates: { main1: tMain1, main2: tMain2, preview: tPreview, close: tClose, fileIcon: tFileIcon, caption: tCaption, modalMain: tModalMain, modal: tModal, progress: tProgress, size: tSize, footer: tFooter, indicator: tIndicator, actions: tActions, actionDelete: tActionDelete, actionUpload: tActionUpload, actionDownload: tActionDownload, actionZoom: tActionZoom, actionDrag: tActionDrag, btnDefault: tBtnDefault, btnLink: tBtnLink, btnBrowse: tBtnBrowse, zoomCache: tZoomCache }, previewMarkupTags: { tagBefore1: tTagBef1, tagBefore2: tTagBef2, tagAfter: tTagAft }, previewContentTemplates: { generic: tGeneric, html: tHtml, image: tImage, text: tText, office: tOffice, gdocs: tGdocs, video: tVideo, audio: tAudio, flash: tFlash, object: tObject, pdf: tPdf, other: tOther }, allowedPreviewTypes: ['image', 'html', 'text', 'video', 'audio', 'flash', 'pdf', 'object'], previewTemplates: {}, previewSettings: { image: {width: "auto", height: "auto", 'max-width': "100%", 'max-height': "100%"}, html: {width: "213px", height: "160px"}, text: {width: "213px", height: "160px"}, office: {width: "213px", height: "160px"}, gdocs: {width: "213px", height: "160px"}, video: {width: "213px", height: "160px"}, audio: {width: "100%", height: "30px"}, flash: {width: "213px", height: "160px"}, object: {width: "213px", height: "160px"}, pdf: {width: "213px", height: "160px"}, other: {width: "213px", height: "160px"} }, previewSettingsSmall: { image: {width: "auto", height: "auto", 'max-width': "100%", 'max-height': "100%"}, html: {width: "100%", height: "160px"}, text: {width: "100%", height: "160px"}, office: {width: "100%", height: "160px"}, gdocs: {width: "100%", height: "160px"}, video: {width: "100%", height: "auto"}, audio: {width: "100%", height: "30px"}, flash: {width: "100%", height: "auto"}, object: {width: "100%", height: "auto"}, pdf: {width: "100%", height: "160px"}, other: {width: "100%", height: "160px"} }, previewZoomSettings: { image: {width: "auto", height: "auto", 'max-width': "100%", 'max-height': "100%"}, html: vDefaultDim, text: vDefaultDim, office: {width: "100%", height: "100%", 'max-width': "100%", 'min-height': "480px"}, gdocs: {width: "100%", height: "100%", 'max-width': "100%", 'min-height': "480px"}, video: {width: "auto", height: "100%", 'max-width': "100%"}, audio: {width: "100%", height: "30px"}, flash: {width: "auto", height: "480px"}, object: {width: "auto", height: "100%", 'max-width': "100%", 'min-height': "480px"}, pdf: vDefaultDim, other: {width: "auto", height: "100%", 'min-height': "480px"} }, fileTypeSettings: { image: function (vType, vName) { return ($h.compare(vType, 'image.*') && !$h.compare(vType, /(tiff?|wmf)$/i) || $h.compare(vName, /\.(gif|png|jpe?g)$/i)); }, html: function (vType, vName) { return $h.compare(vType, 'text/html') || $h.compare(vName, /\.(htm|html)$/i); }, office: function (vType, vName) { return $h.compare(vType, /(word|excel|powerpoint|office)$/i) || $h.compare(vName, /\.(docx?|xlsx?|pptx?|pps|potx?)$/i); }, gdocs: function (vType, vName) { return $h.compare(vType, /(word|excel|powerpoint|office|iwork-pages|tiff?)$/i) || $h.compare(vName, /\.(docx?|xlsx?|pptx?|pps|potx?|rtf|ods|odt|pages|ai|dxf|ttf|tiff?|wmf|e?ps)$/i); }, text: function (vType, vName) { return $h.compare(vType, 'text.*') || $h.compare(vName, /\.(xml|javascript)$/i) || $h.compare(vName, /\.(txt|md|csv|nfo|ini|json|php|js|css)$/i); }, video: function (vType, vName) { return $h.compare(vType, 'video.*') && ($h.compare(vType, /(ogg|mp4|mp?g|mov|webm|3gp)$/i) || $h.compare(vName, /\.(og?|mp4|webm|mp?g|mov|3gp)$/i)); }, audio: function (vType, vName) { return $h.compare(vType, 'audio.*') && ($h.compare(vName, /(ogg|mp3|mp?g|wav)$/i) || $h.compare(vName, /\.(og?|mp3|mp?g|wav)$/i)); }, flash: function (vType, vName) { return $h.compare(vType, 'application/x-shockwave-flash', true) || $h.compare(vName, /\.(swf)$/i); }, pdf: function (vType, vName) { return $h.compare(vType, 'application/pdf', true) || $h.compare(vName, /\.(pdf)$/i); }, object: function () { return true; }, other: function () { return true; } }, fileActionSettings: { showRemove: true, showUpload: true, showDownload: true, showZoom: true, showDrag: true, removeIcon: '', removeClass: 'btn btn-sm btn-kv btn-default btn-outline-secondary', removeErrorClass: 'btn btn-sm btn-kv btn-danger', removeTitle: 'Remove file', uploadIcon: '', uploadClass: 'btn btn-sm btn-kv btn-default btn-outline-secondary', uploadTitle: 'Upload file', uploadRetryIcon: '', uploadRetryTitle: 'Retry upload', downloadIcon: '', downloadClass: 'btn btn-sm btn-kv btn-default btn-outline-secondary', downloadTitle: 'Download file', zoomIcon: '', zoomClass: 'btn btn-sm btn-kv btn-default btn-outline-secondary', zoomTitle: 'View Details', dragIcon: '', dragClass: 'text-info', dragTitle: 'Move / Rearrange', dragSettings: {}, indicatorNew: '', indicatorSuccess: '', indicatorError: '', indicatorLoading: '', indicatorNewTitle: 'Not uploaded yet', indicatorSuccessTitle: 'Uploaded', indicatorErrorTitle: 'Upload Error', indicatorLoadingTitle: 'Uploading ...' } }; $.each(self.defaults, function (key, setting) { if (key === 'allowedPreviewTypes') { if (self.allowedPreviewTypes === undefined) { self.allowedPreviewTypes = setting; } return; } self[key] = $.extend(true, {}, setting, self[key]); }); self._initPreviewTemplates(); }, _initPreviewTemplates: function () { var self = this, cfg = self.defaults, tags = self.previewMarkupTags, tagBef, tagAft = tags.tagAfter; $.each(cfg.previewContentTemplates, function (key, value) { if ($h.isEmpty(self.previewTemplates[key])) { tagBef = tags.tagBefore2; if (key === 'generic' || key === 'image' || key === 'html' || key === 'text') { tagBef = tags.tagBefore1; } self.previewTemplates[key] = tagBef + value + tagAft; } }); }, _initPreviewCache: function () { var self = this; self.previewCache = { data: {}, init: function () { var content = self.initialPreview; if (content.length > 0 && !$h.isArray(content)) { content = content.split(self.initialPreviewDelimiter); } self.previewCache.data = { content: content, config: self.initialPreviewConfig, tags: self.initialPreviewThumbTags }; }, count: function () { return !!self.previewCache.data && !!self.previewCache.data.content ? self.previewCache.data.content.length : 0; }, get: function (i, isDisabled) { var ind = 'init_' + i, data = self.previewCache.data, config = data.config[i], content = data.content[i], previewId = self.previewInitId + '-' + ind, out, $tmp, cat, ftr, fname, ftype, frameClass, asData = $h.ifSet('previewAsData', config, self.initialPreviewAsData), parseTemplate = function (cat, dat, fn, ft, id, ftr, ind, fc, t) { fc = ' file-preview-initial ' + $h.SORT_CSS + (fc ? ' ' + fc : ''); return self._generatePreviewTemplate(cat, dat, fn, ft, id, false, null, fc, ftr, ind, t); }; if (!content) { return ''; } isDisabled = isDisabled === undefined ? true : isDisabled; cat = $h.ifSet('type', config, self.initialPreviewFileType || 'generic'); fname = $h.ifSet('filename', config, $h.ifSet('caption', config)); ftype = $h.ifSet('filetype', config, cat); ftr = self.previewCache.footer(i, isDisabled, (config && config.size || null)); frameClass = $h.ifSet('frameClass', config); if (asData) { out = parseTemplate(cat, content, fname, ftype, previewId, ftr, ind, frameClass); } else { out = parseTemplate('generic', content, fname, ftype, previewId, ftr, ind, frameClass, cat) .setTokens({'content': data.content[i]}); } if (data.tags.length && data.tags[i]) { out = $h.replaceTags(out, data.tags[i]); } /** @namespace config.frameAttr */ if (!$h.isEmpty(config) && !$h.isEmpty(config.frameAttr)) { $tmp = $(document.createElement('div')).html(out); $tmp.find('.file-preview-initial').attr(config.frameAttr); out = $tmp.html(); $tmp.remove(); } return out; }, add: function (content, config, tags, append) { var data = self.previewCache.data, index; if (!$h.isArray(content)) { content = content.split(self.initialPreviewDelimiter); } if (append) { index = data.content.push(content) - 1; data.config[index] = config; data.tags[index] = tags; } else { index = content.length - 1; data.content = content; data.config = config; data.tags = tags; } self.previewCache.data = data; return index; }, set: function (content, config, tags, append) { var data = self.previewCache.data, i, chk; if (!content || !content.length) { return; } if (!$h.isArray(content)) { content = content.split(self.initialPreviewDelimiter); } chk = content.filter(function (n) { return n !== null; }); if (!chk.length) { return; } if (data.content === undefined) { data.content = []; } if (data.config === undefined) { data.config = []; } if (data.tags === undefined) { data.tags = []; } if (append) { for (i = 0; i < content.length; i++) { if (content[i]) { data.content.push(content[i]); } } for (i = 0; i < config.length; i++) { if (config[i]) { data.config.push(config[i]); } } for (i = 0; i < tags.length; i++) { if (tags[i]) { data.tags.push(tags[i]); } } } else { data.content = content; data.config = config; data.tags = tags; } self.previewCache.data = data; }, unset: function (index) { var chk = self.previewCache.count(), rev = self.reversePreviewOrder; if (!chk) { return; } if (chk === 1) { self.previewCache.data.content = []; self.previewCache.data.config = []; self.previewCache.data.tags = []; self.initialPreview = []; self.initialPreviewConfig = []; self.initialPreviewThumbTags = []; return; } self.previewCache.data.content = $h.spliceArray(self.previewCache.data.content, index, rev); self.previewCache.data.config = $h.spliceArray(self.previewCache.data.config, index, rev); self.previewCache.data.tags = $h.spliceArray(self.previewCache.data.tags, index, rev); }, out: function () { var html = '', caption, len = self.previewCache.count(), i, content; if (len === 0) { return {content: '', caption: ''}; } for (i = 0; i < len; i++) { content = self.previewCache.get(i); html = self.reversePreviewOrder ? (content + html) : (html + content); } caption = self._getMsgSelected(len); return {content: html, caption: caption}; }, footer: function (i, isDisabled, size) { var data = self.previewCache.data || {}; if ($h.isEmpty(data.content)) { return ''; } if ($h.isEmpty(data.config) || $h.isEmpty(data.config[i])) { data.config[i] = {}; } isDisabled = isDisabled === undefined ? true : isDisabled; var config = data.config[i], caption = $h.ifSet('caption', config), a, width = $h.ifSet('width', config, 'auto'), url = $h.ifSet('url', config, false), key = $h.ifSet('key', config, null), fs = self.fileActionSettings, initPreviewShowDel = self.initialPreviewShowDelete || false, dUrl = config.downloadUrl || self.initialPreviewDownloadUrl || '', dFil = config.filename || config.caption || '', initPreviewShowDwl = !!(dUrl), sDel = $h.ifSet('showRemove', config, $h.ifSet('showRemove', fs, initPreviewShowDel)), sDwl = $h.ifSet('showDownload', config, $h.ifSet('showDownload', fs, initPreviewShowDwl)), sZm = $h.ifSet('showZoom', config, $h.ifSet('showZoom', fs, true)), sDrg = $h.ifSet('showDrag', config, $h.ifSet('showDrag', fs, true)), dis = (url === false) && isDisabled; sDwl = sDwl && config.downloadUrl !== false && !!dUrl; a = self._renderFileActions(false, sDwl, sDel, sZm, sDrg, dis, url, key, true, dUrl, dFil); return self._getLayoutTemplate('footer').setTokens({ 'progress': self._renderThumbProgress(), 'actions': a, 'caption': caption, 'size': self._getSize(size), 'width': width, 'indicator': '' }); } }; self.previewCache.init(); }, _handler: function ($el, event, callback) { var self = this, ns = self.namespace, ev = event.split(' ').join(ns + ' ') + ns; if (!$el || !$el.length) { return; } $el.off(ev).on(ev, callback); }, _log: function (msg) { var self = this, id = self.$element.attr('id'); if (id) { msg = '"' + id + '": ' + msg; } if (typeof window.console.log !== "undefined") { window.console.log(msg); } else { window.alert(msg); } }, _validate: function () { var self = this, status = self.$element.attr('class').includes('keppler-file'); if (!status) { self._log('The input "type" must be set to "file" for initializing the "bootstrap-fileinput" plugin.'); } return status; }, _errorsExist: function () { var self = this, $err, $errList = self.$errorContainer.find('li'); if ($errList.length) { return true; } $err = $(document.createElement('div')).html(self.$errorContainer.html()); $err.find('.kv-error-close').remove(); $err.find('ul').remove(); return !!$.trim($err.text()).length; }, _errorHandler: function (evt, caption) { var self = this, err = evt.target.error, showError = function (msg) { self._showError(msg.replace('{name}', caption)); }; /** @namespace err.NOT_FOUND_ERR */ /** @namespace err.SECURITY_ERR */ /** @namespace err.NOT_READABLE_ERR */ if (err.code === err.NOT_FOUND_ERR) { showError(self.msgFileNotFound); } else if (err.code === err.SECURITY_ERR) { showError(self.msgFileSecured); } else if (err.code === err.NOT_READABLE_ERR) { showError(self.msgFileNotReadable); } else if (err.code === err.ABORT_ERR) { showError(self.msgFilePreviewAborted); } else { showError(self.msgFilePreviewError); } }, _addError: function (msg) { var self = this, $error = self.$errorContainer; if (msg && $error.length) { $error.html(self.errorCloseButton + msg); self._handler($error.find('.kv-error-close'), 'click', function () { setTimeout(function () { if (self.showPreview && !self.getFrames().length) { self.clear(); } $error.fadeOut('slow'); }, 10); }); } }, _setValidationError: function (css) { var self = this; css = (css ? css + ' ' : '') + 'has-error'; self.$container.removeClass(css).addClass('has-error'); $h.addCss(self.$captionContainer, 'is-invalid'); }, _resetErrors: function (fade) { var self = this, $error = self.$errorContainer; self.isError = false; self.$container.removeClass('has-error'); self.$captionContainer.removeClass('is-invalid'); $error.html(''); if (fade) { $error.fadeOut('slow'); } else { $error.hide(); } }, _showFolderError: function (folders) { var self = this, $error = self.$errorContainer, msg; if (!folders) { return; } if (!self.isAjaxUpload) { self._clearFileInput(); } msg = self.msgFoldersNotAllowed.replace('{n}', folders); self._addError(msg); self._setValidationError(); $error.fadeIn(800); self._raise('filefoldererror', [folders, msg]); }, _showUploadError: function (msg, params, event) { var self = this, $error = self.$errorContainer, ev = event || 'fileuploaderror', e = params && params.id ? '
  • ' + msg + '
  • ' : '
  • ' + msg + '
  • '; if ($error.find('ul').length === 0) { self._addError('
      ' + e + '
    '); } else { $error.find('ul').append(e); } $error.fadeIn(800); self._raise(ev, [params, msg]); self._setValidationError('file-input-new'); return true; }, _showError: function (msg, params, event) { var self = this, $error = self.$errorContainer, ev = event || 'fileerror'; params = params || {}; params.reader = self.reader; self._addError(msg); $error.fadeIn(800); self._raise(ev, [params, msg]); if (!self.isAjaxUpload) { self._clearFileInput(); } self._setValidationError('file-input-new'); self.$btnUpload.attr('disabled', true); return true; }, _noFilesError: function (params) { var self = this, label = self.minFileCount > 1 ? self.filePlural : self.fileSingle, msg = self.msgFilesTooLess.replace('{n}', self.minFileCount).replace('{files}', label), $error = self.$errorContainer; self._addError(msg); self.isError = true; self._updateFileDetails(0); $error.fadeIn(800); self._raise('fileerror', [params, msg]); self._clearFileInput(); self._setValidationError(); }, _parseError: function (operation, jqXHR, errorThrown, fileName) { /** @namespace jqXHR.responseJSON */ var self = this, errMsg = $.trim(errorThrown + ''), textPre, text = jqXHR.responseJSON !== undefined && jqXHR.responseJSON.error !== undefined ? jqXHR.responseJSON.error : jqXHR.responseText; if (self.cancelling && self.msgUploadAborted) { errMsg = self.msgUploadAborted; } if (self.showAjaxErrorDetails && text) { text = $.trim(text.replace(/\n\s*\n/g, '\n')); textPre = text.length ? '
    ' + text + '
    ' : ''; errMsg += errMsg ? textPre : text; } if (!errMsg) { errMsg = self.msgAjaxError.replace('{operation}', operation); } self.cancelling = false; return fileName ? '' + fileName + ': ' + errMsg : errMsg; }, _parseFileType: function (type, name) { var self = this, isValid, vType, cat, i, types = self.allowedPreviewTypes || []; if (type === 'application/text-plain') { return 'text'; } for (i = 0; i < types.length; i++) { cat = types[i]; isValid = self.fileTypeSettings[cat]; vType = isValid(type, name) ? cat : ''; if (!$h.isEmpty(vType)) { return vType; } } return 'other'; }, _getPreviewIcon: function (fname) { var self = this, ext, out = null; if (fname && fname.indexOf('.') > -1) { ext = fname.split('.').pop(); if (self.previewFileIconSettings) { out = self.previewFileIconSettings[ext] || self.previewFileIconSettings[ext.toLowerCase()] || null; } if (self.previewFileExtSettings) { $.each(self.previewFileExtSettings, function (key, func) { if (self.previewFileIconSettings[key] && func(ext)) { out = self.previewFileIconSettings[key]; //noinspection UnnecessaryReturnStatementJS return; } }); } } return out; }, _parseFilePreviewIcon: function (content, fname) { var self = this, icn = self._getPreviewIcon(fname) || self.previewFileIcon, out = content; if (out.indexOf('{previewFileIcon}') > -1) { out = out.setTokens({'previewFileIconClass': self.previewFileIconClass, 'previewFileIcon': icn}); } return out; }, _raise: function (event, params) { var self = this, e = $.Event(event); if (params !== undefined) { self.$element.trigger(e, params); } else { self.$element.trigger(e); } if (e.isDefaultPrevented() || e.result === false) { return false; } switch (event) { // ignore these events case 'filebatchuploadcomplete': case 'filebatchuploadsuccess': case 'fileuploaded': case 'fileclear': case 'filecleared': case 'filereset': case 'fileerror': case 'filefoldererror': case 'fileuploaderror': case 'filebatchuploaderror': case 'filedeleteerror': case 'filecustomerror': case 'filesuccessremove': break; // receive data response via `filecustomerror` event` default: if (!self.ajaxAborted) { self.ajaxAborted = e.result; } break; } return true; }, _listenFullScreen: function (isFullScreen) { var self = this, $modal = self.$modal, $btnFull, $btnBord; if (!$modal || !$modal.length) { return; } $btnFull = $modal && $modal.find('.btn-fullscreen'); $btnBord = $modal && $modal.find('.btn-borderless'); if (!$btnFull.length || !$btnBord.length) { return; } $btnFull.removeClass('active').attr('aria-pressed', 'false'); $btnBord.removeClass('active').attr('aria-pressed', 'false'); if (isFullScreen) { $btnFull.addClass('active').attr('aria-pressed', 'true'); } else { $btnBord.addClass('active').attr('aria-pressed', 'true'); } if ($modal.hasClass('file-zoom-fullscreen')) { self._maximizeZoomDialog(); } else { if (isFullScreen) { self._maximizeZoomDialog(); } else { $btnBord.removeClass('active').attr('aria-pressed', 'false'); } } }, _listen: function () { var self = this, $el = self.$element, $form = self.$form, $cont = self.$container, fullScreenEvents; self._handler($el, 'click', function(e) { if ($el.hasClass('file-no-browse')) { if ($el.data('zoneClicked')) { $el.data('zoneClicked', false); } else { e.preventDefault(); } } }); self._handler($el, 'change', $.proxy(self._change, self)); if (self.showBrowse) { self._handler(self.$btnFile, 'click', $.proxy(self._browse, self)); } self._handler($cont.find('.fileinput-remove:not([disabled])'), 'click', $.proxy(self.clear, self)); self._handler($cont.find('.fileinput-cancel'), 'click', $.proxy(self.cancel, self)); self._initDragDrop(); self._handler($form, 'reset', $.proxy(self.clear, self)); if (!self.isAjaxUpload) { self._handler($form, 'submit', $.proxy(self._submitForm, self)); } self._handler(self.$container.find('.fileinput-upload'), 'click', $.proxy(self._uploadClick, self)); self._handler($(window), 'resize', function () { self._listenFullScreen(screen.width === window.innerWidth && screen.height === window.innerHeight); }); fullScreenEvents = 'webkitfullscreenchange mozfullscreenchange fullscreenchange MSFullscreenChange'; self._handler($(document), fullScreenEvents, function () { self._listenFullScreen($h.checkFullScreen()); }); self._autoFitContent(); self._initClickable(); self._refreshPreview(); }, _autoFitContent: function () { var width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth, self = this, config = width < 400 ? (self.previewSettingsSmall || self.defaults.previewSettingsSmall) : (self.previewSettings || self.defaults.previewSettings), sel; $.each(config, function (cat, settings) { sel = '.file-preview-frame .file-preview-' + cat; self.$preview.find(sel + '.kv-preview-data,' + sel + ' .kv-preview-data').css(settings); }); }, _scanDroppedItems: function (item, files, path) { path = path || ""; var self = this, i, dirReader, readDir, errorHandler = function (e) { self._log('Error scanning dropped files!'); self._log(e); }; if (item.isFile) { item.file(function (file) { files.push(file); }, errorHandler); } else { if (item.isDirectory) { dirReader = item.createReader(); readDir = function () { dirReader.readEntries(function (entries) { if (entries && entries.length > 0) { for (i = 0; i < entries.length; i++) { self._scanDroppedItems(entries[i], files, path + item.name + "/"); } // recursively call readDir() again, since browser can only handle first 100 entries. readDir(); } return null; }, errorHandler); }; readDir(); } } }, _initDragDrop: function () { var self = this, $zone = self.$dropZone; if (self.dropZoneEnabled && self.showPreview) { self._handler($zone, 'dragenter dragover', $.proxy(self._zoneDragEnter, self)); self._handler($zone, 'dragleave', $.proxy(self._zoneDragLeave, self)); self._handler($zone, 'drop', $.proxy(self._zoneDrop, self)); self._handler($(document), 'dragenter dragover drop', self._zoneDragDropInit); } }, _zoneDragDropInit: function (e) { e.stopPropagation(); e.preventDefault(); }, _zoneDragEnter: function (e) { var self = this, hasFiles = $.inArray('Files', e.originalEvent.dataTransfer.types) > -1; self._zoneDragDropInit(e); if (self.isDisabled || !hasFiles) { e.originalEvent.dataTransfer.effectAllowed = 'none'; e.originalEvent.dataTransfer.dropEffect = 'none'; return; } $h.addCss(self.$dropZone, 'file-highlighted'); }, _zoneDragLeave: function (e) { var self = this; self._zoneDragDropInit(e); if (self.isDisabled) { return; } self.$dropZone.removeClass('file-highlighted'); }, _zoneDrop: function (e) { /** @namespace e.originalEvent.dataTransfer */ var self = this, i, $el = self.$element, dataTransfer = e.originalEvent.dataTransfer, files = dataTransfer.files, items = dataTransfer.items, folders = $h.getDragDropFolders(items), processFiles = function () { if (!self.isAjaxUpload) { self.changeTriggered = true; $el.get(0).files = files; setTimeout(function () { self.changeTriggered = false; $el.trigger('change' + self.namespace); }, 10); } else { self._change(e, files); } self.$dropZone.removeClass('file-highlighted'); }; e.preventDefault(); if (self.isDisabled || $h.isEmpty(files)) { return; } if (folders > 0) { if (!self.isAjaxUpload) { self._showFolderError(folders); return; } files = []; for (i = 0; i < items.length; i++) { var item = items[i].webkitGetAsEntry(); if (item) { self._scanDroppedItems(item, files); } } setTimeout(function () { processFiles(); }, 500); } else { processFiles(); } }, _uploadClick: function (e) { var self = this, $btn = self.$container.find('.fileinput-upload'), $form, isEnabled = !$btn.hasClass('disabled') && $h.isEmpty($btn.attr('disabled')); if (e && e.isDefaultPrevented()) { return; } if (!self.isAjaxUpload) { if (isEnabled && $btn.attr('type') !== 'submit') { $form = $btn.closest('form'); // downgrade to normal form submit if possible if ($form.length) { $form.trigger('submit'); } e.preventDefault(); } return; } e.preventDefault(); if (isEnabled) { self.upload(); } }, _submitForm: function () { var self = this; return self._isFileSelectionValid() && !self._abort({}); }, _clearPreview: function () { var self = this, $p = self.$preview, $thumbs = self.showUploadedThumbs ? self.getFrames(':not(.file-preview-success)') : self.getFrames(); $thumbs.each(function () { var $thumb = $(this); $thumb.remove(); $h.cleanZoomCache($p.find('#zoom-' + $thumb.attr('id'))); }); if (!self.getFrames().length || !self.showPreview) { self._resetUpload(); } self._validateDefaultPreview(); }, _initSortable: function () { var self = this, $el = self.$preview, settings, selector = '.' + $h.SORT_CSS, rev = self.reversePreviewOrder; if (!window.KvSortable || $el.find(selector).length === 0) { return; } //noinspection JSUnusedGlobalSymbols settings = { handle: '.drag-handle-init', dataIdAttr: 'data-preview-id', scroll: false, draggable: selector, onSort: function (e) { var oldIndex = e.oldIndex, newIndex = e.newIndex, i = 0; self.initialPreview = $h.moveArray(self.initialPreview, oldIndex, newIndex, rev); self.initialPreviewConfig = $h.moveArray(self.initialPreviewConfig, oldIndex, newIndex, rev); self.previewCache.init(); self.getFrames('.file-preview-initial').each(function () { $(this).attr('data-fileindex', 'init_' + i); i++; }); self._raise('filesorted', { previewId: $(e.item).attr('id'), 'oldIndex': oldIndex, 'newIndex': newIndex, stack: self.initialPreviewConfig }); } }; if ($el.data('kvsortable')) { $el.kvsortable('destroy'); } $.extend(true, settings, self.fileActionSettings.dragSettings); $el.kvsortable(settings); }, _setPreviewContent: function (content) { var self = this; self.$preview.html(content); self._autoFitContent(); }, _initPreview: function (isInit) { var self = this, cap = self.initialCaption || '', out; if (!self.previewCache.count()) { self._clearPreview(); if (isInit) { self._setCaption(cap); } else { self._initCaption(); } return; } out = self.previewCache.out(); cap = isInit && self.initialCaption ? self.initialCaption : out.caption; self._setPreviewContent(out.content); self._setInitThumbAttr(); self._setCaption(cap); self._initSortable(); if (!$h.isEmpty(out.content)) { self.$container.removeClass('file-input-new'); } }, _getZoomButton: function (type) { var self = this, label = self.previewZoomButtonIcons[type], css = self.previewZoomButtonClasses[type], title = ' title="' + (self.previewZoomButtonTitles[type] || '') + '" ', params = title + (type === 'close' ? ' data-dismiss="modal" aria-hidden="true"' : ''); if (type === 'fullscreen' || type === 'borderless' || type === 'toggleheader') { params += ' data-toggle="button" aria-pressed="false" autocomplete="off"'; } return ''; }, _getModalContent: function () { var self = this; return self._getLayoutTemplate('modal').setTokens({ 'rtl': self.rtl ? ' kv-rtl' : '', 'zoomFrameClass': self.frameClass, 'heading': self.msgZoomModalHeading, 'prev': self._getZoomButton('prev'), 'next': self._getZoomButton('next'), 'toggleheader': self._getZoomButton('toggleheader'), 'fullscreen': self._getZoomButton('fullscreen'), 'borderless': self._getZoomButton('borderless'), 'close': self._getZoomButton('close') }); }, _listenModalEvent: function (event) { var self = this, $modal = self.$modal, getParams = function (e) { return { sourceEvent: e, previewId: $modal.data('previewId'), modal: $modal }; }; $modal.on(event + '.bs.modal', function (e) { var $btnFull = $modal.find('.btn-fullscreen'), $btnBord = $modal.find('.btn-borderless'); self._raise('filezoom' + event, getParams(e)); if (event === 'shown') { $btnBord.removeClass('active').attr('aria-pressed', 'false'); $btnFull.removeClass('active').attr('aria-pressed', 'false'); if ($modal.hasClass('file-zoom-fullscreen')) { self._maximizeZoomDialog(); if ($h.checkFullScreen()) { $btnFull.addClass('active').attr('aria-pressed', 'true'); } else { $btnBord.addClass('active').attr('aria-pressed', 'true'); } } } }); }, _initZoom: function () { var self = this, $dialog, modalMain = self._getLayoutTemplate('modalMain'), modalId = '#' + $h.MODAL_ID; if (!self.showPreview) { return; } self.$modal = $(modalId); if (!self.$modal || !self.$modal.length) { $dialog = $(document.createElement('div')).html(modalMain).insertAfter(self.$container); self.$modal = $(modalId).insertBefore($dialog); $dialog.remove(); } $h.initModal(self.$modal); self.$modal.html(self._getModalContent()); $.each($h.MODAL_EVENTS, function (key, event) { self._listenModalEvent(event); }); }, _initZoomButtons: function () { var self = this, previewId = self.$modal.data('previewId') || '', $first, $last, thumbs = self.getFrames().toArray(), len = thumbs.length, $prev = self.$modal.find('.btn-prev'), $next = self.$modal.find('.btn-next'); if (thumbs.length < 2) { $prev.hide(); $next.hide(); return; } else { $prev.show(); $next.show(); } if (!len) { return; } $first = $(thumbs[0]); $last = $(thumbs[len - 1]); $prev.removeAttr('disabled'); $next.removeAttr('disabled'); if ($first.length && $first.attr('id') === previewId) { $prev.attr('disabled', true); } if ($last.length && $last.attr('id') === previewId) { $next.attr('disabled', true); } }, _maximizeZoomDialog: function () { var self = this, $modal = self.$modal, $head = $modal.find('.modal-header:visible'), $foot = $modal.find('.modal-footer:visible'), $body = $modal.find('.modal-body'), h = $(window).height(), diff = 0; $modal.addClass('file-zoom-fullscreen'); if ($head && $head.length) { h -= $head.outerHeight(true); } if ($foot && $foot.length) { h -= $foot.outerHeight(true); } if ($body && $body.length) { diff = $body.outerHeight(true) - $body.height(); h -= diff; } $modal.find('.kv-zoom-body').height(h); }, _resizeZoomDialog: function (fullScreen) { var self = this, $modal = self.$modal, $btnFull = $modal.find('.btn-fullscreen'), $btnBord = $modal.find('.btn-borderless'); if ($modal.hasClass('file-zoom-fullscreen')) { $h.toggleFullScreen(false); if (!fullScreen) { if (!$btnFull.hasClass('active')) { $modal.removeClass('file-zoom-fullscreen'); self.$modal.find('.kv-zoom-body').css('height', self.zoomModalHeight); } else { $btnFull.removeClass('active').attr('aria-pressed', 'false'); } } else { if (!$btnFull.hasClass('active')) { $modal.removeClass('file-zoom-fullscreen'); self._resizeZoomDialog(true); if ($btnBord.hasClass('active')) { $btnBord.removeClass('active').attr('aria-pressed', 'false'); } } } } else { if (!fullScreen) { self._maximizeZoomDialog(); return; } $h.toggleFullScreen(true); } $modal.focus(); }, _setZoomContent: function ($frame, animate) { var self = this, $content, tmplt, body, title, $body, $dataEl, config, pid = $frame.attr('id'), $modal = self.$modal, $prev = $modal.find('.btn-prev'), $next = $modal.find('.btn-next'), $tmp, $btnFull = $modal.find('.btn-fullscreen'), $btnBord = $modal.find('.btn-borderless'), cap, size, $btnTogh = $modal.find('.btn-toggleheader'), $zoomPreview = self.$preview.find('#zoom-' + pid); tmplt = $zoomPreview.attr('data-template') || 'generic'; $content = $zoomPreview.find('.kv-file-content'); body = $content.length ? $content.html() : ''; cap = $frame.data('caption') || ''; size = $frame.data('size') || ''; title = cap + ' ' + size; $modal.find('.kv-zoom-title').attr('title', $('
    ').html(title).text()).html(title); $body = $modal.find('.kv-zoom-body'); $modal.removeClass('kv-single-content'); if (animate) { $tmp = $body.addClass('file-thumb-loading').clone().insertAfter($body); $body.html(body).hide(); $tmp.fadeOut('fast', function () { $body.fadeIn('fast', function () { $body.removeClass('file-thumb-loading'); }); $tmp.remove(); }); } else { $body.html(body); } config = self.previewZoomSettings[tmplt]; if (config) { $dataEl = $body.find('.kv-preview-data'); $h.addCss($dataEl, 'file-zoom-detail'); $.each(config, function (key, value) { $dataEl.css(key, value); if (($dataEl.attr('width') && key === 'width') || ($dataEl.attr('height') && key === 'height')) { $dataEl.removeAttr(key); } }); } $modal.data('previewId', pid); var $img = $body.find('img'); if ($img.length) { $h.adjustOrientedImage($img, true); } self._handler($prev, 'click', function () { self._zoomSlideShow('prev', pid); }); self._handler($next, 'click', function () { self._zoomSlideShow('next', pid); }); self._handler($btnFull, 'click', function () { self._resizeZoomDialog(true); }); self._handler($btnBord, 'click', function () { self._resizeZoomDialog(false); }); self._handler($btnTogh, 'click', function () { var $header = $modal.find('.modal-header'), $floatBar = $modal.find('.modal-body .floating-buttons'), ht, $actions = $header.find('.kv-zoom-actions'), resize = function (height) { var $body = self.$modal.find('.kv-zoom-body'), h = self.zoomModalHeight; if ($modal.hasClass('file-zoom-fullscreen')) { h = $body.outerHeight(true); if (!height) { h = h - $header.outerHeight(true); } } $body.css('height', height ? h + height : h); }; if ($header.is(':visible')) { ht = $header.outerHeight(true); $header.slideUp('slow', function () { $actions.find('.btn').appendTo($floatBar); resize(ht); }); } else { $floatBar.find('.btn').appendTo($actions); $header.slideDown('slow', function () { resize(); }); } $modal.focus(); }); self._handler($modal, 'keydown', function (e) { var key = e.which || e.keyCode; if (key === 37 && !$prev.attr('disabled')) { self._zoomSlideShow('prev', pid); } if (key === 39 && !$next.attr('disabled')) { self._zoomSlideShow('next', pid); } }); }, _zoomPreview: function ($btn) { var self = this, $frame, $modal = self.$modal; if (!$btn.length) { throw 'Cannot zoom to detailed preview!'; } $h.initModal($modal); $modal.html(self._getModalContent()); $frame = $btn.closest($h.FRAMES); self._setZoomContent($frame); $modal.modal('show'); self._initZoomButtons(); }, _zoomSlideShow: function (dir, previewId) { var self = this, $btn = self.$modal.find('.kv-zoom-actions .btn-' + dir), $targFrame, i, thumbs = self.getFrames().toArray(), len = thumbs.length, out; if ($btn.attr('disabled')) { return; } for (i = 0; i < len; i++) { if ($(thumbs[i]).attr('id') === previewId) { out = dir === 'prev' ? i - 1 : i + 1; break; } } if (out < 0 || out >= len || !thumbs[out]) { return; } $targFrame = $(thumbs[out]); if ($targFrame.length) { self._setZoomContent($targFrame, true); } self._initZoomButtons(); self._raise('filezoom' + dir, {'previewId': previewId, modal: self.$modal}); }, _initZoomButton: function () { var self = this; self.$preview.find('.kv-file-zoom').each(function () { var $el = $(this); self._handler($el, 'click', function () { self._zoomPreview($el); }); }); }, _inputFileCount: function() { return this.$element.get(0).files.length; }, _refreshPreview: function() { var self = this, files; if (!self._inputFileCount() || !self.showPreview || !self.isPreviewable) { return; } if (self.isAjaxUpload) { files = self.getFileStack(); self.filestack = []; if (files.length) { self._clearFileInput(); } else { files = self.$element.get(0).files; } } else { files = self.$element.get(0).files; } if (files && files.length) { self.readFiles(files); self._setFileDropZoneTitle(); } }, _clearObjects: function ($el) { $el.find('video audio').each(function () { this.pause(); $(this).remove(); }); $el.find('img object div').each(function () { $(this).remove(); }); }, _clearFileInput: function () { var self = this, $el = self.$element, $srcFrm, $tmpFrm, $tmpEl; if (!self._inputFileCount()) { return; } $srcFrm = $el.closest('form'); $tmpFrm = $(document.createElement('form')); $tmpEl = $(document.createElement('div')); $el.before($tmpEl); if ($srcFrm.length) { $srcFrm.after($tmpFrm); } else { $tmpEl.after($tmpFrm); } $tmpFrm.append($el).trigger('reset'); $tmpEl.before($el).remove(); $tmpFrm.remove(); }, _resetUpload: function () { var self = this; self.uploadCache = {content: [], config: [], tags: [], append: true}; self.uploadCount = 0; self.uploadStatus = {}; self.uploadLog = []; self.uploadAsyncCount = 0; self.loadedImages = []; self.totalImagesCount = 0; self.$btnUpload.removeAttr('disabled'); self._setProgress(0); self.$progress.hide(); self._resetErrors(false); self.ajaxAborted = false; self.ajaxRequests = []; self._resetCanvas(); self.cacheInitialPreview = {}; if (self.overwriteInitial) { self.initialPreview = []; self.initialPreviewConfig = []; self.initialPreviewThumbTags = []; self.previewCache.data = { content: [], config: [], tags: [] }; } }, _resetCanvas: function () { var self = this; if (self.canvas && self.imageCanvasContext) { self.imageCanvasContext.clearRect(0, 0, self.canvas.width, self.canvas.height); } }, _hasInitialPreview: function () { var self = this; return !self.overwriteInitial && self.previewCache.count(); }, _resetPreview: function () { var self = this, out, cap; if (self.previewCache.count()) { out = self.previewCache.out(); self._setPreviewContent(out.content); self._setInitThumbAttr(); cap = self.initialCaption ? self.initialCaption : out.caption; self._setCaption(cap); } else { self._clearPreview(); self._initCaption(); } if (self.showPreview) { self._initZoom(); self._initSortable(); } }, _clearDefaultPreview: function () { var self = this; self.$preview.find('.file-default-preview').remove(); }, _validateDefaultPreview: function () { var self = this; if (!self.showPreview || $h.isEmpty(self.defaultPreviewContent)) { return; } self._setPreviewContent('
    ' + self.defaultPreviewContent + '
    '); self.$container.removeClass('file-input-new'); self._initClickable(); }, _resetPreviewThumbs: function (isAjax) { var self = this, out; if (isAjax) { self._clearPreview(); self.clearStack(); return; } if (self._hasInitialPreview()) { out = self.previewCache.out(); self._setPreviewContent(out.content); self._setInitThumbAttr(); self._setCaption(out.caption); self._initPreviewActions(); } else { self._clearPreview(); } }, _getLayoutTemplate: function (t) { var self = this, template = self.layoutTemplates[t]; if ($h.isEmpty(self.customLayoutTags)) { return template; } return $h.replaceTags(template, self.customLayoutTags); }, _getPreviewTemplate: function (t) { var self = this, template = self.previewTemplates[t]; if ($h.isEmpty(self.customPreviewTags)) { return template; } return $h.replaceTags(template, self.customPreviewTags); }, _getOutData: function (jqXHR, responseData, filesData) { var self = this; jqXHR = jqXHR || {}; responseData = responseData || {}; filesData = filesData || self.filestack.slice(0) || {}; return { form: self.formdata, files: filesData, filenames: self.filenames, filescount: self.getFilesCount(), extra: self._getExtraData(), response: responseData, reader: self.reader, jqXHR: jqXHR }; }, _getMsgSelected: function (n) { var self = this, strFiles = n === 1 ? self.fileSingle : self.filePlural; return n > 0 ? self.msgSelected.replace('{n}', n).replace('{files}', strFiles) : self.msgNoFilesSelected; }, _getFrame: function (id) { var self = this, $frame = $('#' + id); if (!$frame.length) { self._log('Invalid thumb frame with id: "' + id + '".'); return null; } return $frame; }, _getThumbs: function (css) { css = css || ''; return this.getFrames(':not(.file-preview-initial)' + css); }, _getExtraData: function (previewId, index) { var self = this, data = self.uploadExtraData; if (typeof self.uploadExtraData === "function") { data = self.uploadExtraData(previewId, index); } return data; }, _initXhr: function (xhrobj, previewId, fileCount) { var self = this; if (xhrobj.upload) { xhrobj.upload.addEventListener('progress', function (event) { var pct = 0, total = event.total, position = event.loaded || event.position; /** @namespace event.lengthComputable */ if (event.lengthComputable) { pct = Math.floor(position / total * 100); } if (previewId) { self._setAsyncUploadStatus(previewId, pct, fileCount); } else { self._setProgress(pct); } }, false); } return xhrobj; }, _initAjaxSettings: function () { var self = this; self._ajaxSettings = $.extend(true, {}, self.ajaxSettings); self._ajaxDeleteSettings = $.extend(true, {}, self.ajaxDeleteSettings); }, _mergeAjaxCallback: function (funcName, srcFunc, type) { var self = this, settings = self._ajaxSettings, flag = self.mergeAjaxCallbacks, targFunc; if (type === 'delete') { settings = self._ajaxDeleteSettings; flag = self.mergeAjaxDeleteCallbacks; } targFunc = settings[funcName]; if (flag && typeof targFunc === "function") { if (flag === 'before') { settings[funcName] = function () { targFunc.apply(this, arguments); srcFunc.apply(this, arguments); }; } else { settings[funcName] = function () { srcFunc.apply(this, arguments); targFunc.apply(this, arguments); }; } } else { settings[funcName] = srcFunc; } }, _ajaxSubmit: function (fnBefore, fnSuccess, fnComplete, fnError, previewId, index) { var self = this, settings; if (!self._raise('filepreajax', [previewId, index])) { return; } self._uploadExtra(previewId, index); self._initAjaxSettings(); self._mergeAjaxCallback('beforeSend', fnBefore); self._mergeAjaxCallback('success', fnSuccess); self._mergeAjaxCallback('complete', fnComplete); self._mergeAjaxCallback('error', fnError); settings = $.extend(true, {}, { xhr: function () { var xhrobj = $.ajaxSettings.xhr(); return self._initXhr(xhrobj, previewId, self.getFileStack().length); }, url: index && self.uploadUrlThumb ? self.uploadUrlThumb : self.uploadUrl, type: 'POST', dataType: 'json', data: self.formdata, cache: false, processData: false, contentType: false }, self._ajaxSettings); self.ajaxRequests.push($.ajax(settings)); }, _mergeArray: function (prop, content) { var self = this, arr1 = $h.cleanArray(self[prop]), arr2 = $h.cleanArray(content); self[prop] = arr1.concat(arr2); }, _initUploadSuccess: function (out, $thumb, allFiles) { var self = this, append, data, index, $div, $newCache, content, config, tags, i; if (!self.showPreview || typeof out !== 'object' || $.isEmptyObject(out)) { return; } if (out.initialPreview !== undefined && out.initialPreview.length > 0) { self.hasInitData = true; content = out.initialPreview || []; config = out.initialPreviewConfig || []; tags = out.initialPreviewThumbTags || []; append = out.append === undefined || out.append; if (content.length > 0 && !$h.isArray(content)) { content = content.split(self.initialPreviewDelimiter); } self._mergeArray('initialPreview', content); self._mergeArray('initialPreviewConfig', config); self._mergeArray('initialPreviewThumbTags', tags); if ($thumb !== undefined) { if (!allFiles) { index = self.previewCache.add(content, config[0], tags[0], append); data = self.previewCache.get(index, false); $div = $(document.createElement('div')).html(data).hide().insertAfter($thumb); $newCache = $div.find('.kv-zoom-cache'); if ($newCache && $newCache.length) { $newCache.insertAfter($thumb); } $thumb.fadeOut('slow', function () { var $newThumb = $div.find('.file-preview-frame'); if ($newThumb && $newThumb.length) { $newThumb.insertBefore($thumb).fadeIn('slow').css('display:inline-block'); } self._initPreviewActions(); self._clearFileInput(); $h.cleanZoomCache(self.$preview.find('#zoom-' + $thumb.attr('id'))); $thumb.remove(); $div.remove(); self._initSortable(); }); } else { i = $thumb.attr('data-fileindex'); self.uploadCache.content[i] = content[0]; self.uploadCache.config[i] = config[0] || []; self.uploadCache.tags[i] = tags[0] || []; self.uploadCache.append = append; } } else { self.previewCache.set(content, config, tags, append); self._initPreview(); self._initPreviewActions(); } } }, _initSuccessThumbs: function () { var self = this; if (!self.showPreview) { return; } self._getThumbs($h.FRAMES + '.file-preview-success').each(function () { var $thumb = $(this), $preview = self.$preview, $remove = $thumb.find('.kv-file-remove'); $remove.removeAttr('disabled'); self._handler($remove, 'click', function () { var id = $thumb.attr('id'), out = self._raise('filesuccessremove', [id, $thumb.attr('data-fileindex')]); $h.cleanMemory($thumb); if (out === false) { return; } $thumb.fadeOut('slow', function () { $h.cleanZoomCache($preview.find('#zoom-' + id)); $thumb.remove(); if (!self.getFrames().length) { self.reset(); } }); }); }); }, _checkAsyncComplete: function () { var self = this, previewId, i; for (i = 0; i < self.filestack.length; i++) { if (self.filestack[i]) { previewId = self.previewInitId + "-" + i; if ($.inArray(previewId, self.uploadLog) === -1) { return false; } } } return (self.uploadAsyncCount === self.uploadLog.length); }, _uploadExtra: function (previewId, index) { var self = this, data = self._getExtraData(previewId, index); if (data.length === 0) { return; } $.each(data, function (key, value) { self.formdata.append(key, value); }); }, _uploadSingle: function (i, isBatch) { var self = this, total = self.getFileStack().length, formdata = new FormData(), outData, previewId = self.previewInitId + "-" + i, $thumb, chkComplete, $btnUpload, $btnDelete, hasPostData = self.filestack.length > 0 || !$.isEmptyObject(self.uploadExtraData), uploadFailed, $prog = $('#' + previewId).find('.file-thumb-progress'), fnBefore, fnSuccess, fnComplete, fnError, updateUploadLog, params = {id: previewId, index: i}; self.formdata = formdata; if (self.showPreview) { $thumb = $('#' + previewId + ':not(.file-preview-initial)'); $btnUpload = $thumb.find('.kv-file-upload'); $btnDelete = $thumb.find('.kv-file-remove'); $prog.show(); } if (total === 0 || !hasPostData || ($btnUpload && $btnUpload.hasClass('disabled')) || self._abort(params)) { return; } updateUploadLog = function (i, previewId) { if (!uploadFailed) { self.updateStack(i, undefined); } self.uploadLog.push(previewId); if (self._checkAsyncComplete()) { self.fileBatchCompleted = true; } }; chkComplete = function () { var u = self.uploadCache, $initThumbs, i, j, len = 0, data = self.cacheInitialPreview; if (!self.fileBatchCompleted) { return; } if (data && data.content) { len = data.content.length; } setTimeout(function () { var triggerReset = self.getFileStack(true).length === 0; if (self.showPreview) { self.previewCache.set(u.content, u.config, u.tags, u.append); if (len) { for (i = 0; i < u.content.length; i++) { j = i + len; data.content[j] = u.content[i]; //noinspection JSUnresolvedVariable if (data.config.length) { data.config[j] = u.config[i]; } if (data.tags.length) { data.tags[j] = u.tags[i]; } } self.initialPreview = $h.cleanArray(data.content); self.initialPreviewConfig = $h.cleanArray(data.config); self.initialPreviewThumbTags = $h.cleanArray(data.tags); } else { self.initialPreview = u.content; self.initialPreviewConfig = u.config; self.initialPreviewThumbTags = u.tags; } self.cacheInitialPreview = {}; if (self.hasInitData) { self._initPreview(); self._initPreviewActions(); } } self.unlock(triggerReset); if (triggerReset) { self._clearFileInput(); } $initThumbs = self.$preview.find('.file-preview-initial'); if (self.uploadAsync && $initThumbs.length) { $h.addCss($initThumbs, $h.SORT_CSS); self._initSortable(); } self._raise('filebatchuploadcomplete', [self.filestack, self._getExtraData()]); self.uploadCount = 0; self.uploadStatus = {}; self.uploadLog = []; self._setProgress(101); self.ajaxAborted = false; }, 100); }; fnBefore = function (jqXHR) { outData = self._getOutData(jqXHR); self.fileBatchCompleted = false; if (!isBatch) { self.ajaxAborted = false; } if (self.showPreview) { if (!$thumb.hasClass('file-preview-success')) { self._setThumbStatus($thumb, 'Loading'); $h.addCss($thumb, 'file-uploading'); } $btnUpload.attr('disabled', true); $btnDelete.attr('disabled', true); } if (!isBatch) { self.lock(); } self._raise('filepreupload', [outData, previewId, i]); $.extend(true, params, outData); if (self._abort(params)) { jqXHR.abort(); if (!isBatch) { self._setThumbStatus($thumb, 'New'); $thumb.removeClass('file-uploading'); $btnUpload.removeAttr('disabled'); $btnDelete.removeAttr('disabled'); self.unlock(); } self._setProgressCancelled(); } }; fnSuccess = function (data, textStatus, jqXHR) { var pid = self.showPreview && $thumb.attr('id') ? $thumb.attr('id') : previewId; outData = self._getOutData(jqXHR, data); $.extend(true, params, outData); setTimeout(function () { if ($h.isEmpty(data) || $h.isEmpty(data.error)) { if (self.showPreview) { self._setThumbStatus($thumb, 'Success'); $btnUpload.hide(); self._initUploadSuccess(data, $thumb, isBatch); self._setProgress(101, $prog); } self._raise('fileuploaded', [outData, pid, i]); if (!isBatch) { self.updateStack(i, undefined); } else { updateUploadLog(i, pid); } } else { uploadFailed = true; self._showUploadError(data.error, params); self._setPreviewError($thumb, i, self.filestack[i], self.retryErrorUploads); if (!self.retryErrorUploads) { $btnUpload.hide(); } if (isBatch) { updateUploadLog(i, pid); } self._setProgress(101, $('#' + pid).find('.file-thumb-progress'), self.msgUploadError); } }, 100); }; fnComplete = function () { setTimeout(function () { if (self.showPreview) { $btnUpload.removeAttr('disabled'); $btnDelete.removeAttr('disabled'); $thumb.removeClass('file-uploading'); } if (!isBatch) { self.unlock(false); self._clearFileInput(); } else { chkComplete(); } self._initSuccessThumbs(); }, 100); }; fnError = function (jqXHR, textStatus, errorThrown) { var op = self.ajaxOperations.uploadThumb, errMsg = self._parseError(op, jqXHR, errorThrown, (isBatch && self.filestack[i].name ? self.filestack[i].name : null)); uploadFailed = true; setTimeout(function () { if (isBatch) { updateUploadLog(i, previewId); } self.uploadStatus[previewId] = 100; self._setPreviewError($thumb, i, self.filestack[i], self.retryErrorUploads); if (!self.retryErrorUploads) { $btnUpload.hide(); } $.extend(true, params, self._getOutData(jqXHR)); self._setProgress(101, $prog, self.msgAjaxProgressError.replace('{operation}', op)); self._setProgress(101, $('#' + previewId).find('.file-thumb-progress'), self.msgUploadError); self._showUploadError(errMsg, params); }, 100); }; formdata.append(self.uploadFileAttr, self.filestack[i], self.filenames[i]); formdata.append('file_id', i); self._ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError, previewId, i); }, _uploadBatch: function () { var self = this, files = self.filestack, total = files.length, params = {}, fnBefore, fnSuccess, fnError, fnComplete, hasPostData = self.filestack.length > 0 || !$.isEmptyObject(self.uploadExtraData), setAllUploaded; self.formdata = new FormData(); if (total === 0 || !hasPostData || self._abort(params)) { return; } setAllUploaded = function () { $.each(files, function (key) { self.updateStack(key, undefined); }); self._clearFileInput(); }; fnBefore = function (jqXHR) { self.lock(); var outData = self._getOutData(jqXHR); self.ajaxAborted = false; if (self.showPreview) { self._getThumbs().each(function () { var $thumb = $(this), $btnUpload = $thumb.find('.kv-file-upload'), $btnDelete = $thumb.find('.kv-file-remove'); if (!$thumb.hasClass('file-preview-success')) { self._setThumbStatus($thumb, 'Loading'); $h.addCss($thumb, 'file-uploading'); } $btnUpload.attr('disabled', true); $btnDelete.attr('disabled', true); }); } self._raise('filebatchpreupload', [outData]); if (self._abort(outData)) { jqXHR.abort(); self._getThumbs().each(function () { var $thumb = $(this), $btnUpload = $thumb.find('.kv-file-upload'), $btnDelete = $thumb.find('.kv-file-remove'); if ($thumb.hasClass('file-preview-loading')) { self._setThumbStatus($thumb, 'New'); $thumb.removeClass('file-uploading'); } $btnUpload.removeAttr('disabled'); $btnDelete.removeAttr('disabled'); }); self._setProgressCancelled(); } }; fnSuccess = function (data, textStatus, jqXHR) { /** @namespace data.errorkeys */ var outData = self._getOutData(jqXHR, data), key = 0, $thumbs = self._getThumbs(':not(.file-preview-success)'), keys = $h.isEmpty(data) || $h.isEmpty(data.errorkeys) ? [] : data.errorkeys; if ($h.isEmpty(data) || $h.isEmpty(data.error)) { self._raise('filebatchuploadsuccess', [outData]); setAllUploaded(); if (self.showPreview) { $thumbs.each(function () { var $thumb = $(this); self._setThumbStatus($thumb, 'Success'); $thumb.removeClass('file-uploading'); $thumb.find('.kv-file-upload').hide().removeAttr('disabled'); }); self._initUploadSuccess(data); } else { self.reset(); } self._setProgress(101); } else { if (self.showPreview) { $thumbs.each(function () { var $thumb = $(this), i = $thumb.attr('data-fileindex'); $thumb.removeClass('file-uploading'); $thumb.find('.kv-file-upload').removeAttr('disabled'); $thumb.find('.kv-file-remove').removeAttr('disabled'); if (keys.length === 0 || $.inArray(key, keys) !== -1) { self._setPreviewError($thumb, i, self.filestack[i], self.retryErrorUploads); if (!self.retryErrorUploads) { $thumb.find('.kv-file-upload').hide(); self.updateStack(i, undefined); } } else { $thumb.find('.kv-file-upload').hide(); self._setThumbStatus($thumb, 'Success'); self.updateStack(i, undefined); } if (!$thumb.hasClass('file-preview-error') || self.retryErrorUploads) { key++; } }); self._initUploadSuccess(data); } self._showUploadError(data.error, outData, 'filebatchuploaderror'); self._setProgress(101, self.$progress, self.msgUploadError); } }; fnComplete = function () { self.unlock(); self._initSuccessThumbs(); self._clearFileInput(); self._raise('filebatchuploadcomplete', [self.filestack, self._getExtraData()]); }; fnError = function (jqXHR, textStatus, errorThrown) { var outData = self._getOutData(jqXHR), op = self.ajaxOperations.uploadBatch, errMsg = self._parseError(op, jqXHR, errorThrown); self._showUploadError(errMsg, outData, 'filebatchuploaderror'); self.uploadFileCount = total - 1; if (!self.showPreview) { return; } self._getThumbs().each(function () { var $thumb = $(this), key = $thumb.attr('data-fileindex'); $thumb.removeClass('file-uploading'); if (self.filestack[key] !== undefined) { self._setPreviewError($thumb); } }); self._getThumbs().removeClass('file-uploading'); self._getThumbs(' .kv-file-upload').removeAttr('disabled'); self._getThumbs(' .kv-file-delete').removeAttr('disabled'); self._setProgress(101, self.$progress, self.msgAjaxProgressError.replace('{operation}', op)); }; $.each(files, function (key, data) { if (!$h.isEmpty(files[key])) { self.formdata.append(self.uploadFileAttr, data, self.filenames[key]); } }); self._ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError); }, _uploadExtraOnly: function () { var self = this, params = {}, fnBefore, fnSuccess, fnComplete, fnError; self.formdata = new FormData(); if (self._abort(params)) { return; } fnBefore = function (jqXHR) { self.lock(); var outData = self._getOutData(jqXHR); self._raise('filebatchpreupload', [outData]); self._setProgress(50); params.data = outData; params.xhr = jqXHR; if (self._abort(params)) { jqXHR.abort(); self._setProgressCancelled(); } }; fnSuccess = function (data, textStatus, jqXHR) { var outData = self._getOutData(jqXHR, data); if ($h.isEmpty(data) || $h.isEmpty(data.error)) { self._raise('filebatchuploadsuccess', [outData]); self._clearFileInput(); self._initUploadSuccess(data); self._setProgress(101); } else { self._showUploadError(data.error, outData, 'filebatchuploaderror'); } }; fnComplete = function () { self.unlock(); self._clearFileInput(); self._raise('filebatchuploadcomplete', [self.filestack, self._getExtraData()]); }; fnError = function (jqXHR, textStatus, errorThrown) { var outData = self._getOutData(jqXHR), op = self.ajaxOperations.uploadExtra, errMsg = self._parseError(op, jqXHR, errorThrown); params.data = outData; self._showUploadError(errMsg, outData, 'filebatchuploaderror'); self._setProgress(101, self.$progress, self.msgAjaxProgressError.replace('{operation}', op)); }; self._ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError); }, _deleteFileIndex: function ($frame) { var self = this, ind = $frame.attr('data-fileindex'), rev = self.reversePreviewOrder; if (ind.substring(0, 5) === 'init_') { ind = parseInt(ind.replace('init_', '')); self.initialPreview = $h.spliceArray(self.initialPreview, ind, rev); self.initialPreviewConfig = $h.spliceArray(self.initialPreviewConfig, ind, rev); self.initialPreviewThumbTags = $h.spliceArray(self.initialPreviewThumbTags, ind, rev); self.getFrames().each(function () { var $nFrame = $(this), nInd = $nFrame.attr('data-fileindex'); if (nInd.substring(0, 5) === 'init_') { nInd = parseInt(nInd.replace('init_', '')); if (nInd > ind) { nInd--; $nFrame.attr('data-fileindex', 'init_' + nInd); } } }); if (self.uploadAsync) { self.cacheInitialPreview = self.getPreview(); } } }, _initFileActions: function () { var self = this, $preview = self.$preview; if (!self.showPreview) { return; } self._initZoomButton(); self.getFrames(' .kv-file-remove').each(function () { var $el = $(this), $frame = $el.closest($h.FRAMES), hasError, id = $frame.attr('id'), ind = $frame.attr('data-fileindex'), n, cap, status; self._handler($el, 'click', function () { status = self._raise('filepreremove', [id, ind]); if (status === false || !self._validateMinCount()) { return false; } hasError = $frame.hasClass('file-preview-error'); $h.cleanMemory($frame); $frame.fadeOut('slow', function () { $h.cleanZoomCache($preview.find('#zoom-' + id)); self.updateStack(ind, undefined); self._clearObjects($frame); $frame.remove(); if (id && hasError) { self.$errorContainer.find('li[data-file-id="' + id + '"]').fadeOut('fast', function () { $(this).remove(); if (!self._errorsExist()) { self._resetErrors(); } }); } self._clearFileInput(); var filestack = self.getFileStack(true), chk = self.previewCache.count(), len = filestack.length, hasThumb = self.showPreview && self.getFrames().length; if (len === 0 && chk === 0 && !hasThumb) { self.reset(); } else { n = chk + len; cap = n > 1 ? self._getMsgSelected(n) : (filestack[0] ? self._getFileNames()[0] : ''); self._setCaption(cap); } self._raise('fileremoved', [id, ind]); }); }); }); self.getFrames(' .kv-file-upload').each(function () { var $el = $(this); self._handler($el, 'click', function () { var $frame = $el.closest($h.FRAMES), ind = $frame.attr('data-fileindex'); self.$progress.hide(); if ($frame.hasClass('file-preview-error') && !self.retryErrorUploads) { return; } self._uploadSingle(ind, false); }); }); }, _initPreviewActions: function () { var self = this, $preview = self.$preview, deleteExtraData = self.deleteExtraData || {}, btnRemove = $h.FRAMES + ' .kv-file-remove', settings = self.fileActionSettings, origClass = settings.removeClass, errClass = settings.removeErrorClass, resetProgress = function () { var hasFiles = self.isAjaxUpload ? self.previewCache.count() : self._inputFileCount(); if (!$preview.find($h.FRAMES).length && !hasFiles) { self._setCaption(''); self.reset(); self.initialCaption = ''; } }; self._initZoomButton(); $preview.find(btnRemove).each(function () { var $el = $(this), vUrl = $el.data('url') || self.deleteUrl, vKey = $el.data('key'), fnBefore, fnSuccess, fnError; if ($h.isEmpty(vUrl) || vKey === undefined) { return; } var $frame = $el.closest($h.FRAMES), cache = self.previewCache.data, settings, params, index = $frame.attr('data-fileindex'), config, extraData; index = parseInt(index.replace('init_', '')); config = $h.isEmpty(cache.config) && $h.isEmpty(cache.config[index]) ? null : cache.config[index]; extraData = $h.isEmpty(config) || $h.isEmpty(config.extra) ? deleteExtraData : config.extra; if (typeof extraData === "function") { extraData = extraData(); } params = {id: $el.attr('id'), key: vKey, extra: extraData}; fnBefore = function (jqXHR) { self.ajaxAborted = false; self._raise('filepredelete', [vKey, jqXHR, extraData]); if (self._abort()) { jqXHR.abort(); } else { $el.removeClass(errClass); $h.addCss($frame, 'file-uploading'); $h.addCss($el, 'disabled ' + origClass); } }; fnSuccess = function (data, textStatus, jqXHR) { var n, cap; if (!$h.isEmpty(data) && !$h.isEmpty(data.error)) { params.jqXHR = jqXHR; params.response = data; self._showError(data.error, params, 'filedeleteerror'); $frame.removeClass('file-uploading'); $el.removeClass('disabled ' + origClass).addClass(errClass); resetProgress(); return; } $frame.removeClass('file-uploading').addClass('file-deleted'); $frame.fadeOut('slow', function () { index = parseInt(($frame.attr('data-fileindex')).replace('init_', '')); self.previewCache.unset(index); self._deleteFileIndex($frame); n = self.previewCache.count(); cap = n > 0 ? self._getMsgSelected(n) : ''; self._setCaption(cap); self._raise('filedeleted', [vKey, jqXHR, extraData]); $h.cleanZoomCache($preview.find('#zoom-' + $frame.attr('id'))); self._clearObjects($frame); $frame.remove(); resetProgress(); }); }; fnError = function (jqXHR, textStatus, errorThrown) { var op = self.ajaxOperations.deleteThumb, errMsg = self._parseError(op, jqXHR, errorThrown); params.jqXHR = jqXHR; params.response = {}; self._showError(errMsg, params, 'filedeleteerror'); $frame.removeClass('file-uploading'); $el.removeClass('disabled ' + origClass).addClass(errClass); resetProgress(); }; self._initAjaxSettings(); self._mergeAjaxCallback('beforeSend', fnBefore, 'delete'); self._mergeAjaxCallback('success', fnSuccess, 'delete'); self._mergeAjaxCallback('error', fnError, 'delete'); settings = $.extend(true, {}, { url: vUrl, type: 'POST', dataType: 'json', data: $.extend(true, {}, {key: vKey}, extraData) }, self._ajaxDeleteSettings); self._handler($el, 'click', function () { if (!self._validateMinCount()) { return false; } self.ajaxAborted = false; self._raise('filebeforedelete', [vKey, extraData]); //noinspection JSUnresolvedVariable,JSHint if (self.ajaxAborted instanceof Promise) { self.ajaxAborted.then(function (result) { if (!result) { $.ajax(settings); } }); } else { if (!self.ajaxAborted) { $.ajax(settings); } } }); }); }, _hideFileIcon: function () { var self = this; if (self.overwriteInitial) { self.$captionContainer.removeClass('icon-visible'); } }, _showFileIcon: function () { var self = this; $h.addCss(self.$captionContainer, 'icon-visible'); }, _getSize: function (bytes) { var self = this, size = parseFloat(bytes), i, func = self.fileSizeGetter, sizes, out; if (!$.isNumeric(bytes) || !$.isNumeric(size)) { return ''; } if (typeof func === 'function') { out = func(size); } else { if (size === 0) { out = '0.00 B'; } else { i = Math.floor(Math.log(size) / Math.log(1024)); sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']; out = (size / Math.pow(1024, i)).toFixed(2) * 1 + ' ' + sizes[i]; } } return self._getLayoutTemplate('size').replace('{sizeText}', out); }, _generatePreviewTemplate: function (cat, data, fname, ftype, previewId, isError, size, frameClass, foot, ind, templ) { var self = this, caption = self.slug(fname), prevContent, zoomContent = '', styleAttribs = '', screenW = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth, config = screenW < 400 ? (self.previewSettingsSmall[cat] || self.defaults.previewSettingsSmall[cat]) : (self.previewSettings[cat] || self.defaults.previewSettings[cat]), footer = foot || self._renderFileFooter(caption, size, 'auto', isError), hasIconSetting = self._getPreviewIcon(fname), typeCss = 'type-default', forcePrevIcon = hasIconSetting && self.preferIconicPreview, forceZoomIcon = hasIconSetting && self.preferIconicZoomPreview, getContent; if (config) { $.each(config, function (key, val) { styleAttribs += key + ':' + val + ';'; }); } getContent = function (c, d, zoom, frameCss) { var id = zoom ? 'zoom-' + previewId : previewId, tmplt = self._getPreviewTemplate(c), css = (frameClass || '') + ' ' + frameCss; if (self.frameClass) { css = self.frameClass + ' ' + css; } if (zoom) { css = css.replace(' ' + $h.SORT_CSS, ''); } tmplt = self._parseFilePreviewIcon(tmplt, fname); if (c === 'text') { d = $h.htmlEncode(d); } if (cat === 'object' && !ftype) { $.each(self.defaults.fileTypeSettings, function (key, func) { if (key === 'object' || key === 'other') { return; } if (func(fname, ftype)) { typeCss = 'type-' + key; } }); } return tmplt.setTokens({ 'previewId': id, 'caption': caption, 'frameClass': css, 'type': ftype, 'fileindex': ind, 'typeCss': typeCss, 'footer': footer, 'data': d, 'template': templ || cat, 'style': styleAttribs ? 'style="' + styleAttribs + '"' : '' }); }; ind = ind || previewId.slice(previewId.lastIndexOf('-') + 1); if (self.fileActionSettings.showZoom) { zoomContent = getContent((forceZoomIcon ? 'other' : cat), data, true, 'kv-zoom-thumb'); } zoomContent = '\n' + self._getLayoutTemplate('zoomCache').replace('{zoomContent}', zoomContent); prevContent = getContent((forcePrevIcon ? 'other' : cat), data, false, 'kv-preview-thumb'); return prevContent + zoomContent; }, _addToPreview: function ($preview, content) { var self = this; return self.reversePreviewOrder ? $preview.prepend(content) : $preview.append(content); }, _previewDefault: function (file, previewId, isDisabled) { var self = this, $preview = self.$preview; if (!self.showPreview) { return; } var fname = file ? file.name : '', ftype = file ? file.type : '', content, size = file.size || 0, caption = self.slug(fname), isError = isDisabled === true && !self.isAjaxUpload, data = $h.objUrl.createObjectURL(file); self._clearDefaultPreview(); content = self._generatePreviewTemplate('other', data, fname, ftype, previewId, isError, size); self._addToPreview($preview, content); self._setThumbAttr(previewId, caption, size); if (isDisabled === true && self.isAjaxUpload) { self._setThumbStatus($('#' + previewId), 'Error'); } }, _previewFile: function (i, file, theFile, previewId, data, fileInfo) { if (!this.showPreview) { return; } var self = this, fname = file ? file.name : '', ftype = fileInfo.type, caption = fileInfo.name, cat = self._parseFileType(ftype, fname), types = self.allowedPreviewTypes, content, mimes = self.allowedPreviewMimeTypes, $preview = self.$preview, fsize = file.size || 0, chkTypes = types && types.indexOf(cat) >= 0, chkMimes = mimes && mimes.indexOf(ftype) !== -1, iData = (cat === 'text' || cat === 'html' || cat === 'image') ? theFile.target.result : data; /** @namespace window.DOMPurify */ if (cat === 'html' && self.purifyHtml && window.DOMPurify) { iData = window.DOMPurify.sanitize(iData); } if (chkTypes || chkMimes) { content = self._generatePreviewTemplate(cat, iData, fname, ftype, previewId, false, fsize); self._clearDefaultPreview(); self._addToPreview($preview, content); var $img = $preview.find('#' + previewId + ' img'); if ($img.length && self.autoOrientImage) { $h.validateOrientation(file, function (value) { if (!value) { self._validateImage(previewId, caption, ftype, fsize, iData); return; } var $zoomImg = $preview.find('#zoom-' + previewId + ' img'), css = 'rotate-' + value; if (value > 4) { css += ($img.width() > $img.height() ? ' is-portrait-gt4' : ' is-landscape-gt4'); } $h.addCss($img, css); $h.addCss($zoomImg, css); self._raise('fileimageoriented', {'$img': $img, 'file': file}); self._validateImage(previewId, caption, ftype, fsize, iData); $h.adjustOrientedImage($img); }); } else { self._validateImage(previewId, caption, ftype, fsize, iData); } } else { self._previewDefault(file, previewId); } self._setThumbAttr(previewId, caption, fsize); self._initSortable(); }, _setThumbAttr: function (id, caption, size) { var self = this, $frame = $('#' + id); if ($frame.length) { size = size && size > 0 ? self._getSize(size) : ''; $frame.data({'caption': caption, 'size': size}); } }, _setInitThumbAttr: function () { var self = this, data = self.previewCache.data, len = self.previewCache.count(), config, caption, size, previewId; if (len === 0) { return; } for (var i = 0; i < len; i++) { config = data.config[i]; previewId = self.previewInitId + '-' + 'init_' + i; caption = $h.ifSet('caption', config, $h.ifSet('filename', config)); size = $h.ifSet('size', config); self._setThumbAttr(previewId, caption, size); } }, _slugDefault: function (text) { return $h.isEmpty(text) ? '' : String(text).replace(/[\[\]\/\{}:;#%=\(\)\*\+\?\\\^\$\|<>&"']/g, '_'); }, _updateFileDetails: function (numFiles) { var self = this, $el = self.$element, fileStack = self.getFileStack(), name = ($h.isIE(9) && $h.findFileName($el.val())) || ($el[0].files[0] && $el[0].files[0].name) || (fileStack.length && fileStack[0].name) || '', label = self.slug(name), n = self.isAjaxUpload ? fileStack.length : numFiles, nFiles = self.previewCache.count() + n, log = n === 1 ? label : self._getMsgSelected(nFiles); if (self.isError) { self.$previewContainer.removeClass('file-thumb-loading'); self.$previewStatus.html(''); self.$captionContainer.removeClass('icon-visible'); } else { self._showFileIcon(); } self._setCaption(log, self.isError); self.$container.removeClass('file-input-new file-input-ajax-new'); if (arguments.length === 1) { self._raise('fileselect', [numFiles, label]); } if (self.previewCache.count()) { self._initPreviewActions(); } }, _setThumbStatus: function ($thumb, status) { var self = this; if (!self.showPreview) { return; } var icon = 'indicator' + status, msg = icon + 'Title', css = 'file-preview-' + status.toLowerCase(), $indicator = $thumb.find('.file-upload-indicator'), config = self.fileActionSettings; $thumb.removeClass('file-preview-success file-preview-error file-preview-loading'); if (status === 'Success') { $thumb.find('.file-drag-handle').remove(); } $indicator.html(config[icon]); $indicator.attr('title', config[msg]); $thumb.addClass(css); if (status === 'Error' && !self.retryErrorUploads) { $thumb.find('.kv-file-upload').attr('disabled', true); } }, _setProgressCancelled: function () { var self = this; self._setProgress(101, self.$progress, self.msgCancelled); }, _setProgress: function (p, $el, error) { var self = this, pct = Math.min(p, 100), out, pctLimit = self.progressUploadThreshold, t = p <= 100 ? self.progressTemplate : self.progressCompleteTemplate, template = pct < 100 ? self.progressTemplate : (error ? self.progressErrorTemplate : t); $el = $el || self.$progress; if (!$h.isEmpty(template)) { if (pctLimit && pct > pctLimit && p <= 100) { out = template.setTokens({'percent': pctLimit, 'status': self.msgUploadThreshold}); } else { out = template.setTokens({'percent': pct, 'status': (p > 100 ? self.msgUploadEnd : pct + '%')}); } $el.html(out); if (error) { $el.find('[role="progressbar"]').html(error); } } }, _setFileDropZoneTitle: function () { var self = this, $zone = self.$container.find('.file-drop-zone'), title = self.dropZoneTitle, strFiles; if (self.isClickable) { strFiles = $h.isEmpty(self.$element.attr('multiple')) ? self.fileSingle : self.filePlural; title += self.dropZoneClickTitle.replace('{files}', strFiles); } $zone.find('.' + self.dropZoneTitleClass).remove(); if (!self.showPreview || $zone.length === 0 || self.getFileStack().length > 0 || !self.dropZoneEnabled || (!self.isAjaxUpload && self.$element.files)) { return; } if ($zone.find($h.FRAMES).length === 0 && $h.isEmpty(self.defaultPreviewContent)) { $zone.prepend('
    ' + title + '
    '); } self.$container.removeClass('file-input-new'); $h.addCss(self.$container, 'file-input-ajax-new'); }, _setAsyncUploadStatus: function (previewId, pct, total) { var self = this, sum = 0; self._setProgress(pct, $('#' + previewId).find('.file-thumb-progress')); self.uploadStatus[previewId] = pct; $.each(self.uploadStatus, function (key, value) { sum += value; }); self._setProgress(Math.floor(sum / total)); }, _validateMinCount: function () { var self = this, len = self.isAjaxUpload ? self.getFileStack().length : self._inputFileCount(); if (self.validateInitialCount && self.minFileCount > 0 && self._getFileCount(len - 1) < self.minFileCount) { self._noFilesError({}); return false; } return true; }, _getFileCount: function (fileCount) { var self = this, addCount = 0; if (self.validateInitialCount && !self.overwriteInitial) { addCount = self.previewCache.count(); fileCount += addCount; } return fileCount; }, _getFileId: function (file) { var self = this, custom = self.generateFileId, relativePath; if (typeof custom === 'function') { return custom(file, event); } if (!file) { return null; } /** @namespace file.webkitRelativePath */ relativePath = String(file.webkitRelativePath || file.fileName || file.name || null); if (!relativePath) { return null; } return (file.size + '-' + relativePath.replace(/[^0-9a-zA-Z_-]/img, '')); }, _getFileName: function (file) { return file && file.name ? this.slug(file.name) : undefined; }, _getFileIds: function (skipNull) { var self = this; return self.fileids.filter(function (n) { return (skipNull ? n !== undefined : n !== undefined && n !== null); }); }, _getFileNames: function (skipNull) { var self = this; return self.filenames.filter(function (n) { return (skipNull ? n !== undefined : n !== undefined && n !== null); }); }, _setPreviewError: function ($thumb, i, val, repeat) { var self = this; if (i !== undefined) { self.updateStack(i, val); } if (!self.showPreview) { return; } if (self.removeFromPreviewOnError && !repeat) { $thumb.remove(); return; } else { self._setThumbStatus($thumb, 'Error'); } self._refreshUploadButton($thumb, repeat); }, _refreshUploadButton: function ($thumb, repeat) { var self = this, $btn = $thumb.find('.kv-file-upload'), cfg = self.fileActionSettings, icon = cfg.uploadIcon, title = cfg.uploadTitle; if (!$btn.length) { return; } if (repeat) { icon = cfg.uploadRetryIcon; title = cfg.uploadRetryTitle; } $btn.attr('title', title).html(icon); }, _checkDimensions: function (i, chk, $img, $thumb, fname, type, params) { var self = this, msg, dim, tag = chk === 'Small' ? 'min' : 'max', limit = self[tag + 'Image' + type], $imgEl, isValid; if ($h.isEmpty(limit) || !$img.length) { return; } $imgEl = $img[0]; dim = (type === 'Width') ? $imgEl.naturalWidth || $imgEl.width : $imgEl.naturalHeight || $imgEl.height; isValid = chk === 'Small' ? dim >= limit : dim <= limit; if (isValid) { return; } msg = self['msgImage' + type + chk].setTokens({'name': fname, 'size': limit}); self._showUploadError(msg, params); self._setPreviewError($thumb, i, null); }, _validateImage: function (previewId, fname, ftype, fsize, iData) { var self = this, $preview = self.$preview, params, w1, w2, $thumb = $preview.find("#" + previewId), i = $thumb.attr('data-fileindex'), $img = $thumb.find('img'), exifObject; fname = fname || 'Untitled'; $img.one('load', function () { w1 = $thumb.width(); w2 = $preview.width(); if (w1 > w2) { $img.css('width', '100%'); } params = {ind: i, id: previewId}; self._checkDimensions(i, 'Small', $img, $thumb, fname, 'Width', params); self._checkDimensions(i, 'Small', $img, $thumb, fname, 'Height', params); if (!self.resizeImage) { self._checkDimensions(i, 'Large', $img, $thumb, fname, 'Width', params); self._checkDimensions(i, 'Large', $img, $thumb, fname, 'Height', params); } self._raise('fileimageloaded', [previewId]); try { exifObject = window.piexif ? window.piexif.load(iData) : null; } catch (err) { exifObject = null; } self.loadedImages.push({ ind: i, img: $img, thumb: $thumb, pid: previewId, typ: ftype, siz: fsize, validated: false, imgData: iData, exifObj: exifObject }); $thumb.data('exif', exifObject); self._validateAllImages(); }).one('error', function () { self._raise('fileimageloaderror', [previewId]); }).each(function () { if (this.complete) { $(this).trigger('load'); } else { if (this.error) { $(this).trigger('error'); } } }); }, _validateAllImages: function () { var self = this, i, counter = {val: 0}, numImgs = self.loadedImages.length, config, fsize, minSize = self.resizeIfSizeMoreThan; if (numImgs !== self.totalImagesCount) { return; } self._raise('fileimagesloaded'); if (!self.resizeImage) { return; } for (i = 0; i < self.loadedImages.length; i++) { config = self.loadedImages[i]; if (config.validated) { continue; } fsize = config.siz; if (fsize && fsize > minSize * 1000) { self._getResizedImage(config, counter, numImgs); } self.loadedImages[i].validated = true; } }, _getResizedImage: function (config, counter, numImgs) { var self = this, img = $(config.img)[0], width = img.naturalWidth, height = img.naturalHeight, blob, ratio = 1, maxWidth = self.maxImageWidth || width, maxHeight = self.maxImageHeight || height, isValidImage = !!(width && height), chkWidth, chkHeight, canvas = self.imageCanvas, dataURI, context = self.imageCanvasContext, type = config.typ, pid = config.pid, ind = config.ind, $thumb = config.thumb, throwError, msg, exifObj = config.exifObj, exifStr; throwError = function (msg, params, ev) { if (self.isAjaxUpload) { self._showUploadError(msg, params, ev); } else { self._showError(msg, params, ev); } self._setPreviewError($thumb, ind); }; if (!self.filestack[ind] || !isValidImage || (width <= maxWidth && height <= maxHeight)) { if (isValidImage && self.filestack[ind]) { self._raise('fileimageresized', [pid, ind]); } counter.val++; if (counter.val === numImgs) { self._raise('fileimagesresized'); } if (!isValidImage) { throwError(self.msgImageResizeError, {id: pid, 'index': ind}, 'fileimageresizeerror'); return; } } type = type || self.resizeDefaultImageType; chkWidth = width > maxWidth; chkHeight = height > maxHeight; if (self.resizePreference === 'width') { ratio = chkWidth ? maxWidth / width : (chkHeight ? maxHeight / height : 1); } else { ratio = chkHeight ? maxHeight / height : (chkWidth ? maxWidth / width : 1); } self._resetCanvas(); width *= ratio; height *= ratio; canvas.width = width; canvas.height = height; try { context.drawImage(img, 0, 0, width, height); dataURI = canvas.toDataURL(type, self.resizeQuality); if (exifObj) { exifStr = window.piexif.dump(exifObj); dataURI = window.piexif.insert(exifStr, dataURI); } blob = $h.dataURI2Blob(dataURI); self.filestack[ind] = blob; self._raise('fileimageresized', [pid, ind]); counter.val++; if (counter.val === numImgs) { self._raise('fileimagesresized', [undefined, undefined]); } if (!(blob instanceof Blob)) { throwError(self.msgImageResizeError, {id: pid, 'index': ind}, 'fileimageresizeerror'); } } catch (err) { counter.val++; if (counter.val === numImgs) { self._raise('fileimagesresized', [undefined, undefined]); } msg = self.msgImageResizeException.replace('{errors}', err.message); throwError(msg, {id: pid, 'index': ind}, 'fileimageresizeexception'); } }, _initBrowse: function ($container) { var self = this, $el = self.$element; if (self.showBrowse) { self.$btnFile = $container.find('.btn-file').append($el); } else { $el.appendTo($container).attr('tabindex', -1); $h.addCss($el, 'file-no-browse'); } }, _initClickable: function () { var self = this, $zone; if (!self.isClickable) { return; } $zone = self.isAjaxUpload ? self.$dropZone : self.$preview.find('.file-default-preview'); $h.addCss($zone, 'clickable'); $zone.attr('tabindex', -1); self._handler($zone, 'click', function (e) { var $tar = $(e.target), $el = self.$element; if (!$(self.elErrorContainer + ':visible').length && (!$tar.parents('.file-preview-thumbnails').length || $tar.parents('.file-default-preview').length)) { self.$element.data('zoneClicked', true).trigger('click'); $zone.blur(); } }); }, _initCaption: function () { var self = this, cap = self.initialCaption || ''; if (self.overwriteInitial || $h.isEmpty(cap)) { self.$caption.val(''); return false; } self._setCaption(cap); return true; }, _setCaption: function (content, isError) { var self = this, title, out, icon, n, cap, stack = self.getFileStack(); if (!self.$caption.length) { return; } self.$captionContainer.removeClass('icon-visible'); if (isError) { title = $('
    ' + self.msgValidationError + '
    ').text(); n = stack.length; if (n) { cap = n === 1 && stack[0] ? self._getFileNames()[0] : self._getMsgSelected(n); } else { cap = self._getMsgSelected(self.msgNo); } out = $h.isEmpty(content) ? cap : content; icon = '' + self.msgValidationErrorIcon + ''; } else { if ($h.isEmpty(content)) { return; } title = $('
    ' + content + '
    ').text(); out = title; icon = self._getLayoutTemplate('fileIcon'); } self.$captionContainer.addClass('icon-visible'); self.$caption.attr('title', title).val(out); self.$captionIcon.html(icon); }, _createContainer: function () { var self = this, attribs = {"class": 'file-input file-input-new' + (self.rtl ? ' kv-rtl' : '')}, $container = $(document.createElement("div")).attr(attribs).html(self._renderMain()); $container.insertBefore(self.$element); self._initBrowse($container); if (self.theme) { $container.addClass('theme-' + self.theme); } return $container; }, _refreshContainer: function () { var self = this, $container = self.$container, $el = self.$element; $el.insertAfter($container); $container.html(self._renderMain()); self._initBrowse($container); self._validateDisabled(); }, _validateDisabled: function () { var self = this; self.$caption.attr({readonly: self.isDisabled}); }, _renderMain: function () { var self = this, dropCss = self.dropZoneEnabled ? ' file-drop-zone' : 'file-drop-disabled', close = !self.showClose ? '' : self._getLayoutTemplate('close'), preview = !self.showPreview ? '' : self._getLayoutTemplate('preview') .setTokens({'class': self.previewClass, 'dropClass': dropCss}), css = self.isDisabled ? self.captionClass + ' file-caption-disabled' : self.captionClass, caption = self.captionTemplate.setTokens({'class': css + ' kv-fileinput-caption'}); return self.mainTemplate.setTokens({ 'class': self.mainClass + (!self.showBrowse && self.showCaption ? ' no-browse' : ''), 'preview': preview, 'close': close, 'caption': caption, 'upload': self._renderButton('upload'), 'remove': self._renderButton('remove'), 'cancel': self._renderButton('cancel'), 'browse': self._renderButton('browse') }); }, _renderButton: function (type) { var self = this, tmplt = self._getLayoutTemplate('btnDefault'), css = self[type + 'Class'], title = self[type + 'Title'], icon = self[type + 'Icon'], label = self[type + 'Label'], status = self.isDisabled ? ' disabled' : '', btnType = 'button'; switch (type) { case 'remove': if (!self.showRemove) { return ''; } break; case 'cancel': if (!self.showCancel) { return ''; } css += ' kv-hidden'; break; case 'upload': if (!self.showUpload) { return ''; } if (self.isAjaxUpload && !self.isDisabled) { tmplt = self._getLayoutTemplate('btnLink').replace('{href}', self.uploadUrl); } else { btnType = 'submit'; } break; case 'browse': if (!self.showBrowse) { return ''; } tmplt = self._getLayoutTemplate('btnBrowse'); break; default: return ''; } css += type === 'browse' ? ' btn-file' : ' fileinput-' + type + ' fileinput-' + type + '-button'; if (!$h.isEmpty(label)) { label = ' ' + label + ''; } return tmplt.setTokens({ 'type': btnType, 'css': css, 'title': title, 'status': status, 'icon': icon, 'label': label }); }, _renderThumbProgress: function () { var self = this; return '
    ' + self.progressTemplate.setTokens({'percent': '0', 'status': self.msgUploadBegin}) + '
    '; }, _renderFileFooter: function (caption, size, width, isError) { var self = this, config = self.fileActionSettings, rem = config.showRemove, drg = config.showDrag, upl = config.showUpload, zoom = config.showZoom, out, template = self._getLayoutTemplate('footer'), tInd = self._getLayoutTemplate('indicator'), ind = isError ? config.indicatorError : config.indicatorNew, title = isError ? config.indicatorErrorTitle : config.indicatorNewTitle, indicator = tInd.setTokens({'indicator': ind, 'indicatorTitle': title}); size = self._getSize(size); if (self.isAjaxUpload) { out = template.setTokens({ 'actions': self._renderFileActions(upl, false, rem, zoom, drg, false, false, false), 'caption': caption, 'size': size, 'width': width, 'progress': self._renderThumbProgress(), 'indicator': indicator }); } else { out = template.setTokens({ 'actions': self._renderFileActions(false, false, false, zoom, drg, false, false, false), 'caption': caption, 'size': size, 'width': width, 'progress': '', 'indicator': indicator }); } out = $h.replaceTags(out, self.previewThumbTags); return out; }, _renderFileActions: function (showUpl, showDwn, showDel, showZoom, showDrag, disabled, url, key, isInit, dUrl, dFile) { if (!showUpl && !showDwn && !showDel && !showZoom && !showDrag) { return ''; } var self = this, vUrl = url === false ? '' : ' data-url="' + url + '"', vKey = key === false ? '' : ' data-key="' + key + '"', btnDelete = '', btnUpload = '', btnDownload = '', btnZoom = '', btnDrag = '', css, template = self._getLayoutTemplate('actions'), config = self.fileActionSettings, otherButtons = self.otherActionButtons.setTokens({'dataKey': vKey, 'key': key}), removeClass = disabled ? config.removeClass + ' disabled' : config.removeClass; if (showDel) { btnDelete = self._getLayoutTemplate('actionDelete').setTokens({ 'removeClass': removeClass, 'removeIcon': config.removeIcon, 'removeTitle': config.removeTitle, 'dataUrl': vUrl, 'dataKey': vKey, 'key': key }); } if (showUpl) { btnUpload = self._getLayoutTemplate('actionUpload').setTokens({ 'uploadClass': config.uploadClass, 'uploadIcon': config.uploadIcon, 'uploadTitle': config.uploadTitle }); } if (showDwn) { btnDownload = self._getLayoutTemplate('actionDownload').setTokens({ 'downloadClass': config.downloadClass, 'downloadIcon': config.downloadIcon, 'downloadTitle': config.downloadTitle, 'downloadUrl': dUrl || self.initialPreviewDownloadUrl }); btnDownload = btnDownload.setTokens({'filename': dFile, 'key': key}); } if (showZoom) { btnZoom = self._getLayoutTemplate('actionZoom').setTokens({ 'zoomClass': config.zoomClass, 'zoomIcon': config.zoomIcon, 'zoomTitle': config.zoomTitle }); } if (showDrag && isInit) { css = 'drag-handle-init ' + config.dragClass; btnDrag = self._getLayoutTemplate('actionDrag').setTokens({ 'dragClass': css, 'dragTitle': config.dragTitle, 'dragIcon': config.dragIcon }); } return template.setTokens({ 'delete': btnDelete, 'upload': btnUpload, 'download': btnDownload, 'zoom': btnZoom, 'drag': btnDrag, 'other': otherButtons }); }, _browse: function (e) { var self = this; self._raise('filebrowse'); if (e && e.isDefaultPrevented()) { return; } if (self.isError && !self.isAjaxUpload) { self.clear(); } self.$captionContainer.focus(); }, _filterDuplicate: function (file, files, fileIds) { var self = this, fileId = self._getFileId(file); if (fileId && fileIds && fileIds.indexOf(fileId) > -1) { return; } if (!fileIds) { fileIds = []; } files.push(file); fileIds.push(fileId); }, _change: function (e) { var self = this; if (self.changeTriggered) { return; } var $el = self.$element, isDragDrop = arguments.length > 1, isAjaxUpload = self.isAjaxUpload, tfiles = [], files = isDragDrop ? arguments[1] : $el.get(0).files, total, maxCount = !isAjaxUpload && $h.isEmpty($el.attr('multiple')) ? 1 : self.maxFileCount, len, ctr = self.filestack.length, isSingleUpload = $h.isEmpty($el.attr('multiple')), flagSingle = (isSingleUpload && ctr > 0), fileIds = self._getFileIds(), throwError = function (mesg, file, previewId, index) { var p1 = $.extend(true, {}, self._getOutData({}, {}, files), {id: previewId, index: index}), p2 = {id: previewId, index: index, file: file, files: files}; return isAjaxUpload ? self._showUploadError(mesg, p1) : self._showError(mesg, p2); }, maxCountCheck = function (n, m) { var msg = self.msgFilesTooMany.replace('{m}', m).replace('{n}', n); self.isError = throwError(msg, null, null, null); self.$captionContainer.removeClass('icon-visible'); self._setCaption('', true); self.$container.removeClass('file-input-new file-input-ajax-new'); }; self.reader = null; self._resetUpload(); self._hideFileIcon(); if (self.dropZoneEnabled) { self.$container.find('.file-drop-zone .' + self.dropZoneTitleClass).remove(); } if (isAjaxUpload) { $.each(files, function (vKey, vFile) { self._filterDuplicate(vFile, tfiles, fileIds); }); } else { if (e.target && e.target.files === undefined) { files = e.target.value ? [{name: e.target.value.replace(/^.+\\/, '')}] : []; } else { files = e.target.files || {}; } tfiles = files; } if ($h.isEmpty(tfiles) || tfiles.length === 0) { if (!isAjaxUpload) { self.clear(); } self._raise('fileselectnone'); return; } self._resetErrors(); len = tfiles.length; total = self._getFileCount(isAjaxUpload ? (self.getFileStack().length + len) : len); if (maxCount > 0 && total > maxCount) { if (!self.autoReplace || len > maxCount) { maxCountCheck((self.autoReplace && len > maxCount ? len : total), maxCount); return; } if (total > maxCount) { self._resetPreviewThumbs(isAjaxUpload); } } else { if (!isAjaxUpload || flagSingle) { self._resetPreviewThumbs(false); if (flagSingle) { self.clearStack(); } } else { if (isAjaxUpload && ctr === 0 && (!self.previewCache.count() || self.overwriteInitial)) { self._resetPreviewThumbs(true); } } } if (self.isPreviewable) { self.readFiles(tfiles); } else { self._updateFileDetails(1); } }, _abort: function (params) { var self = this, data; if (self.ajaxAborted && typeof self.ajaxAborted === "object" && self.ajaxAborted.message !== undefined) { data = $.extend(true, {}, self._getOutData(), params); data.abortData = self.ajaxAborted.data || {}; data.abortMessage = self.ajaxAborted.message; self._setProgress(101, self.$progress, self.msgCancelled); self._showUploadError(self.ajaxAborted.message, data, 'filecustomerror'); self.cancel(); return true; } return !!self.ajaxAborted; }, _resetFileStack: function () { var self = this, i = 0, newstack = [], newnames = [], newids = []; self._getThumbs().each(function () { var $thumb = $(this), ind = $thumb.attr('data-fileindex'), file = self.filestack[ind], pid = $thumb.attr('id'); if (ind === '-1' || ind === -1) { return; } if (file !== undefined) { newstack[i] = file; newnames[i] = self._getFileName(file); newids[i] = self._getFileId(file); $thumb.attr({'id': self.previewInitId + '-' + i, 'data-fileindex': i}); i++; } else { $thumb.attr({'id': 'uploaded-' + $h.uniqId(), 'data-fileindex': '-1'}); } self.$preview.find('#zoom-' + pid).attr({ 'id': 'zoom-' + $thumb.attr('id'), 'data-fileindex': $thumb.attr('data-fileindex') }); }); self.filestack = newstack; self.filenames = newnames; self.fileids = newids; }, _isFileSelectionValid: function (cnt) { var self = this; cnt = cnt || 0; if (self.required && !self.getFilesCount()) { self.$errorContainer.html(''); self._showUploadError(self.msgFileRequired); return false; } if (self.minFileCount > 0 && self._getFileCount(cnt) < self.minFileCount) { self._noFilesError({}); return false; } return true; }, clearStack: function () { var self = this; self.filestack = []; self.filenames = []; self.fileids = []; return self.$element; }, updateStack: function (i, file) { var self = this; self.filestack[i] = file; self.filenames[i] = self._getFileName(file); self.fileids[i] = file && self._getFileId(file) || null; return self.$element; }, addToStack: function (file) { var self = this; self.filestack.push(file); self.filenames.push(self._getFileName(file)); self.fileids.push(self._getFileId(file)); return self.$element; }, getFileStack: function (skipNull) { var self = this; return self.filestack.filter(function (n) { return (skipNull ? n !== undefined : n !== undefined && n !== null); }); }, getFilesCount: function () { var self = this, len = self.isAjaxUpload ? self.getFileStack().length : self._inputFileCount(); return self._getFileCount(len); }, readFiles: function (files) { this.reader = new FileReader(); var self = this, $el = self.$element, $preview = self.$preview, reader = self.reader, $container = self.$previewContainer, $status = self.$previewStatus, msgLoading = self.msgLoading, msgProgress = self.msgProgress, previewInitId = self.previewInitId, numFiles = files.length, settings = self.fileTypeSettings, ctr = self.filestack.length, readFile, fileTypes = self.allowedFileTypes, typLen = fileTypes ? fileTypes.length : 0, fileExt = self.allowedFileExtensions, strExt = $h.isEmpty(fileExt) ? '' : fileExt.join(', '), maxPreviewSize = self.maxFilePreviewSize && parseFloat(self.maxFilePreviewSize), canPreview = $preview.length && (!maxPreviewSize || isNaN(maxPreviewSize)), throwError = function (msg, file, previewId, index) { var p1 = $.extend(true, {}, self._getOutData({}, {}, files), {id: previewId, index: index}), p2 = {id: previewId, index: index, file: file, files: files}, $thumb; self._previewDefault(file, previewId, true); if (self.isAjaxUpload) { self.addToStack(undefined); setTimeout(function () { readFile(index + 1); }, 100); } else { numFiles = 0; } self._initFileActions(); $thumb = $('#' + previewId); $thumb.find('.kv-file-upload').hide(); if (self.removeFromPreviewOnError) { $thumb.remove(); } self.isError = self.isAjaxUpload ? self._showUploadError(msg, p1) : self._showError(msg, p2); self._updateFileDetails(numFiles); }; self.loadedImages = []; self.totalImagesCount = 0; $.each(files, function (key, file) { var func = self.fileTypeSettings.image; if (func && func(file.type)) { self.totalImagesCount++; } }); readFile = function (i) { if ($h.isEmpty($el.attr('multiple'))) { numFiles = 1; } if (i >= numFiles) { if (self.isAjaxUpload && self.filestack.length > 0) { self._raise('filebatchselected', [self.getFileStack()]); } else { self._raise('filebatchselected', [files]); } $container.removeClass('file-thumb-loading'); $status.html(''); return; } var node = ctr + i, previewId = previewInitId + "-" + node, file = files[i], fSizeKB, j, msg, fnText = settings.text, fnImage = settings.image, fnHtml = settings.html, typ, chk, typ1, typ2, caption = file && file.name ? self.slug(file.name) : '', fileSize = (file && file.size || 0) / 1000, fileExtExpr = '', previewData = file ? $h.objUrl.createObjectURL(file) : null, fileCount = 0, strTypes = '', func, knownTypes = 0, isText, isHtml, isImage, txtFlag, processFileLoaded = function () { var msg = msgProgress.setTokens({ 'index': i + 1, 'files': numFiles, 'percent': 50, 'name': caption }); setTimeout(function () { $status.html(msg); self._updateFileDetails(numFiles); readFile(i + 1); }, 100); self._raise('fileloaded', [file, previewId, i, reader]); }; if (!file) { return; } if (typLen > 0) { for (j = 0; j < typLen; j++) { typ1 = fileTypes[j]; typ2 = self.msgFileTypes[typ1] || typ1; strTypes += j === 0 ? typ2 : ', ' + typ2; } } if (caption === false) { readFile(i + 1); return; } if (caption.length === 0) { msg = self.msgInvalidFileName.replace('{name}', $h.htmlEncode(file.name)); throwError(msg, file, previewId, i); return; } if (!$h.isEmpty(fileExt)) { fileExtExpr = new RegExp('\\.(' + fileExt.join('|') + ')$', 'i'); } fSizeKB = fileSize.toFixed(2); if (self.maxFileSize > 0 && fileSize > self.maxFileSize) { msg = self.msgSizeTooLarge.setTokens({ 'name': caption, 'size': fSizeKB, 'maxSize': self.maxFileSize }); throwError(msg, file, previewId, i); return; } if (self.minFileSize !== null && fileSize <= $h.getNum(self.minFileSize)) { msg = self.msgSizeTooSmall.setTokens({ 'name': caption, 'size': fSizeKB, 'minSize': self.minFileSize }); throwError(msg, file, previewId, i); return; } if (!$h.isEmpty(fileTypes) && $h.isArray(fileTypes)) { for (j = 0; j < fileTypes.length; j += 1) { typ = fileTypes[j]; func = settings[typ]; fileCount += !func || (typeof func !== 'function') ? 0 : (func(file.type, file.name) ? 1 : 0); } if (fileCount === 0) { msg = self.msgInvalidFileType.setTokens({'name': caption, 'types': strTypes}); throwError(msg, file, previewId, i); return; } } if (fileCount === 0 && !$h.isEmpty(fileExt) && $h.isArray(fileExt) && !$h.isEmpty(fileExtExpr)) { chk = $h.compare(caption, fileExtExpr); fileCount += $h.isEmpty(chk) ? 0 : chk.length; if (fileCount === 0) { msg = self.msgInvalidFileExtension.setTokens({'name': caption, 'extensions': strExt}); throwError(msg, file, previewId, i); return; } } if (!self.showPreview) { if (self.isAjaxUpload) { self.addToStack(file); } setTimeout(function () { readFile(i + 1); self._updateFileDetails(numFiles); }, 100); self._raise('fileloaded', [file, previewId, i, reader]); return; } if (!canPreview && fileSize > maxPreviewSize) { self.addToStack(file); $container.addClass('file-thumb-loading'); self._previewDefault(file, previewId); self._initFileActions(); self._updateFileDetails(numFiles); readFile(i + 1); return; } if ($preview.length && FileReader !== undefined) { isText = fnText(file.type, caption); isHtml = fnHtml(file.type, caption); isImage = fnImage(file.type, caption); $status.html(msgLoading.replace('{index}', i + 1).replace('{files}', numFiles)); $container.addClass('file-thumb-loading'); reader.onerror = function (evt) { self._errorHandler(evt, caption); }; reader.onload = function (theFile) { var hex, fileInfo, uint, byte, bytes = [], contents, mime, readTextImage = function (textFlag) { var newReader = new FileReader(); newReader.onerror = function (theFileNew) { self._errorHandler(theFileNew, caption); }; newReader.onload = function (theFileNew) { self._previewFile(i, file, theFileNew, previewId, previewData, fileInfo); self._initFileActions(); processFileLoaded(); }; if (textFlag) { newReader.readAsText(file, self.textEncoding); } else { newReader.readAsDataURL(file); } }; fileInfo = {'name': caption, 'type': file.type}; $.each(settings, function (key, func) { if (key !== 'object' && key !== 'other' && func(file.type, caption)) { knownTypes++; } }); if (knownTypes === 0) {// auto detect mime types from content if no known file types detected uint = new Uint8Array(theFile.target.result); for (j = 0; j < uint.length; j++) { byte = uint[j].toString(16); bytes.push(byte); } hex = bytes.join('').toLowerCase().substring(0, 8); mime = $h.getMimeType(hex, '', ''); if ($h.isEmpty(mime)) { // look for ascii text content contents = $h.arrayBuffer2String(reader.result); mime = $h.isSvg(contents) ? 'image/svg+xml' : $h.getMimeType(hex, contents, file.type); } fileInfo = {'name': caption, 'type': mime}; isText = fnText(mime, ''); isHtml = fnHtml(mime, ''); isImage = fnImage(mime, ''); txtFlag = isText || isHtml; if (txtFlag || isImage) { readTextImage(txtFlag); return; } } self._previewFile(i, file, theFile, previewId, previewData, fileInfo); self._initFileActions(); processFileLoaded(); }; reader.onprogress = function (data) { if (data.lengthComputable) { var fact = (data.loaded / data.total) * 100, progress = Math.ceil(fact); msg = msgProgress.setTokens({ 'index': i + 1, 'files': numFiles, 'percent': progress, 'name': caption }); setTimeout(function () { $status.html(msg); }, 100); } }; if (isText || isHtml) { reader.readAsText(file, self.textEncoding); } else { if (isImage) { reader.readAsDataURL(file); } else { reader.readAsArrayBuffer(file); } } } else { self._previewDefault(file, previewId); setTimeout(function () { readFile(i + 1); self._updateFileDetails(numFiles); }, 100); self._raise('fileloaded', [file, previewId, i, reader]); } self.addToStack(file); }; readFile(0); self._updateFileDetails(numFiles, false); }, lock: function () { var self = this; self._resetErrors(); self.disable(); if (self.showRemove) { self.$container.find('.fileinput-remove').hide(); } if (self.showCancel) { self.$container.find('.fileinput-cancel').show(); } self._raise('filelock', [self.filestack, self._getExtraData()]); return self.$element; }, unlock: function (reset) { var self = this; if (reset === undefined) { reset = true; } self.enable(); if (self.showCancel) { self.$container.find('.fileinput-cancel').hide(); } if (self.showRemove) { self.$container.find('.fileinput-remove').show(); } if (reset) { self._resetFileStack(); } self._raise('fileunlock', [self.filestack, self._getExtraData()]); return self.$element; }, cancel: function () { var self = this, xhr = self.ajaxRequests, len = xhr.length, i; if (len > 0) { for (i = 0; i < len; i += 1) { self.cancelling = true; xhr[i].abort(); } } self._setProgressCancelled(); self._getThumbs().each(function () { var $thumb = $(this), ind = $thumb.attr('data-fileindex'); $thumb.removeClass('file-uploading'); if (self.filestack[ind] !== undefined) { $thumb.find('.kv-file-upload').removeClass('disabled').removeAttr('disabled'); $thumb.find('.kv-file-remove').removeClass('disabled').removeAttr('disabled'); } self.unlock(); }); return self.$element; }, clear: function () { var self = this, cap; if (!self._raise('fileclear')) { return; } self.$btnUpload.removeAttr('disabled'); self._getThumbs().find('video,audio,img').each(function () { $h.cleanMemory($(this)); }); self._clearFileInput(); self._resetUpload(); self.clearStack(); self._resetErrors(true); if (self._hasInitialPreview()) { self._showFileIcon(); self._resetPreview(); self._initPreviewActions(); self.$container.removeClass('file-input-new'); } else { self._getThumbs().each(function () { self._clearObjects($(this)); }); if (self.isAjaxUpload) { self.previewCache.data = {}; } self.$preview.html(''); cap = (!self.overwriteInitial && self.initialCaption.length > 0) ? self.initialCaption : ''; self.$caption.attr('title', '').val(cap); $h.addCss(self.$container, 'file-input-new'); self._validateDefaultPreview(); } if (self.$container.find($h.FRAMES).length === 0) { if (!self._initCaption()) { self.$captionContainer.removeClass('icon-visible'); } } self._hideFileIcon(); self._raise('filecleared'); self.$captionContainer.focus(); self._setFileDropZoneTitle(); return self.$element; }, reset: function () { var self = this; if (!self._raise('filereset')) { return; } self._resetPreview(); self.$container.find('.fileinput-filename').text(''); $h.addCss(self.$container, 'file-input-new'); if (self.getFrames().length || self.dropZoneEnabled) { self.$container.removeClass('file-input-new'); } self.clearStack(); self.formdata = {}; self._setFileDropZoneTitle(); return self.$element; }, disable: function () { var self = this; self.isDisabled = true; self._raise('filedisabled'); self.$element.attr('disabled', 'disabled'); self.$container.find(".kv-fileinput-caption").addClass("file-caption-disabled"); self.$container.find(".fileinput-remove, .fileinput-upload, .file-preview-frame button") .attr("disabled", true); $h.addCss(self.$container.find('.btn-file'), 'disabled'); self._initDragDrop(); return self.$element; }, enable: function () { var self = this; self.isDisabled = false; self._raise('fileenabled'); self.$element.removeAttr('disabled'); self.$container.find(".kv-fileinput-caption").removeClass("file-caption-disabled"); self.$container.find(".fileinput-remove, .fileinput-upload, .file-preview-frame button") .removeAttr("disabled"); self.$container.find('.btn-file').removeClass('disabled'); self._initDragDrop(); return self.$element; }, upload: function () { var self = this, totLen = self.getFileStack().length, i, outData, len, hasExtraData = !$.isEmptyObject(self._getExtraData()); if (!self.isAjaxUpload || self.isDisabled || !self._isFileSelectionValid(totLen)) { return; } self._resetUpload(); if (totLen === 0 && !hasExtraData) { self._showUploadError(self.msgUploadEmpty); return; } self.$progress.show(); self.uploadCount = 0; self.uploadStatus = {}; self.uploadLog = []; self.lock(); self._setProgress(2); if (totLen === 0 && hasExtraData) { self._uploadExtraOnly(); return; } len = self.filestack.length; self.hasInitData = false; if (self.uploadAsync) { outData = self._getOutData(); self._raise('filebatchpreupload', [outData]); self.fileBatchCompleted = false; self.uploadCache = {content: [], config: [], tags: [], append: true}; self.uploadAsyncCount = self.getFileStack().length; for (i = 0; i < len; i++) { self.uploadCache.content[i] = null; self.uploadCache.config[i] = null; self.uploadCache.tags[i] = null; } self.$preview.find('.file-preview-initial').removeClass($h.SORT_CSS); self._initSortable(); self.cacheInitialPreview = self.getPreview(); for (i = 0; i < len; i++) { if (self.filestack[i]) { self._uploadSingle(i, true); } } return; } self._uploadBatch(); return self.$element; }, destroy: function () { var self = this, $form = self.$form, $cont = self.$container, $el = self.$element, ns = self.namespace; $(document).off(ns); $(window).off(ns); if ($form && $form.length) { $form.off(ns); } if (self.isAjaxUpload) { self._clearFileInput(); } self._cleanup(); self._initPreviewCache(); $el.insertBefore($cont).off(ns).removeData(); $cont.off().remove(); return $el; }, refresh: function (options) { var self = this, $el = self.$element; if (typeof options !== 'object' || $h.isEmpty(options)) { options = self.options; } else { options = $.extend(true, {}, self.options, options); } self._init(options, true); self._listen(); return $el; }, zoom: function (frameId) { var self = this, $frame = self._getFrame(frameId), $modal = self.$modal; if (!$frame) { return; } $h.initModal($modal); $modal.html(self._getModalContent()); self._setZoomContent($frame); $modal.modal('show'); self._initZoomButtons(); }, getExif: function (frameId) { var self = this, $frame = self._getFrame(frameId); return $frame && $frame.data('exif') || null; }, getFrames: function (cssFilter) { var self = this, $frames; cssFilter = cssFilter || ''; $frames = self.$preview.find($h.FRAMES + cssFilter); if (self.reversePreviewOrder) { $frames = $($frames.get().reverse()); } return $frames; }, getPreview: function () { var self = this; return { content: self.initialPreview, config: self.initialPreviewConfig, tags: self.initialPreviewThumbTags }; } }; $.fn.fileinput = function (option) { if (!$h.hasFileAPISupport() && !$h.isIE(9)) { return; } var args = Array.apply(null, arguments), retvals = []; args.shift(); this.each(function () { var self = $(this), data = self.data('fileinput'), options = typeof option === 'object' && option, theme = options.theme || self.data('theme'), l = {}, t = {}, lang = options.language || self.data('language') || $.fn.fileinput.defaults.language || 'en', opt; if (!data) { if (theme) { t = $.fn.fileinputThemes[theme] || {}; } if (lang !== 'en' && !$h.isEmpty($.fn.fileinputLocales[lang])) { l = $.fn.fileinputLocales[lang] || {}; } opt = $.extend(true, {}, $.fn.fileinput.defaults, t, $.fn.fileinputLocales.en, l, options, self.data()); data = new FileInput(this, opt); self.data('fileinput', data); } if (typeof option === 'string') { retvals.push(data[option].apply(data, args)); } }); switch (retvals.length) { case 0: return this; case 1: return retvals[0]; default: return retvals; } }; $.fn.fileinput.defaults = { language: 'en', showCaption: true, showBrowse: true, showPreview: true, showRemove: true, showUpload: true, showCancel: true, showClose: true, showUploadedThumbs: true, browseOnZoneClick: false, autoReplace: false, autoOrientImage: true, // for JPEG images based on EXIF orientation tag required: false, rtl: false, hideThumbnailContent: false, generateFileId: null, previewClass: '', captionClass: '', frameClass: 'krajee-default', mainClass: 'file-caption-main', mainTemplate: null, purifyHtml: true, fileSizeGetter: null, initialCaption: '', initialPreview: [], initialPreviewDelimiter: '*$$*', initialPreviewAsData: false, initialPreviewFileType: 'image', initialPreviewConfig: [], initialPreviewThumbTags: [], previewThumbTags: {}, initialPreviewShowDelete: true, initialPreviewDownloadUrl: '', removeFromPreviewOnError: false, deleteUrl: '', deleteExtraData: {}, overwriteInitial: true, previewZoomButtonIcons: { prev: '', next: '', toggleheader: '', fullscreen: '', borderless: '', close: '' }, previewZoomButtonClasses: { prev: 'btn btn-navigate', next: 'btn btn-navigate', toggleheader: 'btn btn-sm btn-kv btn-default btn-outline-secondary', fullscreen: 'btn btn-sm btn-kv btn-default btn-outline-secondary', borderless: 'btn btn-sm btn-kv btn-default btn-outline-secondary', close: 'btn btn-sm btn-kv btn-default btn-outline-secondary' }, preferIconicPreview: false, preferIconicZoomPreview: false, allowedPreviewTypes: undefined, allowedPreviewMimeTypes: null, allowedFileTypes: null, allowedFileExtensions: null, defaultPreviewContent: null, customLayoutTags: {}, customPreviewTags: {}, previewFileIcon: '', previewFileIconClass: 'file-other-icon', previewFileIconSettings: {}, previewFileExtSettings: {}, buttonLabelClass: 'hidden-xs', browseIcon: ' ', browseClass: 'btn btn-primary', removeIcon: '', removeClass: 'btn btn-default btn-secondary', cancelIcon: '', cancelClass: 'btn btn-default btn-secondary', uploadIcon: '', uploadClass: 'btn btn-default btn-secondary', uploadUrl: null, uploadUrlThumb: null, uploadAsync: true, uploadExtraData: {}, zoomModalHeight: 480, minImageWidth: null, minImageHeight: null, maxImageWidth: null, maxImageHeight: null, resizeImage: false, resizePreference: 'width', resizeQuality: 0.92, resizeDefaultImageType: 'image/jpeg', resizeIfSizeMoreThan: 0, // in KB minFileSize: 0, maxFileSize: 0, maxFilePreviewSize: 25600, // 25 MB minFileCount: 0, maxFileCount: 0, validateInitialCount: false, msgValidationErrorClass: 'text-danger', msgValidationErrorIcon: ' ', msgErrorClass: 'file-error-message', progressThumbClass: "progress-bar bg-success progress-bar-success progress-bar-striped active", progressClass: "progress-bar bg-success progress-bar-success progress-bar-striped active", progressCompleteClass: "progress-bar bg-success progress-bar-success", progressErrorClass: "progress-bar bg-danger progress-bar-danger", progressUploadThreshold: 99, previewFileType: 'image', elCaptionContainer: null, elCaptionText: null, elPreviewContainer: null, elPreviewImage: null, elPreviewStatus: null, elErrorContainer: null, errorCloseButton: $h.closeButton('kv-error-close'), slugCallback: null, dropZoneEnabled: true, dropZoneTitleClass: 'file-drop-zone-title', fileActionSettings: {}, otherActionButtons: '', textEncoding: 'UTF-8', ajaxSettings: {}, ajaxDeleteSettings: {}, showAjaxErrorDetails: true, mergeAjaxCallbacks: false, mergeAjaxDeleteCallbacks: false, retryErrorUploads: true, reversePreviewOrder: false }; $.fn.fileinputLocales.en = { fileSingle: 'file', filePlural: 'files', browseLabel: 'Browse …', removeLabel: 'Remove', removeTitle: 'Clear selected files', cancelLabel: 'Cancel', cancelTitle: 'Abort ongoing upload', uploadLabel: 'Upload', uploadTitle: 'Upload selected files', msgNo: 'No', msgNoFilesSelected: 'No files selected', msgCancelled: 'Cancelled', msgPlaceholder: 'Select {files}...', msgZoomModalHeading: 'Detailed Preview', msgFileRequired: 'You must select a file to upload.', msgSizeTooSmall: 'File "{name}" ({size} KB) is too small and must be larger than {minSize} KB.', msgSizeTooLarge: 'File "{name}" ({size} KB) exceeds maximum allowed upload size of {maxSize} KB.', msgFilesTooLess: 'You must select at least {n} {files} to upload.', msgFilesTooMany: 'Number of files selected for upload ({n}) exceeds maximum allowed limit of {m}.', msgFileNotFound: 'File "{name}" not found!', msgFileSecured: 'Security restrictions prevent reading the file "{name}".', msgFileNotReadable: 'File "{name}" is not readable.', msgFilePreviewAborted: 'File preview aborted for "{name}".', msgFilePreviewError: 'An error occurred while reading the file "{name}".', msgInvalidFileName: 'Invalid or unsupported characters in file name "{name}".', msgInvalidFileType: 'Invalid type for file "{name}". Only "{types}" files are supported.', msgInvalidFileExtension: 'Invalid extension for file "{name}". Only "{extensions}" files are supported.', msgFileTypes: { 'image': 'image', 'html': 'HTML', 'text': 'text', 'video': 'video', 'audio': 'audio', 'flash': 'flash', 'pdf': 'PDF', 'object': 'object' }, msgUploadAborted: 'The file upload was aborted', msgUploadThreshold: 'Processing...', msgUploadBegin: 'Initializing...', msgUploadEnd: 'Done', msgUploadEmpty: 'No valid data available for upload.', msgUploadError: 'Error', msgValidationError: 'Validation Error', msgLoading: 'Loading file {index} of {files} …', msgProgress: 'Loading file {index} of {files} - {name} - {percent}% completed.', msgSelected: '{n} {files} selected', msgFoldersNotAllowed: 'Drag & drop files only! {n} folder(s) dropped were skipped.', msgImageWidthSmall: 'Width of image file "{name}" must be at least {size} px.', msgImageHeightSmall: 'Height of image file "{name}" must be at least {size} px.', msgImageWidthLarge: 'Width of image file "{name}" cannot exceed {size} px.', msgImageHeightLarge: 'Height of image file "{name}" cannot exceed {size} px.', msgImageResizeError: 'Could not get the image dimensions to resize.', msgImageResizeException: 'Error while resizing the image.
    {errors}
    ', msgAjaxError: 'Something went wrong with the {operation} operation. Please try again later!', msgAjaxProgressError: '{operation} failed', ajaxOperations: { deleteThumb: 'file delete', uploadThumb: 'file upload', uploadBatch: 'batch file upload', uploadExtra: 'form data upload' }, dropZoneTitle: 'Drag & drop files here …', dropZoneClickTitle: '
    (or click to select {files})', previewZoomButtonTitles: { prev: 'View previous file', next: 'View next file', toggleheader: 'Toggle header', fullscreen: 'Toggle full screen', borderless: 'Toggle borderless mode', close: 'Close detailed preview' } }; $.fn.fileinput.Constructor = FileInput; /** * Convert automatically file inputs with class 'file' into a bootstrap fileinput control. */ $(document).ready(function () { var $input = $('input.file[type=file]'); if ($input.length) { $input.fileinput(); } }); })); /*! * FileInput <_LANG_> Translations * * This file must be loaded after 'fileinput.js'. Patterns in braces '{}', or * any HTML markup tags in the messages must not be converted or translated. * * @see http://github.com/kartik-v/bootstrap-fileinput * * NOTE: this file must be saved in UTF-8 encoding. */ (function ($) { "use strict"; $.fn.fileinputLocales['_LANG_'] = { fileSingle: 'file', filePlural: 'files', browseLabel: 'Browse …', removeLabel: 'Remove', removeTitle: 'Clear selected files', cancelLabel: 'Cancel', cancelTitle: 'Abort ongoing upload', uploadLabel: 'Upload', uploadTitle: 'Upload selected files', msgNo: 'No', msgNoFilesSelected: 'No files selected', msgCancelled: 'Cancelled', msgPlaceholder: 'Select {files}...', msgZoomModalHeading: 'Detailed Preview', msgFileRequired: 'You must select a file to upload.', msgSizeTooSmall: 'File "{name}" ({size} KB) is too small and must be larger than {minSize} KB.', msgSizeTooLarge: 'File "{name}" ({size} KB) exceeds maximum allowed upload size of {maxSize} KB.', msgFilesTooLess: 'You must select at least {n} {files} to upload.', msgFilesTooMany: 'Number of files selected for upload ({n}) exceeds maximum allowed limit of {m}.', msgFileNotFound: 'File "{name}" not found!', msgFileSecured: 'Security restrictions prevent reading the file "{name}".', msgFileNotReadable: 'File "{name}" is not readable.', msgFilePreviewAborted: 'File preview aborted for "{name}".', msgFilePreviewError: 'An error occurred while reading the file "{name}".', msgInvalidFileName: 'Invalid or unsupported characters in file name "{name}".', msgInvalidFileType: 'Invalid type for file "{name}". Only "{types}" files are supported.', msgInvalidFileExtension: 'Invalid extension for file "{name}". Only "{extensions}" files are supported.', msgFileTypes: { 'image': 'image', 'html': 'HTML', 'text': 'text', 'video': 'video', 'audio': 'audio', 'flash': 'flash', 'pdf': 'PDF', 'object': 'object' }, msgUploadAborted: 'The file upload was aborted', msgUploadThreshold: 'Processing...', msgUploadBegin: 'Initializing...', msgUploadEnd: 'Done', msgUploadEmpty: 'No valid data available for upload.', msgUploadError: 'Error', msgValidationError: 'Validation Error', msgLoading: 'Loading file {index} of {files} …', msgProgress: 'Loading file {index} of {files} - {name} - {percent}% completed.', msgSelected: '{n} {files} selected', msgFoldersNotAllowed: 'Drag & drop files only! Skipped {n} dropped folder(s).', msgImageWidthSmall: 'Width of image file "{name}" must be at least {size} px.', msgImageHeightSmall: 'Height of image file "{name}" must be at least {size} px.', msgImageWidthLarge: 'Width of image file "{name}" cannot exceed {size} px.', msgImageHeightLarge: 'Height of image file "{name}" cannot exceed {size} px.', msgImageResizeError: 'Could not get the image dimensions to resize.', msgImageResizeException: 'Error while resizing the image.
    {errors}
    ', msgAjaxError: 'Something went wrong with the {operation} operation. Please try again later!', msgAjaxProgressError: '{operation} failed', ajaxOperations: { deleteThumb: 'file delete', uploadThumb: 'file upload', uploadBatch: 'batch file upload', uploadExtra: 'form data upload' }, dropZoneTitle: 'Drag & drop files here …', dropZoneClickTitle: '
    (or click to select {files})', fileActionSettings: { removeTitle: 'Remove file', uploadTitle: 'Upload file', uploadRetryTitle: 'Retry upload', downloadTitle: 'Download file', zoomTitle: 'View details', dragTitle: 'Move / Rearrange', indicatorNewTitle: 'Not uploaded yet', indicatorSuccessTitle: 'Uploaded', indicatorErrorTitle: 'Upload Error', indicatorLoadingTitle: 'Uploading ...' }, previewZoomButtonTitles: { prev: 'View previous file', next: 'View next file', toggleheader: 'Toggle header', fullscreen: 'Toggle full screen', borderless: 'Toggle borderless mode', close: 'Close detailed preview' } }; })(window.jQuery); /*! * FileInput Spanish Translations * * This file must be loaded after 'fileinput.js'. Patterns in braces '{}', or * any HTML markup tags in the messages must not be converted or translated. * * @see http://github.com/kartik-v/bootstrap-fileinput * * NOTE: this file must be saved in UTF-8 encoding. */ (function ($) { "use strict"; $.fn.fileinputLocales['es'] = { fileSingle: 'archivo', filePlural: 'archivos', browseLabel: 'Examinar …', removeLabel: 'Quitar', removeTitle: 'Quitar archivos seleccionados', cancelLabel: 'Cancelar', cancelTitle: 'Abortar la subida en curso', uploadLabel: 'Subir archivo', uploadTitle: 'Subir archivos seleccionados', msgNo: 'No', msgNoFilesSelected: 'No hay archivos seleccionados', msgCancelled: 'Cancelado', msgPlaceholder: 'Seleccionar {files}...', msgZoomModalHeading: 'Vista previa detallada', msgFileRequired: 'Debes seleccionar un archivo para subir.', msgSizeTooSmall: 'El archivo "{name}" ({size} KB) es demasiado pequeño y debe ser mayor de {minSize} KB.', msgSizeTooLarge: 'El archivo "{name}" ({size} KB) excede el tamaño máximo permitido de {maxSize} KB.', msgFilesTooLess: 'Debe seleccionar al menos {n} {files} a cargar.', msgFilesTooMany: 'El número de archivos seleccionados a cargar ({n}) excede el límite máximo permitido de {m}.', msgFileNotFound: 'Archivo "{name}" no encontrado.', msgFileSecured: 'No es posible acceder al archivo "{name}" porque está siendo usado por otra aplicación o no tiene permisos de lectura.', msgFileNotReadable: 'No es posible acceder al archivo "{name}".', msgFilePreviewAborted: 'Previsualización del archivo "{name}" cancelada.', msgFilePreviewError: 'Ocurrió un error mientras se leía el archivo "{name}".', msgInvalidFileName: 'Caracteres no válidos o no soportados en el nombre del archivo "{name}".', msgInvalidFileType: 'Tipo de archivo no válido para "{name}". Sólo se permiten archivos de tipo "{types}".', msgInvalidFileExtension: 'Extensión de archivo no válida para "{name}". Sólo se permiten archivos "{extensions}".', msgFileTypes: { 'image': 'image', 'html': 'HTML', 'text': 'text', 'video': 'video', 'audio': 'audio', 'flash': 'flash', 'pdf': 'PDF', 'object': 'object' }, msgUploadAborted: 'La carga de archivos se ha cancelado', msgUploadThreshold: 'Procesando...', msgUploadBegin: 'Inicializando...', msgUploadEnd: 'Hecho', msgUploadEmpty: 'No existen datos válidos para el envío.', msgUploadError: 'Error', msgValidationError: 'Error de validación', msgLoading: 'Subiendo archivo {index} de {files} …', msgProgress: 'Subiendo archivo {index} de {files} - {name} - {percent}% completado.', msgSelected: '{n} {files} seleccionado(s)', msgFoldersNotAllowed: 'Arrastre y suelte únicamente archivos. Omitida(s) {n} carpeta(s).', msgImageWidthSmall: 'El ancho de la imagen "{name}" debe ser de al menos {size} px.', msgImageHeightSmall: 'La altura de la imagen "{name}" debe ser de al menos {size} px.', msgImageWidthLarge: 'El ancho de la imagen "{name}" no puede exceder de {size} px.', msgImageHeightLarge: 'La altura de la imagen "{name}" no puede exceder de {size} px.', msgImageResizeError: 'No se pudieron obtener las dimensiones de la imagen para cambiar el tamaño.', msgImageResizeException: 'Error al cambiar el tamaño de la imagen.
    {errors}
    ', msgAjaxError: 'Algo ha ido mal con la operación {operation}. Por favor, inténtelo de nuevo mas tarde.', msgAjaxProgressError: 'La operación {operation} ha fallado', ajaxOperations: { deleteThumb: 'Archivo borrado', uploadThumb: 'Archivo subido', uploadBatch: 'Datos subidos en lote', uploadExtra: 'Datos del formulario subidos ' }, dropZoneTitle: 'Arrastre y suelte aquí los archivos …', dropZoneClickTitle: '
    (o haga clic para seleccionar {files})', fileActionSettings: { removeTitle: 'Eliminar archivo', uploadTitle: 'Subir archivo', uploadRetryTitle: 'Reintentar subir', downloadTitle: 'Descargar archivo', zoomTitle: 'Ver detalles', dragTitle: 'Mover / Reordenar', indicatorNewTitle: 'No subido todavía', indicatorSuccessTitle: 'Subido', indicatorErrorTitle: 'Error al subir', indicatorLoadingTitle: 'Subiendo...' }, previewZoomButtonTitles: { prev: 'Anterior', next: 'Siguiente', toggleheader: 'Mostrar encabezado', fullscreen: 'Pantalla completa', borderless: 'Modo sin bordes', close: 'Cerrar vista detallada' } }; })(window.jQuery); /* piexifjs The MIT License (MIT) Copyright (c) 2014, 2015 hMatoba(https://github.com/hMatoba) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ (function () { "use strict"; var that = {}; that.version = "1.03"; that.remove = function (jpeg) { var b64 = false; if (jpeg.slice(0, 2) == "\xff\xd8") { } else if (jpeg.slice(0, 23) == "data:image/jpeg;base64," || jpeg.slice(0, 22) == "data:image/jpg;base64,") { jpeg = atob(jpeg.split(",")[1]); b64 = true; } else { throw ("Given data is not jpeg."); } var segments = splitIntoSegments(jpeg); if (segments[1].slice(0, 2) == "\xff\xe1" && segments[1].slice(4, 10) == "Exif\x00\x00") { segments = [segments[0]].concat(segments.slice(2)); } else if (segments[2].slice(0, 2) == "\xff\xe1" && segments[2].slice(4, 10) == "Exif\x00\x00") { segments = segments.slice(0, 2).concat(segments.slice(3)); } else { throw("Exif not found."); } var new_data = segments.join(""); if (b64) { new_data = "data:image/jpeg;base64," + btoa(new_data); } return new_data; }; that.insert = function (exif, jpeg) { var b64 = false; if (exif.slice(0, 6) != "\x45\x78\x69\x66\x00\x00") { throw ("Given data is not exif."); } if (jpeg.slice(0, 2) == "\xff\xd8") { } else if (jpeg.slice(0, 23) == "data:image/jpeg;base64," || jpeg.slice(0, 22) == "data:image/jpg;base64,") { jpeg = atob(jpeg.split(",")[1]); b64 = true; } else { throw ("Given data is not jpeg."); } var exifStr = "\xff\xe1" + pack(">H", [exif.length + 2]) + exif; var segments = splitIntoSegments(jpeg); var new_data = mergeSegments(segments, exifStr); if (b64) { new_data = "data:image/jpeg;base64," + btoa(new_data); } return new_data; }; that.load = function (data) { var input_data; if (typeof (data) == "string") { if (data.slice(0, 2) == "\xff\xd8") { input_data = data; } else if (data.slice(0, 23) == "data:image/jpeg;base64," || data.slice(0, 22) == "data:image/jpg;base64,") { input_data = atob(data.split(",")[1]); } else if (data.slice(0, 4) == "Exif") { input_data = data.slice(6); } else { throw ("'load' gots invalid file data."); } } else { throw ("'load' gots invalid type argument."); } var exifDict = {}; var exif_dict = { "0th": {}, "Exif": {}, "GPS": {}, "Interop": {}, "1st": {}, "thumbnail": null }; var exifReader = new ExifReader(input_data); if (exifReader.tiftag === null) { return exif_dict; } if (exifReader.tiftag.slice(0, 2) == "\x49\x49") { exifReader.endian_mark = "<"; } else { exifReader.endian_mark = ">"; } var pointer = unpack(exifReader.endian_mark + "L", exifReader.tiftag.slice(4, 8))[0]; exif_dict["0th"] = exifReader.get_ifd(pointer, "0th"); var first_ifd_pointer = exif_dict["0th"]["first_ifd_pointer"]; delete exif_dict["0th"]["first_ifd_pointer"]; if (34665 in exif_dict["0th"]) { pointer = exif_dict["0th"][34665]; exif_dict["Exif"] = exifReader.get_ifd(pointer, "Exif"); } if (34853 in exif_dict["0th"]) { pointer = exif_dict["0th"][34853]; exif_dict["GPS"] = exifReader.get_ifd(pointer, "GPS"); } if (40965 in exif_dict["Exif"]) { pointer = exif_dict["Exif"][40965]; exif_dict["Interop"] = exifReader.get_ifd(pointer, "Interop"); } if (first_ifd_pointer != "\x00\x00\x00\x00") { pointer = unpack(exifReader.endian_mark + "L", first_ifd_pointer)[0]; exif_dict["1st"] = exifReader.get_ifd(pointer, "1st"); if ((513 in exif_dict["1st"]) && (514 in exif_dict["1st"])) { var end = exif_dict["1st"][513] + exif_dict["1st"][514]; var thumb = exifReader.tiftag.slice(exif_dict["1st"][513], end); exif_dict["thumbnail"] = thumb; } } return exif_dict; }; that.dump = function (exif_dict_original) { var TIFF_HEADER_LENGTH = 8; var exif_dict = copy(exif_dict_original); var header = "Exif\x00\x00\x4d\x4d\x00\x2a\x00\x00\x00\x08"; var exif_is = false; var gps_is = false; var interop_is = false; var first_is = false; var zeroth_ifd, exif_ifd, interop_ifd, gps_ifd, first_ifd; if ("0th" in exif_dict) { zeroth_ifd = exif_dict["0th"]; } else { zeroth_ifd = {}; } if ((("Exif" in exif_dict) && (Object.keys(exif_dict["Exif"]).length)) || (("Interop" in exif_dict) && (Object.keys(exif_dict["Interop"]).length))) { zeroth_ifd[34665] = 1; exif_is = true; exif_ifd = exif_dict["Exif"]; if (("Interop" in exif_dict) && Object.keys(exif_dict["Interop"]).length) { exif_ifd[40965] = 1; interop_is = true; interop_ifd = exif_dict["Interop"]; } else if (Object.keys(exif_ifd).indexOf(that.ExifIFD.InteroperabilityTag.toString()) > -1) { delete exif_ifd[40965]; } } else if (Object.keys(zeroth_ifd).indexOf(that.ImageIFD.ExifTag.toString()) > -1) { delete zeroth_ifd[34665]; } if (("GPS" in exif_dict) && (Object.keys(exif_dict["GPS"]).length)) { zeroth_ifd[that.ImageIFD.GPSTag] = 1; gps_is = true; gps_ifd = exif_dict["GPS"]; } else if (Object.keys(zeroth_ifd).indexOf(that.ImageIFD.GPSTag.toString()) > -1) { delete zeroth_ifd[that.ImageIFD.GPSTag]; } if (("1st" in exif_dict) && ("thumbnail" in exif_dict) && (exif_dict["thumbnail"] != null)) { first_is = true; exif_dict["1st"][513] = 1; exif_dict["1st"][514] = 1; first_ifd = exif_dict["1st"]; } var zeroth_set = _dict_to_bytes(zeroth_ifd, "0th", 0); var zeroth_length = (zeroth_set[0].length + exif_is * 12 + gps_is * 12 + 4 + zeroth_set[1].length); var exif_set, exif_bytes = "", exif_length = 0, gps_set, gps_bytes = "", gps_length = 0, interop_set, interop_bytes = "", interop_length = 0, first_set, first_bytes = "", thumbnail; if (exif_is) { exif_set = _dict_to_bytes(exif_ifd, "Exif", zeroth_length); exif_length = exif_set[0].length + interop_is * 12 + exif_set[1].length; } if (gps_is) { gps_set = _dict_to_bytes(gps_ifd, "GPS", zeroth_length + exif_length); gps_bytes = gps_set.join(""); gps_length = gps_bytes.length; } if (interop_is) { var offset = zeroth_length + exif_length + gps_length; interop_set = _dict_to_bytes(interop_ifd, "Interop", offset); interop_bytes = interop_set.join(""); interop_length = interop_bytes.length; } if (first_is) { var offset = zeroth_length + exif_length + gps_length + interop_length; first_set = _dict_to_bytes(first_ifd, "1st", offset); thumbnail = _get_thumbnail(exif_dict["thumbnail"]); if (thumbnail.length > 64000) { throw ("Given thumbnail is too large. max 64kB"); } } var exif_pointer = "", gps_pointer = "", interop_pointer = "", first_ifd_pointer = "\x00\x00\x00\x00"; if (exif_is) { var pointer_value = TIFF_HEADER_LENGTH + zeroth_length; var pointer_str = pack(">L", [pointer_value]); var key = 34665; var key_str = pack(">H", [key]); var type_str = pack(">H", [TYPES["Long"]]); var length_str = pack(">L", [1]); exif_pointer = key_str + type_str + length_str + pointer_str; } if (gps_is) { var pointer_value = TIFF_HEADER_LENGTH + zeroth_length + exif_length; var pointer_str = pack(">L", [pointer_value]); var key = 34853; var key_str = pack(">H", [key]); var type_str = pack(">H", [TYPES["Long"]]); var length_str = pack(">L", [1]); gps_pointer = key_str + type_str + length_str + pointer_str; } if (interop_is) { var pointer_value = (TIFF_HEADER_LENGTH + zeroth_length + exif_length + gps_length); var pointer_str = pack(">L", [pointer_value]); var key = 40965; var key_str = pack(">H", [key]); var type_str = pack(">H", [TYPES["Long"]]); var length_str = pack(">L", [1]); interop_pointer = key_str + type_str + length_str + pointer_str; } if (first_is) { var pointer_value = (TIFF_HEADER_LENGTH + zeroth_length + exif_length + gps_length + interop_length); first_ifd_pointer = pack(">L", [pointer_value]); var thumbnail_pointer = (pointer_value + first_set[0].length + 24 + 4 + first_set[1].length); var thumbnail_p_bytes = ("\x02\x01\x00\x04\x00\x00\x00\x01" + pack(">L", [thumbnail_pointer])); var thumbnail_length_bytes = ("\x02\x02\x00\x04\x00\x00\x00\x01" + pack(">L", [thumbnail.length])); first_bytes = (first_set[0] + thumbnail_p_bytes + thumbnail_length_bytes + "\x00\x00\x00\x00" + first_set[1] + thumbnail); } var zeroth_bytes = (zeroth_set[0] + exif_pointer + gps_pointer + first_ifd_pointer + zeroth_set[1]); if (exif_is) { exif_bytes = exif_set[0] + interop_pointer + exif_set[1]; } return (header + zeroth_bytes + exif_bytes + gps_bytes + interop_bytes + first_bytes); }; function copy(obj) { return JSON.parse(JSON.stringify(obj)); } function _get_thumbnail(jpeg) { var segments = splitIntoSegments(jpeg); while (("\xff\xe0" <= segments[1].slice(0, 2)) && (segments[1].slice(0, 2) <= "\xff\xef")) { segments = [segments[0]].concat(segments.slice(2)); } return segments.join(""); } function _pack_byte(array) { return pack(">" + nStr("B", array.length), array); } function _pack_short(array) { return pack(">" + nStr("H", array.length), array); } function _pack_long(array) { return pack(">" + nStr("L", array.length), array); } function _value_to_bytes(raw_value, value_type, offset) { var four_bytes_over = ""; var value_str = ""; var length, new_value, num, den; if (value_type == "Byte") { length = raw_value.length; if (length <= 4) { value_str = (_pack_byte(raw_value) + nStr("\x00", 4 - length)); } else { value_str = pack(">L", [offset]); four_bytes_over = _pack_byte(raw_value); } } else if (value_type == "Short") { length = raw_value.length; if (length <= 2) { value_str = (_pack_short(raw_value) + nStr("\x00\x00", 2 - length)); } else { value_str = pack(">L", [offset]); four_bytes_over = _pack_short(raw_value); } } else if (value_type == "Long") { length = raw_value.length; if (length <= 1) { value_str = _pack_long(raw_value); } else { value_str = pack(">L", [offset]); four_bytes_over = _pack_long(raw_value); } } else if (value_type == "Ascii") { new_value = raw_value + "\x00"; length = new_value.length; if (length > 4) { value_str = pack(">L", [offset]); four_bytes_over = new_value; } else { value_str = new_value + nStr("\x00", 4 - length); } } else if (value_type == "Rational") { if (typeof (raw_value[0]) == "number") { length = 1; num = raw_value[0]; den = raw_value[1]; new_value = pack(">L", [num]) + pack(">L", [den]); } else { length = raw_value.length; new_value = ""; for (var n = 0; n < length; n++) { num = raw_value[n][0]; den = raw_value[n][1]; new_value += (pack(">L", [num]) + pack(">L", [den])); } } value_str = pack(">L", [offset]); four_bytes_over = new_value; } else if (value_type == "SRational") { if (typeof (raw_value[0]) == "number") { length = 1; num = raw_value[0]; den = raw_value[1]; new_value = pack(">l", [num]) + pack(">l", [den]); } else { length = raw_value.length; new_value = ""; for (var n = 0; n < length; n++) { num = raw_value[n][0]; den = raw_value[n][1]; new_value += (pack(">l", [num]) + pack(">l", [den])); } } value_str = pack(">L", [offset]); four_bytes_over = new_value; } else if (value_type == "Undefined") { length = raw_value.length; if (length > 4) { value_str = pack(">L", [offset]); four_bytes_over = raw_value; } else { value_str = raw_value + nStr("\x00", 4 - length); } } var length_str = pack(">L", [length]); return [length_str, value_str, four_bytes_over]; } function _dict_to_bytes(ifd_dict, ifd, ifd_offset) { var TIFF_HEADER_LENGTH = 8; var tag_count = Object.keys(ifd_dict).length; var entry_header = pack(">H", [tag_count]); var entries_length; if (["0th", "1st"].indexOf(ifd) > -1) { entries_length = 2 + tag_count * 12 + 4; } else { entries_length = 2 + tag_count * 12; } var entries = ""; var values = ""; var key; for (var key in ifd_dict) { if (typeof (key) == "string") { key = parseInt(key); } if ((ifd == "0th") && ([34665, 34853].indexOf(key) > -1)) { continue; } else if ((ifd == "Exif") && (key == 40965)) { continue; } else if ((ifd == "1st") && ([513, 514].indexOf(key) > -1)) { continue; } var raw_value = ifd_dict[key]; var key_str = pack(">H", [key]); var value_type = TAGS[ifd][key]["type"]; var type_str = pack(">H", [TYPES[value_type]]); if (typeof (raw_value) == "number") { raw_value = [raw_value]; } var offset = TIFF_HEADER_LENGTH + entries_length + ifd_offset + values.length; var b = _value_to_bytes(raw_value, value_type, offset); var length_str = b[0]; var value_str = b[1]; var four_bytes_over = b[2]; entries += key_str + type_str + length_str + value_str; values += four_bytes_over; } return [entry_header + entries, values]; } function ExifReader(data) { var segments, app1; if (data.slice(0, 2) == "\xff\xd8") { // JPEG segments = splitIntoSegments(data); app1 = getExifSeg(segments); if (app1) { this.tiftag = app1.slice(10); } else { this.tiftag = null; } } else if (["\x49\x49", "\x4d\x4d"].indexOf(data.slice(0, 2)) > -1) { // TIFF this.tiftag = data; } else if (data.slice(0, 4) == "Exif") { // Exif this.tiftag = data.slice(6); } else { throw ("Given file is neither JPEG nor TIFF."); } } ExifReader.prototype = { get_ifd: function (pointer, ifd_name) { var ifd_dict = {}; var tag_count = unpack(this.endian_mark + "H", this.tiftag.slice(pointer, pointer + 2))[0]; var offset = pointer + 2; var t; if (["0th", "1st"].indexOf(ifd_name) > -1) { t = "Image"; } else { t = ifd_name; } for (var x = 0; x < tag_count; x++) { pointer = offset + 12 * x; var tag = unpack(this.endian_mark + "H", this.tiftag.slice(pointer, pointer + 2))[0]; var value_type = unpack(this.endian_mark + "H", this.tiftag.slice(pointer + 2, pointer + 4))[0]; var value_num = unpack(this.endian_mark + "L", this.tiftag.slice(pointer + 4, pointer + 8))[0]; var value = this.tiftag.slice(pointer + 8, pointer + 12); var v_set = [value_type, value_num, value]; if (tag in TAGS[t]) { ifd_dict[tag] = this.convert_value(v_set); } } if (ifd_name == "0th") { pointer = offset + 12 * tag_count; ifd_dict["first_ifd_pointer"] = this.tiftag.slice(pointer, pointer + 4); } return ifd_dict; }, convert_value: function (val) { var data = null; var t = val[0]; var length = val[1]; var value = val[2]; var pointer; if (t == 1) { // BYTE if (length > 4) { pointer = unpack(this.endian_mark + "L", value)[0]; data = unpack(this.endian_mark + nStr("B", length), this.tiftag.slice(pointer, pointer + length)); } else { data = unpack(this.endian_mark + nStr("B", length), value.slice(0, length)); } } else if (t == 2) { // ASCII if (length > 4) { pointer = unpack(this.endian_mark + "L", value)[0]; data = this.tiftag.slice(pointer, pointer + length - 1); } else { data = value.slice(0, length - 1); } } else if (t == 3) { // SHORT if (length > 2) { pointer = unpack(this.endian_mark + "L", value)[0]; data = unpack(this.endian_mark + nStr("H", length), this.tiftag.slice(pointer, pointer + length * 2)); } else { data = unpack(this.endian_mark + nStr("H", length), value.slice(0, length * 2)); } } else if (t == 4) { // LONG if (length > 1) { pointer = unpack(this.endian_mark + "L", value)[0]; data = unpack(this.endian_mark + nStr("L", length), this.tiftag.slice(pointer, pointer + length * 4)); } else { data = unpack(this.endian_mark + nStr("L", length), value); } } else if (t == 5) { // RATIONAL pointer = unpack(this.endian_mark + "L", value)[0]; if (length > 1) { data = []; for (var x = 0; x < length; x++) { data.push([unpack(this.endian_mark + "L", this.tiftag.slice(pointer + x * 8, pointer + 4 + x * 8))[0], unpack(this.endian_mark + "L", this.tiftag.slice(pointer + 4 + x * 8, pointer + 8 + x * 8))[0] ]); } } else { data = [unpack(this.endian_mark + "L", this.tiftag.slice(pointer, pointer + 4))[0], unpack(this.endian_mark + "L", this.tiftag.slice(pointer + 4, pointer + 8))[0] ]; } } else if (t == 7) { // UNDEFINED BYTES if (length > 4) { pointer = unpack(this.endian_mark + "L", value)[0]; data = this.tiftag.slice(pointer, pointer + length); } else { data = value.slice(0, length); } } else if (t == 10) { // SRATIONAL pointer = unpack(this.endian_mark + "L", value)[0]; if (length > 1) { data = []; for (var x = 0; x < length; x++) { data.push([unpack(this.endian_mark + "l", this.tiftag.slice(pointer + x * 8, pointer + 4 + x * 8))[0], unpack(this.endian_mark + "l", this.tiftag.slice(pointer + 4 + x * 8, pointer + 8 + x * 8))[0] ]); } } else { data = [unpack(this.endian_mark + "l", this.tiftag.slice(pointer, pointer + 4))[0], unpack(this.endian_mark + "l", this.tiftag.slice(pointer + 4, pointer + 8))[0] ]; } } else { throw ("Exif might be wrong. Got incorrect value " + "type to decode. type:" + t); } if ((data instanceof Array) && (data.length == 1)) { return data[0]; } else { return data; } }, }; if (typeof window !== "undefined" && typeof window.btoa === "function") { var btoa = window.btoa; } if (typeof btoa === "undefined") { var btoa = function (input) { var output = ""; var chr1, chr2, chr3, enc1, enc2, enc3, enc4; var i = 0; var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; while (i < input.length) { chr1 = input.charCodeAt(i++); chr2 = input.charCodeAt(i++); chr3 = input.charCodeAt(i++); enc1 = chr1 >> 2; enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); enc4 = chr3 & 63; if (isNaN(chr2)) { enc3 = enc4 = 64; } else if (isNaN(chr3)) { enc4 = 64; } output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) + keyStr.charAt(enc3) + keyStr.charAt(enc4); } return output; }; } if (typeof window !== "undefined" && typeof window.atob === "function") { var atob = window.atob; } if (typeof atob === "undefined") { var atob = function (input) { var output = ""; var chr1, chr2, chr3; var enc1, enc2, enc3, enc4; var i = 0; var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ""); while (i < input.length) { enc1 = keyStr.indexOf(input.charAt(i++)); enc2 = keyStr.indexOf(input.charAt(i++)); enc3 = keyStr.indexOf(input.charAt(i++)); enc4 = keyStr.indexOf(input.charAt(i++)); chr1 = (enc1 << 2) | (enc2 >> 4); chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); chr3 = ((enc3 & 3) << 6) | enc4; output = output + String.fromCharCode(chr1); if (enc3 != 64) { output = output + String.fromCharCode(chr2); } if (enc4 != 64) { output = output + String.fromCharCode(chr3); } } return output; }; } function getImageSize(imageArray) { var segments = slice2Segments(imageArray); var seg, width, height, SOF = [192, 193, 194, 195, 197, 198, 199, 201, 202, 203, 205, 206, 207]; for (var x = 0; x < segments.length; x++) { seg = segments[x]; if (SOF.indexOf(seg[1]) >= 0) { height = seg[5] * 256 + seg[6]; width = seg[7] * 256 + seg[8]; break; } } return [width, height]; } function pack(mark, array) { if (!(array instanceof Array)) { throw ("'pack' error. Got invalid type argument."); } if ((mark.length - 1) != array.length) { throw ("'pack' error. " + (mark.length - 1) + " marks, " + array.length + " elements."); } var littleEndian; if (mark[0] == "<") { littleEndian = true; } else if (mark[0] == ">") { littleEndian = false; } else { throw (""); } var packed = ""; var p = 1; var val = null; var c = null; var valStr = null; while (c = mark[p]) { if (c.toLowerCase() == "b") { val = array[p - 1]; if ((c == "b") && (val < 0)) { val += 0x100; } if ((val > 0xff) || (val < 0)) { throw ("'pack' error."); } else { valStr = String.fromCharCode(val); } } else if (c == "H") { val = array[p - 1]; if ((val > 0xffff) || (val < 0)) { throw ("'pack' error."); } else { valStr = String.fromCharCode(Math.floor((val % 0x10000) / 0x100)) + String.fromCharCode(val % 0x100); if (littleEndian) { valStr = valStr.split("").reverse().join(""); } } } else if (c.toLowerCase() == "l") { val = array[p - 1]; if ((c == "l") && (val < 0)) { val += 0x100000000; } if ((val > 0xffffffff) || (val < 0)) { throw ("'pack' error."); } else { valStr = String.fromCharCode(Math.floor(val / 0x1000000)) + String.fromCharCode(Math.floor((val % 0x1000000) / 0x10000)) + String.fromCharCode(Math.floor((val % 0x10000) / 0x100)) + String.fromCharCode(val % 0x100); if (littleEndian) { valStr = valStr.split("").reverse().join(""); } } } else { throw ("'pack' error."); } packed += valStr; p += 1; } return packed; } function unpack(mark, str) { if (typeof (str) != "string") { throw ("'unpack' error. Got invalid type argument."); } var l = 0; for (var markPointer = 1; markPointer < mark.length; markPointer++) { if (mark[markPointer].toLowerCase() == "b") { l += 1; } else if (mark[markPointer].toLowerCase() == "h") { l += 2; } else if (mark[markPointer].toLowerCase() == "l") { l += 4; } else { throw ("'unpack' error. Got invalid mark."); } } if (l != str.length) { throw ("'unpack' error. Mismatch between symbol and string length. " + l + ":" + str.length); } var littleEndian; if (mark[0] == "<") { littleEndian = true; } else if (mark[0] == ">") { littleEndian = false; } else { throw ("'unpack' error."); } var unpacked = []; var strPointer = 0; var p = 1; var val = null; var c = null; var length = null; var sliced = ""; while (c = mark[p]) { if (c.toLowerCase() == "b") { length = 1; sliced = str.slice(strPointer, strPointer + length); val = sliced.charCodeAt(0); if ((c == "b") && (val >= 0x80)) { val -= 0x100; } } else if (c == "H") { length = 2; sliced = str.slice(strPointer, strPointer + length); if (littleEndian) { sliced = sliced.split("").reverse().join(""); } val = sliced.charCodeAt(0) * 0x100 + sliced.charCodeAt(1); } else if (c.toLowerCase() == "l") { length = 4; sliced = str.slice(strPointer, strPointer + length); if (littleEndian) { sliced = sliced.split("").reverse().join(""); } val = sliced.charCodeAt(0) * 0x1000000 + sliced.charCodeAt(1) * 0x10000 + sliced.charCodeAt(2) * 0x100 + sliced.charCodeAt(3); if ((c == "l") && (val >= 0x80000000)) { val -= 0x100000000; } } else { throw ("'unpack' error. " + c); } unpacked.push(val); strPointer += length; p += 1; } return unpacked; } function nStr(ch, num) { var str = ""; for (var i = 0; i < num; i++) { str += ch; } return str; } function splitIntoSegments(data) { if (data.slice(0, 2) != "\xff\xd8") { throw ("Given data isn't JPEG."); } var head = 2; var segments = ["\xff\xd8"]; while (true) { if (data.slice(head, head + 2) == "\xff\xda") { segments.push(data.slice(head)); break; } else { var length = unpack(">H", data.slice(head + 2, head + 4))[0]; var endPoint = head + length + 2; segments.push(data.slice(head, endPoint)); head = endPoint; } if (head >= data.length) { throw ("Wrong JPEG data."); } } return segments; } function getExifSeg(segments) { var seg; for (var i = 0; i < segments.length; i++) { seg = segments[i]; if (seg.slice(0, 2) == "\xff\xe1" && seg.slice(4, 10) == "Exif\x00\x00") { return seg; } } return null; } function mergeSegments(segments, exif) { if (segments[1].slice(0, 2) == "\xff\xe0" && (segments[2].slice(0, 2) == "\xff\xe1" && segments[2].slice(4, 10) == "Exif\x00\x00")) { if (exif) { segments[2] = exif; segments = ["\xff\xd8"].concat(segments.slice(2)); } else if (exif == null) { segments = segments.slice(0, 2).concat(segments.slice(3)); } else { segments = segments.slice(0).concat(segments.slice(2)); } } else if (segments[1].slice(0, 2) == "\xff\xe0") { if (exif) { segments[1] = exif; } } else if (segments[1].slice(0, 2) == "\xff\xe1" && segments[1].slice(4, 10) == "Exif\x00\x00") { if (exif) { segments[1] = exif; } else if (exif == null) { segments = segments.slice(0).concat(segments.slice(2)); } } else { if (exif) { segments = [segments[0], exif].concat(segments.slice(1)); } } return segments.join(""); } function toHex(str) { var hexStr = ""; for (var i = 0; i < str.length; i++) { var h = str.charCodeAt(i); var hex = ((h < 10) ? "0" : "") + h.toString(16); hexStr += hex + " "; } return hexStr; } var TYPES = { "Byte": 1, "Ascii": 2, "Short": 3, "Long": 4, "Rational": 5, "Undefined": 7, "SLong": 9, "SRational": 10 }; var TAGS = { 'Image': { 11: { 'name': 'ProcessingSoftware', 'type': 'Ascii' }, 254: { 'name': 'NewSubfileType', 'type': 'Long' }, 255: { 'name': 'SubfileType', 'type': 'Short' }, 256: { 'name': 'ImageWidth', 'type': 'Long' }, 257: { 'name': 'ImageLength', 'type': 'Long' }, 258: { 'name': 'BitsPerSample', 'type': 'Short' }, 259: { 'name': 'Compression', 'type': 'Short' }, 262: { 'name': 'PhotometricInterpretation', 'type': 'Short' }, 263: { 'name': 'Threshholding', 'type': 'Short' }, 264: { 'name': 'CellWidth', 'type': 'Short' }, 265: { 'name': 'CellLength', 'type': 'Short' }, 266: { 'name': 'FillOrder', 'type': 'Short' }, 269: { 'name': 'DocumentName', 'type': 'Ascii' }, 270: { 'name': 'ImageDescription', 'type': 'Ascii' }, 271: { 'name': 'Make', 'type': 'Ascii' }, 272: { 'name': 'Model', 'type': 'Ascii' }, 273: { 'name': 'StripOffsets', 'type': 'Long' }, 274: { 'name': 'Orientation', 'type': 'Short' }, 277: { 'name': 'SamplesPerPixel', 'type': 'Short' }, 278: { 'name': 'RowsPerStrip', 'type': 'Long' }, 279: { 'name': 'StripByteCounts', 'type': 'Long' }, 282: { 'name': 'XResolution', 'type': 'Rational' }, 283: { 'name': 'YResolution', 'type': 'Rational' }, 284: { 'name': 'PlanarConfiguration', 'type': 'Short' }, 290: { 'name': 'GrayResponseUnit', 'type': 'Short' }, 291: { 'name': 'GrayResponseCurve', 'type': 'Short' }, 292: { 'name': 'T4Options', 'type': 'Long' }, 293: { 'name': 'T6Options', 'type': 'Long' }, 296: { 'name': 'ResolutionUnit', 'type': 'Short' }, 301: { 'name': 'TransferFunction', 'type': 'Short' }, 305: { 'name': 'Software', 'type': 'Ascii' }, 306: { 'name': 'DateTime', 'type': 'Ascii' }, 315: { 'name': 'Artist', 'type': 'Ascii' }, 316: { 'name': 'HostComputer', 'type': 'Ascii' }, 317: { 'name': 'Predictor', 'type': 'Short' }, 318: { 'name': 'WhitePoint', 'type': 'Rational' }, 319: { 'name': 'PrimaryChromaticities', 'type': 'Rational' }, 320: { 'name': 'ColorMap', 'type': 'Short' }, 321: { 'name': 'HalftoneHints', 'type': 'Short' }, 322: { 'name': 'TileWidth', 'type': 'Short' }, 323: { 'name': 'TileLength', 'type': 'Short' }, 324: { 'name': 'TileOffsets', 'type': 'Short' }, 325: { 'name': 'TileByteCounts', 'type': 'Short' }, 330: { 'name': 'SubIFDs', 'type': 'Long' }, 332: { 'name': 'InkSet', 'type': 'Short' }, 333: { 'name': 'InkNames', 'type': 'Ascii' }, 334: { 'name': 'NumberOfInks', 'type': 'Short' }, 336: { 'name': 'DotRange', 'type': 'Byte' }, 337: { 'name': 'TargetPrinter', 'type': 'Ascii' }, 338: { 'name': 'ExtraSamples', 'type': 'Short' }, 339: { 'name': 'SampleFormat', 'type': 'Short' }, 340: { 'name': 'SMinSampleValue', 'type': 'Short' }, 341: { 'name': 'SMaxSampleValue', 'type': 'Short' }, 342: { 'name': 'TransferRange', 'type': 'Short' }, 343: { 'name': 'ClipPath', 'type': 'Byte' }, 344: { 'name': 'XClipPathUnits', 'type': 'Long' }, 345: { 'name': 'YClipPathUnits', 'type': 'Long' }, 346: { 'name': 'Indexed', 'type': 'Short' }, 347: { 'name': 'JPEGTables', 'type': 'Undefined' }, 351: { 'name': 'OPIProxy', 'type': 'Short' }, 512: { 'name': 'JPEGProc', 'type': 'Long' }, 513: { 'name': 'JPEGInterchangeFormat', 'type': 'Long' }, 514: { 'name': 'JPEGInterchangeFormatLength', 'type': 'Long' }, 515: { 'name': 'JPEGRestartInterval', 'type': 'Short' }, 517: { 'name': 'JPEGLosslessPredictors', 'type': 'Short' }, 518: { 'name': 'JPEGPointTransforms', 'type': 'Short' }, 519: { 'name': 'JPEGQTables', 'type': 'Long' }, 520: { 'name': 'JPEGDCTables', 'type': 'Long' }, 521: { 'name': 'JPEGACTables', 'type': 'Long' }, 529: { 'name': 'YCbCrCoefficients', 'type': 'Rational' }, 530: { 'name': 'YCbCrSubSampling', 'type': 'Short' }, 531: { 'name': 'YCbCrPositioning', 'type': 'Short' }, 532: { 'name': 'ReferenceBlackWhite', 'type': 'Rational' }, 700: { 'name': 'XMLPacket', 'type': 'Byte' }, 18246: { 'name': 'Rating', 'type': 'Short' }, 18249: { 'name': 'RatingPercent', 'type': 'Short' }, 32781: { 'name': 'ImageID', 'type': 'Ascii' }, 33421: { 'name': 'CFARepeatPatternDim', 'type': 'Short' }, 33422: { 'name': 'CFAPattern', 'type': 'Byte' }, 33423: { 'name': 'BatteryLevel', 'type': 'Rational' }, 33432: { 'name': 'Copyright', 'type': 'Ascii' }, 33434: { 'name': 'ExposureTime', 'type': 'Rational' }, 34377: { 'name': 'ImageResources', 'type': 'Byte' }, 34665: { 'name': 'ExifTag', 'type': 'Long' }, 34675: { 'name': 'InterColorProfile', 'type': 'Undefined' }, 34853: { 'name': 'GPSTag', 'type': 'Long' }, 34857: { 'name': 'Interlace', 'type': 'Short' }, 34858: { 'name': 'TimeZoneOffset', 'type': 'Long' }, 34859: { 'name': 'SelfTimerMode', 'type': 'Short' }, 37387: { 'name': 'FlashEnergy', 'type': 'Rational' }, 37388: { 'name': 'SpatialFrequencyResponse', 'type': 'Undefined' }, 37389: { 'name': 'Noise', 'type': 'Undefined' }, 37390: { 'name': 'FocalPlaneXResolution', 'type': 'Rational' }, 37391: { 'name': 'FocalPlaneYResolution', 'type': 'Rational' }, 37392: { 'name': 'FocalPlaneResolutionUnit', 'type': 'Short' }, 37393: { 'name': 'ImageNumber', 'type': 'Long' }, 37394: { 'name': 'SecurityClassification', 'type': 'Ascii' }, 37395: { 'name': 'ImageHistory', 'type': 'Ascii' }, 37397: { 'name': 'ExposureIndex', 'type': 'Rational' }, 37398: { 'name': 'TIFFEPStandardID', 'type': 'Byte' }, 37399: { 'name': 'SensingMethod', 'type': 'Short' }, 40091: { 'name': 'XPTitle', 'type': 'Byte' }, 40092: { 'name': 'XPComment', 'type': 'Byte' }, 40093: { 'name': 'XPAuthor', 'type': 'Byte' }, 40094: { 'name': 'XPKeywords', 'type': 'Byte' }, 40095: { 'name': 'XPSubject', 'type': 'Byte' }, 50341: { 'name': 'PrintImageMatching', 'type': 'Undefined' }, 50706: { 'name': 'DNGVersion', 'type': 'Byte' }, 50707: { 'name': 'DNGBackwardVersion', 'type': 'Byte' }, 50708: { 'name': 'UniqueCameraModel', 'type': 'Ascii' }, 50709: { 'name': 'LocalizedCameraModel', 'type': 'Byte' }, 50710: { 'name': 'CFAPlaneColor', 'type': 'Byte' }, 50711: { 'name': 'CFALayout', 'type': 'Short' }, 50712: { 'name': 'LinearizationTable', 'type': 'Short' }, 50713: { 'name': 'BlackLevelRepeatDim', 'type': 'Short' }, 50714: { 'name': 'BlackLevel', 'type': 'Rational' }, 50715: { 'name': 'BlackLevelDeltaH', 'type': 'SRational' }, 50716: { 'name': 'BlackLevelDeltaV', 'type': 'SRational' }, 50717: { 'name': 'WhiteLevel', 'type': 'Short' }, 50718: { 'name': 'DefaultScale', 'type': 'Rational' }, 50719: { 'name': 'DefaultCropOrigin', 'type': 'Short' }, 50720: { 'name': 'DefaultCropSize', 'type': 'Short' }, 50721: { 'name': 'ColorMatrix1', 'type': 'SRational' }, 50722: { 'name': 'ColorMatrix2', 'type': 'SRational' }, 50723: { 'name': 'CameraCalibration1', 'type': 'SRational' }, 50724: { 'name': 'CameraCalibration2', 'type': 'SRational' }, 50725: { 'name': 'ReductionMatrix1', 'type': 'SRational' }, 50726: { 'name': 'ReductionMatrix2', 'type': 'SRational' }, 50727: { 'name': 'AnalogBalance', 'type': 'Rational' }, 50728: { 'name': 'AsShotNeutral', 'type': 'Short' }, 50729: { 'name': 'AsShotWhiteXY', 'type': 'Rational' }, 50730: { 'name': 'BaselineExposure', 'type': 'SRational' }, 50731: { 'name': 'BaselineNoise', 'type': 'Rational' }, 50732: { 'name': 'BaselineSharpness', 'type': 'Rational' }, 50733: { 'name': 'BayerGreenSplit', 'type': 'Long' }, 50734: { 'name': 'LinearResponseLimit', 'type': 'Rational' }, 50735: { 'name': 'CameraSerialNumber', 'type': 'Ascii' }, 50736: { 'name': 'LensInfo', 'type': 'Rational' }, 50737: { 'name': 'ChromaBlurRadius', 'type': 'Rational' }, 50738: { 'name': 'AntiAliasStrength', 'type': 'Rational' }, 50739: { 'name': 'ShadowScale', 'type': 'SRational' }, 50740: { 'name': 'DNGPrivateData', 'type': 'Byte' }, 50741: { 'name': 'MakerNoteSafety', 'type': 'Short' }, 50778: { 'name': 'CalibrationIlluminant1', 'type': 'Short' }, 50779: { 'name': 'CalibrationIlluminant2', 'type': 'Short' }, 50780: { 'name': 'BestQualityScale', 'type': 'Rational' }, 50781: { 'name': 'RawDataUniqueID', 'type': 'Byte' }, 50827: { 'name': 'OriginalRawFileName', 'type': 'Byte' }, 50828: { 'name': 'OriginalRawFileData', 'type': 'Undefined' }, 50829: { 'name': 'ActiveArea', 'type': 'Short' }, 50830: { 'name': 'MaskedAreas', 'type': 'Short' }, 50831: { 'name': 'AsShotICCProfile', 'type': 'Undefined' }, 50832: { 'name': 'AsShotPreProfileMatrix', 'type': 'SRational' }, 50833: { 'name': 'CurrentICCProfile', 'type': 'Undefined' }, 50834: { 'name': 'CurrentPreProfileMatrix', 'type': 'SRational' }, 50879: { 'name': 'ColorimetricReference', 'type': 'Short' }, 50931: { 'name': 'CameraCalibrationSignature', 'type': 'Byte' }, 50932: { 'name': 'ProfileCalibrationSignature', 'type': 'Byte' }, 50934: { 'name': 'AsShotProfileName', 'type': 'Byte' }, 50935: { 'name': 'NoiseReductionApplied', 'type': 'Rational' }, 50936: { 'name': 'ProfileName', 'type': 'Byte' }, 50937: { 'name': 'ProfileHueSatMapDims', 'type': 'Long' }, 50938: { 'name': 'ProfileHueSatMapData1', 'type': 'Float' }, 50939: { 'name': 'ProfileHueSatMapData2', 'type': 'Float' }, 50940: { 'name': 'ProfileToneCurve', 'type': 'Float' }, 50941: { 'name': 'ProfileEmbedPolicy', 'type': 'Long' }, 50942: { 'name': 'ProfileCopyright', 'type': 'Byte' }, 50964: { 'name': 'ForwardMatrix1', 'type': 'SRational' }, 50965: { 'name': 'ForwardMatrix2', 'type': 'SRational' }, 50966: { 'name': 'PreviewApplicationName', 'type': 'Byte' }, 50967: { 'name': 'PreviewApplicationVersion', 'type': 'Byte' }, 50968: { 'name': 'PreviewSettingsName', 'type': 'Byte' }, 50969: { 'name': 'PreviewSettingsDigest', 'type': 'Byte' }, 50970: { 'name': 'PreviewColorSpace', 'type': 'Long' }, 50971: { 'name': 'PreviewDateTime', 'type': 'Ascii' }, 50972: { 'name': 'RawImageDigest', 'type': 'Undefined' }, 50973: { 'name': 'OriginalRawFileDigest', 'type': 'Undefined' }, 50974: { 'name': 'SubTileBlockSize', 'type': 'Long' }, 50975: { 'name': 'RowInterleaveFactor', 'type': 'Long' }, 50981: { 'name': 'ProfileLookTableDims', 'type': 'Long' }, 50982: { 'name': 'ProfileLookTableData', 'type': 'Float' }, 51008: { 'name': 'OpcodeList1', 'type': 'Undefined' }, 51009: { 'name': 'OpcodeList2', 'type': 'Undefined' }, 51022: { 'name': 'OpcodeList3', 'type': 'Undefined' } }, 'Exif': { 33434: { 'name': 'ExposureTime', 'type': 'Rational' }, 33437: { 'name': 'FNumber', 'type': 'Rational' }, 34850: { 'name': 'ExposureProgram', 'type': 'Short' }, 34852: { 'name': 'SpectralSensitivity', 'type': 'Ascii' }, 34855: { 'name': 'ISOSpeedRatings', 'type': 'Short' }, 34856: { 'name': 'OECF', 'type': 'Undefined' }, 34864: { 'name': 'SensitivityType', 'type': 'Short' }, 34865: { 'name': 'StandardOutputSensitivity', 'type': 'Long' }, 34866: { 'name': 'RecommendedExposureIndex', 'type': 'Long' }, 34867: { 'name': 'ISOSpeed', 'type': 'Long' }, 34868: { 'name': 'ISOSpeedLatitudeyyy', 'type': 'Long' }, 34869: { 'name': 'ISOSpeedLatitudezzz', 'type': 'Long' }, 36864: { 'name': 'ExifVersion', 'type': 'Undefined' }, 36867: { 'name': 'DateTimeOriginal', 'type': 'Ascii' }, 36868: { 'name': 'DateTimeDigitized', 'type': 'Ascii' }, 37121: { 'name': 'ComponentsConfiguration', 'type': 'Undefined' }, 37122: { 'name': 'CompressedBitsPerPixel', 'type': 'Rational' }, 37377: { 'name': 'ShutterSpeedValue', 'type': 'SRational' }, 37378: { 'name': 'ApertureValue', 'type': 'Rational' }, 37379: { 'name': 'BrightnessValue', 'type': 'SRational' }, 37380: { 'name': 'ExposureBiasValue', 'type': 'SRational' }, 37381: { 'name': 'MaxApertureValue', 'type': 'Rational' }, 37382: { 'name': 'SubjectDistance', 'type': 'Rational' }, 37383: { 'name': 'MeteringMode', 'type': 'Short' }, 37384: { 'name': 'LightSource', 'type': 'Short' }, 37385: { 'name': 'Flash', 'type': 'Short' }, 37386: { 'name': 'FocalLength', 'type': 'Rational' }, 37396: { 'name': 'SubjectArea', 'type': 'Short' }, 37500: { 'name': 'MakerNote', 'type': 'Undefined' }, 37510: { 'name': 'UserComment', 'type': 'Ascii' }, 37520: { 'name': 'SubSecTime', 'type': 'Ascii' }, 37521: { 'name': 'SubSecTimeOriginal', 'type': 'Ascii' }, 37522: { 'name': 'SubSecTimeDigitized', 'type': 'Ascii' }, 40960: { 'name': 'FlashpixVersion', 'type': 'Undefined' }, 40961: { 'name': 'ColorSpace', 'type': 'Short' }, 40962: { 'name': 'PixelXDimension', 'type': 'Long' }, 40963: { 'name': 'PixelYDimension', 'type': 'Long' }, 40964: { 'name': 'RelatedSoundFile', 'type': 'Ascii' }, 40965: { 'name': 'InteroperabilityTag', 'type': 'Long' }, 41483: { 'name': 'FlashEnergy', 'type': 'Rational' }, 41484: { 'name': 'SpatialFrequencyResponse', 'type': 'Undefined' }, 41486: { 'name': 'FocalPlaneXResolution', 'type': 'Rational' }, 41487: { 'name': 'FocalPlaneYResolution', 'type': 'Rational' }, 41488: { 'name': 'FocalPlaneResolutionUnit', 'type': 'Short' }, 41492: { 'name': 'SubjectLocation', 'type': 'Short' }, 41493: { 'name': 'ExposureIndex', 'type': 'Rational' }, 41495: { 'name': 'SensingMethod', 'type': 'Short' }, 41728: { 'name': 'FileSource', 'type': 'Undefined' }, 41729: { 'name': 'SceneType', 'type': 'Undefined' }, 41730: { 'name': 'CFAPattern', 'type': 'Undefined' }, 41985: { 'name': 'CustomRendered', 'type': 'Short' }, 41986: { 'name': 'ExposureMode', 'type': 'Short' }, 41987: { 'name': 'WhiteBalance', 'type': 'Short' }, 41988: { 'name': 'DigitalZoomRatio', 'type': 'Rational' }, 41989: { 'name': 'FocalLengthIn35mmFilm', 'type': 'Short' }, 41990: { 'name': 'SceneCaptureType', 'type': 'Short' }, 41991: { 'name': 'GainControl', 'type': 'Short' }, 41992: { 'name': 'Contrast', 'type': 'Short' }, 41993: { 'name': 'Saturation', 'type': 'Short' }, 41994: { 'name': 'Sharpness', 'type': 'Short' }, 41995: { 'name': 'DeviceSettingDescription', 'type': 'Undefined' }, 41996: { 'name': 'SubjectDistanceRange', 'type': 'Short' }, 42016: { 'name': 'ImageUniqueID', 'type': 'Ascii' }, 42032: { 'name': 'CameraOwnerName', 'type': 'Ascii' }, 42033: { 'name': 'BodySerialNumber', 'type': 'Ascii' }, 42034: { 'name': 'LensSpecification', 'type': 'Rational' }, 42035: { 'name': 'LensMake', 'type': 'Ascii' }, 42036: { 'name': 'LensModel', 'type': 'Ascii' }, 42037: { 'name': 'LensSerialNumber', 'type': 'Ascii' }, 42240: { 'name': 'Gamma', 'type': 'Rational' } }, 'GPS': { 0: { 'name': 'GPSVersionID', 'type': 'Byte' }, 1: { 'name': 'GPSLatitudeRef', 'type': 'Ascii' }, 2: { 'name': 'GPSLatitude', 'type': 'Rational' }, 3: { 'name': 'GPSLongitudeRef', 'type': 'Ascii' }, 4: { 'name': 'GPSLongitude', 'type': 'Rational' }, 5: { 'name': 'GPSAltitudeRef', 'type': 'Byte' }, 6: { 'name': 'GPSAltitude', 'type': 'Rational' }, 7: { 'name': 'GPSTimeStamp', 'type': 'Rational' }, 8: { 'name': 'GPSSatellites', 'type': 'Ascii' }, 9: { 'name': 'GPSStatus', 'type': 'Ascii' }, 10: { 'name': 'GPSMeasureMode', 'type': 'Ascii' }, 11: { 'name': 'GPSDOP', 'type': 'Rational' }, 12: { 'name': 'GPSSpeedRef', 'type': 'Ascii' }, 13: { 'name': 'GPSSpeed', 'type': 'Rational' }, 14: { 'name': 'GPSTrackRef', 'type': 'Ascii' }, 15: { 'name': 'GPSTrack', 'type': 'Rational' }, 16: { 'name': 'GPSImgDirectionRef', 'type': 'Ascii' }, 17: { 'name': 'GPSImgDirection', 'type': 'Rational' }, 18: { 'name': 'GPSMapDatum', 'type': 'Ascii' }, 19: { 'name': 'GPSDestLatitudeRef', 'type': 'Ascii' }, 20: { 'name': 'GPSDestLatitude', 'type': 'Rational' }, 21: { 'name': 'GPSDestLongitudeRef', 'type': 'Ascii' }, 22: { 'name': 'GPSDestLongitude', 'type': 'Rational' }, 23: { 'name': 'GPSDestBearingRef', 'type': 'Ascii' }, 24: { 'name': 'GPSDestBearing', 'type': 'Rational' }, 25: { 'name': 'GPSDestDistanceRef', 'type': 'Ascii' }, 26: { 'name': 'GPSDestDistance', 'type': 'Rational' }, 27: { 'name': 'GPSProcessingMethod', 'type': 'Undefined' }, 28: { 'name': 'GPSAreaInformation', 'type': 'Undefined' }, 29: { 'name': 'GPSDateStamp', 'type': 'Ascii' }, 30: { 'name': 'GPSDifferential', 'type': 'Short' }, 31: { 'name': 'GPSHPositioningError', 'type': 'Rational' } }, 'Interop': { 1: { 'name': 'InteroperabilityIndex', 'type': 'Ascii' } }, }; TAGS["0th"] = TAGS["Image"]; TAGS["1st"] = TAGS["Image"]; that.TAGS = TAGS; that.ImageIFD = { ProcessingSoftware:11, NewSubfileType:254, SubfileType:255, ImageWidth:256, ImageLength:257, BitsPerSample:258, Compression:259, PhotometricInterpretation:262, Threshholding:263, CellWidth:264, CellLength:265, FillOrder:266, DocumentName:269, ImageDescription:270, Make:271, Model:272, StripOffsets:273, Orientation:274, SamplesPerPixel:277, RowsPerStrip:278, StripByteCounts:279, XResolution:282, YResolution:283, PlanarConfiguration:284, GrayResponseUnit:290, GrayResponseCurve:291, T4Options:292, T6Options:293, ResolutionUnit:296, TransferFunction:301, Software:305, DateTime:306, Artist:315, HostComputer:316, Predictor:317, WhitePoint:318, PrimaryChromaticities:319, ColorMap:320, HalftoneHints:321, TileWidth:322, TileLength:323, TileOffsets:324, TileByteCounts:325, SubIFDs:330, InkSet:332, InkNames:333, NumberOfInks:334, DotRange:336, TargetPrinter:337, ExtraSamples:338, SampleFormat:339, SMinSampleValue:340, SMaxSampleValue:341, TransferRange:342, ClipPath:343, XClipPathUnits:344, YClipPathUnits:345, Indexed:346, JPEGTables:347, OPIProxy:351, JPEGProc:512, JPEGInterchangeFormat:513, JPEGInterchangeFormatLength:514, JPEGRestartInterval:515, JPEGLosslessPredictors:517, JPEGPointTransforms:518, JPEGQTables:519, JPEGDCTables:520, JPEGACTables:521, YCbCrCoefficients:529, YCbCrSubSampling:530, YCbCrPositioning:531, ReferenceBlackWhite:532, XMLPacket:700, Rating:18246, RatingPercent:18249, ImageID:32781, CFARepeatPatternDim:33421, CFAPattern:33422, BatteryLevel:33423, Copyright:33432, ExposureTime:33434, ImageResources:34377, ExifTag:34665, InterColorProfile:34675, GPSTag:34853, Interlace:34857, TimeZoneOffset:34858, SelfTimerMode:34859, FlashEnergy:37387, SpatialFrequencyResponse:37388, Noise:37389, FocalPlaneXResolution:37390, FocalPlaneYResolution:37391, FocalPlaneResolutionUnit:37392, ImageNumber:37393, SecurityClassification:37394, ImageHistory:37395, ExposureIndex:37397, TIFFEPStandardID:37398, SensingMethod:37399, XPTitle:40091, XPComment:40092, XPAuthor:40093, XPKeywords:40094, XPSubject:40095, PrintImageMatching:50341, DNGVersion:50706, DNGBackwardVersion:50707, UniqueCameraModel:50708, LocalizedCameraModel:50709, CFAPlaneColor:50710, CFALayout:50711, LinearizationTable:50712, BlackLevelRepeatDim:50713, BlackLevel:50714, BlackLevelDeltaH:50715, BlackLevelDeltaV:50716, WhiteLevel:50717, DefaultScale:50718, DefaultCropOrigin:50719, DefaultCropSize:50720, ColorMatrix1:50721, ColorMatrix2:50722, CameraCalibration1:50723, CameraCalibration2:50724, ReductionMatrix1:50725, ReductionMatrix2:50726, AnalogBalance:50727, AsShotNeutral:50728, AsShotWhiteXY:50729, BaselineExposure:50730, BaselineNoise:50731, BaselineSharpness:50732, BayerGreenSplit:50733, LinearResponseLimit:50734, CameraSerialNumber:50735, LensInfo:50736, ChromaBlurRadius:50737, AntiAliasStrength:50738, ShadowScale:50739, DNGPrivateData:50740, MakerNoteSafety:50741, CalibrationIlluminant1:50778, CalibrationIlluminant2:50779, BestQualityScale:50780, RawDataUniqueID:50781, OriginalRawFileName:50827, OriginalRawFileData:50828, ActiveArea:50829, MaskedAreas:50830, AsShotICCProfile:50831, AsShotPreProfileMatrix:50832, CurrentICCProfile:50833, CurrentPreProfileMatrix:50834, ColorimetricReference:50879, CameraCalibrationSignature:50931, ProfileCalibrationSignature:50932, AsShotProfileName:50934, NoiseReductionApplied:50935, ProfileName:50936, ProfileHueSatMapDims:50937, ProfileHueSatMapData1:50938, ProfileHueSatMapData2:50939, ProfileToneCurve:50940, ProfileEmbedPolicy:50941, ProfileCopyright:50942, ForwardMatrix1:50964, ForwardMatrix2:50965, PreviewApplicationName:50966, PreviewApplicationVersion:50967, PreviewSettingsName:50968, PreviewSettingsDigest:50969, PreviewColorSpace:50970, PreviewDateTime:50971, RawImageDigest:50972, OriginalRawFileDigest:50973, SubTileBlockSize:50974, RowInterleaveFactor:50975, ProfileLookTableDims:50981, ProfileLookTableData:50982, OpcodeList1:51008, OpcodeList2:51009, OpcodeList3:51022, NoiseProfile:51041, }; that.ExifIFD = { ExposureTime:33434, FNumber:33437, ExposureProgram:34850, SpectralSensitivity:34852, ISOSpeedRatings:34855, OECF:34856, SensitivityType:34864, StandardOutputSensitivity:34865, RecommendedExposureIndex:34866, ISOSpeed:34867, ISOSpeedLatitudeyyy:34868, ISOSpeedLatitudezzz:34869, ExifVersion:36864, DateTimeOriginal:36867, DateTimeDigitized:36868, ComponentsConfiguration:37121, CompressedBitsPerPixel:37122, ShutterSpeedValue:37377, ApertureValue:37378, BrightnessValue:37379, ExposureBiasValue:37380, MaxApertureValue:37381, SubjectDistance:37382, MeteringMode:37383, LightSource:37384, Flash:37385, FocalLength:37386, SubjectArea:37396, MakerNote:37500, UserComment:37510, SubSecTime:37520, SubSecTimeOriginal:37521, SubSecTimeDigitized:37522, FlashpixVersion:40960, ColorSpace:40961, PixelXDimension:40962, PixelYDimension:40963, RelatedSoundFile:40964, InteroperabilityTag:40965, FlashEnergy:41483, SpatialFrequencyResponse:41484, FocalPlaneXResolution:41486, FocalPlaneYResolution:41487, FocalPlaneResolutionUnit:41488, SubjectLocation:41492, ExposureIndex:41493, SensingMethod:41495, FileSource:41728, SceneType:41729, CFAPattern:41730, CustomRendered:41985, ExposureMode:41986, WhiteBalance:41987, DigitalZoomRatio:41988, FocalLengthIn35mmFilm:41989, SceneCaptureType:41990, GainControl:41991, Contrast:41992, Saturation:41993, Sharpness:41994, DeviceSettingDescription:41995, SubjectDistanceRange:41996, ImageUniqueID:42016, CameraOwnerName:42032, BodySerialNumber:42033, LensSpecification:42034, LensMake:42035, LensModel:42036, LensSerialNumber:42037, Gamma:42240, }; that.GPSIFD = { GPSVersionID:0, GPSLatitudeRef:1, GPSLatitude:2, GPSLongitudeRef:3, GPSLongitude:4, GPSAltitudeRef:5, GPSAltitude:6, GPSTimeStamp:7, GPSSatellites:8, GPSStatus:9, GPSMeasureMode:10, GPSDOP:11, GPSSpeedRef:12, GPSSpeed:13, GPSTrackRef:14, GPSTrack:15, GPSImgDirectionRef:16, GPSImgDirection:17, GPSMapDatum:18, GPSDestLatitudeRef:19, GPSDestLatitude:20, GPSDestLongitudeRef:21, GPSDestLongitude:22, GPSDestBearingRef:23, GPSDestBearing:24, GPSDestDistanceRef:25, GPSDestDistance:26, GPSProcessingMethod:27, GPSAreaInformation:28, GPSDateStamp:29, GPSDifferential:30, GPSHPositioningError:31, }; that.InteropIFD = { InteroperabilityIndex:1, }; that.GPSHelper = { degToDmsRational:function (degFloat) { var minFloat = degFloat % 1 * 60; var secFloat = minFloat % 1 * 60; var deg = Math.floor(degFloat); var min = Math.floor(minFloat); var sec = Math.round(secFloat * 100); return [[deg, 1], [min, 1], [sec, 100]]; } }; if (typeof exports !== 'undefined') { if (typeof module !== 'undefined' && module.exports) { exports = module.exports = that; } exports.piexif = that; } else { window.piexif = that; } })(); !function(){"use strict";function e(e){return JSON.parse(JSON.stringify(e))}function t(e){for(var t=y(e);"ÿà"<=t[1].slice(0,2)&&t[1].slice(0,2)<="ÿï";)t=[t[0]].concat(t.slice(2));return t.join("")}function a(e){return s(">"+p("B",e.length),e)}function i(e){return s(">"+p("H",e.length),e)}function n(e){return s(">"+p("L",e.length),e)}function r(e,t,r){var o,l,m,y,c="",S="";if("Byte"==t)o=e.length,4>=o?S=a(e)+p("\x00",4-o):(S=s(">L",[r]),c=a(e));else if("Short"==t)o=e.length,2>=o?S=i(e)+p("\x00\x00",2-o):(S=s(">L",[r]),c=i(e));else if("Long"==t)o=e.length,1>=o?S=n(e):(S=s(">L",[r]),c=n(e));else if("Ascii"==t)l=e+"\x00",o=l.length,o>4?(S=s(">L",[r]),c=l):S=l+p("\x00",4-o);else if("Rational"==t){if("number"==typeof e[0])o=1,m=e[0],y=e[1],l=s(">L",[m])+s(">L",[y]);else{o=e.length,l="";for(var f=0;o>f;f++)m=e[f][0],y=e[f][1],l+=s(">L",[m])+s(">L",[y])}S=s(">L",[r]),c=l}else if("SRational"==t){if("number"==typeof e[0])o=1,m=e[0],y=e[1],l=s(">l",[m])+s(">l",[y]);else{o=e.length,l="";for(var f=0;o>f;f++)m=e[f][0],y=e[f][1],l+=s(">l",[m])+s(">l",[y])}S=s(">L",[r]),c=l}else"Undefined"==t&&(o=e.length,o>4?(S=s(">L",[r]),c=e):S=e+p("\x00",4-o));var h=s(">L",[o]);return[h,S,c]}function o(e,t,a){var i,n=8,o=Object.keys(e).length,l=s(">H",[o]);i=["0th","1st"].indexOf(t)>-1?2+12*o+4:2+12*o;var m,p="",y="";for(var m in e)if("string"==typeof m&&(m=parseInt(m)),!("0th"==t&&[34665,34853].indexOf(m)>-1||"Exif"==t&&40965==m||"1st"==t&&[513,514].indexOf(m)>-1)){var c=e[m],S=s(">H",[m]),f=u[t][m].type,h=s(">H",[g[f]]);"number"==typeof c&&(c=[c]);var d=n+i+a+y.length,P=r(c,f,d),C=P[0],R=P[1],L=P[2];p+=S+h+C+R,y+=L}return[l+p,y]}function l(e){var t,a;if("ÿØ"==e.slice(0,2))t=y(e),a=c(t),a?this.tiftag=a.slice(10):this.tiftag=null;else if(["II","MM"].indexOf(e.slice(0,2))>-1)this.tiftag=e;else{if("Exif"!=e.slice(0,4))throw"Given file is neither JPEG nor TIFF.";this.tiftag=e.slice(6)}}function s(e,t){if(!(t instanceof Array))throw"'pack' error. Got invalid type argument.";if(e.length-1!=t.length)throw"'pack' error. "+(e.length-1)+" marks, "+t.length+" elements.";var a;if("<"==e[0])a=!0;else{if(">"!=e[0])throw"";a=!1}for(var i="",n=1,r=null,o=null,l=null;o=e[n];){if("b"==o.toLowerCase()){if(r=t[n-1],"b"==o&&0>r&&(r+=256),r>255||0>r)throw"'pack' error.";l=String.fromCharCode(r)}else if("H"==o){if(r=t[n-1],r>65535||0>r)throw"'pack' error.";l=String.fromCharCode(Math.floor(r%65536/256))+String.fromCharCode(r%256),a&&(l=l.split("").reverse().join(""))}else{if("l"!=o.toLowerCase())throw"'pack' error.";if(r=t[n-1],"l"==o&&0>r&&(r+=4294967296),r>4294967295||0>r)throw"'pack' error.";l=String.fromCharCode(Math.floor(r/16777216))+String.fromCharCode(Math.floor(r%16777216/65536))+String.fromCharCode(Math.floor(r%65536/256))+String.fromCharCode(r%256),a&&(l=l.split("").reverse().join(""))}i+=l,n+=1}return i}function m(e,t){if("string"!=typeof t)throw"'unpack' error. Got invalid type argument.";for(var a=0,i=1;i"!=e[0])throw"'unpack' error.";n=!1}for(var r=[],o=0,l=1,s=null,m=null,p=null,y="";m=e[l];){if("b"==m.toLowerCase())p=1,y=t.slice(o,o+p),s=y.charCodeAt(0),"b"==m&&s>=128&&(s-=256);else if("H"==m)p=2,y=t.slice(o,o+p),n&&(y=y.split("").reverse().join("")),s=256*y.charCodeAt(0)+y.charCodeAt(1);else{if("l"!=m.toLowerCase())throw"'unpack' error. "+m;p=4,y=t.slice(o,o+p),n&&(y=y.split("").reverse().join("")),s=16777216*y.charCodeAt(0)+65536*y.charCodeAt(1)+256*y.charCodeAt(2)+y.charCodeAt(3),"l"==m&&s>=2147483648&&(s-=4294967296)}r.push(s),o+=p,l+=1}return r}function p(e,t){for(var a="",i=0;t>i;i++)a+=e;return a}function y(e){if("ÿØ"!=e.slice(0,2))throw"Given data isn't JPEG.";for(var t=2,a=["ÿØ"];;){if("ÿÚ"==e.slice(t,t+2)){a.push(e.slice(t));break}var i=m(">H",e.slice(t+2,t+4))[0],n=t+i+2;if(a.push(e.slice(t,n)),t=n,t>=e.length)throw"Wrong JPEG data."}return a}function c(e){for(var t,a=0;aH",[e.length+2])+e,n=y(t),r=S(n,i);return a&&(r="data:image/jpeg;base64,"+h(r)),r},f.load=function(e){var t;if("string"!=typeof e)throw"'load' gots invalid type argument.";if("ÿØ"==e.slice(0,2))t=e;else if("data:image/jpeg;base64,"==e.slice(0,23)||"data:image/jpg;base64,"==e.slice(0,22))t=d(e.split(",")[1]);else{if("Exif"!=e.slice(0,4))throw"'load' gots invalid file data.";t=e.slice(6)}var a={"0th":{},Exif:{},GPS:{},Interop:{},"1st":{},thumbnail:null},i=new l(t);if(null===i.tiftag)return a;"II"==i.tiftag.slice(0,2)?i.endian_mark="<":i.endian_mark=">";var n=m(i.endian_mark+"L",i.tiftag.slice(4,8))[0];a["0th"]=i.get_ifd(n,"0th");var r=a["0th"].first_ifd_pointer;if(delete a["0th"].first_ifd_pointer,34665 in a["0th"]&&(n=a["0th"][34665],a.Exif=i.get_ifd(n,"Exif")),34853 in a["0th"]&&(n=a["0th"][34853],a.GPS=i.get_ifd(n,"GPS")),40965 in a.Exif&&(n=a.Exif[40965],a.Interop=i.get_ifd(n,"Interop")),"\x00\x00\x00\x00"!=r&&(n=m(i.endian_mark+"L",r)[0],a["1st"]=i.get_ifd(n,"1st"),513 in a["1st"]&&514 in a["1st"])){var o=a["1st"][513]+a["1st"][514],s=i.tiftag.slice(a["1st"][513],o);a.thumbnail=s}return a},f.dump=function(a){var i,n,r,l,m,p=8,y=e(a),c="Exif\x00\x00MM\x00*\x00\x00\x00\b",S=!1,h=!1,d=!1,u=!1;i="0th"in y?y["0th"]:{},"Exif"in y&&Object.keys(y.Exif).length||"Interop"in y&&Object.keys(y.Interop).length?(i[34665]=1,S=!0,n=y.Exif,"Interop"in y&&Object.keys(y.Interop).length?(n[40965]=1,d=!0,r=y.Interop):Object.keys(n).indexOf(f.ExifIFD.InteroperabilityTag.toString())>-1&&delete n[40965]):Object.keys(i).indexOf(f.ImageIFD.ExifTag.toString())>-1&&delete i[34665],"GPS"in y&&Object.keys(y.GPS).length?(i[f.ImageIFD.GPSTag]=1,h=!0,l=y.GPS):Object.keys(i).indexOf(f.ImageIFD.GPSTag.toString())>-1&&delete i[f.ImageIFD.GPSTag],"1st"in y&&"thumbnail"in y&&null!=y.thumbnail&&(u=!0,y["1st"][513]=1,y["1st"][514]=1,m=y["1st"]);var P,C,R,L,x,I=o(i,"0th",0),D=I[0].length+12*S+12*h+4+I[1].length,G="",A=0,v="",b=0,T="",k=0,w="";if(S&&(P=o(n,"Exif",D),A=P[0].length+12*d+P[1].length),h&&(C=o(l,"GPS",D+A),v=C.join(""),b=v.length),d){var F=D+A+b;R=o(r,"Interop",F),T=R.join(""),k=T.length}if(u){var F=D+A+b+k;if(L=o(m,"1st",F),x=t(y.thumbnail),x.length>64e3)throw"Given thumbnail is too large. max 64kB"}var B="",E="",M="",O="\x00\x00\x00\x00";if(S){var N=p+D,U=s(">L",[N]),_=34665,H=s(">H",[_]),j=s(">H",[g.Long]),V=s(">L",[1]);B=H+j+V+U}if(h){var N=p+D+A,U=s(">L",[N]),_=34853,H=s(">H",[_]),j=s(">H",[g.Long]),V=s(">L",[1]);E=H+j+V+U}if(d){var N=p+D+A+b,U=s(">L",[N]),_=40965,H=s(">H",[_]),j=s(">H",[g.Long]),V=s(">L",[1]);M=H+j+V+U}if(u){var N=p+D+A+b+k;O=s(">L",[N]);var J=N+L[0].length+24+4+L[1].length,X="\x00\x00\x00\x00"+s(">L",[J]),z="\x00\x00\x00\x00"+s(">L",[x.length]);w=L[0]+X+z+"\x00\x00\x00\x00"+L[1]+x}var Y=I[0]+B+E+O+I[1];return S&&(G=P[0]+M+P[1]),c+Y+G+v+T+w},l.prototype={get_ifd:function(e,t){var a,i={},n=m(this.endian_mark+"H",this.tiftag.slice(e,e+2))[0],r=e+2;a=["0th","1st"].indexOf(t)>-1?"Image":t;for(var o=0;n>o;o++){e=r+12*o;var l=m(this.endian_mark+"H",this.tiftag.slice(e,e+2))[0],s=m(this.endian_mark+"H",this.tiftag.slice(e+2,e+4))[0],p=m(this.endian_mark+"L",this.tiftag.slice(e+4,e+8))[0],y=this.tiftag.slice(e+8,e+12),c=[s,p,y];l in u[a]&&(i[l]=this.convert_value(c))}return"0th"==t&&(e=r+12*n,i.first_ifd_pointer=this.tiftag.slice(e,e+4)),i},convert_value:function(e){var t,a=null,i=e[0],n=e[1],r=e[2];if(1==i)n>4?(t=m(this.endian_mark+"L",r)[0],a=m(this.endian_mark+p("B",n),this.tiftag.slice(t,t+n))):a=m(this.endian_mark+p("B",n),r.slice(0,n));else if(2==i)n>4?(t=m(this.endian_mark+"L",r)[0],a=this.tiftag.slice(t,t+n-1)):a=r.slice(0,n-1);else if(3==i)n>2?(t=m(this.endian_mark+"L",r)[0],a=m(this.endian_mark+p("H",n),this.tiftag.slice(t,t+2*n))):a=m(this.endian_mark+p("H",n),r.slice(0,2*n));else if(4==i)n>1?(t=m(this.endian_mark+"L",r)[0],a=m(this.endian_mark+p("L",n),this.tiftag.slice(t,t+4*n))):a=m(this.endian_mark+p("L",n),r);else if(5==i)if(t=m(this.endian_mark+"L",r)[0],n>1){a=[];for(var o=0;n>o;o++)a.push([m(this.endian_mark+"L",this.tiftag.slice(t+8*o,t+4+8*o))[0],m(this.endian_mark+"L",this.tiftag.slice(t+4+8*o,t+8+8*o))[0]])}else a=[m(this.endian_mark+"L",this.tiftag.slice(t,t+4))[0],m(this.endian_mark+"L",this.tiftag.slice(t+4,t+8))[0]];else if(7==i)n>4?(t=m(this.endian_mark+"L",r)[0],a=this.tiftag.slice(t,t+n)):a=r.slice(0,n);else{if(10!=i)throw"Exif might be wrong. Got incorrect value type to decode. type:"+i;if(t=m(this.endian_mark+"L",r)[0],n>1){a=[];for(var o=0;n>o;o++)a.push([m(this.endian_mark+"l",this.tiftag.slice(t+8*o,t+4+8*o))[0],m(this.endian_mark+"l",this.tiftag.slice(t+4+8*o,t+8+8*o))[0]])}else a=[m(this.endian_mark+"l",this.tiftag.slice(t,t+4))[0],m(this.endian_mark+"l",this.tiftag.slice(t+4,t+8))[0]]}return a instanceof Array&&1==a.length?a[0]:a}},"undefined"!=typeof window&&"function"==typeof window.btoa)var h=window.btoa;if("undefined"==typeof h)var h=function(e){for(var t,a,i,n,r,o,l,s="",m=0,p="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";m>2,r=(3&t)<<4|a>>4,o=(15&a)<<2|i>>6,l=63&i,isNaN(a)?o=l=64:isNaN(i)&&(l=64),s=s+p.charAt(n)+p.charAt(r)+p.charAt(o)+p.charAt(l);return s};if("undefined"!=typeof window&&"function"==typeof window.atob)var d=window.atob;if("undefined"==typeof d)var d=function(e){var t,a,i,n,r,o,l,s="",m=0,p="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";for(e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");m>4,a=(15&r)<<4|o>>2,i=(3&o)<<6|l,s+=String.fromCharCode(t),64!=o&&(s+=String.fromCharCode(a)),64!=l&&(s+=String.fromCharCode(i));return s};var g={Byte:1,Ascii:2,Short:3,Long:4,Rational:5,Undefined:7,SLong:9,SRational:10},u={Image:{11:{name:"ProcessingSoftware",type:"Ascii"},254:{name:"NewSubfileType",type:"Long"},255:{name:"SubfileType",type:"Short"},256:{name:"ImageWidth",type:"Long"},257:{name:"ImageLength",type:"Long"},258:{name:"BitsPerSample",type:"Short"},259:{name:"Compression",type:"Short"},262:{name:"PhotometricInterpretation",type:"Short"},263:{name:"Threshholding",type:"Short"},264:{name:"CellWidth",type:"Short"},265:{name:"CellLength",type:"Short"},266:{name:"FillOrder",type:"Short"},269:{name:"DocumentName",type:"Ascii"},270:{name:"ImageDescription",type:"Ascii"},271:{name:"Make",type:"Ascii"},272:{name:"Model",type:"Ascii"},273:{name:"StripOffsets",type:"Long"},274:{name:"Orientation",type:"Short"},277:{name:"SamplesPerPixel",type:"Short"},278:{name:"RowsPerStrip",type:"Long"},279:{name:"StripByteCounts",type:"Long"},282:{name:"XResolution",type:"Rational"},283:{name:"YResolution",type:"Rational"},284:{name:"PlanarConfiguration",type:"Short"},290:{name:"GrayResponseUnit",type:"Short"},291:{name:"GrayResponseCurve",type:"Short"},292:{name:"T4Options",type:"Long"},293:{name:"T6Options",type:"Long"},296:{name:"ResolutionUnit",type:"Short"},301:{name:"TransferFunction",type:"Short"},305:{name:"Software",type:"Ascii"},306:{name:"DateTime",type:"Ascii"},315:{name:"Artist",type:"Ascii"},316:{name:"HostComputer",type:"Ascii"},317:{name:"Predictor",type:"Short"},318:{name:"WhitePoint",type:"Rational"},319:{name:"PrimaryChromaticities",type:"Rational"},320:{name:"ColorMap",type:"Short"},321:{name:"HalftoneHints",type:"Short"},322:{name:"TileWidth",type:"Short"},323:{name:"TileLength",type:"Short"},324:{name:"TileOffsets",type:"Short"},325:{name:"TileByteCounts",type:"Short"},330:{name:"SubIFDs",type:"Long"},332:{name:"InkSet",type:"Short"},333:{name:"InkNames",type:"Ascii"},334:{name:"NumberOfInks",type:"Short"},336:{name:"DotRange",type:"Byte"},337:{name:"TargetPrinter",type:"Ascii"},338:{name:"ExtraSamples",type:"Short"},339:{name:"SampleFormat",type:"Short"},340:{name:"SMinSampleValue",type:"Short"},341:{name:"SMaxSampleValue",type:"Short"},342:{name:"TransferRange",type:"Short"},343:{name:"ClipPath",type:"Byte"},344:{name:"XClipPathUnits",type:"Long"},345:{name:"YClipPathUnits",type:"Long"},346:{name:"Indexed",type:"Short"},347:{name:"JPEGTables",type:"Undefined"},351:{name:"OPIProxy",type:"Short"},512:{name:"JPEGProc",type:"Long"},513:{name:"JPEGInterchangeFormat",type:"Long"},514:{name:"JPEGInterchangeFormatLength",type:"Long"},515:{name:"JPEGRestartInterval",type:"Short"},517:{name:"JPEGLosslessPredictors",type:"Short"},518:{name:"JPEGPointTransforms",type:"Short"},519:{name:"JPEGQTables",type:"Long"},520:{name:"JPEGDCTables",type:"Long"},521:{name:"JPEGACTables",type:"Long"},529:{name:"YCbCrCoefficients",type:"Rational"},530:{name:"YCbCrSubSampling",type:"Short"},531:{name:"YCbCrPositioning",type:"Short"},532:{name:"ReferenceBlackWhite",type:"Rational"},700:{name:"XMLPacket",type:"Byte"},18246:{name:"Rating",type:"Short"},18249:{name:"RatingPercent",type:"Short"},32781:{name:"ImageID",type:"Ascii"},33421:{name:"CFARepeatPatternDim",type:"Short"},33422:{name:"CFAPattern",type:"Byte"},33423:{name:"BatteryLevel",type:"Rational"},33432:{name:"Copyright",type:"Ascii"},33434:{name:"ExposureTime",type:"Rational"},34377:{name:"ImageResources",type:"Byte"},34665:{name:"ExifTag",type:"Long"},34675:{name:"InterColorProfile",type:"Undefined"},34853:{name:"GPSTag",type:"Long"},34857:{name:"Interlace",type:"Short"},34858:{name:"TimeZoneOffset",type:"Long"},34859:{name:"SelfTimerMode",type:"Short"},37387:{name:"FlashEnergy",type:"Rational"},37388:{name:"SpatialFrequencyResponse",type:"Undefined"},37389:{name:"Noise",type:"Undefined"},37390:{name:"FocalPlaneXResolution",type:"Rational"},37391:{name:"FocalPlaneYResolution",type:"Rational"},37392:{name:"FocalPlaneResolutionUnit",type:"Short"},37393:{name:"ImageNumber",type:"Long"},37394:{name:"SecurityClassification",type:"Ascii"},37395:{name:"ImageHistory",type:"Ascii"},37397:{name:"ExposureIndex",type:"Rational"},37398:{name:"TIFFEPStandardID",type:"Byte"},37399:{name:"SensingMethod",type:"Short"},40091:{name:"XPTitle",type:"Byte"},40092:{name:"XPComment",type:"Byte"},40093:{name:"XPAuthor",type:"Byte"},40094:{name:"XPKeywords",type:"Byte"},40095:{name:"XPSubject",type:"Byte"},50341:{name:"PrintImageMatching",type:"Undefined"},50706:{name:"DNGVersion",type:"Byte"},50707:{name:"DNGBackwardVersion",type:"Byte"},50708:{name:"UniqueCameraModel",type:"Ascii"},50709:{name:"LocalizedCameraModel",type:"Byte"},50710:{name:"CFAPlaneColor",type:"Byte"},50711:{name:"CFALayout",type:"Short"},50712:{name:"LinearizationTable",type:"Short"},50713:{name:"BlackLevelRepeatDim",type:"Short"},50714:{name:"BlackLevel",type:"Rational"},50715:{name:"BlackLevelDeltaH",type:"SRational"},50716:{name:"BlackLevelDeltaV",type:"SRational"},50717:{name:"WhiteLevel",type:"Short"},50718:{name:"DefaultScale",type:"Rational"},50719:{name:"DefaultCropOrigin",type:"Short"},50720:{name:"DefaultCropSize",type:"Short"},50721:{name:"ColorMatrix1",type:"SRational"},50722:{name:"ColorMatrix2",type:"SRational"},50723:{name:"CameraCalibration1",type:"SRational"},50724:{name:"CameraCalibration2",type:"SRational"},50725:{name:"ReductionMatrix1",type:"SRational"},50726:{name:"ReductionMatrix2",type:"SRational"},50727:{name:"AnalogBalance",type:"Rational"},50728:{name:"AsShotNeutral",type:"Short"},50729:{name:"AsShotWhiteXY",type:"Rational"},50730:{name:"BaselineExposure",type:"SRational"},50731:{name:"BaselineNoise",type:"Rational"},50732:{name:"BaselineSharpness",type:"Rational"},50733:{name:"BayerGreenSplit",type:"Long"},50734:{name:"LinearResponseLimit",type:"Rational"},50735:{name:"CameraSerialNumber",type:"Ascii"},50736:{name:"LensInfo",type:"Rational"},50737:{name:"ChromaBlurRadius",type:"Rational"},50738:{name:"AntiAliasStrength",type:"Rational"},50739:{name:"ShadowScale",type:"SRational"},50740:{name:"DNGPrivateData",type:"Byte"},50741:{name:"MakerNoteSafety",type:"Short"},50778:{name:"CalibrationIlluminant1",type:"Short"},50779:{name:"CalibrationIlluminant2",type:"Short"},50780:{name:"BestQualityScale",type:"Rational"},50781:{name:"RawDataUniqueID",type:"Byte"},50827:{name:"OriginalRawFileName",type:"Byte"},50828:{name:"OriginalRawFileData",type:"Undefined"},50829:{name:"ActiveArea",type:"Short"},50830:{name:"MaskedAreas",type:"Short"},50831:{name:"AsShotICCProfile",type:"Undefined"},50832:{name:"AsShotPreProfileMatrix",type:"SRational"},50833:{name:"CurrentICCProfile",type:"Undefined"},50834:{name:"CurrentPreProfileMatrix",type:"SRational"},50879:{name:"ColorimetricReference",type:"Short"},50931:{name:"CameraCalibrationSignature",type:"Byte"},50932:{name:"ProfileCalibrationSignature",type:"Byte"},50934:{name:"AsShotProfileName",type:"Byte"},50935:{name:"NoiseReductionApplied",type:"Rational"},50936:{name:"ProfileName",type:"Byte"},50937:{name:"ProfileHueSatMapDims",type:"Long"},50938:{name:"ProfileHueSatMapData1",type:"Float"},50939:{name:"ProfileHueSatMapData2",type:"Float"},50940:{name:"ProfileToneCurve",type:"Float"},50941:{name:"ProfileEmbedPolicy",type:"Long"},50942:{name:"ProfileCopyright",type:"Byte"},50964:{name:"ForwardMatrix1",type:"SRational"},50965:{name:"ForwardMatrix2",type:"SRational"},50966:{name:"PreviewApplicationName",type:"Byte"},50967:{name:"PreviewApplicationVersion",type:"Byte"},50968:{name:"PreviewSettingsName",type:"Byte"},50969:{name:"PreviewSettingsDigest",type:"Byte"},50970:{name:"PreviewColorSpace",type:"Long"},50971:{name:"PreviewDateTime",type:"Ascii"},50972:{name:"RawImageDigest",type:"Undefined"},50973:{name:"OriginalRawFileDigest",type:"Undefined"},50974:{name:"SubTileBlockSize",type:"Long"},50975:{name:"RowInterleaveFactor",type:"Long"},50981:{name:"ProfileLookTableDims",type:"Long"},50982:{name:"ProfileLookTableData",type:"Float"},51008:{name:"OpcodeList1",type:"Undefined"},51009:{name:"OpcodeList2",type:"Undefined"},51022:{name:"OpcodeList3",type:"Undefined"}},Exif:{33434:{name:"ExposureTime",type:"Rational"},33437:{name:"FNumber",type:"Rational"},34850:{name:"ExposureProgram",type:"Short"},34852:{name:"SpectralSensitivity",type:"Ascii"},34855:{name:"ISOSpeedRatings",type:"Short"},34856:{name:"OECF",type:"Undefined"},34864:{name:"SensitivityType",type:"Short"},34865:{name:"StandardOutputSensitivity",type:"Long"},34866:{name:"RecommendedExposureIndex",type:"Long"},34867:{name:"ISOSpeed",type:"Long"},34868:{name:"ISOSpeedLatitudeyyy",type:"Long"},34869:{name:"ISOSpeedLatitudezzz",type:"Long"},36864:{name:"ExifVersion",type:"Undefined"},36867:{name:"DateTimeOriginal",type:"Ascii"},36868:{name:"DateTimeDigitized",type:"Ascii"},37121:{name:"ComponentsConfiguration",type:"Undefined"},37122:{name:"CompressedBitsPerPixel",type:"Rational"},37377:{name:"ShutterSpeedValue",type:"SRational"},37378:{name:"ApertureValue",type:"Rational"},37379:{name:"BrightnessValue",type:"SRational"},37380:{name:"ExposureBiasValue",type:"SRational"},37381:{name:"MaxApertureValue",type:"Rational"},37382:{name:"SubjectDistance",type:"Rational"},37383:{name:"MeteringMode",type:"Short"},37384:{name:"LightSource",type:"Short"},37385:{name:"Flash",type:"Short"},37386:{name:"FocalLength",type:"Rational"},37396:{name:"SubjectArea",type:"Short"},37500:{name:"MakerNote",type:"Undefined"},37510:{name:"UserComment",type:"Ascii"},37520:{name:"SubSecTime",type:"Ascii"},37521:{name:"SubSecTimeOriginal",type:"Ascii"},37522:{name:"SubSecTimeDigitized",type:"Ascii"},40960:{name:"FlashpixVersion",type:"Undefined"},40961:{name:"ColorSpace",type:"Short"},40962:{name:"PixelXDimension",type:"Long"},40963:{name:"PixelYDimension",type:"Long"},40964:{name:"RelatedSoundFile",type:"Ascii"},40965:{name:"InteroperabilityTag",type:"Long"},41483:{name:"FlashEnergy",type:"Rational"},41484:{name:"SpatialFrequencyResponse",type:"Undefined"},41486:{name:"FocalPlaneXResolution",type:"Rational"},41487:{name:"FocalPlaneYResolution",type:"Rational"},41488:{name:"FocalPlaneResolutionUnit",type:"Short"},41492:{name:"SubjectLocation",type:"Short"},41493:{name:"ExposureIndex",type:"Rational"},41495:{name:"SensingMethod",type:"Short"},41728:{name:"FileSource",type:"Undefined"},41729:{name:"SceneType",type:"Undefined"},41730:{name:"CFAPattern",type:"Undefined"},41985:{name:"CustomRendered",type:"Short"},41986:{name:"ExposureMode",type:"Short"},41987:{name:"WhiteBalance",type:"Short"},41988:{name:"DigitalZoomRatio",type:"Rational"},41989:{name:"FocalLengthIn35mmFilm",type:"Short"},41990:{name:"SceneCaptureType",type:"Short"},41991:{name:"GainControl",type:"Short"},41992:{name:"Contrast",type:"Short"},41993:{name:"Saturation",type:"Short"},41994:{name:"Sharpness",type:"Short"},41995:{name:"DeviceSettingDescription",type:"Undefined"},41996:{name:"SubjectDistanceRange",type:"Short"},42016:{name:"ImageUniqueID",type:"Ascii"},42032:{name:"CameraOwnerName",type:"Ascii"},42033:{name:"BodySerialNumber",type:"Ascii"},42034:{name:"LensSpecification",type:"Rational"},42035:{name:"LensMake",type:"Ascii"},42036:{name:"LensModel",type:"Ascii"},42037:{name:"LensSerialNumber",type:"Ascii"},42240:{name:"Gamma",type:"Rational"}},GPS:{0:{name:"GPSVersionID",type:"Byte"},1:{name:"GPSLatitudeRef",type:"Ascii"},2:{name:"GPSLatitude",type:"Rational"},3:{name:"GPSLongitudeRef",type:"Ascii"},4:{name:"GPSLongitude",type:"Rational"},5:{name:"GPSAltitudeRef",type:"Byte"},6:{name:"GPSAltitude",type:"Rational"},7:{name:"GPSTimeStamp",type:"Rational"},8:{name:"GPSSatellites",type:"Ascii"},9:{name:"GPSStatus",type:"Ascii"},10:{name:"GPSMeasureMode",type:"Ascii"},11:{name:"GPSDOP",type:"Rational"},12:{name:"GPSSpeedRef",type:"Ascii"},13:{name:"GPSSpeed",type:"Rational"},14:{name:"GPSTrackRef",type:"Ascii"},15:{name:"GPSTrack",type:"Rational"},16:{name:"GPSImgDirectionRef",type:"Ascii"},17:{name:"GPSImgDirection",type:"Rational"},18:{name:"GPSMapDatum",type:"Ascii"},19:{name:"GPSDestLatitudeRef",type:"Ascii"},20:{name:"GPSDestLatitude",type:"Rational"},21:{name:"GPSDestLongitudeRef",type:"Ascii"},22:{name:"GPSDestLongitude",type:"Rational"},23:{name:"GPSDestBearingRef",type:"Ascii"},24:{name:"GPSDestBearing",type:"Rational"},25:{name:"GPSDestDistanceRef",type:"Ascii"},26:{name:"GPSDestDistance",type:"Rational"},27:{name:"GPSProcessingMethod",type:"Undefined"},28:{name:"GPSAreaInformation",type:"Undefined"},29:{name:"GPSDateStamp",type:"Ascii"},30:{name:"GPSDifferential",type:"Short"},31:{name:"GPSHPositioningError",type:"Rational"}},Interop:{1:{name:"InteroperabilityIndex",type:"Ascii"}}};u["0th"]=u.Image,u["1st"]=u.Image,f.TAGS=u,f.ImageIFD={ProcessingSoftware:11,NewSubfileType:254,SubfileType:255,ImageWidth:256,ImageLength:257,BitsPerSample:258,Compression:259,PhotometricInterpretation:262,Threshholding:263,CellWidth:264,CellLength:265,FillOrder:266,DocumentName:269,ImageDescription:270,Make:271,Model:272,StripOffsets:273,Orientation:274,SamplesPerPixel:277,RowsPerStrip:278,StripByteCounts:279,XResolution:282,YResolution:283,PlanarConfiguration:284,GrayResponseUnit:290,GrayResponseCurve:291,T4Options:292,T6Options:293,ResolutionUnit:296,TransferFunction:301,Software:305,DateTime:306,Artist:315,HostComputer:316,Predictor:317,WhitePoint:318,PrimaryChromaticities:319,ColorMap:320,HalftoneHints:321,TileWidth:322,TileLength:323,TileOffsets:324,TileByteCounts:325,SubIFDs:330,InkSet:332,InkNames:333,NumberOfInks:334,DotRange:336,TargetPrinter:337,ExtraSamples:338,SampleFormat:339,SMinSampleValue:340,SMaxSampleValue:341,TransferRange:342,ClipPath:343,XClipPathUnits:344,YClipPathUnits:345,Indexed:346,JPEGTables:347,OPIProxy:351,JPEGProc:512,JPEGInterchangeFormat:513,JPEGInterchangeFormatLength:514,JPEGRestartInterval:515,JPEGLosslessPredictors:517,JPEGPointTransforms:518,JPEGQTables:519,JPEGDCTables:520,JPEGACTables:521,YCbCrCoefficients:529,YCbCrSubSampling:530,YCbCrPositioning:531,ReferenceBlackWhite:532,XMLPacket:700,Rating:18246,RatingPercent:18249,ImageID:32781,CFARepeatPatternDim:33421,CFAPattern:33422,BatteryLevel:33423,Copyright:33432,ExposureTime:33434,ImageResources:34377,ExifTag:34665,InterColorProfile:34675,GPSTag:34853,Interlace:34857,TimeZoneOffset:34858,SelfTimerMode:34859,FlashEnergy:37387,SpatialFrequencyResponse:37388,Noise:37389,FocalPlaneXResolution:37390,FocalPlaneYResolution:37391,FocalPlaneResolutionUnit:37392,ImageNumber:37393,SecurityClassification:37394,ImageHistory:37395,ExposureIndex:37397,TIFFEPStandardID:37398,SensingMethod:37399,XPTitle:40091,XPComment:40092,XPAuthor:40093,XPKeywords:40094,XPSubject:40095,PrintImageMatching:50341,DNGVersion:50706,DNGBackwardVersion:50707,UniqueCameraModel:50708,LocalizedCameraModel:50709,CFAPlaneColor:50710,CFALayout:50711,LinearizationTable:50712,BlackLevelRepeatDim:50713,BlackLevel:50714,BlackLevelDeltaH:50715,BlackLevelDeltaV:50716,WhiteLevel:50717,DefaultScale:50718,DefaultCropOrigin:50719,DefaultCropSize:50720,ColorMatrix1:50721,ColorMatrix2:50722,CameraCalibration1:50723,CameraCalibration2:50724,ReductionMatrix1:50725,ReductionMatrix2:50726,AnalogBalance:50727,AsShotNeutral:50728,AsShotWhiteXY:50729,BaselineExposure:50730,BaselineNoise:50731,BaselineSharpness:50732,BayerGreenSplit:50733,LinearResponseLimit:50734,CameraSerialNumber:50735,LensInfo:50736,ChromaBlurRadius:50737,AntiAliasStrength:50738,ShadowScale:50739,DNGPrivateData:50740,MakerNoteSafety:50741,CalibrationIlluminant1:50778,CalibrationIlluminant2:50779,BestQualityScale:50780,RawDataUniqueID:50781,OriginalRawFileName:50827,OriginalRawFileData:50828,ActiveArea:50829,MaskedAreas:50830,AsShotICCProfile:50831,AsShotPreProfileMatrix:50832,CurrentICCProfile:50833,CurrentPreProfileMatrix:50834,ColorimetricReference:50879,CameraCalibrationSignature:50931,ProfileCalibrationSignature:50932,AsShotProfileName:50934,NoiseReductionApplied:50935,ProfileName:50936,ProfileHueSatMapDims:50937,ProfileHueSatMapData1:50938,ProfileHueSatMapData2:50939,ProfileToneCurve:50940,ProfileEmbedPolicy:50941,ProfileCopyright:50942,ForwardMatrix1:50964,ForwardMatrix2:50965,PreviewApplicationName:50966,PreviewApplicationVersion:50967,PreviewSettingsName:50968,PreviewSettingsDigest:50969,PreviewColorSpace:50970,PreviewDateTime:50971,RawImageDigest:50972,OriginalRawFileDigest:50973,SubTileBlockSize:50974,RowInterleaveFactor:50975,ProfileLookTableDims:50981,ProfileLookTableData:50982,OpcodeList1:51008,OpcodeList2:51009,OpcodeList3:51022,NoiseProfile:51041},f.ExifIFD={ExposureTime:33434,FNumber:33437,ExposureProgram:34850,SpectralSensitivity:34852,ISOSpeedRatings:34855,OECF:34856,SensitivityType:34864,StandardOutputSensitivity:34865,RecommendedExposureIndex:34866,ISOSpeed:34867,ISOSpeedLatitudeyyy:34868,ISOSpeedLatitudezzz:34869,ExifVersion:36864,DateTimeOriginal:36867,DateTimeDigitized:36868,ComponentsConfiguration:37121,CompressedBitsPerPixel:37122,ShutterSpeedValue:37377,ApertureValue:37378,BrightnessValue:37379,ExposureBiasValue:37380,MaxApertureValue:37381,SubjectDistance:37382,MeteringMode:37383,LightSource:37384,Flash:37385,FocalLength:37386,SubjectArea:37396,MakerNote:37500,UserComment:37510,SubSecTime:37520,SubSecTimeOriginal:37521,SubSecTimeDigitized:37522,FlashpixVersion:40960,ColorSpace:40961,PixelXDimension:40962,PixelYDimension:40963,RelatedSoundFile:40964,InteroperabilityTag:40965,FlashEnergy:41483,SpatialFrequencyResponse:41484,FocalPlaneXResolution:41486,FocalPlaneYResolution:41487,FocalPlaneResolutionUnit:41488,SubjectLocation:41492,ExposureIndex:41493,SensingMethod:41495,FileSource:41728,SceneType:41729,CFAPattern:41730,CustomRendered:41985,ExposureMode:41986,WhiteBalance:41987,DigitalZoomRatio:41988,FocalLengthIn35mmFilm:41989,SceneCaptureType:41990,GainControl:41991,Contrast:41992,Saturation:41993,Sharpness:41994,DeviceSettingDescription:41995,SubjectDistanceRange:41996,ImageUniqueID:42016,CameraOwnerName:42032,BodySerialNumber:42033,LensSpecification:42034,LensMake:42035,LensModel:42036,LensSerialNumber:42037,Gamma:42240},f.GPSIFD={GPSVersionID:0,GPSLatitudeRef:1,GPSLatitude:2,GPSLongitudeRef:3,GPSLongitude:4,GPSAltitudeRef:5,GPSAltitude:6,GPSTimeStamp:7,GPSSatellites:8,GPSStatus:9,GPSMeasureMode:10,GPSDOP:11,GPSSpeedRef:12,GPSSpeed:13,GPSTrackRef:14,GPSTrack:15,GPSImgDirectionRef:16,GPSImgDirection:17,GPSMapDatum:18,GPSDestLatitudeRef:19,GPSDestLatitude:20,GPSDestLongitudeRef:21,GPSDestLongitude:22,GPSDestBearingRef:23,GPSDestBearing:24,GPSDestDistanceRef:25,GPSDestDistance:26,GPSProcessingMethod:27,GPSAreaInformation:28,GPSDateStamp:29,GPSDifferential:30,GPSHPositioningError:31},f.InteropIFD={InteroperabilityIndex:1},f.GPSHelper={degToDmsRational:function(e){var t=e%1*60,a=t%1*60,i=Math.floor(e),n=Math.floor(t),r=Math.round(100*a);return[[i,1],[n,1],[r,100]]}},"undefined"!=typeof exports?("undefined"!=typeof module&&module.exports&&(exports=module.exports=f),exports.piexif=f):window.piexif=f}(); ;(function(factory) { 'use strict'; /* global window: false, define: false, module: false */ var root = typeof window === 'undefined' ? null : window; if (typeof define === 'function' && define.amd) { define(function(){ return factory(root); }); } else if (typeof module !== 'undefined') { module.exports = factory(root); } else { root.DOMPurify = factory(root); } }(function factory(window) { 'use strict'; var DOMPurify = function(window) { return factory(window); }; /** * Version label, exposed for easier checks * if DOMPurify is up to date or not */ DOMPurify.version = '0.7.4'; if (!window || !window.document || window.document.nodeType !== 9) { // not running in a browser, provide a factory function // so that you can pass your own Window DOMPurify.isSupported = false; return DOMPurify; } var document = window.document; var originalDocument = document; var DocumentFragment = window.DocumentFragment; var HTMLTemplateElement = window.HTMLTemplateElement; var NodeFilter = window.NodeFilter; var NamedNodeMap = window.NamedNodeMap || window.MozNamedAttrMap; var Text = window.Text; var Comment = window.Comment; var DOMParser = window.DOMParser; // As per issue #47, the web-components registry is inherited by a // new document created via createHTMLDocument. As per the spec // (http://w3c.github.io/webcomponents/spec/custom/#creating-and-passing-registries) // a new empty registry is used when creating a template contents owner // document, so we use that as our parent document to ensure nothing // is inherited. if (typeof HTMLTemplateElement === 'function') { var template = document.createElement('template'); if (template.content && template.content.ownerDocument) { document = template.content.ownerDocument; } } var implementation = document.implementation; var createNodeIterator = document.createNodeIterator; var getElementsByTagName = document.getElementsByTagName; var createDocumentFragment = document.createDocumentFragment; var importNode = originalDocument.importNode; var hooks = {}; /** * Expose whether this browser supports running the full DOMPurify. */ DOMPurify.isSupported = typeof implementation.createHTMLDocument !== 'undefined' && document.documentMode !== 9; /* Add properties to a lookup table */ var _addToSet = function(set, array) { var l = array.length; while (l--) { if (typeof array[l] === 'string') { array[l] = array[l].toLowerCase(); } set[array[l]] = true; } return set; }; /* Shallow clone an object */ var _cloneObj = function(object) { var newObject = {}; var property; for (property in object) { if (object.hasOwnProperty(property)) { newObject[property] = object[property]; } } return newObject; }; /** * We consider the elements and attributes below to be safe. Ideally * don't add any new ones but feel free to remove unwanted ones. */ /* allowed element names */ var ALLOWED_TAGS = null; var DEFAULT_ALLOWED_TAGS = _addToSet({}, [ // HTML 'a','abbr','acronym','address','area','article','aside','audio','b', 'bdi','bdo','big','blink','blockquote','body','br','button','canvas', 'caption','center','cite','code','col','colgroup','content','data', 'datalist','dd','decorator','del','details','dfn','dir','div','dl','dt', 'element','em','fieldset','figcaption','figure','font','footer','form', 'h1','h2','h3','h4','h5','h6','head','header','hgroup','hr','html','i', 'img','input','ins','kbd','label','legend','li','main','map','mark', 'marquee','menu','menuitem','meter','nav','nobr','ol','optgroup', 'option','output','p','pre','progress','q','rp','rt','ruby','s','samp', 'section','select','shadow','small','source','spacer','span','strike', 'strong','style','sub','summary','sup','table','tbody','td','template', 'textarea','tfoot','th','thead','time','tr','track','tt','u','ul','var', 'video','wbr', // SVG 'svg','altglyph','altglyphdef','altglyphitem','animatecolor', 'animatemotion','animatetransform','circle','clippath','defs','desc', 'ellipse','filter','font','g','glyph','glyphref','hkern','image','line', 'lineargradient','marker','mask','metadata','mpath','path','pattern', 'polygon','polyline','radialgradient','rect','stop','switch','symbol', 'text','textpath','title','tref','tspan','view','vkern', // SVG Filters 'feBlend','feColorMatrix','feComponentTransfer','feComposite', 'feConvolveMatrix','feDiffuseLighting','feDisplacementMap', 'feFlood','feFuncA','feFuncB','feFuncG','feFuncR','feGaussianBlur', 'feMerge','feMergeNode','feMorphology','feOffset', 'feSpecularLighting','feTile','feTurbulence', //MathML 'math','menclose','merror','mfenced','mfrac','mglyph','mi','mlabeledtr', 'mmuliscripts','mn','mo','mover','mpadded','mphantom','mroot','mrow', 'ms','mpspace','msqrt','mystyle','msub','msup','msubsup','mtable','mtd', 'mtext','mtr','munder','munderover', //Text '#text' ]); /* Allowed attribute names */ var ALLOWED_ATTR = null; var DEFAULT_ALLOWED_ATTR = _addToSet({}, [ // HTML 'accept','action','align','alt','autocomplete','background','bgcolor', 'border','cellpadding','cellspacing','checked','cite','class','clear','color', 'cols','colspan','coords','datetime','default','dir','disabled', 'download','enctype','face','for','headers','height','hidden','high','href', 'hreflang','id','ismap','label','lang','list','loop', 'low','max', 'maxlength','media','method','min','multiple','name','noshade','novalidate', 'nowrap','open','optimum','pattern','placeholder','poster','preload','pubdate', 'radiogroup','readonly','rel','required','rev','reversed','rows', 'rowspan','spellcheck','scope','selected','shape','size','span', 'srclang','start','src','step','style','summary','tabindex','title', 'type','usemap','valign','value','width','xmlns', // SVG 'accent-height','accumulate','additivive','alignment-baseline', 'ascent','attributename','attributetype','azimuth','basefrequency', 'baseline-shift','begin','bias','by','clip','clip-path','clip-rule', 'color','color-interpolation','color-interpolation-filters','color-profile', 'color-rendering','cx','cy','d','dx','dy','diffuseconstant','direction', 'display','divisor','dur','edgemode','elevation','end','fill','fill-opacity', 'fill-rule','filter','flood-color','flood-opacity','font-family','font-size', 'font-size-adjust','font-stretch','font-style','font-variant','font-weight', 'fx', 'fy','g1','g2','glyph-name','glyphref','gradientunits','gradienttransform', 'image-rendering','in','in2','k','k1','k2','k3','k4','kerning','keypoints', 'keysplines','keytimes','lengthadjust','letter-spacing','kernelmatrix', 'kernelunitlength','lighting-color','local','marker-end','marker-mid', 'marker-start','markerheight','markerunits','markerwidth','maskcontentunits', 'maskunits','max','mask','mode','min','numoctaves','offset','operator', 'opacity','order','orient','orientation','origin','overflow','paint-order', 'path','pathlength','patterncontentunits','patterntransform','patternunits', 'points','preservealpha','r','rx','ry','radius','refx','refy','repeatcount', 'repeatdur','restart','result','rotate','scale','seed','shape-rendering', 'specularconstant','specularexponent','spreadmethod','stddeviation','stitchtiles', 'stop-color','stop-opacity','stroke-dasharray','stroke-dashoffset','stroke-linecap', 'stroke-linejoin','stroke-miterlimit','stroke-opacity','stroke','stroke-width', 'surfacescale','targetx','targety','transform','text-anchor','text-decoration', 'text-rendering','textlength','u1','u2','unicode','values','viewbox', 'visibility','vert-adv-y','vert-origin-x','vert-origin-y','word-spacing', 'wrap','writing-mode','xchannelselector','ychannelselector','x','x1','x2', 'y','y1','y2','z','zoomandpan', // MathML 'accent','accentunder','bevelled','close','columnsalign','columnlines', 'columnspan','denomalign','depth','display','displaystyle','fence', 'frame','largeop','length','linethickness','lspace','lquote', 'mathbackground','mathcolor','mathsize','mathvariant','maxsize', 'minsize','movablelimits','notation','numalign','open','rowalign', 'rowlines','rowspacing','rowspan','rspace','rquote','scriptlevel', 'scriptminsize','scriptsizemultiplier','selection','separator', 'separators','stretchy','subscriptshift','supscriptshift','symmetric', 'voffset', // XML 'xlink:href','xml:id','xlink:title','xml:space','xmlns:xlink' ]); /* Explicitly forbidden tags (overrides ALLOWED_TAGS/ADD_TAGS) */ var FORBID_TAGS = null; /* Explicitly forbidden attributes (overrides ALLOWED_ATTR/ADD_ATTR) */ var FORBID_ATTR = null; /* Decide if custom data attributes are okay */ var ALLOW_DATA_ATTR = true; /* Decide if unknown protocols are okay */ var ALLOW_UNKNOWN_PROTOCOLS = false; /* Output should be safe for jQuery's $() factory? */ var SAFE_FOR_JQUERY = false; /* Output should be safe for common template engines. * This means, DOMPurify removes data attributes, mustaches and ERB */ var SAFE_FOR_TEMPLATES = false; /* Specify template detection regex for SAFE_FOR_TEMPLATES mode */ var MUSTACHE_EXPR = /\{\{[\s\S]*|[\s\S]*\}\}/gm; var ERB_EXPR = /<%[\s\S]*|[\s\S]*%>/gm; /* Decide if document with ... should be returned */ var WHOLE_DOCUMENT = false; /* Decide if a DOM `HTMLBodyElement` should be returned, instead of a html string. * If `WHOLE_DOCUMENT` is enabled a `HTMLHtmlElement` will be returned instead */ var RETURN_DOM = false; /* Decide if a DOM `DocumentFragment` should be returned, instead of a html string */ var RETURN_DOM_FRAGMENT = false; /* If `RETURN_DOM` or `RETURN_DOM_FRAGMENT` is enabled, decide if the returned DOM * `Node` is imported into the current `Document`. If this flag is not enabled the * `Node` will belong (its ownerDocument) to a fresh `HTMLDocument`, created by * DOMPurify. */ var RETURN_DOM_IMPORT = false; /* Output should be free from DOM clobbering attacks? */ var SANITIZE_DOM = true; /* Keep element content when removing element? */ var KEEP_CONTENT = true; /* Tags to ignore content of when KEEP_CONTENT is true */ var FORBID_CONTENTS = _addToSet({}, [ 'audio', 'head', 'math', 'script', 'style', 'svg', 'video' ]); /* Tags that are safe for data: URIs */ var DATA_URI_TAGS = _addToSet({}, [ 'audio', 'video', 'img', 'source' ]); /* Attributes safe for values like "javascript:" */ var URI_SAFE_ATTRIBUTES = _addToSet({}, [ 'alt','class','for','id','label','name','pattern','placeholder', 'summary','title','value','style','xmlns' ]); /* Keep a reference to config to pass to hooks */ var CONFIG = null; /* Ideally, do not touch anything below this line */ /* ______________________________________________ */ var formElement = document.createElement('form'); /** * _parseConfig * * @param optional config literal */ var _parseConfig = function(cfg) { /* Shield configuration object from tampering */ if (typeof cfg !== 'object') { cfg = {}; } /* Set configuration parameters */ ALLOWED_TAGS = 'ALLOWED_TAGS' in cfg ? _addToSet({}, cfg.ALLOWED_TAGS) : DEFAULT_ALLOWED_TAGS; ALLOWED_ATTR = 'ALLOWED_ATTR' in cfg ? _addToSet({}, cfg.ALLOWED_ATTR) : DEFAULT_ALLOWED_ATTR; FORBID_TAGS = 'FORBID_TAGS' in cfg ? _addToSet({}, cfg.FORBID_TAGS) : {}; FORBID_ATTR = 'FORBID_ATTR' in cfg ? _addToSet({}, cfg.FORBID_ATTR) : {}; ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false; // Default true ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false; // Default false SAFE_FOR_JQUERY = cfg.SAFE_FOR_JQUERY || false; // Default false SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false; // Default false WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false; // Default false RETURN_DOM = cfg.RETURN_DOM || false; // Default false RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false; // Default false RETURN_DOM_IMPORT = cfg.RETURN_DOM_IMPORT || false; // Default false SANITIZE_DOM = cfg.SANITIZE_DOM !== false; // Default true KEEP_CONTENT = cfg.KEEP_CONTENT !== false; // Default true if (SAFE_FOR_TEMPLATES) { ALLOW_DATA_ATTR = false; } if (RETURN_DOM_FRAGMENT) { RETURN_DOM = true; } /* Merge configuration parameters */ if (cfg.ADD_TAGS) { if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) { ALLOWED_TAGS = _cloneObj(ALLOWED_TAGS); } _addToSet(ALLOWED_TAGS, cfg.ADD_TAGS); } if (cfg.ADD_ATTR) { if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) { ALLOWED_ATTR = _cloneObj(ALLOWED_ATTR); } _addToSet(ALLOWED_ATTR, cfg.ADD_ATTR); } /* Add #text in case KEEP_CONTENT is set to true */ if (KEEP_CONTENT) { ALLOWED_TAGS['#text'] = true; } // Prevent further manipulation of configuration. // Not available in IE8, Safari 5, etc. if (Object && 'freeze' in Object) { Object.freeze(cfg); } CONFIG = cfg; }; /** * _forceRemove * * @param a DOM node */ var _forceRemove = function(node) { try { node.parentNode.removeChild(node); } catch (e) { node.outerHTML = ''; } }; /** * _initDocument * * @param a string of dirty markup * @return a DOM, filled with the dirty markup */ var _initDocument = function(dirty) { /* Create a HTML document using DOMParser */ var doc, body; try { doc = new DOMParser().parseFromString(dirty, 'text/html'); } catch (e) {} /* Some browsers throw, some browsers return null for the code above DOMParser with text/html support is only in very recent browsers. */ if (!doc) { doc = implementation.createHTMLDocument(''); body = doc.body; body.parentNode.removeChild(body.parentNode.firstElementChild); body.outerHTML = dirty; } /* Work on whole document or just its body */ if (typeof doc.getElementsByTagName === 'function') { return doc.getElementsByTagName( WHOLE_DOCUMENT ? 'html' : 'body')[0]; } return getElementsByTagName.call(doc, WHOLE_DOCUMENT ? 'html' : 'body')[0]; }; /** * _createIterator * * @param document/fragment to create iterator for * @return iterator instance */ var _createIterator = function(root) { return createNodeIterator.call(root.ownerDocument || root, root, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT, function() { return NodeFilter.FILTER_ACCEPT; }, false ); }; /** * _isClobbered * * @param element to check for clobbering attacks * @return true if clobbered, false if safe */ var _isClobbered = function(elm) { if (elm instanceof Text || elm instanceof Comment) { return false; } if ( typeof elm.nodeName !== 'string' || typeof elm.textContent !== 'string' || typeof elm.removeChild !== 'function' || !(elm.attributes instanceof NamedNodeMap) || typeof elm.removeAttribute !== 'function' || typeof elm.setAttribute !== 'function' ) { return true; } return false; }; /** * _sanitizeElements * * @protect nodeName * @protect textContent * @protect removeChild * * @param node to check for permission to exist * @return true if node was killed, false if left alive */ var _sanitizeElements = function(currentNode) { var tagName, content; /* Execute a hook if present */ _executeHook('beforeSanitizeElements', currentNode, null); /* Check if element is clobbered or can clobber */ if (_isClobbered(currentNode)) { _forceRemove(currentNode); return true; } /* Now let's check the element's type and name */ tagName = currentNode.nodeName.toLowerCase(); /* Execute a hook if present */ _executeHook('uponSanitizeElement', currentNode, { tagName: tagName }); /* Remove element if anything forbids its presence */ if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) { /* Keep content except for black-listed elements */ if (KEEP_CONTENT && !FORBID_CONTENTS[tagName] && typeof currentNode.insertAdjacentHTML === 'function') { try { currentNode.insertAdjacentHTML('AfterEnd', currentNode.innerHTML); } catch (e) {} } _forceRemove(currentNode); return true; } /* Convert markup to cover jQuery behavior */ if (SAFE_FOR_JQUERY && !currentNode.firstElementChild && (!currentNode.content || !currentNode.content.firstElementChild)) { currentNode.innerHTML = currentNode.textContent.replace(/ tag that has an "id" // attribute at the time. if (lcName === 'name' && currentNode.nodeName === 'IMG' && attributes.id) { idAttr = attributes.id; attributes = Array.prototype.slice.apply(attributes); currentNode.removeAttribute('id'); currentNode.removeAttribute(name); if (attributes.indexOf(idAttr) > l) { currentNode.setAttribute('id', idAttr.value); } } else { // This avoids a crash in Safari v9.0 with double-ids. // The trick is to first set the id to be empty and then to // remove the attriubute if (name === 'id') { currentNode.setAttribute(name, ''); } currentNode.removeAttribute(name); } /* Did the hooks approve of the attribute? */ if (!hookEvent.keepAttr) { continue; } /* Make sure attribute cannot clobber */ if (SANITIZE_DOM && (lcName === 'id' || lcName === 'name') && (value in window || value in document || value in formElement)) { continue; } /* Sanitize attribute content to be template-safe */ if (SAFE_FOR_TEMPLATES) { value = value.replace(MUSTACHE_EXPR, ' '); value = value.replace(ERB_EXPR, ' '); } if ( /* Check the name is permitted */ (ALLOWED_ATTR[lcName] && !FORBID_ATTR[lcName] && ( /* Check no script, data or unknown possibly unsafe URI unless we know URI values are safe for that attribute */ URI_SAFE_ATTRIBUTES[lcName] || IS_ALLOWED_URI.test(value.replace(ATTR_WHITESPACE,'')) || /* Keep image data URIs alive if src is allowed */ (lcName === 'src' && value.indexOf('data:') === 0 && DATA_URI_TAGS[currentNode.nodeName.toLowerCase()]) )) || /* Allow potentially valid data-* attributes: * At least one character after "-" (https://html.spec.whatwg.org/multipage/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes) * XML-compatible (https://html.spec.whatwg.org/multipage/infrastructure.html#xml-compatible and http://www.w3.org/TR/xml/#d0e804) * We don't need to check the value; it's always URI safe. */ (ALLOW_DATA_ATTR && DATA_ATTR.test(lcName)) || /* Allow unknown protocols: * This provides support for links that are handled by protocol handlers which may be unknown * ahead of time, e.g. fb:, spotify: */ (ALLOW_UNKNOWN_PROTOCOLS && !IS_SCRIPT_OR_DATA.test(value.replace(ATTR_WHITESPACE,''))) ) { /* Handle invalid data-* attribute set by try-catching it */ try { currentNode.setAttribute(name, value); } catch (e) {} } } /* Execute a hook if present */ _executeHook('afterSanitizeAttributes', currentNode, null); }; /** * _sanitizeShadowDOM * * @param fragment to iterate over recursively * @return void */ var _sanitizeShadowDOM = function(fragment) { var shadowNode; var shadowIterator = _createIterator(fragment); /* Execute a hook if present */ _executeHook('beforeSanitizeShadowDOM', fragment, null); while ( (shadowNode = shadowIterator.nextNode()) ) { /* Execute a hook if present */ _executeHook('uponSanitizeShadowNode', shadowNode, null); /* Sanitize tags and elements */ if (_sanitizeElements(shadowNode)) { continue; } /* Deep shadow DOM detected */ if (shadowNode.content instanceof DocumentFragment) { _sanitizeShadowDOM(shadowNode.content); } /* Check attributes, sanitize if necessary */ _sanitizeAttributes(shadowNode); } /* Execute a hook if present */ _executeHook('afterSanitizeShadowDOM', fragment, null); }; /** * _executeHook * Execute user configurable hooks * * @param {String} entryPoint Name of the hook's entry point * @param {Node} currentNode */ var _executeHook = function(entryPoint, currentNode, data) { if (!hooks[entryPoint]) { return; } hooks[entryPoint].forEach(function(hook) { hook.call(DOMPurify, currentNode, data, CONFIG); }); }; /** * sanitize * Public method providing core sanitation functionality * * @param {String} dirty string * @param {Object} configuration object */ DOMPurify.sanitize = function(dirty, cfg) { var body, currentNode, oldNode, nodeIterator, returnNode; /* Make sure we have a string to sanitize. DO NOT return early, as this will return the wrong type if the user has requested a DOM object rather than a string */ if (!dirty) { dirty = ''; } /* Stringify, in case dirty is an object */ if (typeof dirty !== 'string') { if (typeof dirty.toString !== 'function') { throw new TypeError('toString is not a function'); } else { dirty = dirty.toString(); } } /* Check we can run. Otherwise fall back or ignore */ if (!DOMPurify.isSupported) { if (typeof window.toStaticHTML === 'object' || typeof window.toStaticHTML === 'function') { return window.toStaticHTML(dirty); } return dirty; } /* Assign config vars */ _parseConfig(cfg); /* Exit directly if we have nothing to do */ if (!RETURN_DOM && !WHOLE_DOCUMENT && dirty.indexOf('<') === -1) { return dirty; } /* Initialize the document to work on */ body = _initDocument(dirty); /* Check we have a DOM node from the data */ if (!body) { return RETURN_DOM ? null : ''; } /* Get node iterator */ nodeIterator = _createIterator(body); /* Now start iterating over the created document */ while ( (currentNode = nodeIterator.nextNode()) ) { /* Fix IE's strange behavior with manipulated textNodes #89 */ if (currentNode.nodeType === 3 && currentNode === oldNode) { continue; } /* Sanitize tags and elements */ if (_sanitizeElements(currentNode)) { continue; } /* Shadow DOM detected, sanitize it */ if (currentNode.content instanceof DocumentFragment) { _sanitizeShadowDOM(currentNode.content); } /* Check attributes, sanitize if necessary */ _sanitizeAttributes(currentNode); oldNode = currentNode; } /* Return sanitized string or DOM */ if (RETURN_DOM) { if (RETURN_DOM_FRAGMENT) { returnNode = createDocumentFragment.call(body.ownerDocument); while (body.firstChild) { returnNode.appendChild(body.firstChild); } } else { returnNode = body; } if (RETURN_DOM_IMPORT) { /* adoptNode() is not used because internal state is not reset (e.g. the past names map of a HTMLFormElement), this is safe in theory but we would rather not risk another attack vector. The state that is cloned by importNode() is explicitly defined by the specs. */ returnNode = importNode.call(originalDocument, returnNode, true); } return returnNode; } return WHOLE_DOCUMENT ? body.outerHTML : body.innerHTML; }; /** * addHook * Public method to add DOMPurify hooks * * @param {String} entryPoint * @param {Function} hookFunction */ DOMPurify.addHook = function(entryPoint, hookFunction) { if (typeof hookFunction !== 'function') { return; } hooks[entryPoint] = hooks[entryPoint] || []; hooks[entryPoint].push(hookFunction); }; /** * removeHook * Public method to remove a DOMPurify hook at a given entryPoint * (pops it from the stack of hooks if more are present) * * @param {String} entryPoint * @return void */ DOMPurify.removeHook = function(entryPoint) { if (hooks[entryPoint]) { hooks[entryPoint].pop(); } }; /** * removeHooks * Public method to remove all DOMPurify hooks at a given entryPoint * * @param {String} entryPoint * @return void */ DOMPurify.removeHooks = function(entryPoint) { if (hooks[entryPoint]) { hooks[entryPoint] = []; } }; /** * removeAllHooks * Public method to remove all DOMPurify hooks * * @return void */ DOMPurify.removeAllHooks = function() { hooks = []; }; return DOMPurify; })); (function(e){"use strict";var t=typeof window==="undefined"?null:window;if(typeof define==="function"&&define.amd){define(function(){return e(t)})}else if(typeof module!=="undefined"){module.exports=e(t)}else{t.DOMPurify=e(t)}})(function e(t){"use strict";var r=function(t){return e(t)};r.version="0.7.4";if(!t||!t.document||t.document.nodeType!==9){r.isSupported=false;return r}var n=t.document;var a=n;var i=t.DocumentFragment;var o=t.HTMLTemplateElement;var l=t.NodeFilter;var s=t.NamedNodeMap||t.MozNamedAttrMap;var f=t.Text;var c=t.Comment;var u=t.DOMParser;if(typeof o==="function"){var d=n.createElement("template");if(d.content&&d.content.ownerDocument){n=d.content.ownerDocument}}var m=n.implementation;var p=n.createNodeIterator;var h=n.getElementsByTagName;var v=n.createDocumentFragment;var g=a.importNode;var y={};r.isSupported=typeof m.createHTMLDocument!=="undefined"&&n.documentMode!==9;var b=function(e,t){var r=t.length;while(r--){if(typeof t[r]==="string"){t[r]=t[r].toLowerCase()}e[t[r]]=true}return e};var T=function(e){var t={};var r;for(r in e){if(e.hasOwnProperty(r)){t[r]=e[r]}}return t};var x=null;var k=b({},["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","pre","progress","q","rp","rt","ruby","s","samp","section","select","shadow","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr","svg","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","filter","font","g","glyph","glyphref","hkern","image","line","lineargradient","marker","mask","metadata","mpath","path","pattern","polygon","polyline","radialgradient","rect","stop","switch","symbol","text","textpath","title","tref","tspan","view","vkern","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feMerge","feMergeNode","feMorphology","feOffset","feSpecularLighting","feTile","feTurbulence","math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmuliscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mpspace","msqrt","mystyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","#text"]);var A=null;var w=b({},["accept","action","align","alt","autocomplete","background","bgcolor","border","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","coords","datetime","default","dir","disabled","download","enctype","face","for","headers","height","hidden","high","href","hreflang","id","ismap","label","lang","list","loop","low","max","maxlength","media","method","min","multiple","name","noshade","novalidate","nowrap","open","optimum","pattern","placeholder","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","rows","rowspan","spellcheck","scope","selected","shape","size","span","srclang","start","src","step","style","summary","tabindex","title","type","usemap","valign","value","width","xmlns","accent-height","accumulate","additivive","alignment-baseline","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","clip","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","fill","fill-opacity","fill-rule","filter","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","image-rendering","in","in2","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","mode","min","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","specularconstant","specularexponent","spreadmethod","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","surfacescale","targetx","targety","transform","text-anchor","text-decoration","text-rendering","textlength","u1","u2","unicode","values","viewbox","visibility","vert-adv-y","vert-origin-x","vert-origin-y","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","y","y1","y2","z","zoomandpan","accent","accentunder","bevelled","close","columnsalign","columnlines","columnspan","denomalign","depth","display","displaystyle","fence","frame","largeop","length","linethickness","lspace","lquote","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]);var E=null;var S=null;var M=true;var O=false;var L=false;var D=false;var N=/\{\{[\s\S]*|[\s\S]*\}\}/gm;var _=/<%[\s\S]*|[\s\S]*%>/gm;var C=false;var z=false;var R=false;var F=false;var H=true;var B=true;var W=b({},["audio","head","math","script","style","svg","video"]);var j=b({},["audio","video","img","source"]);var G=b({},["alt","class","for","id","label","name","pattern","placeholder","summary","title","value","style","xmlns"]);var I=null;var q=n.createElement("form");var P=function(e){if(typeof e!=="object"){e={}}x="ALLOWED_TAGS"in e?b({},e.ALLOWED_TAGS):k;A="ALLOWED_ATTR"in e?b({},e.ALLOWED_ATTR):w;E="FORBID_TAGS"in e?b({},e.FORBID_TAGS):{};S="FORBID_ATTR"in e?b({},e.FORBID_ATTR):{};M=e.ALLOW_DATA_ATTR!==false;O=e.ALLOW_UNKNOWN_PROTOCOLS||false;L=e.SAFE_FOR_JQUERY||false;D=e.SAFE_FOR_TEMPLATES||false;C=e.WHOLE_DOCUMENT||false;z=e.RETURN_DOM||false;R=e.RETURN_DOM_FRAGMENT||false;F=e.RETURN_DOM_IMPORT||false;H=e.SANITIZE_DOM!==false;B=e.KEEP_CONTENT!==false;if(D){M=false}if(R){z=true}if(e.ADD_TAGS){if(x===k){x=T(x)}b(x,e.ADD_TAGS)}if(e.ADD_ATTR){if(A===w){A=T(A)}b(A,e.ADD_ATTR)}if(B){x["#text"]=true}if(Object&&"freeze"in Object){Object.freeze(e)}I=e};var U=function(e){try{e.parentNode.removeChild(e)}catch(t){e.outerHTML=""}};var V=function(e){var t,r;try{t=(new u).parseFromString(e,"text/html")}catch(n){}if(!t){t=m.createHTMLDocument("");r=t.body;r.parentNode.removeChild(r.parentNode.firstElementChild);r.outerHTML=e}if(typeof t.getElementsByTagName==="function"){return t.getElementsByTagName(C?"html":"body")[0]}return h.call(t,C?"html":"body")[0]};var K=function(e){return p.call(e.ownerDocument||e,e,l.SHOW_ELEMENT|l.SHOW_COMMENT|l.SHOW_TEXT,function(){return l.FILTER_ACCEPT},false)};var J=function(e){if(e instanceof f||e instanceof c){return false}if(typeof e.nodeName!=="string"||typeof e.textContent!=="string"||typeof e.removeChild!=="function"||!(e.attributes instanceof s)||typeof e.removeAttribute!=="function"||typeof e.setAttribute!=="function"){return true}return false};var Q=function(e){var t,r;re("beforeSanitizeElements",e,null);if(J(e)){U(e);return true}t=e.nodeName.toLowerCase();re("uponSanitizeElement",e,{tagName:t});if(!x[t]||E[t]){if(B&&!W[t]&&typeof e.insertAdjacentHTML==="function"){try{e.insertAdjacentHTML("AfterEnd",e.innerHTML)}catch(n){}}U(e);return true}if(L&&!e.firstElementChild&&(!e.content||!e.content.firstElementChild)){e.innerHTML=e.textContent.replace(/c){e.setAttribute("id",l.value)}}else{if(a==="id"){e.setAttribute(a,"")}e.removeAttribute(a)}if(!f.keepAttr){continue}if(H&&(o==="id"||o==="name")&&(i in t||i in n||i in q)){continue}if(D){i=i.replace(N," ");i=i.replace(_," ")}if(A[o]&&!S[o]&&(G[o]||Y.test(i.replace($,""))||o==="src"&&i.indexOf("data:")===0&&j[e.nodeName.toLowerCase()])||M&&X.test(o)||O&&!Z.test(i.replace($,""))){try{e.setAttribute(a,i)}catch(u){}}}re("afterSanitizeAttributes",e,null)};var te=function(e){var t;var r=K(e);re("beforeSanitizeShadowDOM",e,null);while(t=r.nextNode()){re("uponSanitizeShadowNode",t,null);if(Q(t)){continue}if(t.content instanceof i){te(t.content)}ee(t)}re("afterSanitizeShadowDOM",e,null)};var re=function(e,t,n){if(!y[e]){return}y[e].forEach(function(e){e.call(r,t,n,I)})};r.sanitize=function(e,n){var o,l,s,f,c;if(!e){e=""}if(typeof e!=="string"){if(typeof e.toString!=="function"){throw new TypeError("toString is not a function")}else{e=e.toString()}}if(!r.isSupported){if(typeof t.toStaticHTML==="object"||typeof t.toStaticHTML==="function"){return t.toStaticHTML(e)}return e}P(n);if(!z&&!C&&e.indexOf("<")===-1){return e}o=V(e);if(!o){return z?null:""}f=K(o);while(l=f.nextNode()){if(l.nodeType===3&&l===s){continue}if(Q(l)){continue}if(l.content instanceof i){te(l.content)}ee(l);s=l}if(z){if(R){c=v.call(o.ownerDocument);while(o.firstChild){c.appendChild(o.firstChild)}}else{c=o}if(F){c=g.call(a,c,true)}return c}return C?o.outerHTML:o.innerHTML};r.addHook=function(e,t){if(typeof t!=="function"){return}y[e]=y[e]||[];y[e].push(t)};r.removeHook=function(e){if(y[e]){y[e].pop()}};r.removeHooks=function(e){if(y[e]){y[e]=[]}};r.removeAllHooks=function(){y=[]};return r}); /**! * KvSortable * @author RubaXa * @license MIT * * Changed kvsortable plugin naming to prevent conflict with JQuery UI Sortable * @author Kartik Visweswaran */ (function kvsortableModule(factory) { "use strict"; if (typeof define === "function" && define.amd) { define(factory); } else if (typeof module != "undefined" && typeof module.exports != "undefined") { module.exports = factory(); } else { /* jshint sub:true */ window["KvSortable"] = factory(); } })(function kvsortableFactory() { "use strict"; if (typeof window === "undefined" || !window.document) { return function kvsortableError() { throw new Error("KvSortable.js requires a window with a document"); }; } var dragEl, parentEl, ghostEl, cloneEl, rootEl, nextEl, lastDownEl, scrollEl, scrollParentEl, scrollCustomFn, lastEl, lastCSS, lastParentCSS, oldIndex, newIndex, activeGroup, putKvSortable, autoScroll = {}, tapEvt, touchEvt, moved, /** @const */ R_SPACE = /\s+/g, R_FLOAT = /left|right|inline/, expando = 'KvSortable' + (new Date).getTime(), win = window, document = win.document, parseInt = win.parseInt, setTimeout = win.setTimeout, $ = win.jQuery || win.Zepto, Polymer = win.Polymer, captureMode = false, passiveMode = false, supportDraggable = ('draggable' in document.createElement('div')), supportCssPointerEvents = (function (el) { // false when IE11 if (!!navigator.userAgent.match(/(?:Trident.*rv[ :]?11\.|msie)/i)) { return false; } el = document.createElement('x'); el.style.cssText = 'pointer-events:auto'; return el.style.pointerEvents === 'auto'; })(), _silent = false, abs = Math.abs, min = Math.min, savedInputChecked = [], touchDragOverListeners = [], _autoScroll = _throttle(function (/**Event*/evt, /**Object*/options, /**HTMLElement*/rootEl) { // Bug: https://bugzilla.mozilla.org/show_bug.cgi?id=505521 if (rootEl && options.scroll) { var _this = rootEl[expando], el, rect, sens = options.scrollSensitivity, speed = options.scrollSpeed, x = evt.clientX, y = evt.clientY, winWidth = window.innerWidth, winHeight = window.innerHeight, vx, vy, scrollOffsetX, scrollOffsetY ; // Delect scrollEl if (scrollParentEl !== rootEl) { scrollEl = options.scroll; scrollParentEl = rootEl; scrollCustomFn = options.scrollFn; if (scrollEl === true) { scrollEl = rootEl; do { if ((scrollEl.offsetWidth < scrollEl.scrollWidth) || (scrollEl.offsetHeight < scrollEl.scrollHeight) ) { break; } /* jshint boss:true */ } while (scrollEl = scrollEl.parentNode); } } if (scrollEl) { el = scrollEl; rect = scrollEl.getBoundingClientRect(); vx = (abs(rect.right - x) <= sens) - (abs(rect.left - x) <= sens); vy = (abs(rect.bottom - y) <= sens) - (abs(rect.top - y) <= sens); } if (!(vx || vy)) { vx = (winWidth - x <= sens) - (x <= sens); vy = (winHeight - y <= sens) - (y <= sens); /* jshint expr:true */ (vx || vy) && (el = win); } if (autoScroll.vx !== vx || autoScroll.vy !== vy || autoScroll.el !== el) { autoScroll.el = el; autoScroll.vx = vx; autoScroll.vy = vy; clearInterval(autoScroll.pid); if (el) { autoScroll.pid = setInterval(function () { scrollOffsetY = vy ? vy * speed : 0; scrollOffsetX = vx ? vx * speed : 0; if ('function' === typeof(scrollCustomFn)) { return scrollCustomFn.call(_this, scrollOffsetX, scrollOffsetY, evt); } if (el === win) { win.scrollTo(win.pageXOffset + scrollOffsetX, win.pageYOffset + scrollOffsetY); } else { el.scrollTop += scrollOffsetY; el.scrollLeft += scrollOffsetX; } }, 24); } } } }, 30), _prepareGroup = function (options) { function toFn(value, pull) { if (value === void 0 || value === true) { value = group.name; } if (typeof value === 'function') { return value; } else { return function (to, from) { var fromGroup = from.options.group.name; return pull ? value : value && (value.join ? value.indexOf(fromGroup) > -1 : (fromGroup == value) ); }; } } var group = {}; var originalGroup = options.group; if (!originalGroup || typeof originalGroup != 'object') { originalGroup = {name: originalGroup}; } group.name = originalGroup.name; group.checkPull = toFn(originalGroup.pull, true); group.checkPut = toFn(originalGroup.put); group.revertClone = originalGroup.revertClone; options.group = group; } ; // Detect support a passive mode try { window.addEventListener('test', null, Object.defineProperty({}, 'passive', { get: function () { // `false`, because everything starts to work incorrectly and instead of d'n'd, // begins the page has scrolled. passiveMode = false; captureMode = { capture: false, passive: passiveMode }; } })); } catch (err) {} /** * @class KvSortable * @param {HTMLElement} el * @param {Object} [options] */ function KvSortable(el, options) { if (!(el && el.nodeType && el.nodeType === 1)) { throw 'KvSortable: `el` must be HTMLElement, and not ' + {}.toString.call(el); } this.el = el; // root element this.options = options = _extend({}, options); // Export instance el[expando] = this; // Default options var defaults = { group: Math.random(), sort: true, disabled: false, store: null, handle: null, scroll: true, scrollSensitivity: 30, scrollSpeed: 10, draggable: /[uo]l/i.test(el.nodeName) ? 'li' : '>*', ghostClass: 'kvsortable-ghost', chosenClass: 'kvsortable-chosen', dragClass: 'kvsortable-drag', ignore: 'a, img', filter: null, preventOnFilter: true, animation: 0, setData: function (dataTransfer, dragEl) { dataTransfer.setData('Text', dragEl.textContent); }, dropBubble: false, dragoverBubble: false, dataIdAttr: 'data-id', delay: 0, forceFallback: false, fallbackClass: 'kvsortable-fallback', fallbackOnBody: false, fallbackTolerance: 0, fallbackOffset: {x: 0, y: 0}, supportPointer: KvSortable.supportPointer !== false }; // Set default options for (var name in defaults) { !(name in options) && (options[name] = defaults[name]); } _prepareGroup(options); // Bind all private methods for (var fn in this) { if (fn.charAt(0) === '_' && typeof this[fn] === 'function') { this[fn] = this[fn].bind(this); } } // Setup drag mode this.nativeDraggable = options.forceFallback ? false : supportDraggable; // Bind events _on(el, 'mousedown', this._onTapStart); _on(el, 'touchstart', this._onTapStart); options.supportPointer && _on(el, 'pointerdown', this._onTapStart); if (this.nativeDraggable) { _on(el, 'dragover', this); _on(el, 'dragenter', this); } touchDragOverListeners.push(this._onDragOver); // Restore sorting options.store && this.sort(options.store.get(this)); } KvSortable.prototype = /** @lends KvSortable.prototype */ { constructor: KvSortable, _onTapStart: function (/** Event|TouchEvent */evt) { var _this = this, el = this.el, options = this.options, preventOnFilter = options.preventOnFilter, type = evt.type, touch = evt.touches && evt.touches[0], target = (touch || evt).target, originalTarget = evt.target.shadowRoot && (evt.path && evt.path[0]) || target, filter = options.filter, startIndex; _saveInputCheckedState(el); // Don't trigger start event when an element is been dragged, otherwise the evt.oldindex always wrong when set option.group. if (dragEl) { return; } if (/mousedown|pointerdown/.test(type) && evt.button !== 0 || options.disabled) { return; // only left button or enabled } // cancel dnd if original target is content editable if (originalTarget.isContentEditable) { return; } target = _closest(target, options.draggable, el); if (!target) { return; } if (lastDownEl === target) { // Ignoring duplicate `down` return; } // Get the index of the dragged element within its parent startIndex = _index(target, options.draggable); // Check filter if (typeof filter === 'function') { if (filter.call(this, evt, target, this)) { _dispatchEvent(_this, originalTarget, 'filter', target, el, el, startIndex); preventOnFilter && evt.preventDefault(); return; // cancel dnd } } else if (filter) { filter = filter.split(',').some(function (criteria) { criteria = _closest(originalTarget, criteria.trim(), el); if (criteria) { _dispatchEvent(_this, criteria, 'filter', target, el, el, startIndex); return true; } }); if (filter) { preventOnFilter && evt.preventDefault(); return; // cancel dnd } } if (options.handle && !_closest(originalTarget, options.handle, el)) { return; } // Prepare `dragstart` this._prepareDragStart(evt, touch, target, startIndex); }, _prepareDragStart: function (/** Event */evt, /** Touch */touch, /** HTMLElement */target, /** Number */startIndex) { var _this = this, el = _this.el, options = _this.options, ownerDocument = el.ownerDocument, dragStartFn; if (target && !dragEl && (target.parentNode === el)) { tapEvt = evt; rootEl = el; dragEl = target; parentEl = dragEl.parentNode; nextEl = dragEl.nextSibling; lastDownEl = target; activeGroup = options.group; oldIndex = startIndex; this._lastX = (touch || evt).clientX; this._lastY = (touch || evt).clientY; dragEl.style['will-change'] = 'all'; dragStartFn = function () { // Delayed drag has been triggered // we can re-enable the events: touchmove/mousemove _this._disableDelayedDrag(); // Make the element draggable dragEl.draggable = _this.nativeDraggable; // Chosen item _toggleClass(dragEl, options.chosenClass, true); // Bind the events: dragstart/dragend _this._triggerDragStart(evt, touch); // Drag start event _dispatchEvent(_this, rootEl, 'choose', dragEl, rootEl, rootEl, oldIndex); }; // Disable "draggable" options.ignore.split(',').forEach(function (criteria) { _find(dragEl, criteria.trim(), _disableDraggable); }); _on(ownerDocument, 'mouseup', _this._onDrop); _on(ownerDocument, 'touchend', _this._onDrop); _on(ownerDocument, 'touchcancel', _this._onDrop); _on(ownerDocument, 'selectstart', _this); options.supportPointer && _on(ownerDocument, 'pointercancel', _this._onDrop); if (options.delay) { // If the user moves the pointer or let go the click or touch // before the delay has been reached: // disable the delayed drag _on(ownerDocument, 'mouseup', _this._disableDelayedDrag); _on(ownerDocument, 'touchend', _this._disableDelayedDrag); _on(ownerDocument, 'touchcancel', _this._disableDelayedDrag); _on(ownerDocument, 'mousemove', _this._disableDelayedDrag); _on(ownerDocument, 'touchmove', _this._disableDelayedDrag); options.supportPointer && _on(ownerDocument, 'pointermove', _this._disableDelayedDrag); _this._dragStartTimer = setTimeout(dragStartFn, options.delay); } else { dragStartFn(); } } }, _disableDelayedDrag: function () { var ownerDocument = this.el.ownerDocument; clearTimeout(this._dragStartTimer); _off(ownerDocument, 'mouseup', this._disableDelayedDrag); _off(ownerDocument, 'touchend', this._disableDelayedDrag); _off(ownerDocument, 'touchcancel', this._disableDelayedDrag); _off(ownerDocument, 'mousemove', this._disableDelayedDrag); _off(ownerDocument, 'touchmove', this._disableDelayedDrag); _off(ownerDocument, 'pointermove', this._disableDelayedDrag); }, _triggerDragStart: function (/** Event */evt, /** Touch */touch) { touch = touch || (evt.pointerType == 'touch' ? evt : null); if (touch) { // Touch device support tapEvt = { target: dragEl, clientX: touch.clientX, clientY: touch.clientY }; this._onDragStart(tapEvt, 'touch'); } else if (!this.nativeDraggable) { this._onDragStart(tapEvt, true); } else { _on(dragEl, 'dragend', this); _on(rootEl, 'dragstart', this._onDragStart); } try { if (document.selection) { // Timeout neccessary for IE9 _nextTick(function () { document.selection.empty(); }); } else { window.getSelection().removeAllRanges(); } } catch (err) { } }, _dragStarted: function () { if (rootEl && dragEl) { var options = this.options; // Apply effect _toggleClass(dragEl, options.ghostClass, true); _toggleClass(dragEl, options.dragClass, false); KvSortable.active = this; // Drag start event _dispatchEvent(this, rootEl, 'start', dragEl, rootEl, rootEl, oldIndex); } else { this._nulling(); } }, _emulateDragOver: function () { if (touchEvt) { if (this._lastX === touchEvt.clientX && this._lastY === touchEvt.clientY) { return; } this._lastX = touchEvt.clientX; this._lastY = touchEvt.clientY; if (!supportCssPointerEvents) { _css(ghostEl, 'display', 'none'); } var target = document.elementFromPoint(touchEvt.clientX, touchEvt.clientY); var parent = target; var i = touchDragOverListeners.length; if (target && target.shadowRoot) { target = target.shadowRoot.elementFromPoint(touchEvt.clientX, touchEvt.clientY); parent = target; } if (parent) { do { if (parent[expando]) { while (i--) { touchDragOverListeners[i]({ clientX: touchEvt.clientX, clientY: touchEvt.clientY, target: target, rootEl: parent }); } break; } target = parent; // store last element } /* jshint boss:true */ while (parent = parent.parentNode); } if (!supportCssPointerEvents) { _css(ghostEl, 'display', ''); } } }, _onTouchMove: function (/**TouchEvent*/evt) { if (tapEvt) { var options = this.options, fallbackTolerance = options.fallbackTolerance, fallbackOffset = options.fallbackOffset, touch = evt.touches ? evt.touches[0] : evt, dx = (touch.clientX - tapEvt.clientX) + fallbackOffset.x, dy = (touch.clientY - tapEvt.clientY) + fallbackOffset.y, translate3d = evt.touches ? 'translate3d(' + dx + 'px,' + dy + 'px,0)' : 'translate(' + dx + 'px,' + dy + 'px)'; // only set the status to dragging, when we are actually dragging if (!KvSortable.active) { if (fallbackTolerance && min(abs(touch.clientX - this._lastX), abs(touch.clientY - this._lastY)) < fallbackTolerance ) { return; } this._dragStarted(); } // as well as creating the ghost element on the document body this._appendGhost(); moved = true; touchEvt = touch; _css(ghostEl, 'webkitTransform', translate3d); _css(ghostEl, 'mozTransform', translate3d); _css(ghostEl, 'msTransform', translate3d); _css(ghostEl, 'transform', translate3d); evt.preventDefault(); } }, _appendGhost: function () { if (!ghostEl) { var rect = dragEl.getBoundingClientRect(), css = _css(dragEl), options = this.options, ghostRect; ghostEl = dragEl.cloneNode(true); _toggleClass(ghostEl, options.ghostClass, false); _toggleClass(ghostEl, options.fallbackClass, true); _toggleClass(ghostEl, options.dragClass, true); _css(ghostEl, 'top', rect.top - parseInt(css.marginTop, 10)); _css(ghostEl, 'left', rect.left - parseInt(css.marginLeft, 10)); _css(ghostEl, 'width', rect.width); _css(ghostEl, 'height', rect.height); _css(ghostEl, 'opacity', '0.8'); _css(ghostEl, 'position', 'fixed'); _css(ghostEl, 'zIndex', '100000'); _css(ghostEl, 'pointerEvents', 'none'); options.fallbackOnBody && document.body.appendChild(ghostEl) || rootEl.appendChild(ghostEl); // Fixing dimensions. ghostRect = ghostEl.getBoundingClientRect(); _css(ghostEl, 'width', rect.width * 2 - ghostRect.width); _css(ghostEl, 'height', rect.height * 2 - ghostRect.height); } }, _onDragStart: function (/**Event*/evt, /**boolean*/useFallback) { var _this = this; var dataTransfer = evt.dataTransfer; var options = _this.options; _this._offUpEvents(); if (activeGroup.checkPull(_this, _this, dragEl, evt)) { cloneEl = _clone(dragEl); cloneEl.draggable = false; cloneEl.style['will-change'] = ''; _css(cloneEl, 'display', 'none'); _toggleClass(cloneEl, _this.options.chosenClass, false); // #1143: IFrame support workaround _this._cloneId = _nextTick(function () { rootEl.insertBefore(cloneEl, dragEl); _dispatchEvent(_this, rootEl, 'clone', dragEl); }); } _toggleClass(dragEl, options.dragClass, true); if (useFallback) { if (useFallback === 'touch') { // Bind touch events _on(document, 'touchmove', _this._onTouchMove); _on(document, 'touchend', _this._onDrop); _on(document, 'touchcancel', _this._onDrop); if (options.supportPointer) { _on(document, 'pointermove', _this._onTouchMove); _on(document, 'pointerup', _this._onDrop); } } else { // Old brwoser _on(document, 'mousemove', _this._onTouchMove); _on(document, 'mouseup', _this._onDrop); } _this._loopId = setInterval(_this._emulateDragOver, 50); } else { if (dataTransfer) { dataTransfer.effectAllowed = 'move'; options.setData && options.setData.call(_this, dataTransfer, dragEl); } _on(document, 'drop', _this); // #1143: Бывает элемент с IFrame внутри блокирует `drop`, // поэтому если вызвался `mouseover`, значит надо отменять весь d'n'd. // Breaking Chrome 62+ // _on(document, 'mouseover', _this); _this._dragStartId = _nextTick(_this._dragStarted); } }, _onDragOver: function (/**Event*/evt) { var el = this.el, target, dragRect, targetRect, revert, options = this.options, group = options.group, activeKvSortable = KvSortable.active, isOwner = (activeGroup === group), isMovingBetweenKvSortable = false, canSort = options.sort; if (evt.preventDefault !== void 0) { evt.preventDefault(); !options.dragoverBubble && evt.stopPropagation(); } if (dragEl.animated) { return; } moved = true; if (activeKvSortable && !options.disabled && (isOwner ? canSort || (revert = !rootEl.contains(dragEl)) // Reverting item into the original list : ( putKvSortable === this || ( (activeKvSortable.lastPullMode = activeGroup.checkPull(this, activeKvSortable, dragEl, evt)) && group.checkPut(this, activeKvSortable, dragEl, evt) ) ) ) && (evt.rootEl === void 0 || evt.rootEl === this.el) // touch fallback ) { // Smart auto-scrolling _autoScroll(evt, options, this.el); if (_silent) { return; } target = _closest(evt.target, options.draggable, el); dragRect = dragEl.getBoundingClientRect(); if (putKvSortable !== this) { putKvSortable = this; isMovingBetweenKvSortable = true; } if (revert) { _cloneHide(activeKvSortable, true); parentEl = rootEl; // actualization if (cloneEl || nextEl) { rootEl.insertBefore(dragEl, cloneEl || nextEl); } else if (!canSort) { rootEl.appendChild(dragEl); } return; } if ((el.children.length === 0) || (el.children[0] === ghostEl) || (el === evt.target) && (_ghostIsLast(el, evt)) ) { //assign target only if condition is true if (el.children.length !== 0 && el.children[0] !== ghostEl && el === evt.target) { target = el.lastElementChild; } if (target) { if (target.animated) { return; } targetRect = target.getBoundingClientRect(); } _cloneHide(activeKvSortable, isOwner); if (_onMove(rootEl, el, dragEl, dragRect, target, targetRect, evt) !== false) { if (!dragEl.contains(el)) { el.appendChild(dragEl); parentEl = el; // actualization } this._animate(dragRect, dragEl); target && this._animate(targetRect, target); } } else if (target && !target.animated && target !== dragEl && (target.parentNode[expando] !== void 0)) { if (lastEl !== target) { lastEl = target; lastCSS = _css(target); lastParentCSS = _css(target.parentNode); } targetRect = target.getBoundingClientRect(); var width = targetRect.right - targetRect.left, height = targetRect.bottom - targetRect.top, floating = R_FLOAT.test(lastCSS.cssFloat + lastCSS.display) || (lastParentCSS.display == 'flex' && lastParentCSS['flex-direction'].indexOf('row') === 0), isWide = (target.offsetWidth > dragEl.offsetWidth), isLong = (target.offsetHeight > dragEl.offsetHeight), halfway = (floating ? (evt.clientX - targetRect.left) / width : (evt.clientY - targetRect.top) / height) > 0.5, nextSibling = target.nextElementSibling, after = false ; if (floating) { var elTop = dragEl.offsetTop, tgTop = target.offsetTop; if (elTop === tgTop) { after = (target.previousElementSibling === dragEl) && !isWide || halfway && isWide; } else if (target.previousElementSibling === dragEl || dragEl.previousElementSibling === target) { after = (evt.clientY - targetRect.top) / height > 0.5; } else { after = tgTop > elTop; } } else if (!isMovingBetweenKvSortable) { after = (nextSibling !== dragEl) && !isLong || halfway && isLong; } var moveVector = _onMove(rootEl, el, dragEl, dragRect, target, targetRect, evt, after); if (moveVector !== false) { if (moveVector === 1 || moveVector === -1) { after = (moveVector === 1); } _silent = true; setTimeout(_unsilent, 30); _cloneHide(activeKvSortable, isOwner); if (!dragEl.contains(el)) { if (after && !nextSibling) { el.appendChild(dragEl); } else { target.parentNode.insertBefore(dragEl, after ? nextSibling : target); } } parentEl = dragEl.parentNode; // actualization this._animate(dragRect, dragEl); this._animate(targetRect, target); } } } }, _animate: function (prevRect, target) { var ms = this.options.animation; if (ms) { var currentRect = target.getBoundingClientRect(); if (prevRect.nodeType === 1) { prevRect = prevRect.getBoundingClientRect(); } _css(target, 'transition', 'none'); _css(target, 'transform', 'translate3d(' + (prevRect.left - currentRect.left) + 'px,' + (prevRect.top - currentRect.top) + 'px,0)' ); target.offsetWidth; // repaint _css(target, 'transition', 'all ' + ms + 'ms'); _css(target, 'transform', 'translate3d(0,0,0)'); clearTimeout(target.animated); target.animated = setTimeout(function () { _css(target, 'transition', ''); _css(target, 'transform', ''); target.animated = false; }, ms); } }, _offUpEvents: function () { var ownerDocument = this.el.ownerDocument; _off(document, 'touchmove', this._onTouchMove); _off(document, 'pointermove', this._onTouchMove); _off(ownerDocument, 'mouseup', this._onDrop); _off(ownerDocument, 'touchend', this._onDrop); _off(ownerDocument, 'pointerup', this._onDrop); _off(ownerDocument, 'touchcancel', this._onDrop); _off(ownerDocument, 'pointercancel', this._onDrop); _off(ownerDocument, 'selectstart', this); }, _onDrop: function (/**Event*/evt) { var el = this.el, options = this.options; clearInterval(this._loopId); clearInterval(autoScroll.pid); clearTimeout(this._dragStartTimer); _cancelNextTick(this._cloneId); _cancelNextTick(this._dragStartId); // Unbind events _off(document, 'mouseover', this); _off(document, 'mousemove', this._onTouchMove); if (this.nativeDraggable) { _off(document, 'drop', this); _off(el, 'dragstart', this._onDragStart); } this._offUpEvents(); if (evt) { if (moved) { evt.preventDefault(); !options.dropBubble && evt.stopPropagation(); } ghostEl && ghostEl.parentNode && ghostEl.parentNode.removeChild(ghostEl); if (rootEl === parentEl || KvSortable.active.lastPullMode !== 'clone') { // Remove clone cloneEl && cloneEl.parentNode && cloneEl.parentNode.removeChild(cloneEl); } if (dragEl) { if (this.nativeDraggable) { _off(dragEl, 'dragend', this); } _disableDraggable(dragEl); dragEl.style['will-change'] = ''; // Remove class's _toggleClass(dragEl, this.options.ghostClass, false); _toggleClass(dragEl, this.options.chosenClass, false); // Drag stop event _dispatchEvent(this, rootEl, 'unchoose', dragEl, parentEl, rootEl, oldIndex); if (rootEl !== parentEl) { newIndex = _index(dragEl, options.draggable); if (newIndex >= 0) { // Add event _dispatchEvent(null, parentEl, 'add', dragEl, parentEl, rootEl, oldIndex, newIndex); // Remove event _dispatchEvent(this, rootEl, 'remove', dragEl, parentEl, rootEl, oldIndex, newIndex); // drag from one list and drop into another _dispatchEvent(null, parentEl, 'sort', dragEl, parentEl, rootEl, oldIndex, newIndex); _dispatchEvent(this, rootEl, 'sort', dragEl, parentEl, rootEl, oldIndex, newIndex); } } else { if (dragEl.nextSibling !== nextEl) { // Get the index of the dragged element within its parent newIndex = _index(dragEl, options.draggable); if (newIndex >= 0) { // drag & drop within the same list _dispatchEvent(this, rootEl, 'update', dragEl, parentEl, rootEl, oldIndex, newIndex); _dispatchEvent(this, rootEl, 'sort', dragEl, parentEl, rootEl, oldIndex, newIndex); } } } if (KvSortable.active) { /* jshint eqnull:true */ if (newIndex == null || newIndex === -1) { newIndex = oldIndex; } _dispatchEvent(this, rootEl, 'end', dragEl, parentEl, rootEl, oldIndex, newIndex); // Save sorting this.save(); } } } this._nulling(); }, _nulling: function() { rootEl = dragEl = parentEl = ghostEl = nextEl = cloneEl = lastDownEl = scrollEl = scrollParentEl = tapEvt = touchEvt = moved = newIndex = lastEl = lastCSS = putKvSortable = activeGroup = KvSortable.active = null; savedInputChecked.forEach(function (el) { el.checked = true; }); savedInputChecked.length = 0; }, handleEvent: function (/**Event*/evt) { switch (evt.type) { case 'drop': case 'dragend': this._onDrop(evt); break; case 'dragover': case 'dragenter': if (dragEl) { this._onDragOver(evt); _globalDragOver(evt); } break; case 'mouseover': this._onDrop(evt); break; case 'selectstart': evt.preventDefault(); break; } }, /** * Serializes the item into an array of string. * @returns {String[]} */ toArray: function () { var order = [], el, children = this.el.children, i = 0, n = children.length, options = this.options; for (; i < n; i++) { el = children[i]; if (_closest(el, options.draggable, this.el)) { order.push(el.getAttribute(options.dataIdAttr) || _generateId(el)); } } return order; }, /** * Sorts the elements according to the array. * @param {String[]} order order of the items */ sort: function (order) { var items = {}, rootEl = this.el; this.toArray().forEach(function (id, i) { var el = rootEl.children[i]; if (_closest(el, this.options.draggable, rootEl)) { items[id] = el; } }, this); order.forEach(function (id) { if (items[id]) { rootEl.removeChild(items[id]); rootEl.appendChild(items[id]); } }); }, /** * Save the current sorting */ save: function () { var store = this.options.store; store && store.set(this); }, /** * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. * @param {HTMLElement} el * @param {String} [selector] default: `options.draggable` * @returns {HTMLElement|null} */ closest: function (el, selector) { return _closest(el, selector || this.options.draggable, this.el); }, /** * Set/get option * @param {string} name * @param {*} [value] * @returns {*} */ option: function (name, value) { var options = this.options; if (value === void 0) { return options[name]; } else { options[name] = value; if (name === 'group') { _prepareGroup(options); } } }, /** * Destroy */ destroy: function () { var el = this.el; el[expando] = null; _off(el, 'mousedown', this._onTapStart); _off(el, 'touchstart', this._onTapStart); _off(el, 'pointerdown', this._onTapStart); if (this.nativeDraggable) { _off(el, 'dragover', this); _off(el, 'dragenter', this); } // Remove draggable attributes Array.prototype.forEach.call(el.querySelectorAll('[draggable]'), function (el) { el.removeAttribute('draggable'); }); touchDragOverListeners.splice(touchDragOverListeners.indexOf(this._onDragOver), 1); this._onDrop(); this.el = el = null; } }; function _cloneHide(kvsortable, state) { if (kvsortable.lastPullMode !== 'clone') { state = true; } if (cloneEl && (cloneEl.state !== state)) { _css(cloneEl, 'display', state ? 'none' : ''); if (!state) { if (cloneEl.state) { if (kvsortable.options.group.revertClone) { rootEl.insertBefore(cloneEl, nextEl); kvsortable._animate(dragEl, cloneEl); } else { rootEl.insertBefore(cloneEl, dragEl); } } } cloneEl.state = state; } } function _closest(/**HTMLElement*/el, /**String*/selector, /**HTMLElement*/ctx) { if (el) { ctx = ctx || document; do { if ((selector === '>*' && el.parentNode === ctx) || _matches(el, selector)) { return el; } /* jshint boss:true */ } while (el = _getParentOrHost(el)); } return null; } function _getParentOrHost(el) { var parent = el.host; return (parent && parent.nodeType) ? parent : el.parentNode; } function _globalDragOver(/**Event*/evt) { if (evt.dataTransfer) { evt.dataTransfer.dropEffect = 'move'; } evt.preventDefault(); } function _on(el, event, fn) { el.addEventListener(event, fn, captureMode); } function _off(el, event, fn) { el.removeEventListener(event, fn, captureMode); } function _toggleClass(el, name, state) { if (el) { if (el.classList) { el.classList[state ? 'add' : 'remove'](name); } else { var className = (' ' + el.className + ' ').replace(R_SPACE, ' ').replace(' ' + name + ' ', ' '); el.className = (className + (state ? ' ' + name : '')).replace(R_SPACE, ' '); } } } function _css(el, prop, val) { var style = el && el.style; if (style) { if (val === void 0) { if (document.defaultView && document.defaultView.getComputedStyle) { val = document.defaultView.getComputedStyle(el, ''); } else if (el.currentStyle) { val = el.currentStyle; } return prop === void 0 ? val : val[prop]; } else { if (!(prop in style)) { prop = '-webkit-' + prop; } style[prop] = val + (typeof val === 'string' ? '' : 'px'); } } } function _find(ctx, tagName, iterator) { if (ctx) { var list = ctx.getElementsByTagName(tagName), i = 0, n = list.length; if (iterator) { for (; i < n; i++) { iterator(list[i], i); } } return list; } return []; } function _dispatchEvent(kvsortable, rootEl, name, targetEl, toEl, fromEl, startIndex, newIndex) { kvsortable = (kvsortable || rootEl[expando]); var evt = document.createEvent('Event'), options = kvsortable.options, onName = 'on' + name.charAt(0).toUpperCase() + name.substr(1); evt.initEvent(name, true, true); evt.to = toEl || rootEl; evt.from = fromEl || rootEl; evt.item = targetEl || rootEl; evt.clone = cloneEl; evt.oldIndex = startIndex; evt.newIndex = newIndex; rootEl.dispatchEvent(evt); if (options[onName]) { options[onName].call(kvsortable, evt); } } function _onMove(fromEl, toEl, dragEl, dragRect, targetEl, targetRect, originalEvt, willInsertAfter) { var evt, kvsortable = fromEl[expando], onMoveFn = kvsortable.options.onMove, retVal; evt = document.createEvent('Event'); evt.initEvent('move', true, true); evt.to = toEl; evt.from = fromEl; evt.dragged = dragEl; evt.draggedRect = dragRect; evt.related = targetEl || toEl; evt.relatedRect = targetRect || toEl.getBoundingClientRect(); evt.willInsertAfter = willInsertAfter; fromEl.dispatchEvent(evt); if (onMoveFn) { retVal = onMoveFn.call(kvsortable, evt, originalEvt); } return retVal; } function _disableDraggable(el) { el.draggable = false; } function _unsilent() { _silent = false; } /** @returns {HTMLElement|false} */ function _ghostIsLast(el, evt) { var lastEl = el.lastElementChild, rect = lastEl.getBoundingClientRect(); // 5 — min delta // abs — нельзя добавлять, а то глюки при наведении сверху return (evt.clientY - (rect.top + rect.height) > 5) || (evt.clientX - (rect.left + rect.width) > 5); } /** * Generate id * @param {HTMLElement} el * @returns {String} * @private */ function _generateId(el) { var str = el.tagName + el.className + el.src + el.href + el.textContent, i = str.length, sum = 0; while (i--) { sum += str.charCodeAt(i); } return sum.toString(36); } /** * Returns the index of an element within its parent for a selected set of * elements * @param {HTMLElement} el * @param {selector} selector * @return {number} */ function _index(el, selector) { var index = 0; if (!el || !el.parentNode) { return -1; } while (el && (el = el.previousElementSibling)) { if ((el.nodeName.toUpperCase() !== 'TEMPLATE') && (selector === '>*' || _matches(el, selector))) { index++; } } return index; } function _matches(/**HTMLElement*/el, /**String*/selector) { if (el) { selector = selector.split('.'); var tag = selector.shift().toUpperCase(), re = new RegExp('\\s(' + selector.join('|') + ')(?=\\s)', 'g'); return ( (tag === '' || el.nodeName.toUpperCase() == tag) && (!selector.length || ((' ' + el.className + ' ').match(re) || []).length == selector.length) ); } return false; } function _throttle(callback, ms) { var args, _this; return function () { if (args === void 0) { args = arguments; _this = this; setTimeout(function () { if (args.length === 1) { callback.call(_this, args[0]); } else { callback.apply(_this, args); } args = void 0; }, ms); } }; } function _extend(dst, src) { if (dst && src) { for (var key in src) { if (src.hasOwnProperty(key)) { dst[key] = src[key]; } } } return dst; } function _clone(el) { if (Polymer && Polymer.dom) { return Polymer.dom(el).cloneNode(true); } else if ($) { return $(el).clone(true)[0]; } else { return el.cloneNode(true); } } function _saveInputCheckedState(root) { var inputs = root.getElementsByTagName('input'); var idx = inputs.length; while (idx--) { var el = inputs[idx]; el.checked && savedInputChecked.push(el); } } function _nextTick(fn) { return setTimeout(fn, 0); } function _cancelNextTick(id) { return clearTimeout(id); } // Fixed #973: _on(document, 'touchmove', function (evt) { if (KvSortable.active) { evt.preventDefault(); } }); // Export utils KvSortable.utils = { on: _on, off: _off, css: _css, find: _find, is: function (el, selector) { return !!_closest(el, selector, el); }, extend: _extend, throttle: _throttle, closest: _closest, toggleClass: _toggleClass, clone: _clone, index: _index, nextTick: _nextTick, cancelNextTick: _cancelNextTick }; /** * Create kvsortable instance * @param {HTMLElement} el * @param {Object} [options] */ KvSortable.create = function (el, options) { return new KvSortable(el, options); }; // Export KvSortable.version = '1.7.0'; return KvSortable; }); /** * jQuery plugin for KvSortable */ (function (factory) { "use strict"; if (typeof define === "function" && define.amd) { define(["jquery"], factory); } else { /* jshint sub:true */ factory(jQuery); } })(function ($) { "use strict"; $.fn.kvsortable = function (options) { var retVal, args = arguments; this.each(function () { var $el = $(this), kvsortable = $el.data('kvsortable'); if (!kvsortable && (options instanceof Object || !options)) { kvsortable = new KvSortable(this, options); $el.data('kvsortable', kvsortable); } if (kvsortable) { if (options === 'widget') { retVal = kvsortable; } else if (options === 'destroy') { kvsortable.destroy(); $el.removeData('kvsortable'); } else if (typeof kvsortable[options] === 'function') { retVal = kvsortable[options].apply(kvsortable, [].slice.call(args, 1)); } else if (options in kvsortable.options) { retVal = kvsortable.option.apply(kvsortable, args); } } }); return (retVal === void 0) ? this : retVal; }; }); !function(t){"use strict";"function"==typeof define&&define.amd?define(t):"undefined"!=typeof module&&void 0!==module.exports?module.exports=t():window.KvSortable=t()}(function(){"use strict";function t(e,n){if(!e||!e.nodeType||1!==e.nodeType)throw"KvSortable: `el` must be HTMLElement, and not "+{}.toString.call(e);this.el=e,this.options=n=g({},n),e[U]=this;var i={group:Math.random(),sort:!0,disabled:!1,store:null,handle:null,scroll:!0,scrollSensitivity:30,scrollSpeed:10,draggable:/[uo]l/i.test(e.nodeName)?"li":">*",ghostClass:"kvsortable-ghost",chosenClass:"kvsortable-chosen",dragClass:"kvsortable-drag",ignore:"a, img",filter:null,preventOnFilter:!0,animation:0,setData:function(t,e){t.setData("Text",e.textContent)},dropBubble:!1,dragoverBubble:!1,dataIdAttr:"data-id",delay:0,forceFallback:!1,fallbackClass:"kvsortable-fallback",fallbackOnBody:!1,fallbackTolerance:0,fallbackOffset:{x:0,y:0},supportPointer:!1!==t.supportPointer};for(var r in i)!(r in n)&&(n[r]=i[r]);rt(n);for(var a in this)"_"===a.charAt(0)&&"function"==typeof this[a]&&(this[a]=this[a].bind(this));this.nativeDraggable=!n.forceFallback&&Z,o(e,"mousedown",this._onTapStart),o(e,"touchstart",this._onTapStart),n.supportPointer&&o(e,"pointerdown",this._onTapStart),this.nativeDraggable&&(o(e,"dragover",this),o(e,"dragenter",this)),ot.push(this._onDragOver),n.store&&this.sort(n.store.get(this))}function e(t,e){"clone"!==t.lastPullMode&&(e=!0),w&&w.state!==e&&(a(w,"display",e?"none":""),e||w.state&&(t.options.group.revertClone?(T.insertBefore(w,C),t._animate(_,w)):T.insertBefore(w,_)),w.state=e)}function n(t,e,n){if(t){n=n||W;do{if(">*"===e&&t.parentNode===n||f(t,e))return t}while(t=function(t){var e=t.host;return e&&e.nodeType?e:t.parentNode}(t))}return null}function o(t,e,n){t.addEventListener(e,n,G)}function i(t,e,n){t.removeEventListener(e,n,G)}function r(t,e,n){if(t)if(t.classList)t.classList[n?"add":"remove"](e);else{var o=(" "+t.className+" ").replace(L," ").replace(" "+e+" "," ");t.className=(o+(n?" "+e:"")).replace(L," ")}}function a(t,e,n){var o=t&&t.style;if(o){if(void 0===n)return W.defaultView&&W.defaultView.getComputedStyle?n=W.defaultView.getComputedStyle(t,""):t.currentStyle&&(n=t.currentStyle),void 0===e?n:n[e];e in o||(e="-webkit-"+e),o[e]=n+("string"==typeof n?"":"px")}}function s(t,e,n){if(t){var o=t.getElementsByTagName(e),i=0,r=o.length;if(n)for(;i*"!==e&&!f(t,e)||n++;return n}function f(t,e){if(t){var n=(e=e.split(".")).shift().toUpperCase(),o=new RegExp("\\s("+e.join("|")+")(?=\\s)","g");return!(""!==n&&t.nodeName.toUpperCase()!=n||e.length&&((" "+t.className+" ").match(o)||[]).length!=e.length)}return!1}function p(t,e){var n,o;return function(){void 0===n&&(n=arguments,o=this,q(function(){1===n.length?t.call(o,n[0]):t.apply(o,n),n=void 0},e))}}function g(t,e){if(t&&e)for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n]);return t}function v(t){return z&&z.dom?z.dom(t).cloneNode(!0):V?V(t).clone(!0)[0]:t.cloneNode(!0)}function m(t){return q(t,0)}function b(t){return clearTimeout(t)}if("undefined"==typeof window||!window.document)return function(){throw new Error("KvSortable.js requires a window with a document")};var _,D,y,w,T,C,S,E,k,x,N,B,P,Y,O,X,I,R,A,M,j={},L=/\s+/g,F=/left|right|inline/,U="KvSortable"+(new Date).getTime(),H=window,W=H.document,K=H.parseInt,q=H.setTimeout,V=H.jQuery||H.Zepto,z=H.Polymer,G=!1,Q=!1,Z="draggable"in W.createElement("div"),J=function(t){return!navigator.userAgent.match(/(?:Trident.*rv[ :]?11\.|msie)/i)&&(t=W.createElement("x"),t.style.cssText="pointer-events:auto","auto"===t.style.pointerEvents)}(),$=!1,tt=Math.abs,et=Math.min,nt=[],ot=[],it=p(function(t,e,n){if(n&&e.scroll){var o,i,r,a,s,l,c=n[U],d=e.scrollSensitivity,h=e.scrollSpeed,u=t.clientX,f=t.clientY,p=window.innerWidth,g=window.innerHeight;if(k!==n&&(E=e.scroll,k=n,x=e.scrollFn,!0===E)){E=n;do{if(E.offsetWidth-1:i==t)}}var n={},o=t.group;o&&"object"==typeof o||(o={name:o}),n.name=o.name,n.checkPull=e(o.pull,!0),n.checkPut=e(o.put),n.revertClone=o.revertClone,t.group=n};try{window.addEventListener("test",null,Object.defineProperty({},"passive",{get:function(){G={capture:!1,passive:Q=!1}}}))}catch(t){}return t.prototype={constructor:t,_onTapStart:function(t){var e,o=this,i=this.el,r=this.options,a=r.preventOnFilter,s=t.type,c=t.touches&&t.touches[0],d=(c||t).target,h=t.target.shadowRoot&&t.path&&t.path[0]||d,f=r.filter;if(function(t){for(var e=t.getElementsByTagName("input"),n=e.length;n--;){var o=e[n];o.checked&&nt.push(o)}}(i),!_&&!(/mousedown|pointerdown/.test(s)&&0!==t.button||r.disabled)&&!h.isContentEditable&&(d=n(d,r.draggable,i))&&S!==d){if(e=u(d,r.draggable),"function"==typeof f){if(f.call(this,t,d,this))return l(o,h,"filter",d,i,i,e),void(a&&t.preventDefault())}else if(f&&(f=f.split(",").some(function(t){if(t=n(h,t.trim(),i))return l(o,t,"filter",d,i,i,e),!0})))return void(a&&t.preventDefault());r.handle&&!n(h,r.handle,i)||this._prepareDragStart(t,c,d,e)}},_prepareDragStart:function(t,e,n,i){var a,c=this,h=c.el,u=c.options,f=h.ownerDocument;n&&!_&&n.parentNode===h&&(R=t,T=h,D=(_=n).parentNode,C=_.nextSibling,S=n,X=u.group,Y=i,this._lastX=(e||t).clientX,this._lastY=(e||t).clientY,_.style["will-change"]="all",a=function(){c._disableDelayedDrag(),_.draggable=c.nativeDraggable,r(_,u.chosenClass,!0),c._triggerDragStart(t,e),l(c,T,"choose",_,T,T,Y)},u.ignore.split(",").forEach(function(t){s(_,t.trim(),d)}),o(f,"mouseup",c._onDrop),o(f,"touchend",c._onDrop),o(f,"touchcancel",c._onDrop),o(f,"selectstart",c),u.supportPointer&&o(f,"pointercancel",c._onDrop),u.delay?(o(f,"mouseup",c._disableDelayedDrag),o(f,"touchend",c._disableDelayedDrag),o(f,"touchcancel",c._disableDelayedDrag),o(f,"mousemove",c._disableDelayedDrag),o(f,"touchmove",c._disableDelayedDrag),u.supportPointer&&o(f,"pointermove",c._disableDelayedDrag),c._dragStartTimer=q(a,u.delay)):a())},_disableDelayedDrag:function(){var t=this.el.ownerDocument;clearTimeout(this._dragStartTimer),i(t,"mouseup",this._disableDelayedDrag),i(t,"touchend",this._disableDelayedDrag),i(t,"touchcancel",this._disableDelayedDrag),i(t,"mousemove",this._disableDelayedDrag),i(t,"touchmove",this._disableDelayedDrag),i(t,"pointermove",this._disableDelayedDrag)},_triggerDragStart:function(t,e){(e=e||("touch"==t.pointerType?t:null))?(R={target:_,clientX:e.clientX,clientY:e.clientY},this._onDragStart(R,"touch")):this.nativeDraggable?(o(_,"dragend",this),o(T,"dragstart",this._onDragStart)):this._onDragStart(R,!0);try{W.selection?m(function(){W.selection.empty()}):window.getSelection().removeAllRanges()}catch(t){}},_dragStarted:function(){if(T&&_){var e=this.options;r(_,e.ghostClass,!0),r(_,e.dragClass,!1),t.active=this,l(this,T,"start",_,T,T,Y)}else this._nulling()},_emulateDragOver:function(){if(A){if(this._lastX===A.clientX&&this._lastY===A.clientY)return;this._lastX=A.clientX,this._lastY=A.clientY,J||a(y,"display","none");var t=W.elementFromPoint(A.clientX,A.clientY),e=t,n=ot.length;if(t&&t.shadowRoot&&(e=t=t.shadowRoot.elementFromPoint(A.clientX,A.clientY)),e)do{if(e[U]){for(;n--;)ot[n]({clientX:A.clientX,clientY:A.clientY,target:t,rootEl:e});break}t=e}while(e=e.parentNode);J||a(y,"display","")}},_onTouchMove:function(e){if(R){var n=this.options,o=n.fallbackTolerance,i=n.fallbackOffset,r=e.touches?e.touches[0]:e,s=r.clientX-R.clientX+i.x,l=r.clientY-R.clientY+i.y,c=e.touches?"translate3d("+s+"px,"+l+"px,0)":"translate("+s+"px,"+l+"px)";if(!t.active){if(o&&et(tt(r.clientX-this._lastX),tt(r.clientY-this._lastY))5||e.clientX-(n.left+n.width)>5}(d,o)){if(0!==d.children.length&&d.children[0]!==y&&d===o.target&&(i=d.lastElementChild),i){if(i.animated)return;s=i.getBoundingClientRect()}e(p,g),!1!==c(T,d,_,r,i,s,o)&&(_.contains(d)||(d.appendChild(_),D=d),this._animate(r,_),i&&this._animate(s,i))}else if(i&&!i.animated&&i!==_&&void 0!==i.parentNode[U]){N!==i&&(N=i,B=a(i),P=a(i.parentNode));var b=(s=i.getBoundingClientRect()).right-s.left,S=s.bottom-s.top,E=F.test(B.cssFloat+B.display)||"flex"==P.display&&0===P["flex-direction"].indexOf("row"),k=i.offsetWidth>_.offsetWidth,x=i.offsetHeight>_.offsetHeight,Y=(E?(o.clientX-s.left)/b:(o.clientY-s.top)/S)>.5,O=i.nextElementSibling,R=!1;if(E){var A=_.offsetTop,j=i.offsetTop;R=A===j?i.previousElementSibling===_&&!k||Y&&k:i.previousElementSibling===_||_.previousElementSibling===i?(o.clientY-s.top)/S>.5:j>A}else v||(R=O!==_&&!x||Y&&x);var L=c(T,d,_,r,i,s,o,R);!1!==L&&(1!==L&&-1!==L||(R=1===L),$=!0,q(h,30),e(p,g),_.contains(d)||(R&&!O?d.appendChild(_):i.parentNode.insertBefore(_,R?O:i)),D=_.parentNode,this._animate(r,_),this._animate(s,i))}}},_animate:function(t,e){var n=this.options.animation;if(n){var o=e.getBoundingClientRect();1===t.nodeType&&(t=t.getBoundingClientRect()),a(e,"transition","none"),a(e,"transform","translate3d("+(t.left-o.left)+"px,"+(t.top-o.top)+"px,0)"),e.offsetWidth,a(e,"transition","all "+n+"ms"),a(e,"transform","translate3d(0,0,0)"),clearTimeout(e.animated),e.animated=q(function(){a(e,"transition",""),a(e,"transform",""),e.animated=!1},n)}},_offUpEvents:function(){var t=this.el.ownerDocument;i(W,"touchmove",this._onTouchMove),i(W,"pointermove",this._onTouchMove),i(t,"mouseup",this._onDrop),i(t,"touchend",this._onDrop),i(t,"pointerup",this._onDrop),i(t,"touchcancel",this._onDrop),i(t,"pointercancel",this._onDrop),i(t,"selectstart",this)},_onDrop:function(e){var n=this.el,o=this.options;clearInterval(this._loopId),clearInterval(j.pid),clearTimeout(this._dragStartTimer),b(this._cloneId),b(this._dragStartId),i(W,"mouseover",this),i(W,"mousemove",this._onTouchMove),this.nativeDraggable&&(i(W,"drop",this),i(n,"dragstart",this._onDragStart)),this._offUpEvents(),e&&(M&&(e.preventDefault(),!o.dropBubble&&e.stopPropagation()),y&&y.parentNode&&y.parentNode.removeChild(y),T!==D&&"clone"===t.active.lastPullMode||w&&w.parentNode&&w.parentNode.removeChild(w),_&&(this.nativeDraggable&&i(_,"dragend",this),d(_),_.style["will-change"]="",r(_,this.options.ghostClass,!1),r(_,this.options.chosenClass,!1),l(this,T,"unchoose",_,D,T,Y),T!==D?(O=u(_,o.draggable))>=0&&(l(null,D,"add",_,D,T,Y,O),l(this,T,"remove",_,D,T,Y,O),l(null,D,"sort",_,D,T,Y,O),l(this,T,"sort",_,D,T,Y,O)):_.nextSibling!==C&&(O=u(_,o.draggable))>=0&&(l(this,T,"update",_,D,T,Y,O),l(this,T,"sort",_,D,T,Y,O)),t.active&&(null!=O&&-1!==O||(O=Y),l(this,T,"end",_,D,T,Y,O),this.save()))),this._nulling()},_nulling:function(){T=_=D=y=C=w=S=E=k=R=A=M=O=N=B=I=X=t.active=null,nt.forEach(function(t){t.checked=!0}),nt.length=0},handleEvent:function(t){switch(t.type){case"drop":case"dragend":this._onDrop(t);break;case"dragover":case"dragenter":_&&(this._onDragOver(t),function(t){t.dataTransfer&&(t.dataTransfer.dropEffect="move"),t.preventDefault()}(t));break;case"mouseover":this._onDrop(t);break;case"selectstart":t.preventDefault()}},toArray:function(){for(var t,e=[],o=this.el.children,i=0,r=o.length,a=this.options;i'); $fileUploader.addClass('file-multiple'); $fileList = $('.file-uploader .file-list'); $fileList.append($fileContainer); } else { $fileContainer.append('

    '); } calcSize = function(size) { var i, sizeMap; sizeMap = { 1: 'B', 2: 'KB', 3: 'MB', 4: 'GB' }; i = 1; while (size > 999.99) { size = size / 1024; i++; } return size.toFixed(2) + ' ' + sizeMap[i]; }; $fileInput.on('change', function(e) { $fileContainer.css('background', 'none'); $fileContainer.removeClass('already-uploaded'); return readURL(this); }); readURL = function(input) { var files, reader; files = input.files; if (files && files[0]) { reader = new FileReader(); if ($fileInput.attr('multiple') !== void 0) { return multiFile(reader, files); } else { return justOneFile(reader, files); } } }; multiFile = function(reader, files) { return [].forEach.call(files, function(file) { reader = new FileReader(); reader.onload = function(e) { var base, base1, base2, base3, base4, base5, fileBackground, fileItem, items; if (typeof file === 'object' && file.toString() === '[object File]') { if (-1 === $fileNames.indexOf(file.name)) { $files.push(file); $fileNames.push(file.name); items = $('.file-item').length; $fileContainer.before("
  • "); fileItem = $("#file-item-" + items); fileItem.append("
    "); fileItem.append(""); fileBackground = $("#file-item-background-" + items); if (typeof (base = file.type).includes === "function" ? base.includes('image') : void 0) { fileBackground.css({ 'background-image': "url(" + e.target.result + ")" }); } else if (typeof (base1 = file.type).includes === "function" ? base1.includes('audio') : void 0) { fileBackground.append(""); } else if (typeof (base2 = file.type).includes === "function" ? base2.includes('video') : void 0) { fileBackground.append(""); } else if (typeof (base3 = file.type).includes === "function" ? base3.includes('application') : void 0) { fileBackground.append(""); } else if (typeof (base4 = file.type).includes === "function" ? base4.includes('text') : void 0) { fileBackground.append(""); } else if (typeof (base5 = file.type).includes === "function" ? base5.includes('font') : void 0) { fileBackground.append(""); } else { fileBackground.append(""); } } } return $('.file-icon-delete').click(function() { var filePos, id, namePos; id = this.id.split('-')[3]; $("#" + ($('#file-item-' + id).attr('aria-describedby'))).remove(); $("#file-item-" + id).remove(); filePos = $files.indexOf($files[id]); $files.splice(filePos, 1); namePos = $fileNames.indexOf($fileNames[id]); return $fileNames.splice(namePos, 1); }); }; return reader.readAsDataURL(file); }); }; return justOneFile = function(reader, files) { var base, base1, base2, base3, base4, base5, f, rocketType; f = files[0]; if (f.name.includes('.rocket')) { rocketType = 'KepplerRocket'; } $('.file-container .file-name').text(f.name + " (" + (calcSize(f.size)) + ") - " + (rocketType || f.type || 'unknown')); $fileIcon.removeClass().addClass('file-icon'); if (rocketType) { $fileIcon.addClass('icon-rocket'); } else if (typeof (base = f.type).includes === "function" ? base.includes('image') : void 0) { $fileIcon.addClass('icon-picture'); } else if (typeof (base1 = f.type).includes === "function" ? base1.includes('audio') : void 0) { $fileIcon.addClass('icon-music-tone-alt'); } else if (typeof (base2 = f.type).includes === "function" ? base2.includes('video') : void 0) { $fileIcon.addClass('icon-film'); } else if (typeof (base3 = f.type).includes === "function" ? base3.includes('application') : void 0) { $fileIcon.addClass('icon-notebook'); } else if (typeof (base4 = f.type).includes === "function" ? base4.includes('text') : void 0) { $fileIcon.addClass('icon-doc'); } else if (typeof (base5 = f.type).includes === "function" ? base5.includes('font') : void 0) { $fileIcon.addClass('icon-emotsmile'); } else { $fileIcon.addClass('icon-question'); } reader.onload = function(e) { if (f.type.includes('image')) { $('.file-container').css({ 'background-image': "url(" + e.target.result + ")", 'background-position': 'center', 'background-size': 'contain', 'background-repeat': 'no-repeat' }); return $('.file-container').addClass('already-uploaded'); } }; return reader.readAsDataURL(files[0]); }; }; $(document).on('turbolinks:load', file_uploader); }).call(this); function imgPreview() { xOffset = 20; // separacion de la imagen con respecto al puntero en X yOffset = 20; // separacion de la imagen con respecto al puntero en Y imgMargin = 50; // separacion de la imagen con respecto al borde de la pantalla $('.show-row img, .list-row img').hover(function (e) { $('body').append(`No image source`); xImgOffset = $(window).width() - ($('.img-show').width() + imgMargin); yImgOffset = $(window).height() - ($('.img-show').height() + imgMargin); // breakpoint para que la imagen siempre esté visible en la pantalla $('.img-show') .css({ 'left': ((e.pageX < xImgOffset ? e.pageX : (e.pageY < yImgOffset ? xImgOffset : (e.pageX - ($('.img-show').width() + imgMargin)))) + xOffset) + 'px', 'top': ((e.pageY < yImgOffset ? e.pageY : (yImgOffset)) + yOffset) + 'px' }) }, function () { $('.img-show').remove(); }); $('.show-row img, .list-row img').mousemove(function (e) { $('.img-show') .css({ 'left': ((e.pageX < xImgOffset ? e.pageX : (e.pageY < yImgOffset ? xImgOffset : (e.pageX - ($('.img-show').width() + imgMargin)))) + xOffset) + 'px', 'top': ((e.pageY < (yImgOffset) ? e.pageY : (yImgOffset)) + yOffset) + 'px' }) }); } $(document).on('turbolinks:render', function () { imgPreview() }) $(document).on('turbolinks:load', function () { imgPreview() }) ; /** * jscolor - JavaScript Color Picker * * @link http://jscolor.com * @license For open source use: GPLv3 * For commercial use: JSColor Commercial License * @author Jan Odvarko * @version 2.0.5 * * See usage examples at http://jscolor.com/examples/ */ "use strict"; if (!window.jscolor) { window.jscolor = (function () { var jsc = { register : function () { jsc.attachDOMReadyEvent(jsc.init); jsc.attachEvent(document, 'mousedown', jsc.onDocumentMouseDown); jsc.attachEvent(document, 'touchstart', jsc.onDocumentTouchStart); jsc.attachEvent(window, 'resize', jsc.onWindowResize); }, init : function () { if (jsc.jscolor.lookupClass) { jsc.jscolor.installByClassName(jsc.jscolor.lookupClass); } }, tryInstallOnElements : function (elms, className) { var matchClass = new RegExp('(^|\\s)(' + className + ')(\\s*(\\{[^}]*\\})|\\s|$)', 'i'); for (var i = 0; i < elms.length; i += 1) { if (elms[i].type !== undefined && elms[i].type.toLowerCase() == 'color') { if (jsc.isColorAttrSupported) { // skip inputs of type 'color' if supported by the browser continue; } } var m; if (!elms[i].jscolor && elms[i].className && (m = elms[i].className.match(matchClass))) { var targetElm = elms[i]; var optsStr = null; var dataOptions = jsc.getDataAttr(targetElm, 'jscolor'); if (dataOptions !== null) { optsStr = dataOptions; } else if (m[4]) { optsStr = m[4]; } var opts = {}; if (optsStr) { try { opts = (new Function ('return (' + optsStr + ')'))(); } catch(eParseError) { jsc.warn('Error parsing jscolor options: ' + eParseError + ':\n' + optsStr); } } targetElm.jscolor = new jsc.jscolor(targetElm, opts); } } }, isColorAttrSupported : (function () { var elm = document.createElement('input'); if (elm.setAttribute) { elm.setAttribute('type', 'color'); if (elm.type.toLowerCase() == 'color') { return true; } } return false; })(), isCanvasSupported : (function () { var elm = document.createElement('canvas'); return !!(elm.getContext && elm.getContext('2d')); })(), fetchElement : function (mixed) { return typeof mixed === 'string' ? document.getElementById(mixed) : mixed; }, isElementType : function (elm, type) { return elm.nodeName.toLowerCase() === type.toLowerCase(); }, getDataAttr : function (el, name) { var attrName = 'data-' + name; var attrValue = el.getAttribute(attrName); if (attrValue !== null) { return attrValue; } return null; }, attachEvent : function (el, evnt, func) { if (el.addEventListener) { el.addEventListener(evnt, func, false); } else if (el.attachEvent) { el.attachEvent('on' + evnt, func); } }, detachEvent : function (el, evnt, func) { if (el.removeEventListener) { el.removeEventListener(evnt, func, false); } else if (el.detachEvent) { el.detachEvent('on' + evnt, func); } }, _attachedGroupEvents : {}, attachGroupEvent : function (groupName, el, evnt, func) { if (!jsc._attachedGroupEvents.hasOwnProperty(groupName)) { jsc._attachedGroupEvents[groupName] = []; } jsc._attachedGroupEvents[groupName].push([el, evnt, func]); jsc.attachEvent(el, evnt, func); }, detachGroupEvents : function (groupName) { if (jsc._attachedGroupEvents.hasOwnProperty(groupName)) { for (var i = 0; i < jsc._attachedGroupEvents[groupName].length; i += 1) { var evt = jsc._attachedGroupEvents[groupName][i]; jsc.detachEvent(evt[0], evt[1], evt[2]); } delete jsc._attachedGroupEvents[groupName]; } }, attachDOMReadyEvent : function (func) { var fired = false; var fireOnce = function () { if (!fired) { fired = true; func(); } }; if (document.readyState === 'complete') { setTimeout(fireOnce, 1); // async return; } if (document.addEventListener) { document.addEventListener('DOMContentLoaded', fireOnce, false); // Fallback window.addEventListener('load', fireOnce, false); } else if (document.attachEvent) { // IE document.attachEvent('onreadystatechange', function () { if (document.readyState === 'complete') { document.detachEvent('onreadystatechange', arguments.callee); fireOnce(); } }) // Fallback window.attachEvent('onload', fireOnce); // IE7/8 if (document.documentElement.doScroll && window == window.top) { var tryScroll = function () { if (!document.body) { return; } try { document.documentElement.doScroll('left'); fireOnce(); } catch (e) { setTimeout(tryScroll, 1); } }; tryScroll(); } } }, warn : function (msg) { if (window.console && window.console.warn) { window.console.warn(msg); } }, preventDefault : function (e) { if (e.preventDefault) { e.preventDefault(); } e.returnValue = false; }, captureTarget : function (target) { // IE if (target.setCapture) { jsc._capturedTarget = target; jsc._capturedTarget.setCapture(); } }, releaseTarget : function () { // IE if (jsc._capturedTarget) { jsc._capturedTarget.releaseCapture(); jsc._capturedTarget = null; } }, fireEvent : function (el, evnt) { if (!el) { return; } if (document.createEvent) { var ev = document.createEvent('HTMLEvents'); ev.initEvent(evnt, true, true); el.dispatchEvent(ev); } else if (document.createEventObject) { var ev = document.createEventObject(); el.fireEvent('on' + evnt, ev); } else if (el['on' + evnt]) { // alternatively use the traditional event model el['on' + evnt](); } }, classNameToList : function (className) { return className.replace(/^\s+|\s+$/g, '').split(/\s+/); }, // The className parameter (str) can only contain a single class name hasClass : function (elm, className) { if (!className) { return false; } return -1 != (' ' + elm.className.replace(/\s+/g, ' ') + ' ').indexOf(' ' + className + ' '); }, // The className parameter (str) can contain multiple class names separated by whitespace setClass : function (elm, className) { var classList = jsc.classNameToList(className); for (var i = 0; i < classList.length; i += 1) { if (!jsc.hasClass(elm, classList[i])) { elm.className += (elm.className ? ' ' : '') + classList[i]; } } }, // The className parameter (str) can contain multiple class names separated by whitespace unsetClass : function (elm, className) { var classList = jsc.classNameToList(className); for (var i = 0; i < classList.length; i += 1) { var repl = new RegExp( '^\\s*' + classList[i] + '\\s*|' + '\\s*' + classList[i] + '\\s*$|' + '\\s+' + classList[i] + '(\\s+)', 'g' ); elm.className = elm.className.replace(repl, '$1'); } }, getStyle : function (elm) { return window.getComputedStyle ? window.getComputedStyle(elm) : elm.currentStyle; }, setStyle : (function () { var helper = document.createElement('div'); var getSupportedProp = function (names) { for (var i = 0; i < names.length; i += 1) { if (names[i] in helper.style) { return names[i]; } } }; var props = { borderRadius: getSupportedProp(['borderRadius', 'MozBorderRadius', 'webkitBorderRadius']), boxShadow: getSupportedProp(['boxShadow', 'MozBoxShadow', 'webkitBoxShadow']) }; return function (elm, prop, value) { switch (prop.toLowerCase()) { case 'opacity': var alphaOpacity = Math.round(parseFloat(value) * 100); elm.style.opacity = value; elm.style.filter = 'alpha(opacity=' + alphaOpacity + ')'; break; default: elm.style[props[prop]] = value; break; } }; })(), setBorderRadius : function (elm, value) { jsc.setStyle(elm, 'borderRadius', value || '0'); }, setBoxShadow : function (elm, value) { jsc.setStyle(elm, 'boxShadow', value || 'none'); }, getElementPos : function (e, relativeToViewport) { var x=0, y=0; var rect = e.getBoundingClientRect(); x = rect.left; y = rect.top; if (!relativeToViewport) { var viewPos = jsc.getViewPos(); x += viewPos[0]; y += viewPos[1]; } return [x, y]; }, getElementSize : function (e) { return [e.offsetWidth, e.offsetHeight]; }, // get pointer's X/Y coordinates relative to viewport getAbsPointerPos : function (e) { if (!e) { e = window.event; } var x = 0, y = 0; if (typeof e.changedTouches !== 'undefined' && e.changedTouches.length) { // touch devices x = e.changedTouches[0].clientX; y = e.changedTouches[0].clientY; } else if (typeof e.clientX === 'number') { x = e.clientX; y = e.clientY; } return { x: x, y: y }; }, // get pointer's X/Y coordinates relative to target element getRelPointerPos : function (e) { if (!e) { e = window.event; } var target = e.target || e.srcElement; var targetRect = target.getBoundingClientRect(); var x = 0, y = 0; var clientX = 0, clientY = 0; if (typeof e.changedTouches !== 'undefined' && e.changedTouches.length) { // touch devices clientX = e.changedTouches[0].clientX; clientY = e.changedTouches[0].clientY; } else if (typeof e.clientX === 'number') { clientX = e.clientX; clientY = e.clientY; } x = clientX - targetRect.left; y = clientY - targetRect.top; return { x: x, y: y }; }, getViewPos : function () { var doc = document.documentElement; return [ (window.pageXOffset || doc.scrollLeft) - (doc.clientLeft || 0), (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0) ]; }, getViewSize : function () { var doc = document.documentElement; return [ (window.innerWidth || doc.clientWidth), (window.innerHeight || doc.clientHeight), ]; }, redrawPosition : function () { if (jsc.picker && jsc.picker.owner) { var thisObj = jsc.picker.owner; var tp, vp; if (thisObj.fixed) { // Fixed elements are positioned relative to viewport, // therefore we can ignore the scroll offset tp = jsc.getElementPos(thisObj.targetElement, true); // target pos vp = [0, 0]; // view pos } else { tp = jsc.getElementPos(thisObj.targetElement); // target pos vp = jsc.getViewPos(); // view pos } var ts = jsc.getElementSize(thisObj.targetElement); // target size var vs = jsc.getViewSize(); // view size var ps = jsc.getPickerOuterDims(thisObj); // picker size var a, b, c; switch (thisObj.position.toLowerCase()) { case 'left': a=1; b=0; c=-1; break; case 'right':a=1; b=0; c=1; break; case 'top': a=0; b=1; c=-1; break; default: a=0; b=1; c=1; break; } var l = (ts[b]+ps[b])/2; // compute picker position if (!thisObj.smartPosition) { var pp = [ tp[a], tp[b]+ts[b]-l+l*c ]; } else { var pp = [ -vp[a]+tp[a]+ps[a] > vs[a] ? (-vp[a]+tp[a]+ts[a]/2 > vs[a]/2 && tp[a]+ts[a]-ps[a] >= 0 ? tp[a]+ts[a]-ps[a] : tp[a]) : tp[a], -vp[b]+tp[b]+ts[b]+ps[b]-l+l*c > vs[b] ? (-vp[b]+tp[b]+ts[b]/2 > vs[b]/2 && tp[b]+ts[b]-l-l*c >= 0 ? tp[b]+ts[b]-l-l*c : tp[b]+ts[b]-l+l*c) : (tp[b]+ts[b]-l+l*c >= 0 ? tp[b]+ts[b]-l+l*c : tp[b]+ts[b]-l-l*c) ]; } var x = pp[a]; var y = pp[b]; var positionValue = thisObj.fixed ? 'fixed' : 'absolute'; var contractShadow = (pp[0] + ps[0] > tp[0] || pp[0] < tp[0] + ts[0]) && (pp[1] + ps[1] < tp[1] + ts[1]); jsc._drawPosition(thisObj, x, y, positionValue, contractShadow); } }, _drawPosition : function (thisObj, x, y, positionValue, contractShadow) { var vShadow = contractShadow ? 0 : thisObj.shadowBlur; // px jsc.picker.wrap.style.position = positionValue; jsc.picker.wrap.style.left = x + 'px'; jsc.picker.wrap.style.top = y + 'px'; jsc.setBoxShadow( jsc.picker.boxS, thisObj.shadow ? new jsc.BoxShadow(0, vShadow, thisObj.shadowBlur, 0, thisObj.shadowColor) : null); }, getPickerDims : function (thisObj) { var displaySlider = !!jsc.getSliderComponent(thisObj); var dims = [ 2 * thisObj.insetWidth + 2 * thisObj.padding + thisObj.width + (displaySlider ? 2 * thisObj.insetWidth + jsc.getPadToSliderPadding(thisObj) + thisObj.sliderSize : 0), 2 * thisObj.insetWidth + 2 * thisObj.padding + thisObj.height + (thisObj.closable ? 2 * thisObj.insetWidth + thisObj.padding + thisObj.buttonHeight : 0) ]; return dims; }, getPickerOuterDims : function (thisObj) { var dims = jsc.getPickerDims(thisObj); return [ dims[0] + 2 * thisObj.borderWidth, dims[1] + 2 * thisObj.borderWidth ]; }, getPadToSliderPadding : function (thisObj) { return Math.max(thisObj.padding, 1.5 * (2 * thisObj.pointerBorderWidth + thisObj.pointerThickness)); }, getPadYComponent : function (thisObj) { switch (thisObj.mode.charAt(1).toLowerCase()) { case 'v': return 'v'; break; } return 's'; }, getSliderComponent : function (thisObj) { if (thisObj.mode.length > 2) { switch (thisObj.mode.charAt(2).toLowerCase()) { case 's': return 's'; break; case 'v': return 'v'; break; } } return null; }, onDocumentMouseDown : function (e) { if (!e) { e = window.event; } var target = e.target || e.srcElement; if (target._jscLinkedInstance) { if (target._jscLinkedInstance.showOnClick) { target._jscLinkedInstance.show(); } } else if (target._jscControlName) { jsc.onControlPointerStart(e, target, target._jscControlName, 'mouse'); } else { // Mouse is outside the picker controls -> hide the color picker! if (jsc.picker && jsc.picker.owner) { jsc.picker.owner.hide(); } } }, onDocumentTouchStart : function (e) { if (!e) { e = window.event; } var target = e.target || e.srcElement; if (target._jscLinkedInstance) { if (target._jscLinkedInstance.showOnClick) { target._jscLinkedInstance.show(); } } else if (target._jscControlName) { jsc.onControlPointerStart(e, target, target._jscControlName, 'touch'); } else { if (jsc.picker && jsc.picker.owner) { jsc.picker.owner.hide(); } } }, onWindowResize : function (e) { jsc.redrawPosition(); }, onParentScroll : function (e) { // hide the picker when one of the parent elements is scrolled if (jsc.picker && jsc.picker.owner) { jsc.picker.owner.hide(); } }, _pointerMoveEvent : { mouse: 'mousemove', touch: 'touchmove' }, _pointerEndEvent : { mouse: 'mouseup', touch: 'touchend' }, _pointerOrigin : null, _capturedTarget : null, onControlPointerStart : function (e, target, controlName, pointerType) { var thisObj = target._jscInstance; jsc.preventDefault(e); jsc.captureTarget(target); var registerDragEvents = function (doc, offset) { jsc.attachGroupEvent('drag', doc, jsc._pointerMoveEvent[pointerType], jsc.onDocumentPointerMove(e, target, controlName, pointerType, offset)); jsc.attachGroupEvent('drag', doc, jsc._pointerEndEvent[pointerType], jsc.onDocumentPointerEnd(e, target, controlName, pointerType)); }; registerDragEvents(document, [0, 0]); if (window.parent && window.frameElement) { var rect = window.frameElement.getBoundingClientRect(); var ofs = [-rect.left, -rect.top]; registerDragEvents(window.parent.window.document, ofs); } var abs = jsc.getAbsPointerPos(e); var rel = jsc.getRelPointerPos(e); jsc._pointerOrigin = { x: abs.x - rel.x, y: abs.y - rel.y }; switch (controlName) { case 'pad': // if the slider is at the bottom, move it up switch (jsc.getSliderComponent(thisObj)) { case 's': if (thisObj.hsv[1] === 0) { thisObj.fromHSV(null, 100, null); }; break; case 'v': if (thisObj.hsv[2] === 0) { thisObj.fromHSV(null, null, 100); }; break; } jsc.setPad(thisObj, e, 0, 0); break; case 'sld': jsc.setSld(thisObj, e, 0); break; } jsc.dispatchFineChange(thisObj); }, onDocumentPointerMove : function (e, target, controlName, pointerType, offset) { return function (e) { var thisObj = target._jscInstance; switch (controlName) { case 'pad': if (!e) { e = window.event; } jsc.setPad(thisObj, e, offset[0], offset[1]); jsc.dispatchFineChange(thisObj); break; case 'sld': if (!e) { e = window.event; } jsc.setSld(thisObj, e, offset[1]); jsc.dispatchFineChange(thisObj); break; } } }, onDocumentPointerEnd : function (e, target, controlName, pointerType) { return function (e) { var thisObj = target._jscInstance; jsc.detachGroupEvents('drag'); jsc.releaseTarget(); // Always dispatch changes after detaching outstanding mouse handlers, // in case some user interaction will occur in user's onchange callback // that would intrude with current mouse events jsc.dispatchChange(thisObj); }; }, dispatchChange : function (thisObj) { if (thisObj.valueElement) { if (jsc.isElementType(thisObj.valueElement, 'input')) { jsc.fireEvent(thisObj.valueElement, 'change'); } } }, dispatchFineChange : function (thisObj) { if (thisObj.onFineChange) { var callback; if (typeof thisObj.onFineChange === 'string') { callback = new Function (thisObj.onFineChange); } else { callback = thisObj.onFineChange; } callback.call(thisObj); } }, setPad : function (thisObj, e, ofsX, ofsY) { var pointerAbs = jsc.getAbsPointerPos(e); var x = ofsX + pointerAbs.x - jsc._pointerOrigin.x - thisObj.padding - thisObj.insetWidth; var y = ofsY + pointerAbs.y - jsc._pointerOrigin.y - thisObj.padding - thisObj.insetWidth; var xVal = x * (360 / (thisObj.width - 1)); var yVal = 100 - (y * (100 / (thisObj.height - 1))); switch (jsc.getPadYComponent(thisObj)) { case 's': thisObj.fromHSV(xVal, yVal, null, jsc.leaveSld); break; case 'v': thisObj.fromHSV(xVal, null, yVal, jsc.leaveSld); break; } }, setSld : function (thisObj, e, ofsY) { var pointerAbs = jsc.getAbsPointerPos(e); var y = ofsY + pointerAbs.y - jsc._pointerOrigin.y - thisObj.padding - thisObj.insetWidth; var yVal = 100 - (y * (100 / (thisObj.height - 1))); switch (jsc.getSliderComponent(thisObj)) { case 's': thisObj.fromHSV(null, yVal, null, jsc.leavePad); break; case 'v': thisObj.fromHSV(null, null, yVal, jsc.leavePad); break; } }, _vmlNS : 'jsc_vml_', _vmlCSS : 'jsc_vml_css_', _vmlReady : false, initVML : function () { if (!jsc._vmlReady) { // init VML namespace var doc = document; if (!doc.namespaces[jsc._vmlNS]) { doc.namespaces.add(jsc._vmlNS, 'urn:schemas-microsoft-com:vml'); } if (!doc.styleSheets[jsc._vmlCSS]) { var tags = ['shape', 'shapetype', 'group', 'background', 'path', 'formulas', 'handles', 'fill', 'stroke', 'shadow', 'textbox', 'textpath', 'imagedata', 'line', 'polyline', 'curve', 'rect', 'roundrect', 'oval', 'arc', 'image']; var ss = doc.createStyleSheet(); ss.owningElement.id = jsc._vmlCSS; for (var i = 0; i < tags.length; i += 1) { ss.addRule(jsc._vmlNS + '\\:' + tags[i], 'behavior:url(#default#VML);'); } } jsc._vmlReady = true; } }, createPalette : function () { var paletteObj = { elm: null, draw: null }; if (jsc.isCanvasSupported) { // Canvas implementation for modern browsers var canvas = document.createElement('canvas'); var ctx = canvas.getContext('2d'); var drawFunc = function (width, height, type) { canvas.width = width; canvas.height = height; ctx.clearRect(0, 0, canvas.width, canvas.height); var hGrad = ctx.createLinearGradient(0, 0, canvas.width, 0); hGrad.addColorStop(0 / 6, '#F00'); hGrad.addColorStop(1 / 6, '#FF0'); hGrad.addColorStop(2 / 6, '#0F0'); hGrad.addColorStop(3 / 6, '#0FF'); hGrad.addColorStop(4 / 6, '#00F'); hGrad.addColorStop(5 / 6, '#F0F'); hGrad.addColorStop(6 / 6, '#F00'); ctx.fillStyle = hGrad; ctx.fillRect(0, 0, canvas.width, canvas.height); var vGrad = ctx.createLinearGradient(0, 0, 0, canvas.height); switch (type.toLowerCase()) { case 's': vGrad.addColorStop(0, 'rgba(255,255,255,0)'); vGrad.addColorStop(1, 'rgba(255,255,255,1)'); break; case 'v': vGrad.addColorStop(0, 'rgba(0,0,0,0)'); vGrad.addColorStop(1, 'rgba(0,0,0,1)'); break; } ctx.fillStyle = vGrad; ctx.fillRect(0, 0, canvas.width, canvas.height); }; paletteObj.elm = canvas; paletteObj.draw = drawFunc; } else { // VML fallback for IE 7 and 8 jsc.initVML(); var vmlContainer = document.createElement('div'); vmlContainer.style.position = 'relative'; vmlContainer.style.overflow = 'hidden'; var hGrad = document.createElement(jsc._vmlNS + ':fill'); hGrad.type = 'gradient'; hGrad.method = 'linear'; hGrad.angle = '90'; hGrad.colors = '16.67% #F0F, 33.33% #00F, 50% #0FF, 66.67% #0F0, 83.33% #FF0' var hRect = document.createElement(jsc._vmlNS + ':rect'); hRect.style.position = 'absolute'; hRect.style.left = -1 + 'px'; hRect.style.top = -1 + 'px'; hRect.stroked = false; hRect.appendChild(hGrad); vmlContainer.appendChild(hRect); var vGrad = document.createElement(jsc._vmlNS + ':fill'); vGrad.type = 'gradient'; vGrad.method = 'linear'; vGrad.angle = '180'; vGrad.opacity = '0'; var vRect = document.createElement(jsc._vmlNS + ':rect'); vRect.style.position = 'absolute'; vRect.style.left = -1 + 'px'; vRect.style.top = -1 + 'px'; vRect.stroked = false; vRect.appendChild(vGrad); vmlContainer.appendChild(vRect); var drawFunc = function (width, height, type) { vmlContainer.style.width = width + 'px'; vmlContainer.style.height = height + 'px'; hRect.style.width = vRect.style.width = (width + 1) + 'px'; hRect.style.height = vRect.style.height = (height + 1) + 'px'; // Colors must be specified during every redraw, otherwise IE won't display // a full gradient during a subsequential redraw hGrad.color = '#F00'; hGrad.color2 = '#F00'; switch (type.toLowerCase()) { case 's': vGrad.color = vGrad.color2 = '#FFF'; break; case 'v': vGrad.color = vGrad.color2 = '#000'; break; } }; paletteObj.elm = vmlContainer; paletteObj.draw = drawFunc; } return paletteObj; }, createSliderGradient : function () { var sliderObj = { elm: null, draw: null }; if (jsc.isCanvasSupported) { // Canvas implementation for modern browsers var canvas = document.createElement('canvas'); var ctx = canvas.getContext('2d'); var drawFunc = function (width, height, color1, color2) { canvas.width = width; canvas.height = height; ctx.clearRect(0, 0, canvas.width, canvas.height); var grad = ctx.createLinearGradient(0, 0, 0, canvas.height); grad.addColorStop(0, color1); grad.addColorStop(1, color2); ctx.fillStyle = grad; ctx.fillRect(0, 0, canvas.width, canvas.height); }; sliderObj.elm = canvas; sliderObj.draw = drawFunc; } else { // VML fallback for IE 7 and 8 jsc.initVML(); var vmlContainer = document.createElement('div'); vmlContainer.style.position = 'relative'; vmlContainer.style.overflow = 'hidden'; var grad = document.createElement(jsc._vmlNS + ':fill'); grad.type = 'gradient'; grad.method = 'linear'; grad.angle = '180'; var rect = document.createElement(jsc._vmlNS + ':rect'); rect.style.position = 'absolute'; rect.style.left = -1 + 'px'; rect.style.top = -1 + 'px'; rect.stroked = false; rect.appendChild(grad); vmlContainer.appendChild(rect); var drawFunc = function (width, height, color1, color2) { vmlContainer.style.width = width + 'px'; vmlContainer.style.height = height + 'px'; rect.style.width = (width + 1) + 'px'; rect.style.height = (height + 1) + 'px'; grad.color = color1; grad.color2 = color2; }; sliderObj.elm = vmlContainer; sliderObj.draw = drawFunc; } return sliderObj; }, leaveValue : 1<<0, leaveStyle : 1<<1, leavePad : 1<<2, leaveSld : 1<<3, BoxShadow : (function () { var BoxShadow = function (hShadow, vShadow, blur, spread, color, inset) { this.hShadow = hShadow; this.vShadow = vShadow; this.blur = blur; this.spread = spread; this.color = color; this.inset = !!inset; }; BoxShadow.prototype.toString = function () { var vals = [ Math.round(this.hShadow) + 'px', Math.round(this.vShadow) + 'px', Math.round(this.blur) + 'px', Math.round(this.spread) + 'px', this.color ]; if (this.inset) { vals.push('inset'); } return vals.join(' '); }; return BoxShadow; })(), // // Usage: // var myColor = new jscolor( [, ]) // jscolor : function (targetElement, options) { // General options // this.value = null; // initial HEX color. To change it later, use methods fromString(), fromHSV() and fromRGB() this.valueElement = targetElement; // element that will be used to display and input the color code this.styleElement = targetElement; // element that will preview the picked color using CSS backgroundColor this.required = true; // whether the associated text can be left empty this.refine = true; // whether to refine the entered color code (e.g. uppercase it and remove whitespace) this.hash = false; // whether to prefix the HEX color code with # symbol this.uppercase = true; // whether to show the color code in upper case this.onFineChange = null; // called instantly every time the color changes (value can be either a function or a string with javascript code) this.activeClass = 'jscolor-active'; // class to be set to the target element when a picker window is open on it this.overwriteImportant = false; // whether to overwrite colors of styleElement using !important this.minS = 0; // min allowed saturation (0 - 100) this.maxS = 100; // max allowed saturation (0 - 100) this.minV = 0; // min allowed value (brightness) (0 - 100) this.maxV = 100; // max allowed value (brightness) (0 - 100) // Accessing the picked color // this.hsv = [0, 0, 100]; // read-only [0-360, 0-100, 0-100] this.rgb = [255, 255, 255]; // read-only [0-255, 0-255, 0-255] // Color Picker options // this.width = 181; // width of color palette (in px) this.height = 101; // height of color palette (in px) this.showOnClick = true; // whether to display the color picker when user clicks on its target element this.mode = 'HSV'; // HSV | HVS | HS | HV - layout of the color picker controls this.position = 'bottom'; // left | right | top | bottom - position relative to the target element this.smartPosition = true; // automatically change picker position when there is not enough space for it this.sliderSize = 16; // px this.crossSize = 8; // px this.closable = false; // whether to display the Close button this.closeText = 'Close'; this.buttonColor = '#000000'; // CSS color this.buttonHeight = 18; // px this.padding = 12; // px this.backgroundColor = '#FFFFFF'; // CSS color this.borderWidth = 1; // px this.borderColor = '#BBBBBB'; // CSS color this.borderRadius = 8; // px this.insetWidth = 1; // px this.insetColor = '#BBBBBB'; // CSS color this.shadow = true; // whether to display shadow this.shadowBlur = 15; // px this.shadowColor = 'rgba(0,0,0,0.2)'; // CSS color this.pointerColor = '#4C4C4C'; // px this.pointerBorderColor = '#FFFFFF'; // px this.pointerBorderWidth = 1; // px this.pointerThickness = 2; // px this.zIndex = 1000; this.container = null; // where to append the color picker (BODY element by default) for (var opt in options) { if (options.hasOwnProperty(opt)) { this[opt] = options[opt]; } } this.hide = function () { if (isPickerOwner()) { detachPicker(); } }; this.show = function () { drawPicker(); }; this.redraw = function () { if (isPickerOwner()) { drawPicker(); } }; this.importColor = function () { if (!this.valueElement) { this.exportColor(); } else { if (jsc.isElementType(this.valueElement, 'input')) { if (!this.refine) { if (!this.fromString(this.valueElement.value, jsc.leaveValue)) { if (this.styleElement) { this.styleElement.style.backgroundImage = this.styleElement._jscOrigStyle.backgroundImage; this.styleElement.style.backgroundColor = this.styleElement._jscOrigStyle.backgroundColor; this.styleElement.style.color = this.styleElement._jscOrigStyle.color; } this.exportColor(jsc.leaveValue | jsc.leaveStyle); } } else if (!this.required && /^\s*$/.test(this.valueElement.value)) { this.valueElement.value = ''; if (this.styleElement) { this.styleElement.style.backgroundImage = this.styleElement._jscOrigStyle.backgroundImage; this.styleElement.style.backgroundColor = this.styleElement._jscOrigStyle.backgroundColor; this.styleElement.style.color = this.styleElement._jscOrigStyle.color; } this.exportColor(jsc.leaveValue | jsc.leaveStyle); } else if (this.fromString(this.valueElement.value)) { // managed to import color successfully from the value -> OK, don't do anything } else { this.exportColor(); } } else { // not an input element -> doesn't have any value this.exportColor(); } } }; this.exportColor = function (flags) { if (!(flags & jsc.leaveValue) && this.valueElement) { var value = this.toString(); if (this.uppercase) { value = value.toUpperCase(); } if (this.hash) { value = '#' + value; } if (jsc.isElementType(this.valueElement, 'input')) { this.valueElement.value = value; } else { this.valueElement.innerHTML = value; } } if (!(flags & jsc.leaveStyle)) { if (this.styleElement) { var bgColor = '#' + this.toString(); var fgColor = this.isLight() ? '#000' : '#FFF'; this.styleElement.style.backgroundImage = 'none'; this.styleElement.style.backgroundColor = bgColor; this.styleElement.style.color = fgColor; if (this.overwriteImportant) { this.styleElement.setAttribute('style', 'background: ' + bgColor + ' !important; ' + 'color: ' + fgColor + ' !important;' ); } } } if (!(flags & jsc.leavePad) && isPickerOwner()) { redrawPad(); } if (!(flags & jsc.leaveSld) && isPickerOwner()) { redrawSld(); } }; // h: 0-360 // s: 0-100 // v: 0-100 // this.fromHSV = function (h, s, v, flags) { // null = don't change if (h !== null) { if (isNaN(h)) { return false; } h = Math.max(0, Math.min(360, h)); } if (s !== null) { if (isNaN(s)) { return false; } s = Math.max(0, Math.min(100, this.maxS, s), this.minS); } if (v !== null) { if (isNaN(v)) { return false; } v = Math.max(0, Math.min(100, this.maxV, v), this.minV); } this.rgb = HSV_RGB( h===null ? this.hsv[0] : (this.hsv[0]=h), s===null ? this.hsv[1] : (this.hsv[1]=s), v===null ? this.hsv[2] : (this.hsv[2]=v) ); this.exportColor(flags); }; // r: 0-255 // g: 0-255 // b: 0-255 // this.fromRGB = function (r, g, b, flags) { // null = don't change if (r !== null) { if (isNaN(r)) { return false; } r = Math.max(0, Math.min(255, r)); } if (g !== null) { if (isNaN(g)) { return false; } g = Math.max(0, Math.min(255, g)); } if (b !== null) { if (isNaN(b)) { return false; } b = Math.max(0, Math.min(255, b)); } var hsv = RGB_HSV( r===null ? this.rgb[0] : r, g===null ? this.rgb[1] : g, b===null ? this.rgb[2] : b ); if (hsv[0] !== null) { this.hsv[0] = Math.max(0, Math.min(360, hsv[0])); } if (hsv[2] !== 0) { this.hsv[1] = hsv[1]===null ? null : Math.max(0, this.minS, Math.min(100, this.maxS, hsv[1])); } this.hsv[2] = hsv[2]===null ? null : Math.max(0, this.minV, Math.min(100, this.maxV, hsv[2])); // update RGB according to final HSV, as some values might be trimmed var rgb = HSV_RGB(this.hsv[0], this.hsv[1], this.hsv[2]); this.rgb[0] = rgb[0]; this.rgb[1] = rgb[1]; this.rgb[2] = rgb[2]; this.exportColor(flags); }; this.fromString = function (str, flags) { var m; if (m = str.match(/^\W*([0-9A-F]{3}([0-9A-F]{3})?)\W*$/i)) { // HEX notation // if (m[1].length === 6) { // 6-char notation this.fromRGB( parseInt(m[1].substr(0,2),16), parseInt(m[1].substr(2,2),16), parseInt(m[1].substr(4,2),16), flags ); } else { // 3-char notation this.fromRGB( parseInt(m[1].charAt(0) + m[1].charAt(0),16), parseInt(m[1].charAt(1) + m[1].charAt(1),16), parseInt(m[1].charAt(2) + m[1].charAt(2),16), flags ); } return true; } else if (m = str.match(/^\W*rgba?\(([^)]*)\)\W*$/i)) { var params = m[1].split(','); var re = /^\s*(\d*)(\.\d+)?\s*$/; var mR, mG, mB; if ( params.length >= 3 && (mR = params[0].match(re)) && (mG = params[1].match(re)) && (mB = params[2].match(re)) ) { var r = parseFloat((mR[1] || '0') + (mR[2] || '')); var g = parseFloat((mG[1] || '0') + (mG[2] || '')); var b = parseFloat((mB[1] || '0') + (mB[2] || '')); this.fromRGB(r, g, b, flags); return true; } } return false; }; this.toString = function () { return ( (0x100 | Math.round(this.rgb[0])).toString(16).substr(1) + (0x100 | Math.round(this.rgb[1])).toString(16).substr(1) + (0x100 | Math.round(this.rgb[2])).toString(16).substr(1) ); }; this.toHEXString = function () { return '#' + this.toString().toUpperCase(); }; this.toRGBString = function () { return ('rgb(' + Math.round(this.rgb[0]) + ',' + Math.round(this.rgb[1]) + ',' + Math.round(this.rgb[2]) + ')' ); }; this.isLight = function () { return ( 0.213 * this.rgb[0] + 0.715 * this.rgb[1] + 0.072 * this.rgb[2] > 255 / 2 ); }; this._processParentElementsInDOM = function () { if (this._linkedElementsProcessed) { return; } this._linkedElementsProcessed = true; var elm = this.targetElement; do { // If the target element or one of its parent nodes has fixed position, // then use fixed positioning instead // // Note: In Firefox, getComputedStyle returns null in a hidden iframe, // that's why we need to check if the returned style object is non-empty var currStyle = jsc.getStyle(elm); if (currStyle && currStyle.position.toLowerCase() === 'fixed') { this.fixed = true; } if (elm !== this.targetElement) { // Ensure to attach onParentScroll only once to each parent element // (multiple targetElements can share the same parent nodes) // // Note: It's not just offsetParents that can be scrollable, // that's why we loop through all parent nodes if (!elm._jscEventsAttached) { jsc.attachEvent(elm, 'scroll', jsc.onParentScroll); elm._jscEventsAttached = true; } } } while ((elm = elm.parentNode) && !jsc.isElementType(elm, 'body')); }; // r: 0-255 // g: 0-255 // b: 0-255 // // returns: [ 0-360, 0-100, 0-100 ] // function RGB_HSV (r, g, b) { r /= 255; g /= 255; b /= 255; var n = Math.min(Math.min(r,g),b); var v = Math.max(Math.max(r,g),b); var m = v - n; if (m === 0) { return [ null, 0, 100 * v ]; } var h = r===n ? 3+(b-g)/m : (g===n ? 5+(r-b)/m : 1+(g-r)/m); return [ 60 * (h===6?0:h), 100 * (m/v), 100 * v ]; } // h: 0-360 // s: 0-100 // v: 0-100 // // returns: [ 0-255, 0-255, 0-255 ] // function HSV_RGB (h, s, v) { var u = 255 * (v / 100); if (h === null) { return [ u, u, u ]; } h /= 60; s /= 100; var i = Math.floor(h); var f = i%2 ? h-i : 1-(h-i); var m = u * (1 - s); var n = u * (1 - s * f); switch (i) { case 6: case 0: return [u,n,m]; case 1: return [n,u,m]; case 2: return [m,u,n]; case 3: return [m,n,u]; case 4: return [n,m,u]; case 5: return [u,m,n]; } } function detachPicker () { jsc.unsetClass(THIS.targetElement, THIS.activeClass); jsc.picker.wrap.parentNode.removeChild(jsc.picker.wrap); delete jsc.picker.owner; } function drawPicker () { // At this point, when drawing the picker, we know what the parent elements are // and we can do all related DOM operations, such as registering events on them // or checking their positioning THIS._processParentElementsInDOM(); if (!jsc.picker) { jsc.picker = { owner: null, wrap : document.createElement('div'), box : document.createElement('div'), boxS : document.createElement('div'), // shadow area boxB : document.createElement('div'), // border pad : document.createElement('div'), padB : document.createElement('div'), // border padM : document.createElement('div'), // mouse/touch area padPal : jsc.createPalette(), cross : document.createElement('div'), crossBY : document.createElement('div'), // border Y crossBX : document.createElement('div'), // border X crossLY : document.createElement('div'), // line Y crossLX : document.createElement('div'), // line X sld : document.createElement('div'), sldB : document.createElement('div'), // border sldM : document.createElement('div'), // mouse/touch area sldGrad : jsc.createSliderGradient(), sldPtrS : document.createElement('div'), // slider pointer spacer sldPtrIB : document.createElement('div'), // slider pointer inner border sldPtrMB : document.createElement('div'), // slider pointer middle border sldPtrOB : document.createElement('div'), // slider pointer outer border btn : document.createElement('div'), btnT : document.createElement('span') // text }; jsc.picker.pad.appendChild(jsc.picker.padPal.elm); jsc.picker.padB.appendChild(jsc.picker.pad); jsc.picker.cross.appendChild(jsc.picker.crossBY); jsc.picker.cross.appendChild(jsc.picker.crossBX); jsc.picker.cross.appendChild(jsc.picker.crossLY); jsc.picker.cross.appendChild(jsc.picker.crossLX); jsc.picker.padB.appendChild(jsc.picker.cross); jsc.picker.box.appendChild(jsc.picker.padB); jsc.picker.box.appendChild(jsc.picker.padM); jsc.picker.sld.appendChild(jsc.picker.sldGrad.elm); jsc.picker.sldB.appendChild(jsc.picker.sld); jsc.picker.sldB.appendChild(jsc.picker.sldPtrOB); jsc.picker.sldPtrOB.appendChild(jsc.picker.sldPtrMB); jsc.picker.sldPtrMB.appendChild(jsc.picker.sldPtrIB); jsc.picker.sldPtrIB.appendChild(jsc.picker.sldPtrS); jsc.picker.box.appendChild(jsc.picker.sldB); jsc.picker.box.appendChild(jsc.picker.sldM); jsc.picker.btn.appendChild(jsc.picker.btnT); jsc.picker.box.appendChild(jsc.picker.btn); jsc.picker.boxB.appendChild(jsc.picker.box); jsc.picker.wrap.appendChild(jsc.picker.boxS); jsc.picker.wrap.appendChild(jsc.picker.boxB); } var p = jsc.picker; var displaySlider = !!jsc.getSliderComponent(THIS); var dims = jsc.getPickerDims(THIS); var crossOuterSize = (2 * THIS.pointerBorderWidth + THIS.pointerThickness + 2 * THIS.crossSize); var padToSliderPadding = jsc.getPadToSliderPadding(THIS); var borderRadius = Math.min( THIS.borderRadius, Math.round(THIS.padding * Math.PI)); // px var padCursor = 'crosshair'; // wrap p.wrap.style.clear = 'both'; p.wrap.style.width = (dims[0] + 2 * THIS.borderWidth) + 'px'; p.wrap.style.height = (dims[1] + 2 * THIS.borderWidth) + 'px'; p.wrap.style.zIndex = THIS.zIndex; // picker p.box.style.width = dims[0] + 'px'; p.box.style.height = dims[1] + 'px'; p.boxS.style.position = 'absolute'; p.boxS.style.left = '0'; p.boxS.style.top = '0'; p.boxS.style.width = '100%'; p.boxS.style.height = '100%'; jsc.setBorderRadius(p.boxS, borderRadius + 'px'); // picker border p.boxB.style.position = 'relative'; p.boxB.style.border = THIS.borderWidth + 'px solid'; p.boxB.style.borderColor = THIS.borderColor; p.boxB.style.background = THIS.backgroundColor; jsc.setBorderRadius(p.boxB, borderRadius + 'px'); // IE hack: // If the element is transparent, IE will trigger the event on the elements under it, // e.g. on Canvas or on elements with border p.padM.style.background = p.sldM.style.background = '#FFF'; jsc.setStyle(p.padM, 'opacity', '0'); jsc.setStyle(p.sldM, 'opacity', '0'); // pad p.pad.style.position = 'relative'; p.pad.style.width = THIS.width + 'px'; p.pad.style.height = THIS.height + 'px'; // pad palettes (HSV and HVS) p.padPal.draw(THIS.width, THIS.height, jsc.getPadYComponent(THIS)); // pad border p.padB.style.position = 'absolute'; p.padB.style.left = THIS.padding + 'px'; p.padB.style.top = THIS.padding + 'px'; p.padB.style.border = THIS.insetWidth + 'px solid'; p.padB.style.borderColor = THIS.insetColor; // pad mouse area p.padM._jscInstance = THIS; p.padM._jscControlName = 'pad'; p.padM.style.position = 'absolute'; p.padM.style.left = '0'; p.padM.style.top = '0'; p.padM.style.width = (THIS.padding + 2 * THIS.insetWidth + THIS.width + padToSliderPadding / 2) + 'px'; p.padM.style.height = dims[1] + 'px'; p.padM.style.cursor = padCursor; // pad cross p.cross.style.position = 'absolute'; p.cross.style.left = p.cross.style.top = '0'; p.cross.style.width = p.cross.style.height = crossOuterSize + 'px'; // pad cross border Y and X p.crossBY.style.position = p.crossBX.style.position = 'absolute'; p.crossBY.style.background = p.crossBX.style.background = THIS.pointerBorderColor; p.crossBY.style.width = p.crossBX.style.height = (2 * THIS.pointerBorderWidth + THIS.pointerThickness) + 'px'; p.crossBY.style.height = p.crossBX.style.width = crossOuterSize + 'px'; p.crossBY.style.left = p.crossBX.style.top = (Math.floor(crossOuterSize / 2) - Math.floor(THIS.pointerThickness / 2) - THIS.pointerBorderWidth) + 'px'; p.crossBY.style.top = p.crossBX.style.left = '0'; // pad cross line Y and X p.crossLY.style.position = p.crossLX.style.position = 'absolute'; p.crossLY.style.background = p.crossLX.style.background = THIS.pointerColor; p.crossLY.style.height = p.crossLX.style.width = (crossOuterSize - 2 * THIS.pointerBorderWidth) + 'px'; p.crossLY.style.width = p.crossLX.style.height = THIS.pointerThickness + 'px'; p.crossLY.style.left = p.crossLX.style.top = (Math.floor(crossOuterSize / 2) - Math.floor(THIS.pointerThickness / 2)) + 'px'; p.crossLY.style.top = p.crossLX.style.left = THIS.pointerBorderWidth + 'px'; // slider p.sld.style.overflow = 'hidden'; p.sld.style.width = THIS.sliderSize + 'px'; p.sld.style.height = THIS.height + 'px'; // slider gradient p.sldGrad.draw(THIS.sliderSize, THIS.height, '#000', '#000'); // slider border p.sldB.style.display = displaySlider ? 'block' : 'none'; p.sldB.style.position = 'absolute'; p.sldB.style.right = THIS.padding + 'px'; p.sldB.style.top = THIS.padding + 'px'; p.sldB.style.border = THIS.insetWidth + 'px solid'; p.sldB.style.borderColor = THIS.insetColor; // slider mouse area p.sldM._jscInstance = THIS; p.sldM._jscControlName = 'sld'; p.sldM.style.display = displaySlider ? 'block' : 'none'; p.sldM.style.position = 'absolute'; p.sldM.style.right = '0'; p.sldM.style.top = '0'; p.sldM.style.width = (THIS.sliderSize + padToSliderPadding / 2 + THIS.padding + 2 * THIS.insetWidth) + 'px'; p.sldM.style.height = dims[1] + 'px'; p.sldM.style.cursor = 'default'; // slider pointer inner and outer border p.sldPtrIB.style.border = p.sldPtrOB.style.border = THIS.pointerBorderWidth + 'px solid ' + THIS.pointerBorderColor; // slider pointer outer border p.sldPtrOB.style.position = 'absolute'; p.sldPtrOB.style.left = -(2 * THIS.pointerBorderWidth + THIS.pointerThickness) + 'px'; p.sldPtrOB.style.top = '0'; // slider pointer middle border p.sldPtrMB.style.border = THIS.pointerThickness + 'px solid ' + THIS.pointerColor; // slider pointer spacer p.sldPtrS.style.width = THIS.sliderSize + 'px'; p.sldPtrS.style.height = sliderPtrSpace + 'px'; // the Close button function setBtnBorder () { var insetColors = THIS.insetColor.split(/\s+/); var outsetColor = insetColors.length < 2 ? insetColors[0] : insetColors[1] + ' ' + insetColors[0] + ' ' + insetColors[0] + ' ' + insetColors[1]; p.btn.style.borderColor = outsetColor; } p.btn.style.display = THIS.closable ? 'block' : 'none'; p.btn.style.position = 'absolute'; p.btn.style.left = THIS.padding + 'px'; p.btn.style.bottom = THIS.padding + 'px'; p.btn.style.padding = '0 15px'; p.btn.style.height = THIS.buttonHeight + 'px'; p.btn.style.border = THIS.insetWidth + 'px solid'; setBtnBorder(); p.btn.style.color = THIS.buttonColor; p.btn.style.font = '12px sans-serif'; p.btn.style.textAlign = 'center'; try { p.btn.style.cursor = 'pointer'; } catch(eOldIE) { p.btn.style.cursor = 'hand'; } p.btn.onmousedown = function () { THIS.hide(); }; p.btnT.style.lineHeight = THIS.buttonHeight + 'px'; p.btnT.innerHTML = ''; p.btnT.appendChild(document.createTextNode(THIS.closeText)); // place pointers redrawPad(); redrawSld(); // If we are changing the owner without first closing the picker, // make sure to first deal with the old owner if (jsc.picker.owner && jsc.picker.owner !== THIS) { jsc.unsetClass(jsc.picker.owner.targetElement, THIS.activeClass); } // Set the new picker owner jsc.picker.owner = THIS; // The redrawPosition() method needs picker.owner to be set, that's why we call it here, // after setting the owner if (jsc.isElementType(container, 'body')) { jsc.redrawPosition(); } else { jsc._drawPosition(THIS, 0, 0, 'relative', false); } if (p.wrap.parentNode != container) { container.appendChild(p.wrap); } jsc.setClass(THIS.targetElement, THIS.activeClass); } function redrawPad () { // redraw the pad pointer switch (jsc.getPadYComponent(THIS)) { case 's': var yComponent = 1; break; case 'v': var yComponent = 2; break; } var x = Math.round((THIS.hsv[0] / 360) * (THIS.width - 1)); var y = Math.round((1 - THIS.hsv[yComponent] / 100) * (THIS.height - 1)); var crossOuterSize = (2 * THIS.pointerBorderWidth + THIS.pointerThickness + 2 * THIS.crossSize); var ofs = -Math.floor(crossOuterSize / 2); jsc.picker.cross.style.left = (x + ofs) + 'px'; jsc.picker.cross.style.top = (y + ofs) + 'px'; // redraw the slider switch (jsc.getSliderComponent(THIS)) { case 's': var rgb1 = HSV_RGB(THIS.hsv[0], 100, THIS.hsv[2]); var rgb2 = HSV_RGB(THIS.hsv[0], 0, THIS.hsv[2]); var color1 = 'rgb(' + Math.round(rgb1[0]) + ',' + Math.round(rgb1[1]) + ',' + Math.round(rgb1[2]) + ')'; var color2 = 'rgb(' + Math.round(rgb2[0]) + ',' + Math.round(rgb2[1]) + ',' + Math.round(rgb2[2]) + ')'; jsc.picker.sldGrad.draw(THIS.sliderSize, THIS.height, color1, color2); break; case 'v': var rgb = HSV_RGB(THIS.hsv[0], THIS.hsv[1], 100); var color1 = 'rgb(' + Math.round(rgb[0]) + ',' + Math.round(rgb[1]) + ',' + Math.round(rgb[2]) + ')'; var color2 = '#000'; jsc.picker.sldGrad.draw(THIS.sliderSize, THIS.height, color1, color2); break; } } function redrawSld () { var sldComponent = jsc.getSliderComponent(THIS); if (sldComponent) { // redraw the slider pointer switch (sldComponent) { case 's': var yComponent = 1; break; case 'v': var yComponent = 2; break; } var y = Math.round((1 - THIS.hsv[yComponent] / 100) * (THIS.height - 1)); jsc.picker.sldPtrOB.style.top = (y - (2 * THIS.pointerBorderWidth + THIS.pointerThickness) - Math.floor(sliderPtrSpace / 2)) + 'px'; } } function isPickerOwner () { return jsc.picker && jsc.picker.owner === THIS; } function blurValue () { THIS.importColor(); } // Find the target element if (typeof targetElement === 'string') { var id = targetElement; var elm = document.getElementById(id); if (elm) { this.targetElement = elm; } else { jsc.warn('Could not find target element with ID \'' + id + '\''); } } else if (targetElement) { this.targetElement = targetElement; } else { jsc.warn('Invalid target element: \'' + targetElement + '\''); } if (this.targetElement._jscLinkedInstance) { jsc.warn('Cannot link jscolor twice to the same element. Skipping.'); return; } this.targetElement._jscLinkedInstance = this; // Find the value element this.valueElement = jsc.fetchElement(this.valueElement); // Find the style element this.styleElement = jsc.fetchElement(this.styleElement); var THIS = this; var container = this.container ? jsc.fetchElement(this.container) : document.getElementsByTagName('body')[0]; var sliderPtrSpace = 3; // px // For BUTTON elements it's important to stop them from sending the form when clicked // (e.g. in Safari) if (jsc.isElementType(this.targetElement, 'button')) { if (this.targetElement.onclick) { var origCallback = this.targetElement.onclick; this.targetElement.onclick = function (evt) { origCallback.call(this, evt); return false; }; } else { this.targetElement.onclick = function () { return false; }; } } /* var elm = this.targetElement; do { // If the target element or one of its offsetParents has fixed position, // then use fixed positioning instead // // Note: In Firefox, getComputedStyle returns null in a hidden iframe, // that's why we need to check if the returned style object is non-empty var currStyle = jsc.getStyle(elm); if (currStyle && currStyle.position.toLowerCase() === 'fixed') { this.fixed = true; } if (elm !== this.targetElement) { // attach onParentScroll so that we can recompute the picker position // when one of the offsetParents is scrolled if (!elm._jscEventsAttached) { jsc.attachEvent(elm, 'scroll', jsc.onParentScroll); elm._jscEventsAttached = true; } } } while ((elm = elm.offsetParent) && !jsc.isElementType(elm, 'body')); */ // valueElement if (this.valueElement) { if (jsc.isElementType(this.valueElement, 'input')) { var updateField = function () { THIS.fromString(THIS.valueElement.value, jsc.leaveValue); jsc.dispatchFineChange(THIS); }; jsc.attachEvent(this.valueElement, 'keyup', updateField); jsc.attachEvent(this.valueElement, 'input', updateField); jsc.attachEvent(this.valueElement, 'blur', blurValue); this.valueElement.setAttribute('autocomplete', 'off'); } } // styleElement if (this.styleElement) { this.styleElement._jscOrigStyle = { backgroundImage : this.styleElement.style.backgroundImage, backgroundColor : this.styleElement.style.backgroundColor, color : this.styleElement.style.color }; } if (this.value) { // Try to set the color from the .value option and if unsuccessful, // export the current color this.fromString(this.value) || this.exportColor(); } else { this.importColor(); } } }; //================================ // Public properties and methods //================================ // By default, search for all elements with class="jscolor" and install a color picker on them. // // You can change what class name will be looked for by setting the property jscolor.lookupClass // anywhere in your HTML document. To completely disable the automatic lookup, set it to null. // jsc.jscolor.lookupClass = 'jscolor'; jsc.jscolor.installByClassName = function (className) { var inputElms = document.getElementsByTagName('input'); var buttonElms = document.getElementsByTagName('button'); jsc.tryInstallOnElements(inputElms, className); jsc.tryInstallOnElements(buttonElms, className); }; jsc.register(); return jsc.jscolor; })(); } ; (function() { $(document).on('turbolinks:load', function() { var searchButton, toggleMenu; toggleMenu = function() { var $slice; $slice = $('#sidebar-footer .brand'); return $slice.toggleClass('hidden'); }; $('.sidebar-toggle').click(function() { return toggleMenu(); }); searchButton = function() { $('.search-button').click(function() { if ($(this).hasClass('submit')) { $('#search form').submit(); } $('#search').removeClass('hidding-search').addClass('display-search'); if ($(window).width() < 992) { $('.navbar-custom-menu').addClass('translate'); } $('.hide-search').addClass('appear'); $('.search-bar').focus(); return $(this).addClass('submit'); }); return $('.hide-search').click(function() { $('#search').removeClass('display-search').addClass('hidding-search'); $('.navbar-custom-menu').removeClass('translate'); $('.hide-search').removeClass('appear'); return $('.search-button').removeClass('submit'); }); }; $('.datepicker').datepicker({ dateFormat: 'yy-mm-dd', showOtherMonths: true, selectOtherMonths: true, changeMonth: true, changeYear: true }); $('.close-index-show').click(function() { return $('.index-show').css('right', -$('.index-show').outerWidth()); }); $('#open-historial').click(function() { return $('.control-sidebar').toggleClass('control-sidebar-open'); }); searchButton(); }); $(document).ready(function() { return $('.spinner').css('display', 'block'); }); $(window).load(function() { return $('.spinner').fadeOut(500); }); }).call(this); function notify(notice, state) { const toast = swal.mixin({ toast: true, position: 'top', showConfirmButton: false, timer: 5000, customClass: 'animated tada' }); toast({ type: state == 'error' ? 'error' : 'success', html: `
    ${notice}
    ` }) } ; $( document ).on('turbolinks:load', function() { var open = false; $(".console-btn").click(function(){ if(open===false) { open = true $(".console").removeClass('console-close').addClass('console-open'); } else { open = false $(".console").removeClass('console-open').addClass('console-close'); } }) }) ; $(document).on('turbolinks:load', function() { $(function ($) { var $body = $('body'), $slice = $('#sidebar-footer .brand') // On click, capture state and save it in localStorage $($.AdminLTE.options.sidebarToggleSelector).click(function () { localStorage.setItem('sidebar', $body.hasClass('sidebar-collapse') ? 1 : 0); }); // On ready, read the set state and collapse if needed if (window.width >= 768){ if (localStorage.getItem('sidebar') === '0') { $body.addClass('disable-animations sidebar-collapse'); $slice.toggleClass('hidden') requestAnimationFrame(function () { $body.removeClass('disable-animations'); }); } } }); }); (function() { $(document).on('turbolinks:load', function() { return jQuery(function() { return $('.objects-container').sortable({ axis: 'y', handle: '.drop', distance: 20, update: function() { return $.post($(this).data('update-url'), $(this).sortable('serialize')); } }); }); }); }).call(this); $(document).on('turbolinks:load', function() { $(function ($) { $('.delete').click(function(e){ e.preventDefault() swal({ title: 'Submit your Github username', input: 'text', inputAttributes: { autocapitalize: 'off' }, showCancelButton: true, confirmButtonText: 'Look up', showLoaderOnConfirm: true, preConfirm: (login) => { return fetch(`//api.github.com/users/${login}`) .then(response => { if (!response.ok) { throw new Error(response.statusText) } return response.json() }) .catch(error => { swal.showValidationError( `Request failed: ${error}` ) }) }, allowOutsideClick: () => !swal.isLoading() }).then((result) => { if (result.value) { swal({ title: `${result.value.login}'s avatar`, imageUrl: result.value.avatar_url }) } }) }) }); }); //Override the default confirm dialog by rails $.rails.allowAction = function(link){ if (link.data("confirm") == undefined){ return true; } $.rails.showConfirmationDialog(link); return false; } //User click confirm button $.rails.confirmed = function(link){ link.data("confirm", null); // Turbolinks.visit(link.attr('href')) link.trigger("click.rails"); } //Display the confirmation dialog $.rails.showConfirmationDialog = function(link){ var message = link.data("confirm"); swal({ title: message, type: 'warning', showCancelButton: true }).then((result) => { if (result.value) { $('.spinner').fadeIn(); $.rails.confirmed(link); } }); }; var sweetAlertConfirmConfig = sweetAlertConfirmConfig || {}; // Add default config object (function ($) { var sweetAlertConfirm = function (event) { swalDefaultOptions = { title: sweetAlertConfirmConfig.title || 'Are you sure?', type: sweetAlertConfirmConfig.type || 'warning', showCancelButton: sweetAlertConfirmConfig.showCancelButton || true, confirmButtonText: sweetAlertConfirmConfig.confirmButtonText || "Ok", cancelButtonText: sweetAlertConfirmConfig.cancelButtonText || "Cancel" } if (sweetAlertConfirmConfig.confirmButtonColor !== null) { swalDefaultOptions.confirmButtonColor = sweetAlertConfirmConfig.confirmButtonColor } $linkToVerify = $(this); var swalOptions = swalDefaultOptions; var optionKeys = [ 'text', 'showCancelButton', 'confirmButtonColor', 'cancelButtonColor', 'confirmButtonText', 'cancelButtonText', 'html', 'imageUrl', 'allowOutsideClick', 'customClass' ]; function sweetAlertConfirmedCallback() { if ($linkToVerify.data().remote === true) { $.rails.handleRemote($linkToVerify) } else if ($linkToVerify.data().method !== undefined) { $.rails.handleMethod($linkToVerify); } else { if ($linkToVerify.attr('type') == 'submit') { var name = $linkToVerify.attr('name'), data = name ? { name: name, value: $linkToVerify.val() } : null; $linkToVerify.closest('form').data('ujs:submit-button', data); $linkToVerify.closest('form').submit(); } else { $linkToVerify.data('swal-confirmed', true).click(); } } } if ($linkToVerify.data('swal-confirmed')) { $linkToVerify.data('swal-confirmed', false); return true; } $.each($linkToVerify.data(), function (key, val) { if ($.inArray(key, optionKeys) >= 0) { swalOptions[key] = val; } }); if ($linkToVerify.attr('data-sweet-alert-type')) { swalOptions['type'] = $linkToVerify.attr('data-sweet-alert-type'); } message = $linkToVerify.attr('data-sweet-alert-confirm') swalOptions['title'] = message swal(swalOptions).then(sweetAlertConfirmedCallback, function (dismiss) { return true; }); return false; } $(document).on('ready turbolinks:load page:update ajaxComplete', function () { $('[data-sweet-alert-confirm]').on('click', sweetAlertConfirm) }); $(document).on('ready turbolinks:load page:load', function () { //To avoid "Uncaught TypeError: Cannot read property 'querySelector' of null" on turbolinks if (typeof window.sweetAlertInitialize === 'function') { window.sweetAlertInitialize(); } }); })(jQuery); !function (e, t) { "object" == typeof exports && "undefined" != typeof module ? module.exports = t() : "function" == typeof define && define.amd ? define(t) : e.Sweetalert2 = t() }(this, function () { "use strict"; var q = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (e) { return typeof e } : function (e) { return e && "function" == typeof Symbol && e.constructor === Symbol && e !== Symbol.prototype ? "symbol" : typeof e }, s = function (e, t) { if (!(e instanceof t)) throw new TypeError("Cannot call a class as a function") }, o = function () { function o(e, t) { for (var n = 0; n < t.length; n++) { var o = t[n]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, o.key, o) } } return function (e, t, n) { return t && o(e.prototype, t), n && o(e, n), e } }(), r = Object.assign || function (e) { for (var t = 1; t < arguments.length; t++) { var n = arguments[t]; for (var o in n) Object.prototype.hasOwnProperty.call(n, o) && (e[o] = n[o]) } return e }, i = function e(t, n, o) { null === t && (t = Function.prototype); var r = Object.getOwnPropertyDescriptor(t, n); if (void 0 === r) { var i = Object.getPrototypeOf(t); return null === i ? void 0 : e(i, n, o) } if ("value" in r) return r.value; var a = r.get; return void 0 !== a ? a.call(o) : void 0 }, a = function (e, t) { if ("function" != typeof t && null !== t) throw new TypeError("Super expression must either be null or a function, not " + typeof t); e.prototype = Object.create(t && t.prototype, { constructor: { value: e, enumerable: !1, writable: !0, configurable: !0 } }), t && (Object.setPrototypeOf ? Object.setPrototypeOf(e, t) : e.__proto__ = t) }, u = function (e, t) { if (!e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return !t || "object" != typeof t && "function" != typeof t ? e : t }, t = "SweetAlert2:", c = function (e) { return Array.prototype.slice.call(e) }, d = function (e) { console.warn(t + " " + e) }, V = function (e) { console.error(t + " " + e) }, n = [], l = function (e) { -1 === n.indexOf(e) && (n.push(e), d(e)) }, M = function (e) { return "function" == typeof e ? e() : e }, H = function (e) { return "object" === (void 0 === e ? "undefined" : q(e)) && "function" == typeof e.then }, e = Object.freeze({ cancel: "cancel", backdrop: "overlay", close: "close", esc: "esc", timer: "timer" }), p = function (e) { var t = {}; for (var n in e) t[e[n]] = "swal2-" + e[n]; return t }, I = p(["container", "shown", "height-auto", "iosfix", "popup", "modal", "no-backdrop", "toast", "toast-shown", "toast-column", "fade", "show", "hide", "noanimation", "close", "title", "header", "content", "actions", "confirm", "cancel", "footer", "icon", "icon-text", "image", "input", "file", "range", "select", "radio", "checkbox", "label", "textarea", "inputerror", "validationerror", "progresssteps", "activeprogressstep", "progresscircle", "progressline", "loading", "styled", "top", "top-start", "top-end", "top-left", "top-right", "center", "center-start", "center-end", "center-left", "center-right", "bottom", "bottom-start", "bottom-end", "bottom-left", "bottom-right", "grow-row", "grow-column", "grow-fullscreen"]), f = p(["success", "warning", "info", "question", "error"]), m = { previousBodyPadding: null }, h = function (e, t) { return e.classList.contains(t) }, D = function (e) { if (e.focus(), "file" !== e.type) { var t = e.value; e.value = "", e.value = t } }, g = function (e, t, n) { e && t && ("string" == typeof t && (t = t.split(/\s+/).filter(Boolean)), t.forEach(function (t) { e.forEach ? e.forEach(function (e) { n ? e.classList.add(t) : e.classList.remove(t) }) : n ? e.classList.add(t) : e.classList.remove(t) })) }, R = function (e, t) { g(e, t, !0) }, N = function (e, t) { g(e, t, !1) }, W = function (e, t) { for (var n = 0; n < e.childNodes.length; n++)if (h(e.childNodes[n], t)) return e.childNodes[n] }, z = function (e) { e.style.opacity = "", e.style.display = e.id === I.content ? "block" : "flex" }, U = function (e) { e.style.opacity = "", e.style.display = "none" }, F = function (e) { return e && (e.offsetWidth || e.offsetHeight || e.getClientRects().length) }, b = function () { return document.body.querySelector("." + I.container) }, v = function (e) { var t = b(); return t ? t.querySelector("." + e) : null }, y = function () { return v(I.popup) }, w = function () { var e = y(); return c(e.querySelectorAll("." + I.icon)) }, C = function () { return v(I.title) }, k = function () { return v(I.content) }, x = function () { return v(I.image) }, A = function () { return v(I.progresssteps) }, B = function () { return v(I.confirm) }, P = function () { return v(I.cancel) }, S = function () { return v(I.actions) }, E = function () { return v(I.footer) }, O = function () { return v(I.close) }, K = function () { var e = c(y().querySelectorAll('[tabindex]:not([tabindex="-1"]):not([tabindex="0"])')).sort(function (e, t) { return e = parseInt(e.getAttribute("tabindex")), (t = parseInt(t.getAttribute("tabindex"))) < e ? 1 : e < t ? -1 : 0 }), t = c(y().querySelectorAll('a[href], area[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), iframe, object, embed, [tabindex="0"], [contenteditable], audio[controls], video[controls]')).filter(function (e) { return "-1" !== e.getAttribute("tabindex") }); return function (e) { for (var t = [], n = 0; n < e.length; n++)-1 === t.indexOf(e[n]) && t.push(e[n]); return t }(e.concat(t)).filter(function (e) { return F(e) }) }, L = function () { return !T() && !document.body.classList.contains(I["no-backdrop"]) }, T = function () { return document.body.classList.contains(I["toast-shown"]) }, j = function () { return "undefined" == typeof window || "undefined" == typeof document }, _ = ('\n
    \n
    \n
      \n
      \n \n
      \n
      \n ?\n
      \n
      \n !\n
      \n
      \n i\n
      \n
      \n
      \n \n
      \n
      \n
      \n \n

      \n \n
      \n
      \n
      \n \n \n
      \n \n \n
      \n \n
      \n \n \n
      \n
      \n
      \n \n \n
      \n
      \n
      \n
      \n').replace(/(^|\n)\s*/g, ""), Z = function (e) { var t = b(); if (t && (t.parentNode.removeChild(t), N([document.documentElement, document.body], [I["no-backdrop"], I["toast-shown"], I["has-column"]])), !j()) { var n = document.createElement("div"); n.className = I.container, n.innerHTML = _, ("string" == typeof e.target ? document.querySelector(e.target) : e.target).appendChild(n); var o = y(), r = k(), i = W(r, I.input), a = W(r, I.file), s = r.querySelector("." + I.range + " input"), u = r.querySelector("." + I.range + " output"), c = W(r, I.select), l = r.querySelector("." + I.checkbox + " input"), d = W(r, I.textarea); o.setAttribute("role", e.toast ? "alert" : "dialog"), o.setAttribute("aria-live", e.toast ? "polite" : "assertive"), e.toast || o.setAttribute("aria-modal", "true"); var p = void 0, f = function (e) { Ee.isVisible() && p !== e.target.value && Ee.resetValidationError(), p = e.target.value }; return i.oninput = f, a.onchange = f, c.onchange = f, l.onchange = f, d.oninput = f, s.oninput = function (e) { f(e), u.value = s.value }, s.onchange = function (e) { f(e), s.nextSibling.value = s.value }, o } V("SweetAlert2 requires document to initialize") }, Q = function (e, t) { if (!e) return U(t); if ("object" === (void 0 === e ? "undefined" : q(e))) if (t.innerHTML = "", 0 in e) for (var n = 0; n in e; n++)t.appendChild(e[n].cloneNode(!0)); else t.appendChild(e.cloneNode(!0)); else e && (t.innerHTML = e); z(t) }, Y = function () { if (j()) return !1; var e = document.createElement("div"), t = { WebkitAnimation: "webkitAnimationEnd", OAnimation: "oAnimationEnd oanimationend", animation: "animationend" }; for (var n in t) if (t.hasOwnProperty(n) && void 0 !== e.style[n]) return t[n]; return !1 }(), $ = function (e) { var t, n, o = S(), r = B(), i = P(); if (e.showConfirmButton || e.showCancelButton ? z(o) : U(o), e.showCancelButton ? i.style.display = "inline-block" : U(i), e.showConfirmButton ? (n = "display", (t = r).style.removeProperty ? t.style.removeProperty(n) : t.style.removeAttribute(n)) : U(r), r.innerHTML = e.confirmButtonText, i.innerHTML = e.cancelButtonText, r.setAttribute("aria-label", e.confirmButtonAriaLabel), i.setAttribute("aria-label", e.cancelButtonAriaLabel), r.className = I.confirm, R(r, e.confirmButtonClass), i.className = I.cancel, R(i, e.cancelButtonClass), e.buttonsStyling) { R([r, i], I.styled), e.confirmButtonColor && (r.style.backgroundColor = e.confirmButtonColor), e.cancelButtonColor && (i.style.backgroundColor = e.cancelButtonColor); var a = window.getComputedStyle(r).getPropertyValue("background-color"); r.style.borderLeftColor = a, r.style.borderRightColor = a } else N([r, i], I.styled), r.style.backgroundColor = r.style.borderLeftColor = r.style.borderRightColor = "", i.style.backgroundColor = i.style.borderLeftColor = i.style.borderRightColor = "" }, J = function (e) { var t = k().querySelector("#" + I.content); e.html ? Q(e.html, t) : e.text ? (t.textContent = e.text, z(t)) : U(t) }, X = function (e) { for (var t = w(), n = 0; n < t.length; n++)U(t[n]); if (e.type) if (-1 !== Object.keys(f).indexOf(e.type)) { var o = Ee.getPopup().querySelector("." + I.icon + "." + f[e.type]); z(o), e.animation && R(o, "swal2-animate-" + e.type + "-icon") } else V('Unknown type! Expected "success", "error", "warning", "info" or "question", got "' + e.type + '"') }, G = function (e) { var t = x(); e.imageUrl ? (t.setAttribute("src", e.imageUrl), t.setAttribute("alt", e.imageAlt), z(t), e.imageWidth ? t.setAttribute("width", e.imageWidth) : t.removeAttribute("width"), e.imageHeight ? t.setAttribute("height", e.imageHeight) : t.removeAttribute("height"), t.className = I.image, e.imageClass && R(t, e.imageClass)) : U(t) }, ee = function (r) { var i = A(), a = parseInt(null === r.currentProgressStep ? Ee.getQueueStep() : r.currentProgressStep, 10); r.progressSteps && r.progressSteps.length ? (z(i), i.innerHTML = "", a >= r.progressSteps.length && d("Invalid currentProgressStep parameter, it should be less than progressSteps.length (currentProgressStep like JS arrays starts from 0)"), r.progressSteps.forEach(function (e, t) { var n = document.createElement("li"); if (R(n, I.progresscircle), n.innerHTML = e, t === a && R(n, I.activeprogressstep), i.appendChild(n), t !== r.progressSteps.length - 1) { var o = document.createElement("li"); R(o, I.progressline), r.progressStepsDistance && (o.style.width = r.progressStepsDistance), i.appendChild(o) } })) : U(i) }, te = function (e) { var t = C(); e.titleText ? t.innerText = e.titleText : e.title && ("string" == typeof e.title && (e.title = e.title.split("\n").join("
      ")), Q(e.title, t)) }, ne = function () { null === m.previousBodyPadding && document.body.scrollHeight > window.innerHeight && (m.previousBodyPadding = parseInt(window.getComputedStyle(document.body).getPropertyValue("padding-right")), document.body.style.paddingRight = m.previousBodyPadding + function () { if ("ontouchstart" in window || navigator.msMaxTouchPoints) return 0; var e = document.createElement("div"); e.style.width = "50px", e.style.height = "50px", e.style.overflow = "scroll", document.body.appendChild(e); var t = e.offsetWidth - e.clientWidth; return document.body.removeChild(e), t }() + "px") }, oe = {}, re = function (e, n) { var o = b(), t = y(); if (t) { null !== e && "function" == typeof e && e(t), N(t, I.show), R(t, I.hide); var r = function () { var e, t; T() || (e = window.scrollX, t = window.scrollY, oe.restoreFocusTimeout = setTimeout(function () { oe.previousActiveElement && oe.previousActiveElement.focus ? (oe.previousActiveElement.focus(), oe.previousActiveElement = null) : document.body && document.body.focus() }, 100), void 0 !== e && void 0 !== t && window.scrollTo(e, t), oe.keydownTarget.removeEventListener("keydown", oe.keydownHandler, { capture: oe.keydownListenerCapture }), oe.keydownHandlerAdded = !1), o.parentNode && o.parentNode.removeChild(o), N([document.documentElement, document.body], [I.shown, I["height-auto"], I["no-backdrop"], I["toast-shown"], I["toast-column"]]), L() && (null !== m.previousBodyPadding && (document.body.style.paddingRight = m.previousBodyPadding, m.previousBodyPadding = null), function () { if (h(document.body, I.iosfix)) { var e = parseInt(document.body.style.top, 10); N(document.body, I.iosfix), document.body.style.top = "", document.body.scrollTop = -1 * e } }(), c(document.body.children).forEach(function (e) { e.hasAttribute("data-previous-aria-hidden") ? (e.setAttribute("aria-hidden", e.getAttribute("data-previous-aria-hidden")), e.removeAttribute("data-previous-aria-hidden")) : e.removeAttribute("aria-hidden") })), null !== n && "function" == typeof n && setTimeout(function () { n() }) }; Y && !h(t, I.noanimation) ? t.addEventListener(Y, function e() { t.removeEventListener(Y, e), h(t, I.hide) && r() }) : r() } }; function ie(e) { var t = function e() { for (var t = arguments.length, n = Array(t), o = 0; o < t; o++)n[o] = arguments[o]; if (!(this instanceof e)) return new (Function.prototype.bind.apply(e, [null].concat(n))); Object.getPrototypeOf(e).apply(this, n) }; return t.prototype = r(Object.create(e.prototype), { constructor: t }), "function" == typeof Object.setPrototypeOf ? Object.setPrototypeOf(t, e) : t.__proto__ = e, t } var ae = { title: "", titleText: "", text: "", html: "", footer: "", type: null, toast: !1, customClass: "", target: "body", backdrop: !0, animation: !0, heightAuto: !0, allowOutsideClick: !0, allowEscapeKey: !0, allowEnterKey: !0, stopKeydownPropagation: !0, keydownListenerCapture: !1, showConfirmButton: !0, showCancelButton: !1, preConfirm: null, confirmButtonText: "OK", confirmButtonAriaLabel: "", confirmButtonColor: null, confirmButtonClass: null, cancelButtonText: "Cancel", cancelButtonAriaLabel: "", cancelButtonColor: null, cancelButtonClass: null, buttonsStyling: !0, reverseButtons: !1, focusConfirm: !0, focusCancel: !1, showCloseButton: !1, closeButtonAriaLabel: "Close this dialog", showLoaderOnConfirm: !1, imageUrl: null, imageWidth: null, imageHeight: null, imageAlt: "", imageClass: null, timer: null, width: null, padding: null, background: null, input: null, inputPlaceholder: "", inputValue: "", inputOptions: {}, inputAutoTrim: !0, inputClass: null, inputAttributes: {}, inputValidator: null, grow: !1, position: "center", progressSteps: [], currentProgressStep: null, progressStepsDistance: null, onBeforeOpen: null, onAfterClose: null, onOpen: null, onClose: null, useRejections: !1, expectRejections: !1 }, se = ["useRejections", "expectRejections"], ue = function (e) { return ae.hasOwnProperty(e) || "extraParams" === e }, ce = function (e) { return -1 !== se.indexOf(e) }, le = function (e) { for (var t in e) ue(t) || d('Unknown parameter "' + t + '"'), e.toast && -1 !== ["allowOutsideClick", "allowEnterKey", "backdrop", "focusConfirm", "focusCancel", "heightAuto", "keydownListenerCapture"].indexOf(t) && d('The parameter "' + t + '" is incompatible with toasts'), ce(t) && l('The parameter "' + t + '" is deprecated and will be removed in the next major release.') }, de = '"setDefaults" & "resetDefaults" methods are deprecated in favor of "mixin" method and will be removed in the next major release. For new projects, use "mixin". For past projects already using "setDefaults", support will be provided through an additional package.', pe = {}; var fe = [], me = function () { var e = y(); e || Ee(""), e = y(); var t = S(), n = B(), o = P(); z(t), z(n), R([e, t], I.loading), n.disabled = !0, o.disabled = !0, e.setAttribute("data-loading", !0), e.setAttribute("aria-busy", !0), e.focus() }, he = Object.freeze({ isValidParameter: ue, isDeprecatedParameter: ce, argsToParams: function (n) { var o = {}; switch (q(n[0])) { case "object": r(o, n[0]); break; default: ["title", "html", "type"].forEach(function (e, t) { switch (q(n[t])) { case "string": o[e] = n[t]; break; case "undefined": break; default: V("Unexpected type of " + e + '! Expected "string", got ' + q(n[t])) } }) }return o }, adaptInputValidator: function (n) { return function (e, t) { return n.call(this, e, t).then(function () { }, function (e) { return e }) } }, close: re, closePopup: re, closeModal: re, closeToast: re, isVisible: function () { return !!y() }, clickConfirm: function () { return B().click() }, clickCancel: function () { return P().click() }, getContainer: b, getPopup: y, getTitle: C, getContent: k, getImage: x, getIcons: w, getCloseButton: O, getButtonsWrapper: function () { return l("swal.getButtonsWrapper() is deprecated and will be removed in the next major release, use swal.getActions() instead"), v(I.actions) }, getActions: S, getConfirmButton: B, getCancelButton: P, getFooter: E, getFocusableElements: K, isLoading: function () { return y().hasAttribute("data-loading") }, fire: function () { for (var e = arguments.length, t = Array(e), n = 0; n < e; n++)t[n] = arguments[n]; return new (Function.prototype.bind.apply(this, [null].concat(t))) }, mixin: function (n) { return ie(function (e) { function t() { return s(this, t), u(this, (t.__proto__ || Object.getPrototypeOf(t)).apply(this, arguments)) } return a(t, e), o(t, [{ key: "_main", value: function (e) { return i(t.prototype.__proto__ || Object.getPrototypeOf(t.prototype), "_main", this).call(this, r({}, n, e)) } }]), t }(this)) }, queue: function (e) { var i = this; fe = e; var a = function () { fe = [], document.body.removeAttribute("data-swal2-queue-step") }, s = []; return new Promise(function (r) { !function t(n, o) { n < fe.length ? (document.body.setAttribute("data-swal2-queue-step", n), i(fe[n]).then(function (e) { void 0 !== e.value ? (s.push(e.value), t(n + 1, o)) : (a(), r({ dismiss: e.dismiss })) })) : (a(), r({ value: s })) }(0) }) }, getQueueStep: function () { return document.body.getAttribute("data-swal2-queue-step") }, insertQueueStep: function (e, t) { return t && t < fe.length ? fe.splice(t, 0, e) : fe.push(e) }, deleteQueueStep: function (e) { void 0 !== fe[e] && fe.splice(e, 1) }, showLoading: me, enableLoading: me, getTimerLeft: function () { return oe.timeout && oe.timeout.getTimerLeft() } }), ge = "function" == typeof Symbol ? Symbol : function () { var t = 0; function e(e) { return "__" + e + "_" + Math.floor(1e9 * Math.random()) + "_" + ++t + "__" } return e.iterator = e("Symbol.iterator"), e }(), be = "function" == typeof WeakMap ? WeakMap : function (n, o, t) { function e() { o(this, n, { value: ge("WeakMap") }) } return e.prototype = { delete: function (e) { delete e[this[n]] }, get: function (e) { return e[this[n]] }, has: function (e) { return t.call(e, this[n]) }, set: function (e, t) { o(e, this[n], { configurable: !0, value: t }) } }, e }(ge("WeakMap"), Object.defineProperty, {}.hasOwnProperty), ve = { promise: new be, innerParams: new be, domCache: new be }; function ye() { var e = ve.innerParams.get(this), t = ve.domCache.get(this); e.showConfirmButton || (U(t.confirmButton), e.showCancelButton || U(t.actions)), N([t.popup, t.actions], I.loading), t.popup.removeAttribute("aria-busy"), t.popup.removeAttribute("data-loading"), t.confirmButton.disabled = !1, t.cancelButton.disabled = !1 } var we = function e(t, n) { s(this, e); var o = void 0, r = void 0, i = void 0, a = n; this.start = function () { i = !0, r = new Date, o = setTimeout(t, a) }, this.stop = function () { i = !1, clearTimeout(o), a -= new Date - r }, this.getTimerLeft = function () { return i && (this.stop(), this.start()), a }, this.start() }, Ce = { email: function (e, t) { return /^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9.-]+\.[a-zA-Z0-9-]{2,24}$/.test(e) ? Promise.resolve() : Promise.reject(t && t.validationMessage ? t.validationMessage : "Invalid email address") }, url: function (e, t) { return /^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_+.~#?&//=]*)$/.test(e) ? Promise.resolve() : Promise.reject(t && t.validationMessage ? t.validationMessage : "Invalid URL") } }; var ke = function (e) { var t = b(), n = y(); null !== e.onBeforeOpen && "function" == typeof e.onBeforeOpen && e.onBeforeOpen(n), e.animation ? (R(n, I.show), R(t, I.fade), N(n, I.hide)) : N(n, I.fade), z(n), t.style.overflowY = "hidden", Y && !h(n, I.noanimation) ? n.addEventListener(Y, function e() { n.removeEventListener(Y, e), t.style.overflowY = "auto" }) : t.style.overflowY = "auto", R([document.documentElement, document.body, t], I.shown), e.heightAuto && e.backdrop && !e.toast && R([document.documentElement, document.body], I["height-auto"]), L() && (ne(), function () { if (/iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream && !h(document.body, I.iosfix)) { var e = document.body.scrollTop; document.body.style.top = -1 * e + "px", R(document.body, I.iosfix) } }(), c(document.body.children).forEach(function (e) { e === b() || e.contains(b()) || (e.hasAttribute("aria-hidden") && e.setAttribute("data-previous-aria-hidden", e.getAttribute("aria-hidden")), e.setAttribute("aria-hidden", "true")) })), T() || oe.previousActiveElement || (oe.previousActiveElement = document.activeElement), null !== e.onOpen && "function" == typeof e.onOpen && setTimeout(function () { e.onOpen(n) }) }; var xe = Object.freeze({ hideLoading: ye, disableLoading: ye, getInput: function (e) { var t = ve.innerParams.get(this), n = ve.domCache.get(this); if (!(e = e || t.input)) return null; switch (e) { case "select": case "textarea": case "file": return W(n.content, I[e]); case "checkbox": return n.popup.querySelector("." + I.checkbox + " input"); case "radio": return n.popup.querySelector("." + I.radio + " input:checked") || n.popup.querySelector("." + I.radio + " input:first-child"); case "range": return n.popup.querySelector("." + I.range + " input"); default: return W(n.content, I.input) } }, enableButtons: function () { var e = ve.domCache.get(this); e.confirmButton.disabled = !1, e.cancelButton.disabled = !1 }, disableButtons: function () { var e = ve.domCache.get(this); e.confirmButton.disabled = !0, e.cancelButton.disabled = !0 }, enableConfirmButton: function () { ve.domCache.get(this).confirmButton.disabled = !1 }, disableConfirmButton: function () { ve.domCache.get(this).confirmButton.disabled = !0 }, enableInput: function () { var e = this.getInput(); if (!e) return !1; if ("radio" === e.type) for (var t = e.parentNode.parentNode.querySelectorAll("input"), n = 0; n < t.length; n++)t[n].disabled = !1; else e.disabled = !1 }, disableInput: function () { var e = this.getInput(); if (!e) return !1; if (e && "radio" === e.type) for (var t = e.parentNode.parentNode.querySelectorAll("input"), n = 0; n < t.length; n++)t[n].disabled = !0; else e.disabled = !0 }, showValidationError: function (e) { var t = ve.domCache.get(this); t.validationError.innerHTML = e; var n = window.getComputedStyle(t.popup); t.validationError.style.marginLeft = "-" + n.getPropertyValue("padding-left"), t.validationError.style.marginRight = "-" + n.getPropertyValue("padding-right"), z(t.validationError); var o = this.getInput(); o && (o.setAttribute("aria-invalid", !0), o.setAttribute("aria-describedBy", I.validationerror), D(o), R(o, I.inputerror)) }, resetValidationError: function () { var e = ve.domCache.get(this); e.validationError && U(e.validationError); var t = this.getInput(); t && (t.removeAttribute("aria-invalid"), t.removeAttribute("aria-describedBy"), N(t, I.inputerror)) }, getProgressSteps: function () { return ve.innerParams.get(this).progressSteps }, setProgressSteps: function (e) { var t = ve.innerParams.get(this), n = r({}, t, { progressSteps: e }); ve.innerParams.set(this, n), ee(n) }, showProgressSteps: function () { var e = ve.domCache.get(this); z(e.progressSteps) }, hideProgressSteps: function () { var e = ve.domCache.get(this); U(e.progressSteps) }, _main: function (e) { var L = this; le(e); var T = r({}, ae, e); !function (t) { t.inputValidator || Object.keys(Ce).forEach(function (e) { t.input === e && (t.inputValidator = t.expectRejections ? Ce[e] : Ee.adaptInputValidator(Ce[e])) }), (!t.target || "string" == typeof t.target && !document.querySelector(t.target) || "string" != typeof t.target && !t.target.appendChild) && (d('Target parameter is not valid, defaulting to "body"'), t.target = "body"); var e = void 0, n = y(), o = "string" == typeof t.target ? document.querySelector(t.target) : t.target; e = n && o && n.parentNode !== o.parentNode ? Z(t) : n || Z(t), t.width && (e.style.width = "number" == typeof t.width ? t.width + "px" : t.width), t.padding && (e.style.padding = "number" == typeof t.padding ? t.padding + "px" : t.padding), t.background && (e.style.background = t.background); for (var r = window.getComputedStyle(e).getPropertyValue("background-color"), i = e.querySelectorAll("[class^=swal2-success-circular-line], .swal2-success-fix"), a = 0; a < i.length; a++)i[a].style.backgroundColor = r; var s = b(), u = O(), c = E(); if (te(t), J(t), "string" == typeof t.backdrop ? b().style.background = t.backdrop : t.backdrop || R([document.documentElement, document.body], I["no-backdrop"]), !t.backdrop && t.allowOutsideClick && d('"allowOutsideClick" parameter requires `backdrop` parameter to be set to `true`'), t.position in I ? R(s, I[t.position]) : (d('The "position" parameter is not valid, defaulting to "center"'), R(s, I.center)), t.grow && "string" == typeof t.grow) { var l = "grow-" + t.grow; l in I && R(s, I[l]) } "function" == typeof t.animation && (t.animation = t.animation.call()), t.showCloseButton ? (u.setAttribute("aria-label", t.closeButtonAriaLabel), z(u)) : U(u), e.className = I.popup, t.toast ? (R([document.documentElement, document.body], I["toast-shown"]), R(e, I.toast)) : R(e, I.modal), t.customClass && R(e, t.customClass), ee(t), X(t), G(t), $(t), Q(t.footer, c), !0 === t.animation ? N(e, I.noanimation) : R(e, I.noanimation), t.showLoaderOnConfirm && !t.preConfirm && d("showLoaderOnConfirm is set to true, but preConfirm is not defined.\nshowLoaderOnConfirm should be used together with preConfirm, see usage example:\nhttps://sweetalert2.github.io/#ajax-request") }(T), Object.freeze(T), ve.innerParams.set(this, T), oe.timeout && (oe.timeout.stop(), delete oe.timeout), clearTimeout(oe.restoreFocusTimeout); var j = { popup: y(), container: b(), content: k(), actions: S(), confirmButton: B(), cancelButton: P(), closeButton: O(), validationError: v(I.validationerror), progressSteps: A() }; ve.domCache.set(this, j); var _ = this.constructor; return new Promise(function (t, n) { var o = function (e) { _.closePopup(T.onClose, T.onAfterClose), T.useRejections ? t(e) : t({ value: e }) }, u = function (e) { _.closePopup(T.onClose, T.onAfterClose), T.useRejections ? n(e) : t({ dismiss: e }) }, c = function (e) { _.closePopup(T.onClose, T.onAfterClose), n(e) }; T.timer && (oe.timeout = new we(function () { u("timer"), delete oe.timeout }, T.timer)), T.input && setTimeout(function () { var e = L.getInput(); e && D(e) }, 0); for (var l = function (t) { if (T.showLoaderOnConfirm && _.showLoading(), T.preConfirm) { L.resetValidationError(); var e = Promise.resolve().then(function () { return T.preConfirm(t, T.extraParams) }); T.expectRejections ? e.then(function (e) { return o(e || t) }, function (e) { L.hideLoading(), e && L.showValidationError(e) }) : e.then(function (e) { F(j.validationError) || !1 === e ? L.hideLoading() : o(e || t) }, function (e) { return c(e) }) } else o(t) }, e = function (e) { var t = e.target, n = j.confirmButton, o = j.cancelButton, r = n && (n === t || n.contains(t)), i = o && (o === t || o.contains(t)); switch (e.type) { case "click": if (r && _.isVisible()) if (L.disableButtons(), T.input) { var a = function () { var e = L.getInput(); if (!e) return null; switch (T.input) { case "checkbox": return e.checked ? 1 : 0; case "radio": return e.checked ? e.value : null; case "file": return e.files.length ? e.files[0] : null; default: return T.inputAutoTrim ? e.value.trim() : e.value } }(); if (T.inputValidator) { L.disableInput(); var s = Promise.resolve().then(function () { return T.inputValidator(a, T.extraParams) }); T.expectRejections ? s.then(function () { L.enableButtons(), L.enableInput(), l(a) }, function (e) { L.enableButtons(), L.enableInput(), e && L.showValidationError(e) }) : s.then(function (e) { L.enableButtons(), L.enableInput(), e ? L.showValidationError(e) : l(a) }, function (e) { return c(e) }) } else l(a) } else l(!0); else i && _.isVisible() && (L.disableButtons(), u(_.DismissReason.cancel)) } }, r = j.popup.querySelectorAll("button"), i = 0; i < r.length; i++)r[i].onclick = e, r[i].onmouseover = e, r[i].onmouseout = e, r[i].onmousedown = e; if (j.closeButton.onclick = function () { u(_.DismissReason.close) }, T.toast) j.popup.onclick = function () { T.showConfirmButton || T.showCancelButton || T.showCloseButton || T.input || u(_.DismissReason.close) }; else { var a = !1; j.popup.onmousedown = function () { j.container.onmouseup = function (e) { j.container.onmouseup = void 0, e.target === j.container && (a = !0) } }, j.container.onmousedown = function () { j.popup.onmouseup = function (e) { j.popup.onmouseup = void 0, (e.target === j.popup || j.popup.contains(e.target)) && (a = !0) } }, j.container.onclick = function (e) { a ? a = !1 : e.target === j.container && M(T.allowOutsideClick) && u(_.DismissReason.backdrop) } } T.reverseButtons ? j.confirmButton.parentNode.insertBefore(j.cancelButton, j.confirmButton) : j.confirmButton.parentNode.insertBefore(j.confirmButton, j.cancelButton); var s = function (e, t) { for (var n = K(T.focusCancel), o = 0; o < n.length; o++)return (e += t) === n.length ? e = 0 : -1 === e && (e = n.length - 1), n[e].focus(); j.popup.focus() }; oe.keydownHandlerAdded && (oe.keydownTarget.removeEventListener("keydown", oe.keydownHandler, { capture: oe.keydownListenerCapture }), oe.keydownHandlerAdded = !1), T.toast || (oe.keydownHandler = function (e) { return function (e, t) { if (t.stopKeydownPropagation && e.stopPropagation(), "Enter" !== e.key || e.isComposing) if ("Tab" === e.key) { for (var n = e.target, o = K(t.focusCancel), r = -1, i = 0; i < o.length; i++)if (n === o[i]) { r = i; break } e.shiftKey ? s(r, -1) : s(r, 1), e.stopPropagation(), e.preventDefault() } else -1 !== ["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown", "Left", "Right", "Up", "Down"].indexOf(e.key) ? document.activeElement === j.confirmButton && F(j.cancelButton) ? j.cancelButton.focus() : document.activeElement === j.cancelButton && F(j.confirmButton) && j.confirmButton.focus() : "Escape" !== e.key && "Esc" !== e.key || !0 !== M(t.allowEscapeKey) || u(_.DismissReason.esc); else if (e.target && L.getInput() && e.target.outerHTML === L.getInput().outerHTML) { if (-1 !== ["textarea", "file"].indexOf(t.input)) return; _.clickConfirm(), e.preventDefault() } }(e, T) }, oe.keydownTarget = T.keydownListenerCapture ? window : j.popup, oe.keydownListenerCapture = T.keydownListenerCapture, oe.keydownTarget.addEventListener("keydown", oe.keydownHandler, { capture: oe.keydownListenerCapture }), oe.keydownHandlerAdded = !0), L.enableButtons(), L.hideLoading(), L.resetValidationError(), T.toast && (T.input || T.footer || T.showCloseButton) ? R(document.body, I["toast-column"]) : N(document.body, I["toast-column"]); for (var d = ["input", "file", "range", "select", "radio", "checkbox", "textarea"], p = void 0, f = 0; f < d.length; f++) { var m = I[d[f]], h = W(j.content, m); if (p = L.getInput(d[f])) { for (var g in p.attributes) if (p.attributes.hasOwnProperty(g)) { var b = p.attributes[g].name; "type" !== b && "value" !== b && p.removeAttribute(b) } for (var v in T.inputAttributes) p.setAttribute(v, T.inputAttributes[v]) } h.className = m, T.inputClass && R(h, T.inputClass), U(h) } var y = void 0; switch (T.input) { case "text": case "email": case "password": case "number": case "tel": case "url": (p = W(j.content, I.input)).value = T.inputValue, p.placeholder = T.inputPlaceholder, p.type = T.input, z(p); break; case "file": (p = W(j.content, I.file)).placeholder = T.inputPlaceholder, p.type = T.input, z(p); break; case "range": var w = W(j.content, I.range), C = w.querySelector("input"), k = w.querySelector("output"); C.value = T.inputValue, C.type = T.input, k.value = T.inputValue, z(w); break; case "select": var x = W(j.content, I.select); if (x.innerHTML = "", T.inputPlaceholder) { var A = document.createElement("option"); A.innerHTML = T.inputPlaceholder, A.value = "", A.disabled = !0, A.selected = !0, x.appendChild(A) } y = function (e) { e.forEach(function (e) { var t = e[0], n = e[1], o = document.createElement("option"); o.value = t, o.innerHTML = n, T.inputValue.toString() === t.toString() && (o.selected = !0), x.appendChild(o) }), z(x), x.focus() }; break; case "radio": var B = W(j.content, I.radio); B.innerHTML = "", y = function (e) { e.forEach(function (e) { var t = e[0], n = e[1], o = document.createElement("input"), r = document.createElement("label"); o.type = "radio", o.name = I.radio, o.value = t, T.inputValue.toString() === t.toString() && (o.checked = !0); var i = document.createElement("span"); i.innerHTML = n, i.className = I.label, r.appendChild(o), r.appendChild(i), B.appendChild(r) }), z(B); var t = B.querySelectorAll("input"); t.length && t[0].focus() }; break; case "checkbox": var P = W(j.content, I.checkbox), S = L.getInput("checkbox"); S.type = "checkbox", S.value = 1, S.id = I.checkbox, S.checked = Boolean(T.inputValue), P.querySelector("span").innerHTML = T.inputPlaceholder, z(P); break; case "textarea": var E = W(j.content, I.textarea); E.value = T.inputValue, E.placeholder = T.inputPlaceholder, z(E); break; case null: break; default: V('Unexpected type of input! Expected "text", "email", "password", "number", "tel", "select", "radio", "checkbox", "textarea", "file" or "url", got "' + T.input + '"') }if ("select" === T.input || "radio" === T.input) { var O = function (e) { return y((t = e, n = [], "undefined" != typeof Map && t instanceof Map ? t.forEach(function (e, t) { n.push([t, e]) }) : Object.keys(t).forEach(function (e) { n.push([e, t[e]]) }), n)); var t, n }; H(T.inputOptions) ? (_.showLoading(), T.inputOptions.then(function (e) { L.hideLoading(), O(e) })) : "object" === q(T.inputOptions) ? O(T.inputOptions) : V("Unexpected type of inputOptions! Expected object, Map or Promise, got " + q(T.inputOptions)) } else -1 !== ["text", "email", "number", "tel", "textarea"].indexOf(T.input) && H(T.inputValue) && (_.showLoading(), U(p), T.inputValue.then(function (e) { p.value = "number" === T.input ? parseFloat(e) || 0 : e + "", z(p), p.focus(), L.hideLoading() }).catch(function (e) { V("Error in inputValue promise: " + e), p.value = "", z(p), p.focus(), L.hideLoading() })); ke(T), T.toast || (M(T.allowEnterKey) ? T.focusCancel && F(j.cancelButton) ? j.cancelButton.focus() : T.focusConfirm && F(j.confirmButton) ? j.confirmButton.focus() : s(-1, 1) : document.activeElement && document.activeElement.blur()), j.container.scrollTop = 0 }) } }), Ae = void 0; function Be() { if ("undefined" != typeof window) { "undefined" == typeof Promise && V("This package requires a Promise library, please include a shim to enable it in this browser (See: https://github.com/sweetalert2/sweetalert2/wiki/Migration-from-SweetAlert-to-SweetAlert2#1-ie-support)"); for (var e = arguments.length, t = Array(e), n = 0; n < e; n++)t[n] = arguments[n]; if (0 === t.length) return V("At least 1 argument is expected!"), !1; Ae = this; var o = Object.freeze(this.constructor.argsToParams(t)); Object.defineProperties(this, { params: { value: o, writable: !1, enumerable: !0 } }); var r = this._main(this.params); ve.promise.set(this, r) } } Be.prototype.then = function (e, t) { return ve.promise.get(this).then(e, t) }, Be.prototype.catch = function (e) { return ve.promise.get(this).catch(e) }, Be.prototype.finally = function (e) { return ve.promise.get(this).finally(e) }, r(Be.prototype, xe), r(Be, he), Object.keys(xe).forEach(function (t) { Be[t] = function () { var e; if (Ae) return (e = Ae)[t].apply(e, arguments) } }), Be.DismissReason = e, Be.noop = function () { }, Be.version = "7.26.12"; var Pe, Se, Ee = ie((Pe = Be, Se = function (e) { function t() { return s(this, t), u(this, (t.__proto__ || Object.getPrototypeOf(t)).apply(this, arguments)) } return a(t, Pe), o(t, [{ key: "_main", value: function (e) { return i(t.prototype.__proto__ || Object.getPrototypeOf(t.prototype), "_main", this).call(this, r({}, pe, e)) } }], [{ key: "setDefaults", value: function (t) { if (l(de), !t || "object" !== (void 0 === t ? "undefined" : q(t))) throw new TypeError("SweetAlert2: The argument for setDefaults() is required and has to be a object"); le(t), Object.keys(t).forEach(function (e) { Pe.isValidParameter(e) && (pe[e] = t[e]) }) } }, { key: "resetDefaults", value: function () { l(de), pe = {} } }]), t }(), "undefined" != typeof window && "object" === q(window._swalDefaults) && Se.setDefaults(window._swalDefaults), Se)); return Ee.default = Ee }), "undefined" != typeof window && window.Sweetalert2 && (window.swal = window.sweetAlert = window.Swal = window.SweetAlert = window.Sweetalert2); "undefined" != typeof document && function (e, t) { var n = e.createElement("style"); if (e.getElementsByTagName("head")[0].appendChild(n), n.styleSheet) n.styleSheet.disabled || (n.styleSheet.cssText = t); else try { n.innerHTML = t } catch (e) { n.innerText = t } }(document, "@-webkit-keyframes swal2-show{0%{-webkit-transform:scale(.7);transform:scale(.7)}45%{-webkit-transform:scale(1.05);transform:scale(1.05)}80%{-webkit-transform:scale(.95);transform:scale(.95)}100%{-webkit-transform:scale(1);transform:scale(1)}}@keyframes swal2-show{0%{-webkit-transform:scale(.7);transform:scale(.7)}45%{-webkit-transform:scale(1.05);transform:scale(1.05)}80%{-webkit-transform:scale(.95);transform:scale(.95)}100%{-webkit-transform:scale(1);transform:scale(1)}}@-webkit-keyframes swal2-hide{0%{-webkit-transform:scale(1);transform:scale(1);opacity:1}100%{-webkit-transform:scale(.5);transform:scale(.5);opacity:0}}@keyframes swal2-hide{0%{-webkit-transform:scale(1);transform:scale(1);opacity:1}100%{-webkit-transform:scale(.5);transform:scale(.5);opacity:0}}@-webkit-keyframes swal2-animate-success-line-tip{0%{top:1.1875em;left:.0625em;width:0}54%{top:1.0625em;left:.125em;width:0}70%{top:2.1875em;left:-.375em;width:3.125em}84%{top:3em;left:1.3125em;width:1.0625em}100%{top:2.8125em;left:.875em;width:1.5625em}}@keyframes swal2-animate-success-line-tip{0%{top:1.1875em;left:.0625em;width:0}54%{top:1.0625em;left:.125em;width:0}70%{top:2.1875em;left:-.375em;width:3.125em}84%{top:3em;left:1.3125em;width:1.0625em}100%{top:2.8125em;left:.875em;width:1.5625em}}@-webkit-keyframes swal2-animate-success-line-long{0%{top:3.375em;right:2.875em;width:0}65%{top:3.375em;right:2.875em;width:0}84%{top:2.1875em;right:0;width:3.4375em}100%{top:2.375em;right:.5em;width:2.9375em}}@keyframes swal2-animate-success-line-long{0%{top:3.375em;right:2.875em;width:0}65%{top:3.375em;right:2.875em;width:0}84%{top:2.1875em;right:0;width:3.4375em}100%{top:2.375em;right:.5em;width:2.9375em}}@-webkit-keyframes swal2-rotate-success-circular-line{0%{-webkit-transform:rotate(-45deg);transform:rotate(-45deg)}5%{-webkit-transform:rotate(-45deg);transform:rotate(-45deg)}12%{-webkit-transform:rotate(-405deg);transform:rotate(-405deg)}100%{-webkit-transform:rotate(-405deg);transform:rotate(-405deg)}}@keyframes swal2-rotate-success-circular-line{0%{-webkit-transform:rotate(-45deg);transform:rotate(-45deg)}5%{-webkit-transform:rotate(-45deg);transform:rotate(-45deg)}12%{-webkit-transform:rotate(-405deg);transform:rotate(-405deg)}100%{-webkit-transform:rotate(-405deg);transform:rotate(-405deg)}}@-webkit-keyframes swal2-animate-error-x-mark{0%{margin-top:1.625em;-webkit-transform:scale(.4);transform:scale(.4);opacity:0}50%{margin-top:1.625em;-webkit-transform:scale(.4);transform:scale(.4);opacity:0}80%{margin-top:-.375em;-webkit-transform:scale(1.15);transform:scale(1.15)}100%{margin-top:0;-webkit-transform:scale(1);transform:scale(1);opacity:1}}@keyframes swal2-animate-error-x-mark{0%{margin-top:1.625em;-webkit-transform:scale(.4);transform:scale(.4);opacity:0}50%{margin-top:1.625em;-webkit-transform:scale(.4);transform:scale(.4);opacity:0}80%{margin-top:-.375em;-webkit-transform:scale(1.15);transform:scale(1.15)}100%{margin-top:0;-webkit-transform:scale(1);transform:scale(1);opacity:1}}@-webkit-keyframes swal2-animate-error-icon{0%{-webkit-transform:rotateX(100deg);transform:rotateX(100deg);opacity:0}100%{-webkit-transform:rotateX(0);transform:rotateX(0);opacity:1}}@keyframes swal2-animate-error-icon{0%{-webkit-transform:rotateX(100deg);transform:rotateX(100deg);opacity:0}100%{-webkit-transform:rotateX(0);transform:rotateX(0);opacity:1}}body.swal2-toast-shown .swal2-container{position:fixed;background-color:transparent}body.swal2-toast-shown .swal2-container.swal2-shown{background-color:transparent}body.swal2-toast-shown .swal2-container.swal2-top{top:0;right:auto;bottom:auto;left:50%;-webkit-transform:translateX(-50%);transform:translateX(-50%)}body.swal2-toast-shown .swal2-container.swal2-top-end,body.swal2-toast-shown .swal2-container.swal2-top-right{top:0;right:0;bottom:auto;left:auto}body.swal2-toast-shown .swal2-container.swal2-top-left,body.swal2-toast-shown .swal2-container.swal2-top-start{top:0;right:auto;bottom:auto;left:0}body.swal2-toast-shown .swal2-container.swal2-center-left,body.swal2-toast-shown .swal2-container.swal2-center-start{top:50%;right:auto;bottom:auto;left:0;-webkit-transform:translateY(-50%);transform:translateY(-50%)}body.swal2-toast-shown .swal2-container.swal2-center{top:50%;right:auto;bottom:auto;left:50%;-webkit-transform:translate(-50%,-50%);transform:translate(-50%,-50%)}body.swal2-toast-shown .swal2-container.swal2-center-end,body.swal2-toast-shown .swal2-container.swal2-center-right{top:50%;right:0;bottom:auto;left:auto;-webkit-transform:translateY(-50%);transform:translateY(-50%)}body.swal2-toast-shown .swal2-container.swal2-bottom-left,body.swal2-toast-shown .swal2-container.swal2-bottom-start{top:auto;right:auto;bottom:0;left:0}body.swal2-toast-shown .swal2-container.swal2-bottom{top:auto;right:auto;bottom:0;left:50%;-webkit-transform:translateX(-50%);transform:translateX(-50%)}body.swal2-toast-shown .swal2-container.swal2-bottom-end,body.swal2-toast-shown .swal2-container.swal2-bottom-right{top:auto;right:0;bottom:0;left:auto}body.swal2-toast-column .swal2-toast{flex-direction:column;align-items:stretch}body.swal2-toast-column .swal2-toast .swal2-actions{flex:1;align-self:stretch;height:2.2em;margin-top:.3125em}body.swal2-toast-column .swal2-toast .swal2-loading{justify-content:center}body.swal2-toast-column .swal2-toast .swal2-input{height:2em;margin:.3125em auto;font-size:1em}body.swal2-toast-column .swal2-toast .swal2-validationerror{font-size:1em}.swal2-popup.swal2-toast{flex-direction:row;align-items:center;width:auto;padding:.625em;box-shadow:0 0 .625em #d9d9d9;overflow-y:hidden}.swal2-popup.swal2-toast .swal2-header{flex-direction:row}.swal2-popup.swal2-toast .swal2-title{flex-grow:1;justify-content:flex-start;margin:0 .6em;font-size:1em}.swal2-popup.swal2-toast .swal2-footer{margin:.5em 0 0;padding:.5em 0 0;font-size:.8em}.swal2-popup.swal2-toast .swal2-close{position:initial;width:.8em;height:.8em;line-height:.8}.swal2-popup.swal2-toast .swal2-content{justify-content:flex-start;font-size:1em}.swal2-popup.swal2-toast .swal2-icon{width:2em;min-width:2em;height:2em;margin:0}.swal2-popup.swal2-toast .swal2-icon-text{font-size:2em;font-weight:700;line-height:1em}.swal2-popup.swal2-toast .swal2-icon.swal2-success .swal2-success-ring{width:2em;height:2em}.swal2-popup.swal2-toast .swal2-icon.swal2-error [class^=swal2-x-mark-line]{top:.875em;width:1.375em}.swal2-popup.swal2-toast .swal2-icon.swal2-error [class^=swal2-x-mark-line][class$=left]{left:.3125em}.swal2-popup.swal2-toast .swal2-icon.swal2-error [class^=swal2-x-mark-line][class$=right]{right:.3125em}.swal2-popup.swal2-toast .swal2-actions{height:auto;margin:0 .3125em}.swal2-popup.swal2-toast .swal2-styled{margin:0 .3125em;padding:.3125em .625em;font-size:1em}.swal2-popup.swal2-toast .swal2-styled:focus{box-shadow:0 0 0 .0625em #fff,0 0 0 .125em rgba(50,100,150,.4)}.swal2-popup.swal2-toast .swal2-success{border-color:#a5dc86}.swal2-popup.swal2-toast .swal2-success [class^=swal2-success-circular-line]{position:absolute;width:2em;height:2.8125em;-webkit-transform:rotate(45deg);transform:rotate(45deg);border-radius:50%}.swal2-popup.swal2-toast .swal2-success [class^=swal2-success-circular-line][class$=left]{top:-.25em;left:-.9375em;-webkit-transform:rotate(-45deg);transform:rotate(-45deg);-webkit-transform-origin:2em 2em;transform-origin:2em 2em;border-radius:4em 0 0 4em}.swal2-popup.swal2-toast .swal2-success [class^=swal2-success-circular-line][class$=right]{top:-.25em;left:.9375em;-webkit-transform-origin:0 2em;transform-origin:0 2em;border-radius:0 4em 4em 0}.swal2-popup.swal2-toast .swal2-success .swal2-success-ring{width:2em;height:2em}.swal2-popup.swal2-toast .swal2-success .swal2-success-fix{top:0;left:.4375em;width:.4375em;height:2.6875em}.swal2-popup.swal2-toast .swal2-success [class^=swal2-success-line]{height:.3125em}.swal2-popup.swal2-toast .swal2-success [class^=swal2-success-line][class$=tip]{top:1.125em;left:.1875em;width:.75em}.swal2-popup.swal2-toast .swal2-success [class^=swal2-success-line][class$=long]{top:.9375em;right:.1875em;width:1.375em}.swal2-popup.swal2-toast.swal2-show{-webkit-animation:showSweetToast .5s;animation:showSweetToast .5s}.swal2-popup.swal2-toast.swal2-hide{-webkit-animation:hideSweetToast .2s forwards;animation:hideSweetToast .2s forwards}.swal2-popup.swal2-toast .swal2-animate-success-icon .swal2-success-line-tip{-webkit-animation:animate-toast-success-tip .75s;animation:animate-toast-success-tip .75s}.swal2-popup.swal2-toast .swal2-animate-success-icon .swal2-success-line-long{-webkit-animation:animate-toast-success-long .75s;animation:animate-toast-success-long .75s}@-webkit-keyframes showSweetToast{0%{-webkit-transform:translateY(-.625em) rotateZ(2deg);transform:translateY(-.625em) rotateZ(2deg);opacity:0}33%{-webkit-transform:translateY(0) rotateZ(-2deg);transform:translateY(0) rotateZ(-2deg);opacity:.5}66%{-webkit-transform:translateY(.3125em) rotateZ(2deg);transform:translateY(.3125em) rotateZ(2deg);opacity:.7}100%{-webkit-transform:translateY(0) rotateZ(0);transform:translateY(0) rotateZ(0);opacity:1}}@keyframes showSweetToast{0%{-webkit-transform:translateY(-.625em) rotateZ(2deg);transform:translateY(-.625em) rotateZ(2deg);opacity:0}33%{-webkit-transform:translateY(0) rotateZ(-2deg);transform:translateY(0) rotateZ(-2deg);opacity:.5}66%{-webkit-transform:translateY(.3125em) rotateZ(2deg);transform:translateY(.3125em) rotateZ(2deg);opacity:.7}100%{-webkit-transform:translateY(0) rotateZ(0);transform:translateY(0) rotateZ(0);opacity:1}}@-webkit-keyframes hideSweetToast{0%{opacity:1}33%{opacity:.5}100%{-webkit-transform:rotateZ(1deg);transform:rotateZ(1deg);opacity:0}}@keyframes hideSweetToast{0%{opacity:1}33%{opacity:.5}100%{-webkit-transform:rotateZ(1deg);transform:rotateZ(1deg);opacity:0}}@-webkit-keyframes animate-toast-success-tip{0%{top:.5625em;left:.0625em;width:0}54%{top:.125em;left:.125em;width:0}70%{top:.625em;left:-.25em;width:1.625em}84%{top:1.0625em;left:.75em;width:.5em}100%{top:1.125em;left:.1875em;width:.75em}}@keyframes animate-toast-success-tip{0%{top:.5625em;left:.0625em;width:0}54%{top:.125em;left:.125em;width:0}70%{top:.625em;left:-.25em;width:1.625em}84%{top:1.0625em;left:.75em;width:.5em}100%{top:1.125em;left:.1875em;width:.75em}}@-webkit-keyframes animate-toast-success-long{0%{top:1.625em;right:1.375em;width:0}65%{top:1.25em;right:.9375em;width:0}84%{top:.9375em;right:0;width:1.125em}100%{top:.9375em;right:.1875em;width:1.375em}}@keyframes animate-toast-success-long{0%{top:1.625em;right:1.375em;width:0}65%{top:1.25em;right:.9375em;width:0}84%{top:.9375em;right:0;width:1.125em}100%{top:.9375em;right:.1875em;width:1.375em}}body.swal2-shown:not(.swal2-no-backdrop):not(.swal2-toast-shown){overflow-y:hidden}body.swal2-height-auto{height:auto!important}body.swal2-no-backdrop .swal2-shown{top:auto;right:auto;bottom:auto;left:auto;background-color:transparent}body.swal2-no-backdrop .swal2-shown>.swal2-modal{box-shadow:0 0 10px rgba(0,0,0,.4)}body.swal2-no-backdrop .swal2-shown.swal2-top{top:0;left:50%;-webkit-transform:translateX(-50%);transform:translateX(-50%)}body.swal2-no-backdrop .swal2-shown.swal2-top-left,body.swal2-no-backdrop .swal2-shown.swal2-top-start{top:0;left:0}body.swal2-no-backdrop .swal2-shown.swal2-top-end,body.swal2-no-backdrop .swal2-shown.swal2-top-right{top:0;right:0}body.swal2-no-backdrop .swal2-shown.swal2-center{top:50%;left:50%;-webkit-transform:translate(-50%,-50%);transform:translate(-50%,-50%)}body.swal2-no-backdrop .swal2-shown.swal2-center-left,body.swal2-no-backdrop .swal2-shown.swal2-center-start{top:50%;left:0;-webkit-transform:translateY(-50%);transform:translateY(-50%)}body.swal2-no-backdrop .swal2-shown.swal2-center-end,body.swal2-no-backdrop .swal2-shown.swal2-center-right{top:50%;right:0;-webkit-transform:translateY(-50%);transform:translateY(-50%)}body.swal2-no-backdrop .swal2-shown.swal2-bottom{bottom:0;left:50%;-webkit-transform:translateX(-50%);transform:translateX(-50%)}body.swal2-no-backdrop .swal2-shown.swal2-bottom-left,body.swal2-no-backdrop .swal2-shown.swal2-bottom-start{bottom:0;left:0}body.swal2-no-backdrop .swal2-shown.swal2-bottom-end,body.swal2-no-backdrop .swal2-shown.swal2-bottom-right{right:0;bottom:0}.swal2-container{display:flex;position:fixed;top:0;right:0;bottom:0;left:0;flex-direction:row;align-items:center;justify-content:center;padding:10px;background-color:transparent;z-index:1060;overflow-x:hidden;-webkit-overflow-scrolling:touch}.swal2-container.swal2-top{align-items:flex-start}.swal2-container.swal2-top-left,.swal2-container.swal2-top-start{align-items:flex-start;justify-content:flex-start}.swal2-container.swal2-top-end,.swal2-container.swal2-top-right{align-items:flex-start;justify-content:flex-end}.swal2-container.swal2-center{align-items:center}.swal2-container.swal2-center-left,.swal2-container.swal2-center-start{align-items:center;justify-content:flex-start}.swal2-container.swal2-center-end,.swal2-container.swal2-center-right{align-items:center;justify-content:flex-end}.swal2-container.swal2-bottom{align-items:flex-end}.swal2-container.swal2-bottom-left,.swal2-container.swal2-bottom-start{align-items:flex-end;justify-content:flex-start}.swal2-container.swal2-bottom-end,.swal2-container.swal2-bottom-right{align-items:flex-end;justify-content:flex-end}.swal2-container.swal2-grow-fullscreen>.swal2-modal{display:flex!important;flex:1;align-self:stretch;justify-content:center}.swal2-container.swal2-grow-row>.swal2-modal{display:flex!important;flex:1;align-content:center;justify-content:center}.swal2-container.swal2-grow-column{flex:1;flex-direction:column}.swal2-container.swal2-grow-column.swal2-bottom,.swal2-container.swal2-grow-column.swal2-center,.swal2-container.swal2-grow-column.swal2-top{align-items:center}.swal2-container.swal2-grow-column.swal2-bottom-left,.swal2-container.swal2-grow-column.swal2-bottom-start,.swal2-container.swal2-grow-column.swal2-center-left,.swal2-container.swal2-grow-column.swal2-center-start,.swal2-container.swal2-grow-column.swal2-top-left,.swal2-container.swal2-grow-column.swal2-top-start{align-items:flex-start}.swal2-container.swal2-grow-column.swal2-bottom-end,.swal2-container.swal2-grow-column.swal2-bottom-right,.swal2-container.swal2-grow-column.swal2-center-end,.swal2-container.swal2-grow-column.swal2-center-right,.swal2-container.swal2-grow-column.swal2-top-end,.swal2-container.swal2-grow-column.swal2-top-right{align-items:flex-end}.swal2-container.swal2-grow-column>.swal2-modal{display:flex!important;flex:1;align-content:center;justify-content:center}.swal2-container:not(.swal2-top):not(.swal2-top-start):not(.swal2-top-end):not(.swal2-top-left):not(.swal2-top-right):not(.swal2-center-start):not(.swal2-center-end):not(.swal2-center-left):not(.swal2-center-right):not(.swal2-bottom):not(.swal2-bottom-start):not(.swal2-bottom-end):not(.swal2-bottom-left):not(.swal2-bottom-right):not(.swal2-grow-fullscreen)>.swal2-modal{margin:auto}@media all and (-ms-high-contrast:none),(-ms-high-contrast:active){.swal2-container .swal2-modal{margin:0!important}}.swal2-container.swal2-fade{transition:background-color .1s}.swal2-container.swal2-shown{background-color:rgba(0,0,0,.4)}.swal2-popup{display:none;position:relative;flex-direction:column;justify-content:center;width:32em;max-width:100%;padding:1.25em;border-radius:.3125em;background:#fff;font-family:inherit;font-size:1.5rem;box-sizing:border-box}.swal2-popup:focus{outline:0}.swal2-popup.swal2-loading{overflow-y:hidden}.swal2-popup .swal2-header{display:flex;flex-direction:column;align-items:center}.swal2-popup .swal2-title{display:block;position:relative;max-width:100%;margin:0 0 .4em;padding:0;color:#595959;font-size:1.875em;font-weight:600;text-align:center;text-transform:none;word-wrap:break-word}.swal2-popup .swal2-actions{align-items:center;justify-content:center;margin:1.25em auto 0;z-index:1}.swal2-popup .swal2-actions:not(.swal2-loading) .swal2-styled[disabled]{opacity:.4}.swal2-popup .swal2-actions:not(.swal2-loading) .swal2-styled:hover{background-image:linear-gradient(rgba(0,0,0,.1),rgba(0,0,0,.1))}.swal2-popup .swal2-actions:not(.swal2-loading) .swal2-styled:active{background-image:linear-gradient(rgba(0,0,0,.2),rgba(0,0,0,.2))}.swal2-popup .swal2-actions.swal2-loading .swal2-styled.swal2-confirm{width:2.5em;height:2.5em;margin:.46875em;padding:0;border:.25em solid transparent;border-radius:100%;border-color:transparent;background-color:transparent!important;color:transparent;cursor:default;box-sizing:border-box;-webkit-animation:swal2-rotate-loading 1.5s linear 0s infinite normal;animation:swal2-rotate-loading 1.5s linear 0s infinite normal;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.swal2-popup .swal2-actions.swal2-loading .swal2-styled.swal2-cancel{margin-right:30px;margin-left:30px}.swal2-popup .swal2-actions.swal2-loading :not(.swal2-styled).swal2-confirm::after{display:inline-block;width:15px;height:15px;margin-left:5px;border:3px solid #999;border-radius:50%;border-right-color:transparent;box-shadow:1px 1px 1px #fff;content:'';-webkit-animation:swal2-rotate-loading 1.5s linear 0s infinite normal;animation:swal2-rotate-loading 1.5s linear 0s infinite normal}.swal2-popup .swal2-styled{margin:0 .3125em;padding:.625em 2em;font-weight:500;box-shadow:none}.swal2-popup .swal2-styled:not([disabled]){cursor:pointer}.swal2-popup .swal2-styled.swal2-confirm{border:0;border-radius:.25em;background:initial;background-color:#3085d6;color:#fff;font-size:1.0625em}.swal2-popup .swal2-styled.swal2-cancel{border:0;border-radius:.25em;background:initial;background-color:#aaa;color:#fff;font-size:1.0625em}.swal2-popup .swal2-styled:focus{outline:0;box-shadow:0 0 0 2px #fff,0 0 0 4px rgba(50,100,150,.4)}.swal2-popup .swal2-styled::-moz-focus-inner{border:0}.swal2-popup .swal2-footer{justify-content:center;margin:1.25em 0 0;padding:1em 0 0;border-top:1px solid #eee;color:#545454;font-size:1em}.swal2-popup .swal2-image{max-width:100%;margin:1.25em auto}.swal2-popup .swal2-close{position:absolute;top:0;right:0;justify-content:center;width:1.2em;height:1.2em;padding:0;transition:color .1s ease-out;border:none;border-radius:0;background:0 0;color:#ccc;font-family:serif;font-size:2.5em;line-height:1.2;cursor:pointer;overflow:hidden}.swal2-popup .swal2-close:hover{-webkit-transform:none;transform:none;color:#f27474}.swal2-popup>.swal2-checkbox,.swal2-popup>.swal2-file,.swal2-popup>.swal2-input,.swal2-popup>.swal2-radio,.swal2-popup>.swal2-select,.swal2-popup>.swal2-textarea{display:none}.swal2-popup .swal2-content{justify-content:center;margin:0;padding:0;color:#545454;font-size:1.125em;font-weight:300;line-height:normal;z-index:1;word-wrap:break-word}.swal2-popup #swal2-content{text-align:center}.swal2-popup .swal2-checkbox,.swal2-popup .swal2-file,.swal2-popup .swal2-input,.swal2-popup .swal2-radio,.swal2-popup .swal2-select,.swal2-popup .swal2-textarea{margin:1em auto}.swal2-popup .swal2-file,.swal2-popup .swal2-input,.swal2-popup .swal2-textarea{width:100%;transition:border-color .3s,box-shadow .3s;border:1px solid #d9d9d9;border-radius:.1875em;font-size:1.125em;box-shadow:inset 0 1px 1px rgba(0,0,0,.06);box-sizing:border-box}.swal2-popup .swal2-file.swal2-inputerror,.swal2-popup .swal2-input.swal2-inputerror,.swal2-popup .swal2-textarea.swal2-inputerror{border-color:#f27474!important;box-shadow:0 0 2px #f27474!important}.swal2-popup .swal2-file:focus,.swal2-popup .swal2-input:focus,.swal2-popup .swal2-textarea:focus{border:1px solid #b4dbed;outline:0;box-shadow:0 0 3px #c4e6f5}.swal2-popup .swal2-file::-webkit-input-placeholder,.swal2-popup .swal2-input::-webkit-input-placeholder,.swal2-popup .swal2-textarea::-webkit-input-placeholder{color:#ccc}.swal2-popup .swal2-file:-ms-input-placeholder,.swal2-popup .swal2-input:-ms-input-placeholder,.swal2-popup .swal2-textarea:-ms-input-placeholder{color:#ccc}.swal2-popup .swal2-file::-ms-input-placeholder,.swal2-popup .swal2-input::-ms-input-placeholder,.swal2-popup .swal2-textarea::-ms-input-placeholder{color:#ccc}.swal2-popup .swal2-file::placeholder,.swal2-popup .swal2-input::placeholder,.swal2-popup .swal2-textarea::placeholder{color:#ccc}.swal2-popup .swal2-range input{width:80%}.swal2-popup .swal2-range output{width:20%;font-weight:600;text-align:center}.swal2-popup .swal2-range input,.swal2-popup .swal2-range output{height:2.625em;margin:1em auto;padding:0;font-size:1.125em;line-height:2.625em}.swal2-popup .swal2-input{height:2.625em;padding:.75em}.swal2-popup .swal2-input[type=number]{max-width:10em}.swal2-popup .swal2-file{font-size:1.125em}.swal2-popup .swal2-textarea{height:6.75em;padding:.75em}.swal2-popup .swal2-select{min-width:50%;max-width:100%;padding:.375em .625em;color:#545454;font-size:1.125em}.swal2-popup .swal2-checkbox,.swal2-popup .swal2-radio{align-items:center;justify-content:center}.swal2-popup .swal2-checkbox label,.swal2-popup .swal2-radio label{margin:0 .6em;font-size:1.125em}.swal2-popup .swal2-checkbox input,.swal2-popup .swal2-radio input{margin:0 .4em}.swal2-popup .swal2-validationerror{display:none;align-items:center;justify-content:center;padding:.625em;background:#f0f0f0;color:#666;font-size:1em;font-weight:300;overflow:hidden}.swal2-popup .swal2-validationerror::before{display:inline-block;width:1.5em;min-width:1.5em;height:1.5em;margin:0 .625em;border-radius:50%;background-color:#f27474;color:#fff;font-weight:600;line-height:1.5em;text-align:center;content:'!';zoom:normal}@supports (-ms-accelerator:true){.swal2-range input{width:100%!important}.swal2-range output{display:none}}@media all and (-ms-high-contrast:none),(-ms-high-contrast:active){.swal2-range input{width:100%!important}.swal2-range output{display:none}}@-moz-document url-prefix(){.swal2-close:focus{outline:2px solid rgba(50,100,150,.4)}}.swal2-icon{position:relative;justify-content:center;width:5em;height:5em;margin:1.25em auto 1.875em;border:.25em solid transparent;border-radius:50%;line-height:5em;cursor:default;box-sizing:content-box;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;zoom:normal}.swal2-icon-text{font-size:3.75em}.swal2-icon.swal2-error{border-color:#f27474}.swal2-icon.swal2-error .swal2-x-mark{position:relative;flex-grow:1}.swal2-icon.swal2-error [class^=swal2-x-mark-line]{display:block;position:absolute;top:2.3125em;width:2.9375em;height:.3125em;border-radius:.125em;background-color:#f27474}.swal2-icon.swal2-error [class^=swal2-x-mark-line][class$=left]{left:1.0625em;-webkit-transform:rotate(45deg);transform:rotate(45deg)}.swal2-icon.swal2-error [class^=swal2-x-mark-line][class$=right]{right:1em;-webkit-transform:rotate(-45deg);transform:rotate(-45deg)}.swal2-icon.swal2-warning{border-color:#facea8;color:#f8bb86}.swal2-icon.swal2-info{border-color:#9de0f6;color:#3fc3ee}.swal2-icon.swal2-question{border-color:#c9dae1;color:#87adbd}.swal2-icon.swal2-success{border-color:#a5dc86}.swal2-icon.swal2-success [class^=swal2-success-circular-line]{position:absolute;width:3.75em;height:7.5em;-webkit-transform:rotate(45deg);transform:rotate(45deg);border-radius:50%}.swal2-icon.swal2-success [class^=swal2-success-circular-line][class$=left]{top:-.4375em;left:-2.0635em;-webkit-transform:rotate(-45deg);transform:rotate(-45deg);-webkit-transform-origin:3.75em 3.75em;transform-origin:3.75em 3.75em;border-radius:7.5em 0 0 7.5em}.swal2-icon.swal2-success [class^=swal2-success-circular-line][class$=right]{top:-.6875em;left:1.875em;-webkit-transform:rotate(-45deg);transform:rotate(-45deg);-webkit-transform-origin:0 3.75em;transform-origin:0 3.75em;border-radius:0 7.5em 7.5em 0}.swal2-icon.swal2-success .swal2-success-ring{position:absolute;top:-.25em;left:-.25em;width:100%;height:100%;border:.25em solid rgba(165,220,134,.3);border-radius:50%;z-index:2;box-sizing:content-box}.swal2-icon.swal2-success .swal2-success-fix{position:absolute;top:.5em;left:1.625em;width:.4375em;height:5.625em;-webkit-transform:rotate(-45deg);transform:rotate(-45deg);z-index:1}.swal2-icon.swal2-success [class^=swal2-success-line]{display:block;position:absolute;height:.3125em;border-radius:.125em;background-color:#a5dc86;z-index:2}.swal2-icon.swal2-success [class^=swal2-success-line][class$=tip]{top:2.875em;left:.875em;width:1.5625em;-webkit-transform:rotate(45deg);transform:rotate(45deg)}.swal2-icon.swal2-success [class^=swal2-success-line][class$=long]{top:2.375em;right:.5em;width:2.9375em;-webkit-transform:rotate(-45deg);transform:rotate(-45deg)}.swal2-progresssteps{align-items:center;margin:0 0 1.25em;padding:0;font-weight:600}.swal2-progresssteps li{display:inline-block;position:relative}.swal2-progresssteps .swal2-progresscircle{width:2em;height:2em;border-radius:2em;background:#3085d6;color:#fff;line-height:2em;text-align:center;z-index:20}.swal2-progresssteps .swal2-progresscircle:first-child{margin-left:0}.swal2-progresssteps .swal2-progresscircle:last-child{margin-right:0}.swal2-progresssteps .swal2-progresscircle.swal2-activeprogressstep{background:#3085d6}.swal2-progresssteps .swal2-progresscircle.swal2-activeprogressstep~.swal2-progresscircle{background:#add8e6}.swal2-progresssteps .swal2-progresscircle.swal2-activeprogressstep~.swal2-progressline{background:#add8e6}.swal2-progresssteps .swal2-progressline{width:2.5em;height:.4em;margin:0 -1px;background:#3085d6;z-index:10}[class^=swal2]{-webkit-tap-highlight-color:transparent}.swal2-show{-webkit-animation:swal2-show .3s;animation:swal2-show .3s}.swal2-show.swal2-noanimation{-webkit-animation:none;animation:none}.swal2-hide{-webkit-animation:swal2-hide .15s forwards;animation:swal2-hide .15s forwards}.swal2-hide.swal2-noanimation{-webkit-animation:none;animation:none}[dir=rtl] .swal2-close{right:auto;left:0}.swal2-animate-success-icon .swal2-success-line-tip{-webkit-animation:swal2-animate-success-line-tip .75s;animation:swal2-animate-success-line-tip .75s}.swal2-animate-success-icon .swal2-success-line-long{-webkit-animation:swal2-animate-success-line-long .75s;animation:swal2-animate-success-line-long .75s}.swal2-animate-success-icon .swal2-success-circular-line-right{-webkit-animation:swal2-rotate-success-circular-line 4.25s ease-in;animation:swal2-rotate-success-circular-line 4.25s ease-in}.swal2-animate-error-icon{-webkit-animation:swal2-animate-error-icon .5s;animation:swal2-animate-error-icon .5s}.swal2-animate-error-icon .swal2-x-mark{-webkit-animation:swal2-animate-error-x-mark .5s;animation:swal2-animate-error-x-mark .5s}@-webkit-keyframes swal2-rotate-loading{0%{-webkit-transform:rotate(0);transform:rotate(0)}100%{-webkit-transform:rotate(360deg);transform:rotate(360deg)}}@keyframes swal2-rotate-loading{0%{-webkit-transform:rotate(0);transform:rotate(0)}100%{-webkit-transform:rotate(360deg);transform:rotate(360deg)}}"); $('.keppler-switch').click(function(event) { event.preventDefault() $(this).find('input') .toggleClass('active') .attr('checked', $(this).find('input').hasClass('active')) }) ; (function() { $(document).on('turbolinks:load', function() { return $('body').tooltip({ selector: "[data-toggle~='tooltip']" }); }); }).call(this); (function() { var upload_records; upload_records = function() { return $('#upload').click(function() { $('#upload-file').click(); return $('#upload-file').change(function() { $('.waiting').css('display', 'block'); return $('#upload-form').submit(); }); }); }; $(document).on('turbolinks:load', upload_records); }).call(this); (function() { }).call(this);